blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0923efe5d2553fb9efb897f240f19e04f104f6cb | ee22fa7476a52f3fe2f9bc88d6c8f43f614cdba6 | /UVA/11462.cpp | f6f17c4d4a93aa5fcbb032ae328978af963f7e15 | [] | no_license | Sillyplus/Solution | 704bff07a29709f64e3e1634946618170d426b72 | 48dcaa075852f8cda1db22ec1733600edea59422 | refs/heads/master | 2020-12-17T04:53:07.089633 | 2016-07-02T10:01:28 | 2016-07-02T10:01:28 | 21,733,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 786 | cpp | //
// main.cpp
// p11462
//
// Created by Silly on 14-1-27.
// Copyright (c) 2014年 Silly. All rights reserved.
//
#include <iostream>
#include <cstring>
int x[102] = {0};
int main(int argc, const char * argv[])
{
int n, k;
while (scanf("%d", &n) == 1 && n) {
memset(x, 0, sizeof(x));
for (int i = 0; i < n; i++) {
scanf("%d", &k);
x[k]++;
}
int t = 1;
for (int i = 0 ; i <= 100; i++) {
if (x[i]) {
for (int j = 0; j < x[i]; j++) {
if (!t) {
printf("%c", ' ');
}
t = 0;
printf("%d", i);
}
}
}
printf("\n");
}
return 0;
}
| [
"oi_boy@sina.cn"
] | oi_boy@sina.cn |
76149d52e5d27af04835f9eee48d09891ebeca25 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /chrome/browser/ui/app_list/app_list_positioner_unittest.cc | 24fce11708f827a6a19eecdb05b62d69c535f552 | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 13,798 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/app_list/app_list_positioner.h"
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const int kScreenWidth = 800;
const int kScreenHeight = 600;
const int kWindowWidth = 100;
const int kWindowHeight = 200;
// Size of the menu bar along the top of the screen.
const int kMenuBarSize = 22;
// Size of the normal (non-hidden) shelf.
const int kShelfSize = 30;
// The distance the shelf will appear from the edge of the screen.
const int kMinDistanceFromEdge = 3;
// A cursor position that is within the shelf. This must be < kShelfSize.
const int kCursorOnShelf = kShelfSize / 2;
// A cursor position that should be ignored.
const int kCursorIgnore = -300;
// A position for the center of the window that causes the window to overlap the
// edge of the screen. This must be < kWindowWidth / 2 and < kWindowHeight / 2.
const int kWindowNearEdge = kWindowWidth / 4;
// A position for the center of the window that places the window away from all
// edges of the screen. This must be > kWindowWidth / 2, > kWindowHeight / 2, <
// kScreenWidth - kWindowWidth / 2 and < kScreenHeight - kWindowHeight / 2.
const int kWindowAwayFromEdge = 158;
} // namespace
class AppListPositionerUnitTest : public testing::Test {
public:
void ResetPositioner() {
gfx::Size view_size(kWindowWidth, kWindowHeight);
positioner_.reset(
new AppListPositioner(display_, view_size, kMinDistanceFromEdge));
}
void SetUp() override {
display_.set_bounds(gfx::Rect(0, 0, kScreenWidth, kScreenHeight));
// Assume there is a menu bar at the top of the screen, as on Mac and Unity.
// This is for cases where the work area does not fill the entire screen.
display_.set_work_area(
gfx::Rect(0, kMenuBarSize, kScreenWidth, kScreenHeight - kMenuBarSize));
ResetPositioner();
cursor_ = gfx::Point();
}
// Sets up the test environment with the shelf along a given edge of the work
// area.
void PlaceShelf(AppListPositioner::ScreenEdge edge) {
ResetPositioner();
switch (edge) {
case AppListPositioner::SCREEN_EDGE_UNKNOWN:
break;
case AppListPositioner::SCREEN_EDGE_LEFT:
positioner_->WorkAreaInset(kShelfSize, 0, 0, 0);
break;
case AppListPositioner::SCREEN_EDGE_RIGHT:
positioner_->WorkAreaInset(0, 0, kShelfSize, 0);
break;
case AppListPositioner::SCREEN_EDGE_TOP:
positioner_->WorkAreaInset(0, kShelfSize, 0, 0);
break;
case AppListPositioner::SCREEN_EDGE_BOTTOM:
positioner_->WorkAreaInset(0, 0, 0, kShelfSize);
break;
}
}
// Set up the test mouse cursor in a given location.
void PlaceCursor(int x, int y) {
cursor_ = gfx::Point(x, y);
}
gfx::Point DoGetAnchorPointForScreenCorner(
AppListPositioner::ScreenCorner corner) const {
return positioner_->GetAnchorPointForScreenCorner(corner);
}
gfx::Point DoGetAnchorPointForShelfCorner(
AppListPositioner::ScreenEdge shelf_edge) const {
return positioner_->GetAnchorPointForShelfCorner(shelf_edge);
}
gfx::Point DoGetAnchorPointForShelfCenter(
AppListPositioner::ScreenEdge shelf_edge) const {
return positioner_->GetAnchorPointForShelfCenter(shelf_edge);
}
gfx::Point DoGetAnchorPointForShelfCursor(
AppListPositioner::ScreenEdge shelf_edge) const {
return positioner_->GetAnchorPointForShelfCursor(shelf_edge, cursor_);
}
AppListPositioner::ScreenEdge DoGetShelfEdge(
const gfx::Rect& shelf_rect) const {
return positioner_->GetShelfEdge(shelf_rect);
}
int DoGetCursorDistanceFromShelf(
AppListPositioner::ScreenEdge shelf_edge) const {
return positioner_->GetCursorDistanceFromShelf(shelf_edge, cursor_);
}
private:
display::Display display_;
std::unique_ptr<AppListPositioner> positioner_;
gfx::Point cursor_;
};
TEST_F(AppListPositionerUnitTest, ScreenCorner) {
// Position the app list in a corner of the screen.
// Top-left corner.
EXPECT_EQ(gfx::Point(kWindowWidth / 2 + kMinDistanceFromEdge,
kMenuBarSize + kWindowHeight / 2 + kMinDistanceFromEdge),
DoGetAnchorPointForScreenCorner(
AppListPositioner::SCREEN_CORNER_TOP_LEFT));
// Top-right corner.
EXPECT_EQ(gfx::Point(kScreenWidth - kWindowWidth / 2 - kMinDistanceFromEdge,
kMenuBarSize + kWindowHeight / 2 + kMinDistanceFromEdge),
DoGetAnchorPointForScreenCorner(
AppListPositioner::SCREEN_CORNER_TOP_RIGHT));
// Bottom-left corner.
EXPECT_EQ(
gfx::Point(kWindowWidth / 2 + kMinDistanceFromEdge,
kScreenHeight - kWindowHeight / 2 - kMinDistanceFromEdge),
DoGetAnchorPointForScreenCorner(
AppListPositioner::SCREEN_CORNER_BOTTOM_LEFT));
// Bottom-right corner.
EXPECT_EQ(
gfx::Point(kScreenWidth - kWindowWidth / 2 - kMinDistanceFromEdge,
kScreenHeight - kWindowHeight / 2 - kMinDistanceFromEdge),
DoGetAnchorPointForScreenCorner(
AppListPositioner::SCREEN_CORNER_BOTTOM_RIGHT));
}
TEST_F(AppListPositionerUnitTest, ShelfCorner) {
// Position the app list on the shelf, aligned with the top or left corner.
// Shelf on left. Expect app list in top-left corner.
PlaceShelf(AppListPositioner::SCREEN_EDGE_LEFT);
EXPECT_EQ(
gfx::Point(kShelfSize + kWindowWidth / 2 + kMinDistanceFromEdge,
kMenuBarSize + kWindowHeight / 2 + kMinDistanceFromEdge),
DoGetAnchorPointForShelfCorner(AppListPositioner::SCREEN_EDGE_LEFT));
// Shelf on right. Expect app list in top-right corner.
PlaceShelf(AppListPositioner::SCREEN_EDGE_RIGHT);
EXPECT_EQ(
gfx::Point(
kScreenWidth - kShelfSize - kWindowWidth / 2 - kMinDistanceFromEdge,
kMenuBarSize + kWindowHeight / 2 + kMinDistanceFromEdge),
DoGetAnchorPointForShelfCorner(AppListPositioner::SCREEN_EDGE_RIGHT));
// Shelf on top. Expect app list in top-left corner.
PlaceShelf(AppListPositioner::SCREEN_EDGE_TOP);
EXPECT_EQ(gfx::Point(kWindowWidth / 2 + kMinDistanceFromEdge,
kMenuBarSize + kShelfSize + kWindowHeight / 2 +
kMinDistanceFromEdge),
DoGetAnchorPointForShelfCorner(AppListPositioner::SCREEN_EDGE_TOP));
// Shelf on bottom. Expect app list in bottom-left corner.
PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
EXPECT_EQ(
gfx::Point(kWindowWidth / 2 + kMinDistanceFromEdge,
kScreenHeight - kShelfSize - kWindowHeight / 2 -
kMinDistanceFromEdge),
DoGetAnchorPointForShelfCorner(AppListPositioner::SCREEN_EDGE_BOTTOM));
}
TEST_F(AppListPositionerUnitTest, ShelfCenter) {
// Position the app list on the shelf, aligned with the shelf center.
PlaceShelf(AppListPositioner::SCREEN_EDGE_LEFT);
// Shelf on left. Expect app list to be center-left.
EXPECT_EQ(
gfx::Point(kShelfSize + kWindowWidth / 2 + kMinDistanceFromEdge,
(kMenuBarSize + kScreenHeight) / 2),
DoGetAnchorPointForShelfCenter(AppListPositioner::SCREEN_EDGE_LEFT));
// Shelf on right. Expect app list to be center-right.
PlaceShelf(AppListPositioner::SCREEN_EDGE_RIGHT);
EXPECT_EQ(
gfx::Point(
kScreenWidth - kShelfSize - kWindowWidth / 2 - kMinDistanceFromEdge,
(kMenuBarSize + kScreenHeight) / 2),
DoGetAnchorPointForShelfCenter(AppListPositioner::SCREEN_EDGE_RIGHT));
// Shelf on top. Expect app list to be top-center.
PlaceShelf(AppListPositioner::SCREEN_EDGE_TOP);
EXPECT_EQ(gfx::Point(kScreenWidth / 2,
kMenuBarSize + kShelfSize + kWindowHeight / 2 +
kMinDistanceFromEdge),
DoGetAnchorPointForShelfCenter(AppListPositioner::SCREEN_EDGE_TOP));
// Shelf on bottom. Expect app list to be bottom-center.
PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
EXPECT_EQ(
gfx::Point(kScreenWidth / 2,
kScreenHeight - kShelfSize - kWindowHeight / 2 -
kMinDistanceFromEdge),
DoGetAnchorPointForShelfCenter(AppListPositioner::SCREEN_EDGE_BOTTOM));
}
TEST_F(AppListPositionerUnitTest, ShelfCursor) {
// Position the app list on the shelf, aligned with the mouse cursor.
// Shelf on left. Expect app list in top-left corner.
PlaceShelf(AppListPositioner::SCREEN_EDGE_LEFT);
PlaceCursor(kCursorIgnore, kWindowAwayFromEdge);
EXPECT_EQ(
gfx::Point(kShelfSize + kWindowWidth / 2 + kMinDistanceFromEdge,
kWindowAwayFromEdge),
DoGetAnchorPointForShelfCursor(AppListPositioner::SCREEN_EDGE_LEFT));
// Shelf on right. Expect app list in top-right corner.
PlaceShelf(AppListPositioner::SCREEN_EDGE_RIGHT);
PlaceCursor(kCursorIgnore, kWindowAwayFromEdge);
EXPECT_EQ(
gfx::Point(
kScreenWidth - kShelfSize - kWindowWidth / 2 - kMinDistanceFromEdge,
kWindowAwayFromEdge),
DoGetAnchorPointForShelfCursor(AppListPositioner::SCREEN_EDGE_RIGHT));
// Shelf on top. Expect app list in top-left corner.
PlaceShelf(AppListPositioner::SCREEN_EDGE_TOP);
PlaceCursor(kWindowAwayFromEdge, kCursorIgnore);
EXPECT_EQ(gfx::Point(kWindowAwayFromEdge,
kMenuBarSize + kShelfSize + kWindowHeight / 2 +
kMinDistanceFromEdge),
DoGetAnchorPointForShelfCursor(AppListPositioner::SCREEN_EDGE_TOP));
// Shelf on bottom. Expect app list in bottom-left corner.
PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
PlaceCursor(kWindowAwayFromEdge, kCursorIgnore);
EXPECT_EQ(
gfx::Point(kWindowAwayFromEdge,
kScreenHeight - kShelfSize - kWindowHeight / 2 -
kMinDistanceFromEdge),
DoGetAnchorPointForShelfCursor(AppListPositioner::SCREEN_EDGE_BOTTOM));
// Shelf on bottom. Mouse near left edge. App list must not go off screen.
PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
PlaceCursor(kWindowNearEdge, kCursorIgnore);
EXPECT_EQ(
gfx::Point(kWindowWidth / 2 + kMinDistanceFromEdge,
kScreenHeight - kShelfSize - kWindowHeight / 2 -
kMinDistanceFromEdge),
DoGetAnchorPointForShelfCursor(AppListPositioner::SCREEN_EDGE_BOTTOM));
// Shelf on bottom. Mouse near right edge. App list must not go off screen.
PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
PlaceCursor(kScreenWidth - kWindowNearEdge, kCursorIgnore);
EXPECT_EQ(
gfx::Point(kScreenWidth - kWindowWidth / 2 - kMinDistanceFromEdge,
kScreenHeight - kShelfSize - kWindowHeight / 2 -
kMinDistanceFromEdge),
DoGetAnchorPointForShelfCursor(AppListPositioner::SCREEN_EDGE_BOTTOM));
}
TEST_F(AppListPositionerUnitTest, GetShelfEdge) {
gfx::Rect shelf_rect;
// Shelf on left.
shelf_rect =
gfx::Rect(0, kMenuBarSize, kShelfSize, kScreenHeight - kMenuBarSize);
EXPECT_EQ(AppListPositioner::SCREEN_EDGE_LEFT, DoGetShelfEdge(shelf_rect));
// Shelf on right.
shelf_rect = gfx::Rect(kScreenWidth - kShelfSize,
kMenuBarSize,
kShelfSize,
kScreenHeight - kMenuBarSize);
EXPECT_EQ(AppListPositioner::SCREEN_EDGE_RIGHT, DoGetShelfEdge(shelf_rect));
// Shelf on top.
shelf_rect = gfx::Rect(0, 0, kScreenWidth, kShelfSize);
EXPECT_EQ(AppListPositioner::SCREEN_EDGE_TOP, DoGetShelfEdge(shelf_rect));
// Shelf on bottom.
shelf_rect =
gfx::Rect(0, kScreenHeight - kShelfSize, kScreenWidth, kShelfSize);
EXPECT_EQ(AppListPositioner::SCREEN_EDGE_BOTTOM, DoGetShelfEdge(shelf_rect));
// A couple of inconclusive cases, which should return unknown.
shelf_rect = gfx::Rect();
EXPECT_EQ(AppListPositioner::SCREEN_EDGE_UNKNOWN, DoGetShelfEdge(shelf_rect));
shelf_rect = gfx::Rect(-10, 0, kScreenWidth, kShelfSize);
EXPECT_EQ(AppListPositioner::SCREEN_EDGE_UNKNOWN, DoGetShelfEdge(shelf_rect));
shelf_rect = gfx::Rect(10, 0, kScreenWidth - 20, kShelfSize);
EXPECT_EQ(AppListPositioner::SCREEN_EDGE_UNKNOWN, DoGetShelfEdge(shelf_rect));
shelf_rect = gfx::Rect(0, kShelfSize, kScreenWidth, 60);
EXPECT_EQ(AppListPositioner::SCREEN_EDGE_UNKNOWN, DoGetShelfEdge(shelf_rect));
}
TEST_F(AppListPositionerUnitTest, GetCursorDistanceFromShelf) {
// Shelf on left.
PlaceShelf(AppListPositioner::SCREEN_EDGE_LEFT);
PlaceCursor(kWindowAwayFromEdge, kCursorIgnore);
EXPECT_EQ(kWindowAwayFromEdge - kShelfSize,
DoGetCursorDistanceFromShelf(AppListPositioner::SCREEN_EDGE_LEFT));
// Shelf on right.
PlaceShelf(AppListPositioner::SCREEN_EDGE_RIGHT);
PlaceCursor(kScreenWidth - kWindowAwayFromEdge, kCursorIgnore);
EXPECT_EQ(kWindowAwayFromEdge - kShelfSize,
DoGetCursorDistanceFromShelf(AppListPositioner::SCREEN_EDGE_RIGHT));
// Shelf on top.
PlaceShelf(AppListPositioner::SCREEN_EDGE_TOP);
PlaceCursor(kCursorIgnore, kMenuBarSize + kWindowAwayFromEdge);
EXPECT_EQ(kWindowAwayFromEdge - kShelfSize,
DoGetCursorDistanceFromShelf(AppListPositioner::SCREEN_EDGE_TOP));
// Shelf on bottom.
PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
PlaceCursor(kCursorIgnore, kScreenHeight - kWindowAwayFromEdge);
EXPECT_EQ(
kWindowAwayFromEdge - kShelfSize,
DoGetCursorDistanceFromShelf(AppListPositioner::SCREEN_EDGE_BOTTOM));
// Shelf on bottom. Cursor inside shelf; expect 0.
PlaceShelf(AppListPositioner::SCREEN_EDGE_BOTTOM);
PlaceCursor(kCursorIgnore, kScreenHeight - kCursorOnShelf);
EXPECT_EQ(
0, DoGetCursorDistanceFromShelf(AppListPositioner::SCREEN_EDGE_BOTTOM));
}
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
9a9a3cbf5c6b2354cea52d9628e2f8b5e2d0b679 | 49bae5d7b641d32dd09c207253b3269db8dcf2b3 | /libs/level4/vulkan/renderencoder.cpp | 2056df1a727c51e220847bdb5f81526e8ca365be | [] | no_license | DeanoC/old_wyrd | 744702f2157894dce4eca6dfdb1895bd3c7b1cb6 | 97cb85b5d756adbef4c899e72c4e121f049e6ec3 | refs/heads/master | 2020-07-26T20:12:26.167716 | 2019-01-08T13:44:00 | 2019-01-08T13:44:00 | 208,752,240 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,159 | cpp | #include "core/core.h"
#include "render/bindingtable.h"
#include "render/buffer.h"
#include "render/commandqueue.h"
#include "render/pipeline.h"
#include "render/viewport.h"
#include "vulkan/bindingtable.h"
#include "vulkan/buffer.h"
#include "vulkan/texture.h"
#include "vulkan/semaphore.h"
#include "vulkan/renderencoder.h"
#include "vulkan/renderpass.h"
#include "vulkan/rendertarget.h"
#include "vulkan/pipeline.h"
#include "types.h"
namespace Vulkan {
auto RenderEncoder::clearTexture(Render::TextureConstPtr const& texture_,
std::array<float_t, 4> const& floats_) -> void
{
Texture* texture = texture_->getStage<Texture>(Texture::s_stage);
if(texture->entireRange.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT)
{
VkClearColorValue colour;
std::memcpy(&colour.float32, floats_.data(), floats_.size() * sizeof(float));
vkCmdClearColorImage(texture->image, texture->imageLayout, &colour, 1, &texture->entireRange);
} else
{
VkClearDepthStencilValue ds;
ds.depth = floats_[0];
ds.stencil = (uint32_t) floats_[1]; // this only works upto 23 integer bits but stencil cap at 8 so..
vkCmdClearDepthStencilImage(texture->image, texture->imageLayout, &ds, 1, &texture->entireRange);
}
}
auto RenderEncoder::blit(Render::TextureConstPtr const& src_,
Render::TextureConstPtr const& dst_) -> void
{
auto src = src_->getStage<Texture>(Texture::s_stage);
auto dst = src_->getStage<Texture>(Texture::s_stage);
VkImageBlit blitter = {
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
{{0, 0, 0}, {(int32_t) src_->width, (int32_t) src_->height, 1}},
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
{{0, 0, 0}, {(int32_t) dst_->width, (int32_t) dst_->height, 1}},
};
vkCmdBlitImage(src->image,
src->imageLayout,
dst->image,
dst->imageLayout,
1,
&blitter,
VK_FILTER_LINEAR);
}
auto RenderEncoder::beginRenderPass(
Render::RenderPassConstPtr const& renderPass_,
Render::RenderTargetConstPtr const& renderTarget_
) -> void
{
auto vulkanRenderPass = renderPass_->getStage<RenderPass>(Vulkan::RenderPass::s_stage);
auto vulkanRenderTarget = renderTarget_->getStage<RenderTarget>(Vulkan::RenderTarget::s_stage);
VkRenderPassBeginInfo beginInfo{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
beginInfo.renderPass = vulkanRenderPass->renderpass;
// TODO pick correct clear type based on target format
std::vector<VkClearValue> clearValues(renderPass_->numTargets);
for(auto i = 0u; i < renderPass_->numTargets; ++i)
{
auto const& target = renderPass_->getTargets()[i];
auto const& clearVal = renderPass_->getClearValues()[i];
auto& clearValue = clearValues[i];
if(!Render::GtfCracker::isDepthStencil(target.format))
{
clearValue.color.float32[0] = clearVal.x;
clearValue.color.float32[1] = clearVal.y;
clearValue.color.float32[2] = clearVal.z;
clearValue.color.float32[3] = clearVal.w;
} else
{
clearValue.depthStencil.depth = clearVal.x;
clearValue.depthStencil.stencil = (uint8_t)(clearVal.y * 255.0f);
}
}
beginInfo.clearValueCount = (uint32_t)clearValues.size();
beginInfo.pClearValues = clearValues.data();
beginInfo.framebuffer = vulkanRenderTarget->framebuffer;
beginInfo.renderArea.offset = {renderTarget_->renderOffset[0], renderTarget_->renderOffset[1]};
beginInfo.renderArea.extent = {renderTarget_->renderExtent[0], renderTarget_->renderExtent[1]};
vkCmdBeginRenderPass(&beginInfo, VK_SUBPASS_CONTENTS_INLINE);
/*
VkClearAttachment clearAttachment;
clearAttachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
clearAttachment.clearValue = {1.0, 1.0f, 0.0f,1.0f};
clearAttachment.colorAttachment = 0;
VkClearRect clearRect;
clearRect.baseArrayLayer = 0;
clearRect.layerCount = 1;
clearRect.rect = {0,0,640,160};
vkCmdClearAttachments(1, &clearAttachment, 1, &clearRect );
*/
}
auto RenderEncoder::endRenderPass() -> void
{
vkCmdEndRenderPass();
}
auto RenderEncoder::resolveForDisplay(
Render::TextureConstPtr const& src_,
uint32_t width_, uint32_t height_,
VkImage display_) -> void
{
auto src = src_->getStage<Texture>(Texture::s_stage);
std::array<VkImageMemoryBarrier, 2> barriers;
VkImageMemoryBarrier& sbarrier = barriers[0];
VkImageMemoryBarrier& pbarrier = barriers[1];
sbarrier = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
pbarrier = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
sbarrier.oldLayout = src->imageLayout;
sbarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
src->imageLayout = sbarrier.newLayout;
sbarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
sbarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
sbarrier.image = src->image;
sbarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
sbarrier.subresourceRange.baseMipLevel = 0;
sbarrier.subresourceRange.baseArrayLayer = 0;
sbarrier.subresourceRange.levelCount = 1;
sbarrier.subresourceRange.layerCount = 1;
sbarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
sbarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
pbarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
pbarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
pbarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
pbarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
pbarrier.image = display_;
pbarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
pbarrier.subresourceRange.baseMipLevel = 0;
pbarrier.subresourceRange.baseArrayLayer = 0;
pbarrier.subresourceRange.levelCount = 1;
pbarrier.subresourceRange.layerCount = 1;
pbarrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
pbarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
vkCmdPipelineBarrier(
VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
0,
0, nullptr,
0, nullptr,
2, barriers.data());
if(src_->samples == 1)
{
VkImageBlit blitter = {
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
{{0, 0, 0}, {(int32_t) src_->width, (int32_t) src_->height, 1}},
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
{{0, 0, 0}, {(int32_t) width_, (int32_t) height_, 1}},
};
vkCmdBlitImage(src->image,
src->imageLayout,
display_,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1, &blitter, VK_FILTER_LINEAR);
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = display_;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.layerCount = 1;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
vkCmdPipelineBarrier(
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
0,
0, nullptr,
0, nullptr,
1, &barrier);
} else
{
// TODO MSAA resolve
assert(false);
}
}
auto RenderEncoder::bind(Render::RenderPipelineConstPtr const& pipeline_, Render::BindingTableConstPtr const& bindingTable_) -> void
{
auto pipeline = pipeline_->getStage<RenderPipeline>(RenderPipeline::s_stage);
auto bindingTable = bindingTable_->getStage<BindingTable>(BindingTable::s_stage);
bind(pipeline_);
vkCmdBindDescriptorSets(
VK_PIPELINE_BIND_POINT_GRAPHICS,
pipeline->layout,
0,
(uint32_t)bindingTable->descriptorSets.size(),
bindingTable->descriptorSets.data(),
0,
nullptr);
}
auto RenderEncoder::bind(Render::RenderPipelineConstPtr const& pipeline_) -> void
{
auto pipeline = pipeline_->getStage<RenderPipeline>(RenderPipeline::s_stage);
vkCmdBindPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline->pipeline);
}
auto RenderEncoder::bindVertexBuffer(Render::BufferConstPtr const& buffer_, uint64_t offset_,
uint32_t bindingIndex) -> void
{
assert(buffer_->canBeReadByVertex());
auto buffer = buffer_->getStage<Buffer>(Buffer::s_stage);
vkCmdBindVertexBuffers(bindingIndex, 1, &buffer->buffer, &offset_);
}
auto RenderEncoder::bindIndexBuffer(Render::BufferConstPtr const& buffer_, uint8_t bitSize_, uint64_t offset_) -> void
{
assert(buffer_->canBeReadByIndex());
assert(bitSize_ == 16 || bitSize_ == 32);
auto buffer = buffer_->getStage<Buffer>(Buffer::s_stage);
vkCmdBindIndexBuffer(buffer->buffer, offset_, VkIndexType(bitSize_ / 32));
}
auto RenderEncoder::pushConstants(Render::RenderPipelineConstPtr const& pipeline_,
Render::PushConstantRange const& range_, void const* data_) -> void
{
auto pipeline = pipeline_->getStage<RenderPipeline>(RenderPipeline::s_stage);
vkCmdPushConstants(pipeline->layout, from(range_.shaderAccess), range_.offset, range_.sizeInBytes, data_);
}
auto RenderEncoder::draw(uint32_t vertexCount_, uint32_t vertexOffset_, uint32_t instanceCount_,
uint32_t instanceOffset_) -> void
{
vkCmdDraw(vertexCount_, instanceCount_, vertexOffset_, instanceOffset_);
}
auto RenderEncoder::drawIndexed(uint32_t indexCount_, uint32_t indexOffset_, uint32_t vertexOffset,
uint32_t instanceCount_, uint32_t instanceOffset_) -> void
{
vkCmdDrawIndexed(indexCount_, instanceCount_, indexOffset_, vertexOffset, instanceOffset_);
}
auto RenderEncoder::setDynamicViewport(uint32_t viewportIndex_, Render::ViewportDef const& viewport_) -> void
{
VkViewport vkviewport{};
vkviewport.x = viewport_.x;
vkviewport.y = viewport_.y;
vkviewport.width = viewport_.width;
vkviewport.height = viewport_.height;
vkviewport.minDepth = viewport_.minDepth;
vkviewport.maxDepth = viewport_.maxDepth;
vkCmdSetViewport(viewportIndex_, 1, &vkviewport);
}
auto RenderEncoder::setDynamicScissor(uint32_t viewportIndex_, Render::Scissor const& scissor_) -> void
{
VkRect2D scissor{};
scissor.offset.x = scissor_.offset[0];
scissor.offset.y = scissor_.offset[1];
scissor.extent.width = scissor_.extent[0];
scissor.extent.height = scissor_.extent[1];
vkCmdSetScissor(viewportIndex_, 1, &scissor);
}
} | [
"me@deanoc.com"
] | me@deanoc.com |
0caa4c133e1141572718a174179fb49aa870c3d9 | f5bec63dd3dd888ebc55eeadfebf0ff39f50f486 | /framework/utilities.cpp | 595c1c632bc0fd4ddeb4ccf4747a2cedc938d212 | [] | no_license | jaenster/Charon | 0db2281b9def6547268ab767cd06e99f56cda510 | 43a8c9b08882416ebf8389bf31af7bc822a16b47 | refs/heads/master | 2023-09-04T12:10:23.269039 | 2021-01-03T13:56:41 | 2021-01-03T13:56:41 | 273,071,832 | 0 | 0 | null | 2020-06-29T08:12:23 | 2020-06-17T20:27:43 | C++ | UTF-8 | C++ | false | false | 8,537 | cpp | #define _USE_MATH_DEFINES
#include "../headers/D2Structs.h"
#include "../headers/common.h"
#include "../headers/feature.h"
#include "../headers/utilities.h"
#include "../headers/remote.h"
#include <iostream>
#include <cmath>
#include <unordered_map>
#include <random>
REMOTEFUNC(void __stdcall, D2Drawline, (int X1, int Y1, int X2, int Y2, DWORD dwColor, DWORD dwAlpha), 0x4F6380)
REMOTEFUNC(void __stdcall, D2DrawRectangle, (int X1, int Y1, int X2, int Y2, DWORD dwColor, DWORD dwAlpha), 0x4F6340)
REMOTEFUNC(long __fastcall, GetMouseXOffset, (), 0x45AFC0)
REMOTEFUNC(long __fastcall, GetMouseYOffset, (), 0x45AFB0)
REMOTEREF(POINT, AutomapOffset, 0x7A5198)
REMOTEREF(int, Divisor, 0x711254)
namespace D2 {
int ScreenWidth = 0, ScreenHeight = 0;
namespace Defs {
typedef POINT p_t;
}
}
DPOINT xvector = { 16.0, 8.0 }, yvector = { -16.0, 8.0 };
std::random_device rd; // obtain a random number from hardware
std::mt19937 gen(rd()); // seed the generator
int randIntInRange(int low, int high) {
std::uniform_int_distribution<> distr(low, high);
return distr(gen);
}
double randDoubleInRange(double low, double high) {
std::uniform_real_distribution<> distr(low, high);
return distr(gen);
}
DPOINT::DPOINT(double x, double y) {
this->x = x;
this->y = y;
}
void DrawRectangle(POINT a, POINT b, DWORD dwColor) {
if (
a.x >= 0 && a.x < D2::ScreenWidth ||
b.x >= 0 && b.x < D2::ScreenWidth ||
a.y >= 0 && a.y < D2::ScreenHeight ||
b.y >= 0 && b.y < D2::ScreenHeight
) {
D2DrawRectangle(a.x, a.y, b.x, b.y, dwColor, 0xFF);
}
}
void DrawLine(POINT a, POINT b, DWORD dwColor) {
if (
a.x >= 0 && a.x < D2::ScreenWidth ||
b.x >= 0 && b.x < D2::ScreenWidth ||
a.y >= 0 && a.y < D2::ScreenHeight ||
b.y >= 0 && b.y < D2::ScreenHeight
) {
D2Drawline(a.x, a.y, b.x, b.y, dwColor, 0xFF);
}
}
void DrawDot(POINT pos, DWORD dwColor) {
DrawLine({ pos.x - 1, pos.y }, { pos.x + 1, pos.y }, dwColor);
DrawLine({ pos.x, pos.y - 1 }, { pos.x, pos.y + 1 }, dwColor);
}
DPOINT DPOINT::operator +(const DPOINT& p) {
return { x + p.x, y + p.y };
}
DPOINT DPOINT::operator -(const DPOINT& p) {
return { x - p.x, y - p.y };
}
DPOINT DPOINT::operator /(const double d) {
return { x / d, y / d };
}
double DPOINT::distanceTo(DPOINT target) {
DPOINT v = target - *this;
return sqrt(v.x * v.x + v.y + v.y);
}
POINT DPOINT::toScreen(POINT screenadjust) {
return {
screenadjust.x + (long)(x * xvector.x + y * yvector.x) - GetMouseXOffset(),
screenadjust.y + (long)(x * xvector.y + y * yvector.y) - GetMouseYOffset()
};
}
POINT DPOINT::toAutomap(POINT screenadjust) {
return {
screenadjust.x + (long)((x * xvector.x + y * yvector.x) / (double)Divisor) - AutomapOffset.x + 8,
screenadjust.y + (long)((x * xvector.y + y * yvector.y) / (double)Divisor) - AutomapOffset.y - 8
};
}
void DPOINT::DrawAutomapX(DWORD dwColor, double size) {
DrawLine(DPOINT(x - size, y).toAutomap(), DPOINT(x + size, y).toAutomap(), dwColor);
DrawLine(DPOINT(x, y - size).toAutomap(), DPOINT(x, y + size).toAutomap(), dwColor);
}
void DPOINT::DrawWorldX(DWORD dwColor, double size) {
DrawLine(DPOINT(x - size, y).toScreen(), DPOINT(x + size, y).toScreen(), dwColor);
DrawLine(DPOINT(x, y - size).toScreen(), DPOINT(x, y + size).toScreen(), dwColor);
}
void DPOINT::DrawAutomapDot(DWORD dwColor) {
DrawLine(this->toAutomap({ -1, 0 }), this->toAutomap({ 1, 0 }), dwColor);
DrawLine(this->toAutomap({ 0, -1 }), this->toAutomap({ 0, 1 }), dwColor);
}
void DPOINT::DrawWorldDot(DWORD dwColor) {
DrawLine(this->toScreen({ -1, 0 }), this->toScreen({ 1, 0 }), dwColor);
DrawLine(this->toScreen({ 0, -1 }), this->toScreen({ 0, 1 }), dwColor);
}
namespace D2 {
namespace Types {
void UnitAny::DrawAutomapX(DWORD dwColor, double size) { return this->pos().DrawAutomapX(dwColor, size); }
void UnitAny::DrawWorldX(DWORD dwColor, double size) { return this->pos().DrawWorldX(dwColor, size); }
void UnitAny::DrawAutomapDot(DWORD dwColor) { return this->pos().DrawAutomapDot(dwColor); }
void UnitAny::DrawWorldDot(DWORD dwColor) { return this->pos().DrawWorldDot(dwColor); }
double UnitAny::distanceTo(UnitAny* pTarget) {
return this->pos().distanceTo(pTarget->pos());
}
std::vector<PresetUnit*> Room2::getAllPresetUnits() {
std::vector<PresetUnit*> ret;
for (D2::Types::PresetUnit* unit = this->pPreset; unit != NULL; unit = unit->pPresetNext) {
ret.push_back(unit);
}
return ret;
}
std::vector<Room1*> Level::getAllRoom1() {
std::vector<Room1*> ret;
for (D2::Types::Room2* room = this->pRoom2First; room != NULL; room = room->pRoom2Next) {
if (room->pRoom1) {
ret.push_back(room->pRoom1);
}
}
return ret;
}
std::vector<Room2*> Level::getAllRoom2() {
std::vector<Room2*> ret;
for (D2::Types::Room2* room = this->pRoom2First; room != NULL; room = room->pRoom2Next) {
ret.push_back(room);
}
return ret;
}
DPOINT PresetUnit::pos(Room2* pRoom, DPOINT adjust) {
return { adjust.x + (double)pRoom->dwPosX * 5 + (double)this->dwPosX, adjust.y + (double)pRoom->dwPosY * 5 + (double)this->dwPosY };
}
DPOINT UnitAny::pos(DPOINT adjust) {
if (this->dwType == 2 || this->dwType == 5) {
return { adjust.x + (double)this->pObjectPath->dwPosX, adjust.y + (double)this->pObjectPath->dwPosY };
}
if (this->dwType == 4) {
return { adjust.x + (double)this->pItemPath->dwPosX, adjust.y + (double)this->pItemPath->dwPosY };
}
return { adjust.x + (double)this->pPath->xPos + (double)this->pPath->xOffset / 65536.0, adjust.y + (double)this->pPath->yPos + (double)this->pPath->yOffset / 65536.0 };
}
DPOINT UnitAny::getTargetPos(DPOINT adjust) {
if (this->dwType == 2 || this->dwType == 4) {
return this->pos();
}
return { (double)this->pPath->xTarget, (double)this->pPath->yTarget };
}
Room1* LivingUnit::getRoom1() {
if (this->pPath && this->pPath->pRoom1) {
return this->pPath->pRoom1;
}
return nullptr;
}
Room2* LivingUnit::getRoom2() {
if (this->pPath && this->pPath->pRoom1 && this->pPath->pRoom1->pRoom2) {
return this->pPath->pRoom1->pRoom2;
}
return nullptr;
}
Level* LivingUnit::getLevel() {
if (this->pPath && this->pPath->pRoom1 && this->pPath->pRoom1->pRoom2 && this->pPath->pRoom1->pRoom2->pLevel) {
return this->pPath->pRoom1->pRoom2->pLevel;
}
return nullptr;
}
DWORD LivingUnit::unitHP() {
return D2::GetUnitStat(this, 6, 0) >> 8;
}
bool LivingUnit::isPlayerFriendly() {
return D2::GetUnitStat(this, 172, 0) == 2;
}
bool LivingUnit::isPlayerHostile() {
return D2::GetUnitStat(this, 172, 0) == 0;
}
bool LivingUnit::isAttackable() {
return this->dwFlags & 0x4;
}
bool LivingUnit::isPlayerEnemy() {
return this->unitHP() > 0 && this->isPlayerHostile() && this->isAttackable();
}
WORD CollMap::getCollision(DWORD localx, DWORD localy, WORD mask) {
return pMapStart[localx + localy * dwSizeGameX] & mask;
}
WORD Room1::getCollision(DWORD localx, DWORD localy, WORD mask) {
return Coll->pMapStart[localx + localy * Coll->dwSizeGameX] & mask;
}
WORD Room2::getCollision(DWORD localx, DWORD localy, WORD mask) {
return pRoom1->Coll->pMapStart[localx + localy * pRoom1->Coll->dwSizeGameX] & mask;
}
DWORD Room2::getWorldX() {
return pRoom1->dwXStart;
}
DWORD Room2::getWorldY() {
return pRoom1->dwYStart;
}
DWORD Room2::getWorldWidth() {
return pRoom1->dwXSize;
}
DWORD Room2::getWorldHeight() {
return pRoom1->dwYSize;
}
}
}
| [
"38635886+Nishimura-Katsuo@users.noreply.github.com"
] | 38635886+Nishimura-Katsuo@users.noreply.github.com |
ec3cf61efd5055ad8062107370184ef9a3e6e4d4 | ea380383f5c430dc49e9ea2fce588fd8917a8c00 | /Bag/bag.cpp | dba8fa1bc9a855bd81166bfd835cdf4d1c350ee8 | [] | no_license | fw2h/CPP_gyak | af1556459b56220ee836ec7915c29ddb4c3646ef | d6c425b9e050d1eaf082c0de09ed142c4d43334c | refs/heads/main | 2023-03-17T19:16:24.946315 | 2021-03-12T09:13:50 | 2021-03-12T09:13:50 | 347,004,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,645 | cpp | #include "bag.h"
#include <iostream>
using namespace std;
void Bag::clear()
{
_vec.clear();
_maxind = 0;
}
void Bag::putIn(int e)
{
size_t ind;
if (logSearch(e, ind))
{
++_vec[ind].count;
if (_vec[ind].count > _vec[_maxind].count)
_maxind = ind;
}
else
{
_vec.insert(_vec.begin() + ind, Item(e, 1));
if (_maxind >= ind && _vec.size() > 1)
++_maxind;
}
}
void Bag::takeOut(int e)
{
size_t ind;
if (logSearch(e, ind))
{
if (_vec[ind].count > 1)
--_vec[ind].count;
else _vec.erase(_vec.begin() + ind);
_maxind = _vec.size() > 0 ? maxSearch() : 0;
}
//else throw NOT_IN_BAG;
}
int Bag::mostFrequent() const
{
if (_vec.size() == 0)
throw EMPTY_BAG;
return _vec[_maxind].value;
}
size_t Bag::maxSearch() const
{
if (_vec.size() == 0)
throw EMPTY_BAG;
size_t max =_vec[0].count;
size_t ind = 0;
for (size_t i = 1; i < _vec.size(); ++i)
{
if (_vec[i].count > max)
{
max = _vec[i].count;
ind = i;
}
}
return ind;
}
bool Bag::logSearch(int e, size_t &index) const
{
bool l = false;
int ah = 0;
int fh = _vec.size() -1;
while(!l && ah <= fh)
{
index = (ah + fh) / 2;
if (_vec[index].value > e)
fh = index -1;
else if (_vec[index].value < e)
ah = index + 1;
else
l = true;
}
if(!l)
index = ah;
return l;
}
| [
"root@DESKTOP-BRGCR5H.localdomain"
] | root@DESKTOP-BRGCR5H.localdomain |
0b29ea025bc19b80a33d600959d0a6d6255344a4 | 1d6abe27a802d53f7fbd6eb5e59949044cbb3b98 | /tensorflow/lite/delegates/gpu/cl/kernels/max_unpooling.cc | 0bea5e4b6b79e559d4708923f12fac0b69b43937 | [
"Apache-2.0"
] | permissive | STSjeerasak/tensorflow | 6bc8bf27fb74fd51a71150f25dc1127129f70222 | b57499d4ec0c24adc3a840a8e7e82bd4ce0d09ed | refs/heads/master | 2022-12-20T20:32:15.855563 | 2020-09-29T21:22:35 | 2020-09-29T21:29:31 | 299,743,927 | 5 | 1 | Apache-2.0 | 2020-09-29T21:38:19 | 2020-09-29T21:38:18 | null | UTF-8 | C++ | false | false | 6,630 | cc | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/gpu/cl/kernels/max_unpooling.h"
#include <string>
#include "tensorflow/lite/delegates/gpu/cl/kernels/util.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/work_group_picking.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
std::string GetMaxUnpoolingKernelCode(const OperationDef& op_def,
GPUOperation* op) {
auto src_desc = op_def.src_tensors[0];
src_desc.SetTextureAddressMode(TextureAddressMode::ZERO);
if (op_def.IsBatchSupported()) {
src_desc.SetStateVar("BatchedWidth", "true");
}
op->AddSrcTensor("src_tensor", src_desc);
auto src_ind_desc = op_def.src_tensors[1];
src_ind_desc.SetTextureAddressMode(TextureAddressMode::ZERO);
if (op_def.IsBatchSupported()) {
src_ind_desc.SetStateVar("BatchedWidth", "true");
}
op->AddSrcTensor("src_indices", src_ind_desc);
auto dst_desc = op_def.dst_tensors[0];
if (op_def.IsBatchSupported()) {
dst_desc.SetStateVar("BatchedWidth", "true");
}
op->AddDstTensor("dst_tensor", dst_desc);
std::string c = GetCommonDefines(op_def.precision);
c += "__kernel void main_function(\n";
c += "$0) {\n";
c += " int X = get_global_id(0);\n";
if (op_def.dst_tensors[0].HasAxis(Axis::DEPTH)) {
c += " int linear_id_1 = get_global_id(1);\n";
c += " int Y = linear_id_1 / args.dst_tensor.Depth();\n";
c += " int Z = linear_id_1 % args.dst_tensor.Depth();\n";
c += " int src_z = (Z + args.padding_z) / args.stride_z;\n";
} else {
c += " int Y = get_global_id(1);\n";
}
c += " int S = get_global_id(2);\n";
c += " if (X >= args.dst_tensor.Width() || Y >= args.dst_tensor.Height() || "
"S >= args.dst_tensor.Slices()) { \n";
c += " return; \n";
c += " } \n";
if (op_def.dst_tensors[0].HasAxis(Axis::BATCH)) {
c += " int linear_id_0 = get_global_id(0);\n";
c += " int X0 = linear_id_0 / args.dst_tensor.Batch();\n";
c += " int B = linear_id_0 % args.dst_tensor.Batch();\n";
c += " int src_x0 = (X0 + args.padding_x * args.dst_tensor.Batch()) / "
"args.stride_x;\n";
c += " int src_x = src_x0 * args.dst_tensor.Batch() + B;\n";
} else {
c += " int src_x = (X + args.padding_x) / args.stride_x;\n";
}
c += " int src_y = (Y + args.padding_y) / args.stride_y;\n";
std::string src_args = op_def.dst_tensors[0].HasAxis(Axis::DEPTH)
? "src_x, src_y, src_z, S"
: "src_x, src_y, S";
if (op_def.src_tensors[0].storage_type == TensorStorageType::BUFFER) {
if (op_def.dst_tensors[0].HasAxis(Axis::DEPTH)) {
c += " bool outside = src_x < 0 || src_y < 0 || src_z < 0 || src_x >= "
"args.src_tensor.Width() || src_y >= args.src_tensor.Height() || "
"src_z >= args.src_tensor.Depth();\n";
} else {
c += " bool outside = src_x < 0 || src_y < 0 || src_x >= "
"args.src_tensor.Width() || src_y >= args.src_tensor.Height();\n";
}
c += " FLT4 src = (FLT4)(0.0f);\n";
c += " int4 ind = (int4)(0);\n";
c += " if (!outside) {\n";
c += " src = args.src_tensor.Read(" + src_args + ");\n";
c += " ind = convert_int4(args.src_indices.Read(" + src_args + "));\n";
c += " }\n";
} else {
c += " FLT4 src = args.src_tensor.Read(" + src_args + ");\n";
c +=
" int4 ind = convert_int4(args.src_indices.Read(" + src_args + "));\n";
}
if (op_def.dst_tensors[0].HasAxis(Axis::BATCH)) {
c += " int t_x = X0 - (src_x0 * args.stride_x - args.padding_x * "
"args.dst_tensor.Batch());\n";
} else {
c += " int t_x = X - (src_x * args.stride_x - args.padding_x);\n";
}
c += " int t_y = Y - (src_y * args.stride_y - args.padding_y);\n";
if (op_def.dst_tensors[0].HasAxis(Axis::DEPTH)) {
c += " int t_z = Z - (src_z * args.stride_z - args.padding_z);\n";
c += " int t_index = (t_y * args.kernel_size_x + t_x) * "
"args.kernel_size_z + t_z;\n";
} else {
c += " int t_index = t_y * args.kernel_size_x + t_x;\n";
}
c += " FLT4 result;\n";
const std::string channels[] = {".x", ".y", ".z", ".w"};
for (int i = 0; i < 4; ++i) {
const auto& s = channels[i];
c += " result" + s + "= t_index == ind" + s + "? src" + s + ": 0.0f;\n";
}
if (op_def.dst_tensors[0].HasAxis(Axis::DEPTH)) {
c += " args.dst_tensor.Write(result, X, Y, Z, S);\n";
} else {
c += " args.dst_tensor.Write(result, X, Y, S);\n";
}
c += "}\n";
return c;
}
} // namespace
GPUOperation CreateMaxUnpooling(const OperationDef& definition,
const MaxUnpooling2DAttributes& attr) {
GPUOperation op(definition);
op.args_.AddInt("kernel_size_x", attr.kernel.w);
op.args_.AddInt("padding_x", attr.padding.appended.w);
op.args_.AddInt("stride_x", attr.strides.w);
op.args_.AddInt("kernel_size_y", attr.kernel.h);
op.args_.AddInt("padding_y", attr.padding.appended.h);
op.args_.AddInt("stride_y", attr.strides.h);
op.code_ = GetMaxUnpoolingKernelCode(definition, &op);
op.tensor_to_grid_ = TensorToGrid::kWBToX_HDToY_SToZ;
return op;
}
GPUOperation CreateMaxUnpooling(const OperationDef& definition,
const MaxUnpooling3DAttributes& attr) {
GPUOperation op(definition);
op.args_.AddInt("kernel_size_x", attr.kernel.w);
op.args_.AddInt("padding_x", attr.padding.appended.w);
op.args_.AddInt("stride_x", attr.strides.w);
op.args_.AddInt("kernel_size_y", attr.kernel.h);
op.args_.AddInt("padding_y", attr.padding.appended.h);
op.args_.AddInt("stride_y", attr.strides.h);
op.args_.AddInt("kernel_size_z", attr.kernel.d);
op.args_.AddInt("padding_z", attr.padding.appended.d);
op.args_.AddInt("stride_z", attr.strides.d);
op.code_ = GetMaxUnpoolingKernelCode(definition, &op);
op.tensor_to_grid_ = TensorToGrid::kWBToX_HDToY_SToZ;
return op;
}
} // namespace cl
} // namespace gpu
} // namespace tflite
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
cc354522cdcdf5d4c780c9fc38f7e187c8cd923f | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir12766/dir12767/dir13029/dir15097/dir15260/dir18144/file18514.cpp | 4f4b50cae8d74d965aac7b4c4bacf9d56b9a9277 | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #ifndef file18514
#error "macro file18514 must be defined"
#endif
static const char* file18514String = "file18514"; | [
"tgeng@google.com"
] | tgeng@google.com |
199b412e3bc734ace2f1c99890e8487697e6c1c6 | 4eeb0e76853ce88ee63bca5dcb0ca62d843a86ac | /src/qt/utilitydialog.cpp | 69f6e971aab2200a6fcbfaa0b2f643cc2a9e22ba | [
"MIT"
] | permissive | Kalkicoin/Kalkicoin | e4fb06803d6ca21a04381db16bef074e07df8d6b | 6e03399f8954477f43da70401d7999c7d14778a3 | refs/heads/master | 2020-04-23T20:38:16.883027 | 2019-02-19T09:45:44 | 2019-02-19T09:45:44 | 169,476,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,010 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "utilitydialog.h"
#include "ui_helpmessagedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "intro.h"
#include "guiutil.h"
#include "clientversion.h"
#include "init.h"
#include "util.h"
#include <stdio.h>
#include <QCloseEvent>
#include <QLabel>
#include <QRegExp>
#include <QTextTable>
#include <QTextCursor>
#include <QVBoxLayout>
/** "Help message" or "About" dialog box */
HelpMessageDialog::HelpMessageDialog(QWidget* parent, bool about) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
ui(new Ui::HelpMessageDialog)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nHelpMessageDialogWindow", this->size(), this);
QString version = tr("Kalkicoin Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion());
/* On x86 add a bit specifier to the version so that users can distinguish between
* 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious.
*/
#if defined(__x86_64__)
version += " " + tr("(%1-bit)").arg(64);
#elif defined(__i386__)
version += " " + tr("(%1-bit)").arg(32);
#endif
if (about) {
setWindowTitle(tr("About Kalkicoin Core"));
/// HTML-format the license message from the core
QString licenseInfo = QString::fromStdString(LicenseInfo());
QString licenseInfoHTML = licenseInfo;
// Make URLs clickable
QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2);
uri.setMinimal(true); // use non-greedy matching
licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>");
// Replace newlines with HTML breaks
licenseInfoHTML.replace("\n\n", "<br><br>");
ui->aboutMessage->setTextFormat(Qt::RichText);
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
text = version + "\n" + licenseInfo;
ui->aboutMessage->setText(version + "<br><br>" + licenseInfoHTML);
ui->aboutMessage->setWordWrap(true);
ui->helpMessage->setVisible(false);
} else {
setWindowTitle(tr("Command-line options"));
QString header = tr("Usage:") + "\n" +
" kalkicoin-qt [" + tr("command-line options") + "] " + "\n";
QTextCursor cursor(ui->helpMessage->document());
cursor.insertText(version);
cursor.insertBlock();
cursor.insertText(header);
cursor.insertBlock();
std::string strUsage = HelpMessage(HMM_BITCOIN_QT);
strUsage += HelpMessageGroup(tr("UI Options:").toStdString());
strUsage += HelpMessageOpt("-choosedatadir", strprintf(tr("Choose data directory on startup (default: %u)").toStdString(), DEFAULT_CHOOSE_DATADIR));
strUsage += HelpMessageOpt("-lang=<lang>", tr("Set language, for example \"de_DE\" (default: system locale)").toStdString());
strUsage += HelpMessageOpt("-min", tr("Start minimized").toStdString());
strUsage += HelpMessageOpt("-rootcertificates=<file>", tr("Set SSL root certificates for payment request (default: -system-)").toStdString());
strUsage += HelpMessageOpt("-splash", strprintf(tr("Show splash screen on startup (default: %u)").toStdString(), DEFAULT_SPLASHSCREEN));
QString coreOptions = QString::fromStdString(strUsage);
text = version + "\n" + header + "\n" + coreOptions;
QTextTableFormat tf;
tf.setBorderStyle(QTextFrameFormat::BorderStyle_None);
tf.setCellPadding(2);
QVector<QTextLength> widths;
widths << QTextLength(QTextLength::PercentageLength, 35);
widths << QTextLength(QTextLength::PercentageLength, 65);
tf.setColumnWidthConstraints(widths);
QTextCharFormat bold;
bold.setFontWeight(QFont::Bold);
Q_FOREACH (const QString &line, coreOptions.split("\n")) {
if (line.startsWith(" -"))
{
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::PreviousCell);
cursor.movePosition(QTextCursor::NextRow);
cursor.insertText(line.trimmed());
cursor.movePosition(QTextCursor::NextCell);
} else if (line.startsWith(" ")) {
cursor.insertText(line.trimmed()+' ');
} else if (line.size() > 0) {
//Title of a group
if (cursor.currentTable())
cursor.currentTable()->appendRows(1);
cursor.movePosition(QTextCursor::Down);
cursor.insertText(line.trimmed(), bold);
cursor.insertTable(1, 2, tf);
}
}
ui->helpMessage->moveCursor(QTextCursor::Start);
ui->scrollArea->setVisible(false);
}
}
HelpMessageDialog::~HelpMessageDialog()
{
GUIUtil::saveWindowGeometry("nHelpMessageDialogWindow", this);
delete ui;
}
void HelpMessageDialog::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
fprintf(stdout, "%s\n", qPrintable(text));
}
void HelpMessageDialog::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
void HelpMessageDialog::on_okButton_accepted()
{
close();
}
/** "Shutdown" window */
ShutdownWindow::ShutdownWindow(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f)
{
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(new QLabel(
tr("Kalkicoin Core is shutting down...") + "<br /><br />" +
tr("Do not shut down the computer until this window disappears.")));
setLayout(layout);
}
void ShutdownWindow::showShutdownWindow(BitcoinGUI* window)
{
if (!window)
return;
// Show a simple window indicating shutdown status
QWidget* shutdownWindow = new ShutdownWindow();
// We don't hold a direct pointer to the shutdown window after creation, so use
// Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually.
shutdownWindow->setAttribute(Qt::WA_DeleteOnClose);
shutdownWindow->setWindowTitle(window->windowTitle());
// Center shutdown window at where main window was
const QPoint global = window->mapToGlobal(window->rect().center());
shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2);
shutdownWindow->show();
}
void ShutdownWindow::closeEvent(QCloseEvent* event)
{
event->ignore();
}
| [
"kalkicoin.com@gmail.com"
] | kalkicoin.com@gmail.com |
f7d0dd9cc9166d9f14d2760fda89b4c5af14cea5 | 40fd26d94ade05ef5da48f67a6b88894a4b2a572 | /core/tokenizer/TokenizerRulesFacade.cpp | 88b59962676397c58b4a0a856ba1bfed08d268e1 | [] | no_license | prograholic/compiler | 0276322784ebc289318a19c9c4e7e96a2b3a6bb6 | 6dc48fc7666adf7ed5da27785f38070932986154 | refs/heads/master | 2016-08-05T00:31:57.446105 | 2013-06-28T09:21:59 | 2013-06-28T09:21:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,204 | cpp | #include "core/tokenizer/TokenizerRulesFacade.h"
#include <algorithm>
#include <boost/smart_ptr/make_shared.hpp>
#include <boost/foreach.hpp>
#include "core/tokenizer/rules/AlphaNumTokenizerRule.h"
#include "core/tokenizer/rules/DoubleQuotedTextTokenizerRule.h"
#include "core/tokenizer/rules/OneSymbolTokenizerRule.h"
#include "core/tokenizer/rules/RelationOperatorTokenizerRule.h"
#include "core/tokenizer/rules/IncrementDecrementTokenizerRule.h"
#include "core/tokenizer/rules/AssignmentTokenizerRule.h"
#include "core/tokenizer/rules/PredefinedNameTokenizerRule.h"
#include "core/tokenizer/rules/IntegerConstantTokenizerRule.h"
namespace
{
struct TokenizerRuleComparator
{
bool operator()(TokenizerRulePtr left, TokenizerRulePtr right)
{
return left->priority() > right->priority();
}
};
}
TokenizerRulesFacade::TokenizerRulesFacade()
{
constructRules();
sortWithPriority();
}
TokenizerRuleList TokenizerRulesFacade::getTokenizerRules(int firstSymbol) const
{
/// @todo create previously prepared lists for given symbol
TokenizerRuleList result;
BOOST_FOREACH(const TokenizerRulePtr & tokenizerRule, mTokenizerRuleList)
{
if (tokenizerRule->firstSymbolFits(firstSymbol))
{
result.push_back(tokenizerRule);
}
}
return result;
}
void TokenizerRulesFacade::constructPredefinedSymbolTokenizers()
{
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Return, "return"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_If, "if"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Else, "else"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_While, "while"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Do, "do"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_For, "for"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Continue, "continue"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Break, "break"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Switch, "switch"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Case, "case"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Default, "default"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Goto, "goto"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Const, "const"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Volatile, "volatile"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Register, "register"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Restricted, "restricted"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Static, "static"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Inline, "inline"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Signed, "signed"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Unsigned, "unsigned"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Void, "void"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Char, "char"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Short, "short"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Int, "int"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Long, "long"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Float, "float"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Double, "double"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Struct, "struct"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Enum, "enum"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Union, "union"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Typedef, "typedef"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Extern, "extern"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Auto, "auto"));
mTokenizerRuleList.push_back(boost::make_shared<PredefinedNameTokenizerRule>(TK_Sizeof, "sizeof"));
}
void TokenizerRulesFacade::constructRules()
{
mTokenizerRuleList.push_back(boost::make_shared<AlphaNumTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<DoubleQuotedTextTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<SemicolonTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<StarTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<AssignmentTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<OpenParenTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<CloseParenTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<OpenBraceTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<CloseBraceTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<OpenBracketTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<CloseBracketTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<RelationOperatorTokenizerRule>());
mTokenizerRuleList.push_back(boost::make_shared<IncrementDecrementTokenizerRule>('+'));
mTokenizerRuleList.push_back(boost::make_shared<IncrementDecrementTokenizerRule>('-'));
mTokenizerRuleList.push_back(boost::make_shared<IntegerConstantTokenizerRule>());
constructPredefinedSymbolTokenizers();
}
void TokenizerRulesFacade::sortWithPriority()
{
std::sort(mTokenizerRuleList.begin(), mTokenizerRuleList.end(), TokenizerRuleComparator());
}
| [
"alexey.kutumov@gmail.com"
] | alexey.kutumov@gmail.com |
063cba0d7d68c62aee96c8dc02a1f2d213db3139 | 6996392046b4f6a55728a5a2142791d5876f497e | /saturation.h | 163938537e5c7b77e8247f2c11fe885e4621edf2 | [] | no_license | paszkowskiDamian/PhotoApp | 2395a2ab57bc14540814660d2b9d6e532f403685 | a7d7d9d91f94263a83a33152c572a9f654fc22f5 | refs/heads/filter | 2021-01-22T04:02:21.863942 | 2017-02-09T21:28:23 | 2017-02-09T21:28:23 | 81,496,158 | 0 | 0 | null | 2017-02-09T21:28:24 | 2017-02-09T21:22:19 | C++ | UTF-8 | C++ | false | false | 215 | h | #ifndef SATURATION_H
#define SATURATION_H
#include "Filter.h"
class Saturation : public Filter
{
public:
Saturation(QPixmap*);
virtual QImage pipe(QImage);
~Saturation();
private:
};
#endif // SATURATION_H
| [
"paszko.damian@gmail.com"
] | paszko.damian@gmail.com |
67ce6eb74496deb0536861d7c1109a3e6594bed3 | c057e033602e465adfa3d84d80331a3a21cef609 | /C/testcases/CWE127_Buffer_Underread/s03/CWE127_Buffer_Underread__new_wchar_t_cpy_17.cpp | fa81fc5428ba6ac6ba25e160e1f42100858277a7 | [] | no_license | Anzsley/My_Juliet_Test_Suite_v1.3_for_C_Cpp | 12c2796ae7e580d89e4e7b8274dddf920361c41c | f278f1464588ffb763b7d06e2650fda01702148f | refs/heads/main | 2023-04-11T08:29:22.597042 | 2021-04-09T11:53:16 | 2021-04-09T11:53:16 | 356,251,613 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,220 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE127_Buffer_Underread__new_wchar_t_cpy_17.cpp
Label Definition File: CWE127_Buffer_Underread__new.label.xml
Template File: sources-sink-17.tmpl.cpp
*/
/*
* @description
* CWE: 127 Buffer Under-read
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sink: cpy
* BadSink : Copy data to string using wcscpy
* Flow Variant: 17 Control flow: for loops
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE127_Buffer_Underread__new_wchar_t_cpy_17
{
#ifndef OMITBAD
void bad()
{
int i;
wchar_t * data;
data = NULL;
for(i = 0; i < 1; i++)
{
{
wchar_t * dataBuffer = new wchar_t[100];
wmemset(dataBuffer, L'A', 100-1);
dataBuffer[100-1] = L'\0';
/* FLAW: Set data pointer to before the allocated memory buffer */
data = dataBuffer - 8;
}
}
{
wchar_t dest[100*2];
wmemset(dest, L'C', 100*2-1); /* fill with 'C's */
dest[100*2-1] = L'\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
wcscpy(dest, data);
printWLine(dest);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by new [] so can't safely call delete [] on it */
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() - use goodsource in the for statement */
static void goodG2B()
{
int h;
wchar_t * data;
data = NULL;
for(h = 0; h < 1; h++)
{
{
wchar_t * dataBuffer = new wchar_t[100];
wmemset(dataBuffer, L'A', 100-1);
dataBuffer[100-1] = L'\0';
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
}
}
{
wchar_t dest[100*2];
wmemset(dest, L'C', 100*2-1); /* fill with 'C's */
dest[100*2-1] = L'\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
wcscpy(dest, data);
printWLine(dest);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by new [] so can't safely call delete [] on it */
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE127_Buffer_Underread__new_wchar_t_cpy_17; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"65642214+Anzsley@users.noreply.github.com"
] | 65642214+Anzsley@users.noreply.github.com |
80f2f3276acf16a80d144e0fa15d94d8a12f7a3c | 169e75df163bb311198562d286d37aad14677101 | /tensorflow/tensorflow/core/kernels/cwise_op_abs.cc | 1920c54e80759735686d8ac3e17feb4fb4310337 | [
"Apache-2.0"
] | permissive | zylo117/tensorflow-gpu-macosx | e553d17b769c67dfda0440df8ac1314405e4a10a | 181bc2b37aa8a3eeb11a942d8f330b04abc804b3 | refs/heads/master | 2022-10-19T21:35:18.148271 | 2020-10-15T02:33:20 | 2020-10-15T02:33:20 | 134,240,831 | 116 | 26 | Apache-2.0 | 2022-10-04T23:36:22 | 2018-05-21T08:29:12 | C++ | UTF-8 | C++ | false | false | 2,031 | cc | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/cwise_ops_common.h"
namespace tensorflow {
REGISTER5(UnaryOp, CPU, "Abs", functor::abs, float, Eigen::half, double, int32,
int64);
REGISTER2(UnaryOp, CPU, "ComplexAbs", functor::abs, complex64, complex128);
#if GOOGLE_CUDA
REGISTER4(UnaryOp, GPU, "Abs", functor::abs, float, Eigen::half, double, int64);
REGISTER2(UnaryOp, GPU, "ComplexAbs", functor::abs, complex64, complex128);
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("Abs")
.Device(DEVICE_GPU)
.HostMemory("x")
.HostMemory("y")
.TypeConstraint<int32>("T"),
UnaryOp<CPUDevice, functor::abs<int32>>);
#endif
#if TENSORFLOW_USE_SYCL
REGISTER3(UnaryOp, SYCL, "Abs", functor::abs, float, double, int64);
REGISTER_KERNEL_BUILDER(Name("Abs")
.Device(DEVICE_SYCL)
.HostMemory("x")
.HostMemory("y")
.TypeConstraint<int32>("T"),
UnaryOp<CPUDevice, functor::abs<int32>>);
#endif // TENSORFLOW_USE_SYCL
} // namespace tensorflow
| [
"thomas.warfel@pnnl.gov"
] | thomas.warfel@pnnl.gov |
609a992f5d680a9a4a17c182141a6c224e0b6386 | 741335a951c5e99c190d3e34d1590b7d4f03ebe4 | /eve/math/TVector2.h | 07e6d1cd09647132ed16023ad6bdd9181e62d0c2 | [
"BSD-3-Clause"
] | permissive | mrvux/Eve | 3221582287971579d9aba895184c1b87e69b0025 | 2106e1136425a0a8fe0e9befca0529bf2c5326f5 | refs/heads/master | 2021-01-22T13:41:39.619612 | 2014-11-10T10:39:52 | 2014-11-10T10:39:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,898 | h |
#if !defined(__EVE_MATH_TVECTOR_H__)
#error "Do not include this header directly, include eve/math/Tvector.h instead"
#endif
#pragma once
#ifndef __EVE_MATH_TVECTOR_2_H__
#define __EVE_MATH_TVECTOR_2_H__
#ifndef __EVE_CORE_INCLUDES_H__
#include "eve/core/Includes.h"
#endif
#ifndef __EVE_MATH_MATH_H__
#include "eve/math/Math.h"
#endif
namespace eve
{
namespace math
{
template<typename T> class TVec3;
/**
* \class eve::math::TVec2
*
* \brief Template 2 components vector.
*/
template<typename T>
class TVec2
{
//////////////////////////////////////
// DATA //
//////////////////////////////////////
public:
T x;
T y;
//////////////////////////////////////
// METHOD //
//////////////////////////////////////
public:
TVec2(void);
TVec2(T nx, T ny);
TVec2(T n);
TVec2(const TVec2<T>& src);
explicit TVec2(const T *d);
template<typename FromT>
TVec2(const TVec2<FromT>& src);
void set(T ax, T ay);
void set(const TVec2<T> &rhs);
// Operators
template<typename FromT>
TVec2<T>& operator=(const TVec2<FromT>& rhs);
TVec2<T> & operator=(const TVec2<T>& rhs);
T& operator[](int32_t n);
const T& operator[](int32_t n) const;
T * ptr(void) const;
const TVec2<T> operator + (const TVec2<T>& rhs) const;
const TVec2<T> operator - (const TVec2<T>& rhs) const;
const TVec2<T> operator * (const TVec2<T>& rhs) const;
const TVec2<T> operator / (const TVec2<T>& rhs) const;
TVec2<T> & operator += (const TVec2<T>& rhs);
TVec2<T> & operator -= (const TVec2<T>& rhs);
TVec2<T> & operator *= (const TVec2<T>& rhs);
TVec2<T> & operator /= (const TVec2<T>& rhs);
const TVec2<T> operator + (T rhs) const;
const TVec2<T> operator - (T rhs) const;
const TVec2<T> operator * (T rhs) const;
const TVec2<T> operator / (T rhs) const;
TVec2<T> & operator += (T rhs);
TVec2<T> & operator -= (T rhs);
TVec2<T> & operator *= (T rhs);
TVec2<T> & operator /= (T rhs);
TVec2<T> operator-() const;
bool operator==(const TVec2<T> &rhs) const;
bool operator!=(const TVec2<T> &rhs) const;
T dot(const TVec2<T> &rhs) const;
//! Returns the z component of the cross if the two operands were TVec3's on the XY plane, the equivalent of TVec3(*this).cross( TVec3(rhs) ).z
T cross(const TVec2<T> &rhs) const;
T distance(const TVec2<T> &rhs) const;
T distanceSquared(const TVec2<T> &rhs) const;
T length(void) const;
void normalize(void);
TVec2<T> normalized(void) const;
// tests for zero-length
void safeNormalize(void);
TVec2<T> safeNormalized(void) const;
void rotate(T radians);
T lengthSquared(void) const;
//! Limits the length of a TVec2 to \a maxLength, scaling it proportionally if necessary.
void limit(T maxLength);
//! Returns a copy of the TVec2 with its length limited to \a maxLength, scaling it proportionally if necessary.
TVec2<T> limited(T maxLength) const;
void invert(void);
TVec2<T> inverted(void) const;
TVec2<T> lerp(T fact, const TVec2<T>& r) const;
void lerpEq(T fact, const TVec2<T> &rhs);
bool equal(TVec2<T> const & other);
bool equal(TVec2<T> const & other, T epsilon);
static bool equal(TVec2<T> const & x, TVec2<T> const & y);
static bool equal(TVec2<T> const & x, TVec2<T> const & y, T epsilon);
// GLSL inspired swizzling functions.
TVec2<T> xx(void) const;
TVec2<T> xy(void) const;
TVec2<T> yx(void) const;
TVec2<T> yy(void) const;
TVec3<T> xxx(void) const;
TVec3<T> xxy(void) const;
TVec3<T> xyx(void) const;
TVec3<T> xyy(void) const;
TVec3<T> yxx(void) const;
TVec3<T> yxy(void) const;
TVec3<T> yyx(void) const;
TVec3<T> yyy(void) const;
static TVec2<T> max(void);
static TVec2<T> zero(void);
static TVec2<T> one(void);
static TVec2<T> xAxis(void);
static TVec2<T> yAxis(void);
static TVec2<T> xAxisNeg(void);
static TVec2<T> yAxisNeg(void);
static TVec2<T> NaN(void);
}; // class TVector2
} // namespace math
} // namespace eve
//=================================================================================================
template<typename T>
eve::math::TVec2<T>::TVec2(void)
: x(0)
, y(0)
{}
template<typename T>
eve::math::TVec2<T>::TVec2(T nx, T ny)
: x(nx)
, y(ny)
{}
template<typename T>
eve::math::TVec2<T>::TVec2(T n)
: x(n)
, y(n)
{}
template<typename T>
eve::math::TVec2<T>::TVec2(const eve::math::TVec2<T> & src)
: x(src.x)
, y(src.y)
{}
template<typename T>
eve::math::TVec2<T>::TVec2(const T *d)
: x(d[0])
, y(d[1])
{}
template<typename T>
template<typename FromT>
eve::math::TVec2<T>::TVec2(const eve::math::TVec2<FromT> & src)
: x(static_cast<T>(src.x))
, y(static_cast<T>(src.y))
{}
//=================================================================================================
template<typename T>
EVE_FORCE_INLINE void eve::math::TVec2<T>::set(T ax, T ay)
{
x = ax; y = ay;
}
template<typename T>
EVE_FORCE_INLINE void eve::math::TVec2<T>::set(const TVec2<T> & rhs)
{
x = rhs.x; y = rhs.y;
}
//=================================================================================================
template<typename T>
template<typename FromT>
EVE_FORCE_INLINE eve::math::TVec2<T> & eve::math::TVec2<T>::operator=(const eve::math::TVec2<FromT> & rhs)
{
x = static_cast<T>(rhs.x);
y = static_cast<T>(rhs.y);
return *this;
}
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> & eve::math::TVec2<T>::operator=(const eve::math::TVec2<T> & rhs)
{
x = rhs.x;
y = rhs.y;
return *this;
}
//=================================================================================================
template<typename T>
EVE_FORCE_INLINE T & eve::math::TVec2<T>::operator[](int32_t n)
{
EVE_ASSERT(n >= 0 && n <= 1);
return (&x)[n];
}
template<typename T>
EVE_FORCE_INLINE const T & eve::math::TVec2<T>::operator[](int32_t n) const
{
EVE_ASSERT(n >= 0 && n <= 1);
return (&x)[n];
}
template<typename T>
EVE_FORCE_INLINE T* eve::math::TVec2<T>::ptr(void) const
{
return &(const_cast<TVec2*>(this)->x);
}
//=================================================================================================
template<typename T>
EVE_FORCE_INLINE const eve::math::TVec2<T> eve::math::TVec2<T>::operator+(const eve::math::TVec2<T> & rhs) const { return eve::math::TVec2<T>(x + rhs.x, y + rhs.y); }
template<typename T>
EVE_FORCE_INLINE const eve::math::TVec2<T> eve::math::TVec2<T>::operator-(const eve::math::TVec2<T> & rhs) const { return eve::math::TVec2<T>(x - rhs.x, y - rhs.y); }
template<typename T>
EVE_FORCE_INLINE const eve::math::TVec2<T> eve::math::TVec2<T>::operator*(const eve::math::TVec2<T> & rhs) const { return eve::math::TVec2<T>(x * rhs.x, y * rhs.y); }
template<typename T>
EVE_FORCE_INLINE const eve::math::TVec2<T> eve::math::TVec2<T>::operator/(const eve::math::TVec2<T> & rhs) const { return eve::math::TVec2<T>(x / rhs.x, y / rhs.y); }
//=================================================================================================
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> & eve::math::TVec2<T>::operator+=(const eve::math::TVec2<T> & rhs) { x += rhs.x; y += rhs.y; return *this; }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> & eve::math::TVec2<T>::operator-=(const eve::math::TVec2<T> & rhs) { x -= rhs.x; y -= rhs.y; return *this; }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> & eve::math::TVec2<T>::operator*=(const eve::math::TVec2<T> & rhs) { x *= rhs.x; y *= rhs.y; return *this; }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> & eve::math::TVec2<T>::operator/=(const eve::math::TVec2<T> & rhs) { x /= rhs.x; y /= rhs.y; return *this; }
//=================================================================================================
template<typename T>
EVE_FORCE_INLINE const eve::math::TVec2<T> eve::math::TVec2<T>::operator+(T rhs) const { return eve::math::TVec2<T>(x + rhs, y + rhs); }
template<typename T>
EVE_FORCE_INLINE const eve::math::TVec2<T> eve::math::TVec2<T>::operator-(T rhs) const { return eve::math::TVec2<T>(x - rhs, y - rhs); }
template<typename T>
EVE_FORCE_INLINE const eve::math::TVec2<T> eve::math::TVec2<T>::operator*(T rhs) const { return eve::math::TVec2<T>(x * rhs, y * rhs); }
template<typename T>
EVE_FORCE_INLINE const eve::math::TVec2<T> eve::math::TVec2<T>::operator/(T rhs) const { return eve::math::TVec2<T>(x / rhs, y / rhs); }
//=================================================================================================
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T>& eve::math::TVec2<T>::operator+=(T rhs) { x += rhs; y += rhs; return *this; }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T>& eve::math::TVec2<T>::operator-=(T rhs) { x -= rhs; y -= rhs; return *this; }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T>& eve::math::TVec2<T>::operator*=(T rhs) { x *= rhs; y *= rhs; return *this; }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T>& eve::math::TVec2<T>::operator/=(T rhs) { x /= rhs; y /= rhs; return *this; }
//=================================================================================================
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> eve::math::TVec2<T>::operator-() const { return eve::math::TVec2<T>(-x, -y); }
//=================================================================================================
template<typename T>
EVE_FORCE_INLINE bool eve::math::TVec2<T>::operator==(const eve::math::TVec2<T> & rhs) const
{
return (x == rhs.x) && (y == rhs.y);
}
template<typename T>
EVE_FORCE_INLINE bool eve::math::TVec2<T>::operator!=(const eve::math::TVec2<T> & rhs) const
{
return !(*this == rhs);
}
//=================================================================================================
template<typename T>
EVE_FORCE_INLINE T eve::math::TVec2<T>::dot(const eve::math::TVec2<T> &rhs) const
{
return x * rhs.x + y * rhs.y;
}
template<typename T>
EVE_FORCE_INLINE T eve::math::TVec2<T>::cross(const eve::math::TVec2<T> &rhs) const
{
return x * rhs.y - y * rhs.x;
}
template<typename T>
EVE_FORCE_INLINE T eve::math::TVec2<T>::distance(const eve::math::TVec2<T> &rhs) const
{
return (*this - rhs).length();
}
template<typename T>
EVE_FORCE_INLINE T eve::math::TVec2<T>::distanceSquared(const eve::math::TVec2<T> &rhs) const
{
return (*this - rhs).lengthSquared();
}
template<typename T>
EVE_FORCE_INLINE T eve::math::TVec2<T>::length(void) const
{
return eve::math::sqrt(x*x + y*y);
}
template<typename T>
EVE_FORCE_INLINE void eve::math::TVec2<T>::normalize(void)
{
T invS = static_cast<T>(1) / length();
x *= invS;
y *= invS;
}
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> eve::math::TVec2<T>::normalized(void) const
{
T invS = static_cast<T>(1) / length();
return eve::math::TVec2<T>(x * invS, y * invS);
}
template<typename T>
EVE_FORCE_INLINE void eve::math::TVec2<T>::safeNormalize(void)
{
T s = lengthSquared();
if (s > 0) {
T invL = static_cast<T>(1) / eve::math::sqrt(s);
x *= invL;
y *= invL;
}
}
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> eve::math::TVec2<T>::safeNormalized(void) const
{
T s = lengthSquared();
if (s > 0) {
T invL = static_cast<T>(1) / eve::math::sqrt(s);
return eve::math::TVec2<T>(x * invL, y * invL);
}
else
return eve::math::TVec2<T>::zero();
}
template<typename T>
EVE_FORCE_INLINE void eve::math::TVec2<T>::rotate(T radians)
{
T cosa = eve::math::cos(radians);
T sina = eve::math::sin(radians);
T rx = x * cosa - y * sina;
y = x * sina + y * cosa;
x = rx;
}
template<typename T>
EVE_FORCE_INLINE T eve::math::TVec2<T>::lengthSquared(void) const
{
return x * x + y * y;
}
template<typename T>
EVE_FORCE_INLINE void eve::math::TVec2<T>::limit(T maxLength)
{
T lengthSquared = x * x + y * y;
if ((lengthSquared > maxLength * maxLength) && (lengthSquared > 0)) {
T ratio = maxLength / eve::math::sqrt(lengthSquared);
x *= ratio;
y *= ratio;
}
}
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> eve::math::TVec2<T>::limited(T maxLength) const
{
T lengthSquared = x * x + y * y;
if ((lengthSquared > maxLength * maxLength) && (lengthSquared > 0))
{
T ratio = maxLength / eve::math::sqrt(lengthSquared);
return eve::math::TVec2<T>(x * ratio, y * ratio);
}
else
return *this;
}
template<typename T>
EVE_FORCE_INLINE void eve::math::TVec2<T>::invert(void)
{
x = -x;
y = -y;
}
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> eve::math::TVec2<T>::inverted(void) const
{
return eve::math::TVec2<T>(-x, -y);
}
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> eve::math::TVec2<T>::lerp(T fact, const eve::math::TVec2<T>& r) const
{
return (*this) + (r - (*this)) * fact;
}
template<typename T>
EVE_FORCE_INLINE void eve::math::TVec2<T>::lerpEq(T fact, const eve::math::TVec2<T> &rhs)
{
x = x + (rhs.x - x) * fact; y = y + (rhs.y - y) * fact;
}
template<typename T>
EVE_FORCE_INLINE static bool eve::math::TVec2<T>::equal(eve::math::TVec2<T> const & x, eve::math::TVec2<T> const & y)
{
return (eve::math::equal(x.x, y.x) && eve::math::equal(x.y, y.y));
}
template<typename T>
EVE_FORCE_INLINE static bool eve::math::TVec2<T>::equal(eve::math::TVec2<T> const & x, eve::math::TVec2<T> const & y, T epsilon)
{
return (eve::math::equal(x.x, y.x, epsilon) && eve::math::equal(x.y, y.y, epsilon));
}
template<typename T>
EVE_FORCE_INLINE bool eve::math::TVec2<T>::equal(eve::math::TVec2<T> const & other)
{
return (eve::math::equal(x, other.x) && eve::math::equal(y, other.y));
}
template<typename T>
EVE_FORCE_INLINE bool eve::math::TVec2<T>::equal(eve::math::TVec2<T> const & other, T epsilon)
{
return (eve::math::equal(x, other.x, epsilon) && eve::math::equal(y, other.y, epsilon));
}
//=================================================================================================
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> eve::math::TVec2<T>::xx(void) const { return eve::math::TVec2<T>(x, x); }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> eve::math::TVec2<T>::xy(void) const { return eve::math::TVec2<T>(x, y); }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> eve::math::TVec2<T>::yx(void) const { return eve::math::TVec2<T>(y, x); }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec2<T> eve::math::TVec2<T>::yy(void) const { return eve::math::TVec2<T>(y, y); }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec3<T> eve::math::TVec2<T>::xxx(void) const { return eve::math::TVec3<T>(x, x, x); }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec3<T> eve::math::TVec2<T>::xxy(void) const { return eve::math::TVec3<T>(x, x, y); }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec3<T> eve::math::TVec2<T>::xyx(void) const { return eve::math::TVec3<T>(x, y, x); }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec3<T> eve::math::TVec2<T>::xyy(void) const { return eve::math::TVec3<T>(x, y, y); }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec3<T> eve::math::TVec2<T>::yxx(void) const { return eve::math::TVec3<T>(y, x, x); }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec3<T> eve::math::TVec2<T>::yxy(void) const { return eve::math::TVec3<T>(y, x, y); }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec3<T> eve::math::TVec2<T>::yyx(void) const { return eve::math::TVec3<T>(y, y, x); }
template<typename T>
EVE_FORCE_INLINE eve::math::TVec3<T> eve::math::TVec2<T>::yyy(void) const { return eve::math::TVec3<T>(y, y, y); }
//=================================================================================================
template<typename T>
EVE_FORCE_INLINE static eve::math::TVec2<T> eve::math::TVec2<T>::max(void)
{
return eve::math::TVec2<T>(std::numeric_limits<T>::max(), std::numeric_limits<T>::max());
}
template<typename T>
EVE_FORCE_INLINE static eve::math::TVec2<T> eve::math::TVec2<T>::zero(void)
{
return eve::math::TVec2<T>(0, 0);
}
template<typename T>
EVE_FORCE_INLINE static eve::math::TVec2<T> eve::math::TVec2<T>::one(void)
{
return eve::math::TVec2<T>(1, 1);
}
template<typename T>
EVE_FORCE_INLINE static eve::math::TVec2<T> eve::math::TVec2<T>::xAxis(void) { return eve::math::TVec2<T>(1, 0); }
template<typename T>
EVE_FORCE_INLINE static eve::math::TVec2<T> eve::math::TVec2<T>::yAxis(void) { return eve::math::TVec2<T>(0, 1); }
template<typename T>
EVE_FORCE_INLINE static eve::math::TVec2<T> eve::math::TVec2<T>::xAxisNeg(void) { return eve::math::TVec2<T>(-1, 0); }
template<typename T>
EVE_FORCE_INLINE static eve::math::TVec2<T> eve::math::TVec2<T>::yAxisNeg(void) { return eve::math::TVec2<T>(0, -1); }
template<typename T>
EVE_FORCE_INLINE static eve::math::TVec2<T> eve::math::TVec2<T>::NaN(void) { return eve::math::TVec2<T>(eve::math::NaN(), eve::math::NaN()); }
#endif // __EVE_MATH_TVECTOR_2_H__
| [
"romain@ftopia.com"
] | romain@ftopia.com |
729a09d0df836dfd5cd276e567143207d4977845 | 321b8ca726aae37e2e5dba76eb489ce23ffde511 | /GraphicsEngine/GraphicsEngine/Mesh.hpp | cf34ca4cefb88f94e2b01fd6083beda87d6b415d | [] | no_license | AshishGogna/TrueEngine | a51d1efabe27003b6feccb34ff9cbf8a6d9c7483 | b1b8349ee4266d890fcad6148e4c8ec39716516c | refs/heads/master | 2021-09-13T07:31:39.298839 | 2018-04-26T13:53:49 | 2018-04-26T13:53:49 | 115,484,851 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | hpp | //
// Mesh.hpp
// GraphicsEngine
//
// Created by Ashish Gogna on 03/02/18.
// Copyright © 2018 Ashish Gogna. All rights reserved.
//
#ifndef Mesh_hpp
#define Mesh_hpp
#include <stdio.h>
#include <GL/glew.h>
#include <iostream>
#include "Vertex.hpp"
#include <vector>
#include "Transform.hpp"
using namespace std;
class Mesh
{
private:
int id;
GLuint vbo;
GLuint ibo;
void Init();
void AddVertices(vector<Vertex> vertices, vector<int> indices);
public:
int size;
Transform transform;
Mesh();
Mesh(int id, vector<Vertex> vertices, vector<int> indices);
void Draw();
};
#endif /* Mesh_hpp */
| [
"ashishgogna9@gmail.com"
] | ashishgogna9@gmail.com |
df2238f5b0f7c5d1a33693411505e84e07a451d5 | ce690903b0cad896ea15642460c1d14c8ec4250e | /good/Filmora-Screen-Windows/inc/Externlib/MultiMediaSDK/Interface/C++/COM/DecMgr.h | 02e91d61624d1d4158c039ab729ab3d93c4aad78 | [] | no_license | LuckyKingSSS/demo | a572e280979a019246e6d51cb7c6bfa947829a5c | db4f55389d4ed2d3ada29083116654e2107e333e | refs/heads/master | 2021-07-05T22:09:17.065287 | 2017-09-28T05:51:51 | 2017-09-28T05:51:51 | 105,107,036 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 19,246 | h | /*! \file DecMgr.h
* \brief 解码器接口调用说明
* Detailed
*应用层可以通过调用DecMgr模块获取IDecMgr的接口,通过该接口的GetMediaInfo方法获取媒体信息接口IMediaInfo,
*该接口提供了获取媒体信息的方法。为了获取ID3或媒体的其它信息,那么可以调用IMediaInfo接口中的QueryInerface方法,查询是否支持该接口。
*为了获取音视频流接口IMediaStream,使用IDecMgr接口的CreateMediaDecoder方法,创建媒体解码器IMediaDecoder接口,
*通过QueryInterface方法查询IVideoOutput, IAudioOutput接口,它们提供了获取音视频解码器接口IMediaStream的方法GetVideoOutput, GetAudioOutput。
*IMediaDecoder接口提供了动态切换流的方法ChangeStream。如果是外挂字幕,通过IMediaStream接口的QueryInterface方法,
*获取外挂字幕解码设置接口ISubPicSetting,通过该接口获取各种设置的方法。
*/
#pragma once
#include <scombase.h>
#include "COMMacro.h"
#include "TextDef.h"
#include "DecodeParam.h"
#include "CodecDefine.h"
#include "CommonInterface.h"
/*!
* \class ISubPicStreamInfo
* \brief 获取字幕的信息接口
*/
// {FB73C029-B0BD-4cbb-A0CE-971E64D4BDD4}
DEFINE_GUID(IID_ISubPicStreamInfo,
0xfb73c029, 0xb0bd, 0x4cbb, 0xa0, 0xce, 0x97, 0x1e, 0x64, 0xd4, 0xbd, 0xd4);
EXTERN_C const IID IID_ISubPicStreamInfo;
MACRO_MIDL_INTERFACE(ISubPicStreamInfo, "FB73C029-B0BD-4cbb-A0CE-971E64D4BDD4")
: public IUnknown
{
public:
/*! \fn virtual STDMETHODIMP_(SUPPIC_TYPE) GetType(void)
* \brief 获取字幕的类型, 外挂还是内嵌
* \retval 字幕的类型
*/
virtual STDMETHODIMP_(SUPPIC_TYPE) GetType(void) = 0;
/*! \fn virtual STDMETHODIMP_(UINT) GetID(void)
* \brief 获取字幕的ID
* \retval 字幕的ID
*/
virtual STDMETHODIMP_(UINT) GetID(void) = 0;
/*! \fn virtual STDMETHODIMP_(UINT) GetFourCC(void)
* \brief 获取字幕的FourCC
* \retval 字幕的FourCC
*/
virtual STDMETHODIMP_(UINT) GetFourCC(void) = 0;
/*! \fn virtual STDMETHODIMP GetLanguage(BSTR * ppLanguage)
* \brief 获取字幕的语言
* \param ppLanguage [int/out] 字幕的语言
* \retval HRESULT 获取结果
*\ \warning 输出的ppLanguage,必须使用SysFreeString释放,否则会造成内存泄露
*/
virtual STDMETHODIMP GetLanguage(BSTR * ppLanguage) = 0;
/*! \fn virtual STDMETHODIMP GetDescription(BSTR * ppDescription)
* \brief 获取字幕的描述
* \param ppDescription [int/out] 字幕的描述
* \retval HRESULT 获取结果
* \warning 输出的ppDescription,必须使用SysFreeString释放,否则会造成内存泄露
*/
virtual STDMETHODIMP GetDescription(BSTR * ppDescription) = 0;
};
/*!
* \class ISubPicStreamInfos
* \brief 字幕信息枚举接口
*/
// {4291F08A-95C4-45c3-AF5B-1CC55A3F2CF7}
DEFINE_GUID(IID_ISubPicStreamInfos,
0x4291f08a, 0x95c4, 0x45c3, 0xaf, 0x5b, 0x1c, 0xc5, 0x5a, 0x3f, 0x2c, 0xf7);
EXTERN_C const IID IID_ISubPicStreamInfos;
MACRO_MIDL_INTERFACE(ISubPicStreamInfos, "4291F08A-95C4-45c3-AF5B-1CC55A3F2CF7")
: public IUnknown
{
public:
/*! \fn virtual STDMETHODIMP_(int) GetCount(void)
* \brief 获取字幕的数量
* \retval 字幕的数量
*/
virtual STDMETHODIMP_(int) GetCount(void) = 0;
/*! \fn virtual STDMETHODIMP GetItem(int nIndex, ISubPicStreamInfo** ppItem)
* \brief 获取指定的字幕信息接口
* \param nIndex [in] 字幕的索引号
* \param ppItem [out] 字幕信息接口
* \retval 获取的结果
* \see ISubPicStreamInfo
* \warning ppItem使用完毕后,一定要调用Release方法释放,避免内存泄露。
*/
virtual STDMETHODIMP GetItem(int nIndex, ISubPicStreamInfo** ppItem) = 0;
};
/*!
* \class IStreamInfos
* \brief 流信息枚举接口
*/
// {5DD650C8-40A3-4d0d-B460-0BA5804A1AAD}
DEFINE_GUID(IID_IStreamInfos,
0x5dd650c8, 0x40a3, 0x4d0d, 0xb4, 0x60, 0xb, 0xa5, 0x80, 0x4a, 0x1a, 0xad);
EXTERN_C const IID IID_IStreamInfos;
MACRO_MIDL_INTERFACE(IStreamInfos, "5DD650C8-40A3-4d0d-B460-0BA5804A1AAD")
: public IUnknown
{
public:
/*! \fn virtual STDMETHODIMP_(int) GetCount(void)
* \brief 获取流的数量
* \retval 流的数量
*/
virtual STDMETHODIMP_(int) GetCount(void) = 0;
/*! \fn virtual STDMETHODIMP GetItem(int nIndex, IStreamInfo** ppItem)
* \brief 获取指定的流信息接口
* \param nIndex [in] 流的索引号
* \param ppItem [out] 流信息接口
* \retval 获取的结果
* \see IStreamInfo
* \warning ppItem使用完毕后,一定要调用Release方法释放,避免内存泄露。
*/
virtual STDMETHODIMP GetItem(int nIndex, IStreamInfo** ppItem) = 0;
};
/*!
* \class IProgramInfo
* \brief 节目信息接口,用于获取媒体文件中的节目信息
*/
// {F5FA588B-55AF-4fa9-8913-323CFF39C231}
DEFINE_GUID(IID_IProgramInfo,
0xf5fa588b, 0x55af, 0x4fa9, 0x89, 0x13, 0x32, 0x3c, 0xff, 0x39, 0xc2, 0x31);
EXTERN_C const IID IID_IProgramInfo;
MACRO_MIDL_INTERFACE(IProgramInfo, "F5FA588B-55AF-4fa9-8913-323CFF39C231")
: public IUnknown
{
public:
/*! \fn virtual STDMETHODIMP_(UINT) GetNumber(void)
* \brief 获取节目在Number,暂无实际意义
* \retval 节目的Number
*/
virtual STDMETHODIMP_(UINT) GetNumber(void) = 0;
/*! \fn virtual STDMETHODIMP_(UINT) GetID(void)
* \brief 获取节目的ID,ID是节目的唯一标示
* \retval 节目的ID
*/
virtual STDMETHODIMP_(UINT) GetID(void) = 0;
/*! \fn virtual STDMETHODIMP_(double) GetMediaLength(void)
* \brief 获取节目的时间长度,单位是秒
* \retval 节目的时长
* \note 取节目中各路流,时长的最大值
*/
virtual STDMETHODIMP_(double) GetMediaLength(void) = 0;
/*! \fn virtual STDMETHODIMP_(int) GetBitrate()
* \brief 获取节目的码率
* \retval 节目的码率
* \note 取各路流码率之和
*/
virtual STDMETHODIMP_(int) GetBitrate() = 0;
/*! \fn virtual STDMETHODIMP_(UINT) GetTimeStampReferenceStreamID(void)
* \brief 获取节目时间戳参考流ID,
* \retval 时间戳参考流ID
*/
virtual STDMETHODIMP_(UINT) GetTimeStampReferenceStreamID(void) = 0;
/*! \fn virtual STDMETHODIMP GetVideoStreamInfos(IStreamInfos** ppVideoStreamInfos)
* \brief 获取视频流信息枚举器接口,
* \param ppVideoStreamInfos [out] 视频流枚举器接口
* \retval 获取结果
* \see IStreamInfos
*/
virtual STDMETHODIMP GetVideoStreamInfos(IStreamInfos** ppVideoStreamInfos) = 0;
/*! \fn virtual STDMETHODIMP GetAudioStreamInfos(IStreamInfos** ppAudioStreamInfos)
* \brief 获取音频流信息枚举器接口,
* \param ppAudioStreamInfos [out] 音频流信息枚举器接口
* \retval 获取结果
* \see IStreamInfos
*/
virtual STDMETHODIMP GetAudioStreamInfos(IStreamInfos** ppAudioStreamInfos) = 0;
/*! \fn virtual STDMETHODIMP GetSubPicStreamInfos(ISubPicStreamInfos** ppSubPicStreamInfos)
* \brief 获取字幕流信息枚举器接口,
* \param ppSubPicStreamInfos [out] 字幕流信息枚举器接口
* \retval 获取结果
* \see ISubPicStreamInfos
*/
virtual STDMETHODIMP GetSubPicStreamInfos(ISubPicStreamInfos** ppSubPicStreamInfos) = 0;
};
/*!
* \class IProgramInfos
* \brief 节目信息枚举器接口
*/
// {E04C85FD-D887-4716-8D7A-D18A17CE60EC}
DEFINE_GUID(IID_IProgramInfos,
0xe04c85fd, 0xd887, 0x4716, 0x8d, 0x7a, 0xd1, 0x8a, 0x17, 0xce, 0x60, 0xec);
EXTERN_C const IID IID_IProgramInfos;
MACRO_MIDL_INTERFACE(IProgramInfos, "E04C85FD-D887-4716-8D7A-D18A17CE60EC")
: public IUnknown
{
public:
/*! \fn virtual STDMETHODIMP_(int) GetCount(void)
* \brief 获取节目的数量
* \retval 节目的数量
*/
virtual STDMETHODIMP_(int) GetCount() = 0;
/*! \fn virtual STDMETHODIMP GetItem(int nIndex, IProgramInfo** ppItem)
* \brief 获取指定的节目信息接口
* \param nIndex [in] 节目的索引号
* \param ppItem [out] 节目信息接口
* \retval 获取的结果
* \see IProgramInfo
*/
virtual STDMETHODIMP GetItem(int nIndex, IProgramInfo** ppItem) = 0;
};
/*!
* \class IMetaDataInfo
* \brief 获取MetaData信息接口
*/
// {80DEF872-887D-4426-B31B-771011CF3427}
DEFINE_GUID(IID_IMetaDataInfo,
0x80def872, 0x887d, 0x4426, 0xb3, 0x1b, 0x77, 0x10, 0x11, 0xcf, 0x34, 0x27);
EXTERN_C const IID IID_IMetaDataInfo;
MACRO_MIDL_INTERFACE(IMetaDataInfo, "80DEF872-887D-4426-B31B-771011CF3427")
: public IUnknown
{
public:
/*! \fn virtual STDMETHODIMP GetArtist(BSTR *pArtist)
* \brief 获取艺术家信息
* \param pArtist [out] 艺术家信息
* \retval 获取的结果
*/
virtual STDMETHODIMP GetArtist(BSTR *pArtist) = 0;
/*! \fn virtual STDMETHODIMP GetTitle(BSTR *pTitle)
* \brief 获取标题信息
* \param pTitle [out] 标题信息
* \retval 获取的结果
*/
virtual STDMETHODIMP GetTitle(BSTR *pTitle) = 0;
/*! \fn virtual STDMETHODIMP GetTrackNumber(BSTR *pTrackNumber)
* \brief 获取音轨号
* \param pTrackNumber [out] 音轨号
* \retval 获取的结果
*/
virtual STDMETHODIMP GetTrackNumber(BSTR *pTrackNumber) = 0;
/*! \fn virtual STDMETHODIMP GetAlbum(BSTR *pAlbum)
* \brief 获取专辑名称
* \param pAlbum [out] 专辑名称
* \retval 获取的结果
*/
virtual STDMETHODIMP GetAlbum(BSTR *pAlbum) = 0;
/*! \fn virtual STDMETHODIMP GetDate(BSTR *pDate)
* \brief 获取年代
* \param pDate [out] 年代
* \retval 获取的结果
*/
virtual STDMETHODIMP GetDate(BSTR *pDate) = 0;
/*! \fn virtual STDMETHODIMP GetGenre(BSTR *pGenre)
* \brief 获取风格
* \param pGenre [out] 风格
* \retval 获取的结果
*/
virtual STDMETHODIMP GetGenre(BSTR *pGenre) = 0;
/*! \fn virtual STDMETHODIMP GetPublisher(BSTR *pPublisher)
* \brief 获取发行商
* \param pPublisher [out] 发行商
* \retval 获取的结果
*/
virtual STDMETHODIMP GetPublisher(BSTR *pPublisher) = 0;
};
/*!
* \class IMediaInfo
* \brief 获取媒体文件信息接口
*/
// {10CA4A98-A525-42a5-9282-DD64406261B2}
DEFINE_GUID(IID_IMediaInfo,
0x10ca4a98, 0xa525, 0x42a5, 0x92, 0x82, 0xdd, 0x64, 0x40, 0x62, 0x61, 0xb2);
EXTERN_C const IID IID_IMediaInfo;
MACRO_MIDL_INTERFACE(IMediaInfo, "10CA4A98-A525-42a5-9282-DD64406261B2")
: public IUnknown
{
public:
/*! \fn virtual STDMETHODIMP_(UINT) GetFourCC()
* \brief 获取文件FourCC
* \retval 文件FourCC
*/
virtual STDMETHODIMP_(UINT) GetFourCC() = 0;
/*! \fn virtual STDMETHODIMP GetFileName(BSTR * pFileName)
* \brief 获取文件名
* \param pFileName [out] 文件名
* \retval 获取的结果
*/
virtual STDMETHODIMP GetFileName(BSTR * pFileName) = 0;
/*! \fn virtual STDMETHODIMP GetDescription(BSTR * ppDescription)
* \brief 获取文件的描述信息
* \param ppDescription [out] 文件的描述信息
* \retval 获取的结果
*/
virtual STDMETHODIMP GetDescription(BSTR * ppDescription) = 0;
/*! \fn virtual STDMETHODIMP_(double) GetMediaLength(void)
* \brief 获取媒体文件的播放时长
* \retval 媒体文件的播放时长
* \note 媒体文件播放时长,取媒体文件中包含的各路节目,时长的最大值
*/
virtual STDMETHODIMP_(double) GetMediaLength(void) = 0;
/*! \fn virtual STDMETHODIMP_(int) GetBitrate(void)
* \brief 获取媒体文件的码率
* \retval 媒体文件的码率
* \note 媒体文件的码率,取各路节目码率之和
*/
virtual STDMETHODIMP_(int) GetBitrate(void) = 0;
/*! \fn virtual STDMETHODIMP GetIPrograms(IProgramInfos **ppProgramInfos)
* \brief 获取节目信息枚举器接口
* \retval 获取结果
* \see IProgramInfos
*/
virtual STDMETHODIMP GetIPrograms(IProgramInfos **ppProgramInfos) = 0;
/*! \fn virtual STDMETHODIMP GetIPrograms(IProgramInfos **ppProgramInfos)
* \brief 获取隔行逐行扫描信息
* \retval 获取结果
* \see IProgramInfos
*/
virtual STDMETHODIMP_(AV_SCAN_TYPE) GetScanType() = 0;
};
// {89D89E0A-02F1-47a1-8756-323A9098937E}
DEFINE_GUID(IID_ISubPicSetting,
0x89d89e0a, 0x2f1, 0x47a1, 0x87, 0x56, 0x32, 0x3a, 0x90, 0x98, 0x93, 0x7e);
EXTERN_C const IID IID_ISubPicSetting;
/*!
* \class ISubPicSetting
* \brief 字幕显示设置接口
*/
MACRO_MIDL_INTERFACE(ISubPicSetting, "89D89E0A-02F1-47a1-8756-323A9098937E")
: public IUnknown
{
public:
/*! \brief 设置字幕显示图像的大小
* \param nWidth [in] 字幕的宽
* \param nHeight [in] 字幕的高
* \retval 设置结果
*/
virtual STDMETHODIMP SetRect(int nWidth, int nHeight) = 0;
/*! \brief 获取字幕图像的大小
* \param pWidth [out] 字幕的宽
* \param pHeight [out] 字幕的高
* \retval 获取结果
*/
virtual STDMETHODIMP GetRect(int * pWidth, int * pHeight) = 0;
/*! \brief 设置字幕显示效果,是否使用缺省模式
* \param bUse [int] 1表示使用,0表示不使用
* \retval 设置结果
*/
virtual STDMETHODIMP SetUseDefaultStyle(int bUse) = 0;
/*! \brief 获取当前字幕显示效果,是否采用缺省模式
* \retval 1表示采用,0表示未采用
*/
virtual STDMETHODIMP_(int) GetUseDefaultStyle(void) = 0;
/*! \brief 设置字幕显示的字体
* \param fontName [int] 字体名称
* \retval 设置结果
*/
virtual STDMETHODIMP SetFontName(const BSTR fontName) = 0;
/*! \brief 获取当前字幕显示的字体
* \param pFontName [out] 字体名称
* \retval 获取结果
*/
virtual STDMETHODIMP GetFontName(BSTR * pFontName) = 0;
/*! \brief 设置字幕显示的字号
* \param nFontSize [int] 字号
* \retval 设置结果
*/
virtual STDMETHODIMP SetFontSize(int nFontSize) = 0;
/*! \brief 获取当前字幕显示的字号
* \retval 字号
*/
virtual STDMETHODIMP_(int) GetFontSize(void) = 0;
/*! \brief 设置当前字幕显示的字体样式
* \param nStyle [in] 字体样式,取值范围PCSFontStyleRegular | PCSFontStyleBold | PCSFontStyleItalic | PCSFontStyleUnderline
* \retval 设置结果
*/
virtual STDMETHODIMP SetStyle(UINT nStyle) = 0;
/*! \brief 获取当前字幕显示的字体样式
* \retval 字体样式
*/
virtual STDMETHODIMP_(UINT) GetStyle(void) = 0;
/*! \brief 设置当前字幕显示的字体颜色
* \param fontColor [in] 字体颜色
* \retval 设置结果
*/
virtual STDMETHODIMP SetFontColor(COLORREF fontColor) = 0;
/*! \brief 获取当前字幕显示的字体颜色
* \retval 字体颜色
*/
virtual STDMETHODIMP_(COLORREF) GetFontColor(void) = 0;
/*! \brief 设置字幕显示的字体是否使用阴影
* \param bUse [in] 1表示使用,0表示不使用
* \retval 设置结果
*/
virtual STDMETHODIMP SetUseShadow(int bUse) = 0;
/*! \brief 获取字幕显示的字体是否使用阴影
* \retval 1表示使用,0表示未使用
*/
virtual STDMETHODIMP_(int) GetUseShadow(void) = 0;
/*! \brief 设置文字阴影的参数
* \param paramShadow [in] 文字阴影的参数
* \retval 设置结果
* \note 只有当设置使用文字阴影后,才有效
*/
virtual STDMETHODIMP_(int) SetParamShadow(SHADOWPARAM paramShadow) = 0;
/*! \brief 获取当前字幕显示的文字阴影参数
* \retval 文字阴影的参数
* \see SHADOWPARAM
*/
virtual STDMETHODIMP_(SHADOWPARAM) GetParamShadow(void) = 0;
/*! \brief 设置光晕效果
* \param nValue [in] 光晕值,0为无光晕效果
* \param dwColor [int] 光晕颜色值
* \retval 设置结果
*/
virtual STDMETHODIMP SetHalation(int nValue, COLORREF dwColor) = 0;
/*! \brief 获取当前设置的光晕效果
* \param pValue [out] 光晕值
* \param pColor [out] 光晕颜色值
* \retval 获取结果
*/
virtual STDMETHODIMP GetHalation(int *pValue, COLORREF * pColor) = 0;
/*! \brief 设置旋转角度
* \param nAngle [in] 旋转角度
* \retval 设置结果
*/
virtual STDMETHODIMP SetAngle(int nAngle) = 0;
/*! \brief 获取旋转角度
* \retval 旋转角度
*/
virtual STDMETHODIMP_(int) GetAngle(void) = 0;
/*! \brief 设置字幕图片视频图片上的位置
* \param nXCoordinate [in] 字幕图片左上角在视频图片上的X坐标
* \param nYCoordinate [in] 字幕图片左上角在视频图片上的Y坐标
* \retval 设置结果
*/
virtual STDMETHODIMP SetLeftTopPos(int nXCoordinate, int nYCoordinate) = 0;
/*! \brief 获取当前字幕图片视频图片上的位置
* \param pXCoordinate [out] 字幕图片左上角在视频图片上的X坐标
* \param pYCoordinate [out] 字幕图片左上角在视频图片上的Y坐标
* \retval 获取结果
*/
virtual STDMETHODIMP GetLeftTopPos(int * pXCoordinate, int * pYCoordinate) = 0;
};
/*!
* \class IMediaDecoder
* \brief 媒体解码器接口,通过QueryInterface方法查询IVideoOutput, IAudioOutput接口,它们提供了获取音视频流(IMediaStream)的输出方法
* \see IVideoOutput IAudioOutput 接口
*/
// {C8BD5D61-172A-4ca2-98B7-DE5F1E995D72}
DEFINE_GUID(IID_IMediaDecoder,
0xc8bd5d61, 0x172a, 0x4ca2, 0x98, 0xb7, 0xde, 0x5f, 0x1e, 0x99, 0x5d, 0x72);
EXTERN_C const IID IID_IMediaDecoder;
MACRO_MIDL_INTERFACE(IMediaDecoder, "C8BD5D61-172A-4ca2-98B7-DE5F1E995D72")
: public IUnknown
{
public:
};
/*!
* \class IDecMgr
* \brief 解码管理器接口,通过它可以获取解码器接口IMediaDecoder,以及文件信息接口IMediaInfo
* \see IMediaDecoder IMediaInfo
*/
// {5AD2BE35-3038-4c6a-8C7F-3698526A898F}
DEFINE_GUID(IID_IDecMgr,
0x5ad2be35, 0x3038, 0x4c6a, 0x8c, 0x7f, 0x36, 0x98, 0x52, 0x6a, 0x89, 0x8f);
EXTERN_C const IID IID_IDecMgr;
MACRO_MIDL_INTERFACE(IDecMgr, "5AD2BE35-3038-4c6a-8C7F-3698526A898F")
: public IUnknown
{
public:
/*! \fn virtual STDMETHODIMP_(IMediaDecoder *) CreateMediaDecoder(const BSTR pMediaPath, FILE_TYPE fileType, const DecParam * pVideoDecParam, const DecParam * pAudioDecParam, DEC_MODEL DecMod)
* \brief 根据媒体文件路径及其解码参数,创建解码器接口IMediaDecoder
* \param pMediaPath [int] 媒体文件路径
* \param fileType [int] 媒体文件类型 分为音视频文件,与外挂字幕
* \param pVideoDecParam [in] 视频解码参数
* \param pAudioDecParam [in] 音频解码参数
* \param DecMod [in] 解码方式选择
* \retval 解码器接口 IMediaDecoder
* \see FILE_TYPE DecParam DEC_MODEL IMediaDecoder
*/
virtual STDMETHODIMP_(IMediaDecoder *) CreateMediaDecoder(const BSTR pMediaPath, FILE_TYPE fileType, const DecParam * pVideoDecParam, const DecParam * pAudioDecParam, DEC_MODEL DecMod) = 0;
/*! \fn virtual STDMETHODIMP GetMediaInfo(const BSTR pMediaPath, FILE_TYPE fileType, DEC_MODEL DecMod, IMediaInfo** ppIMediaInfo)
* \brief 根据媒体文件路径及参数,获取媒体文件信息接口IMediaInfo
* \param pMediaPath [int] 媒体文件路径
* \param fileType [int] 媒体文件类型 分为音视频文件,与外挂字幕
* \param DecMod [in] 解码方式选择
* \param ppIMediaInfo 媒体信息接口
* \retval 获取结果
* \see FILE_TYPE DEC_MODEL IMediaInfo
*/
virtual STDMETHODIMP GetMediaInfo(const BSTR pMediaPath, FILE_TYPE fileType, DEC_MODEL DecMod, IMediaInfo** ppIMediaInfo) = 0;
virtual STDMETHODIMP_(IMediaDecoder *) CreateMediaDecoder(const BSTR pMediaPath, FILE_TYPE fileType, const DecParam * pVideoDecParam, const DecParam * pAudioDecParam, DEC_MODEL DecMod,IMediaInfo* pIMediaInfo) = 0;
};
// {E71EAD89-1CCD-4c34-97A8-7D45B5F16613}
//定义组件对象DecMgr
MIDL_DEFINE_GUID(CLSID, CLSID_CDecMgr, 0xe71ead89, 0x1ccd, 0x4c34, 0x97, 0xa8, 0x7d, 0x45, 0xb5, 0xf1, 0x66, 0x13);
EXTERN_C const CLSID CLSID_CDecMgr;
| [
"wangbiao@wondershare.cn"
] | wangbiao@wondershare.cn |
7b8233dae4a84d1f6ef6978b11161532ea341e02 | 057382cd5ed939152c4a937c2cdc5aaa74e66523 | /console/generator.cpp | 85f30705bf739341e7b51a7fbb9a70858bd8e603 | [] | no_license | Veala/GrShell | 41b56e779d26bdeec8e86af0bd545e28610ed329 | d3e9df481eee31195e9e09ee3339bdc62ce047ad | refs/heads/master | 2021-09-04T12:36:39.282668 | 2018-01-18T16:34:25 | 2018-01-18T16:34:25 | 109,154,467 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,468 | cpp | #include "generator.h"
generator::generator()
{
//genData["-gVOLT"] = "5.0E-01";
//genData["-gFREQ"] = "160.0E+06";
if (signal::sigData["-sType"] == "LFM")
sig = new signal_LFM(gFreq);
if (signal::sigData["-sType"] == "SIN")
sig = new signal_SIN(gFreq);
if (signal::sigData["-sType"] == "IMP")
sig = new signal_IMP(gFreq);
// if (signal::sigData["-sType"] == "")
// sig = new signal_IMP(gFreq);
sig->isChangeSigP = &stateGen.isChangeSigP;
//sig->gF = &gFreq;
commands.push_back("getAllP");
commands.push_back("setP");
commands.push_back("delP");
commands.push_back("signal");
commands.push_back("start");
commands.push_back("commands");
commands.push_back("exit");
}
void generator::execShell()
{
string command;
cout << "generator:";
while(getline(cin,command)) {
if (command == "") {
//cout << "=>";
} else if ((std::find(commands.begin(), commands.end(), command) == commands.end())) {
cout << command << " is not command" << endl;
} else if (command == "commands") {
for (std::list<string>::iterator it = commands.begin(); it!=commands.end(); ++it)
cout << *it << endl;
} else if (command == "exit") {
//code
break;
} else if (command == "getAllP") {
for (std::map<string,string>::iterator it=genData.begin(); it!=genData.end(); ++it)
cout << "key: " << it->first << "; value: " << it->second << endl;
} else if (command == "setP") {
cout << "key:";
string key, value; getline(cin,key);
std::map<string,string>::iterator it = genData.find(key);
cout << "value:"; getline(cin,value);
genData[key] = value;
if (it == genData.end()) cout << "New 'key-value' added" << endl;
stateGen.isChangeGenP = 1;
} else if (command == "delP") {
cout << "key:";
string key; getline(cin,key);
std::map<string,string>::iterator it = genData.find(key);
if (it == genData.end()) { cout << "Key not find" << endl; }
else { genData.erase(it); cout << "Key was delete" << endl; stateGen.isChangeGenP = 1; }
} else if (command == "signal") {
sig->execShell();
} else if (command == "start") {
start();
}
cout << "generator:";
}
}
void generator::start()
{
if(stateGen.isOpenSes)
if (openSession()) return; else { stateGen.isOpenSes=0; stateGen.isCloseSes=1; }
ViChar buffer[5000];
error = viPrintf(vi, "*CLS\n");
do {
Sleep(50);
error = viPrintf(vi, "*OPC?\n");
error = viScanf(vi, "%t", buffer);
} while(strcmp(buffer,"1\n") != 0);
// Query the instrument identity
error = viPrintf(vi, "*IDN?\n");
error = viScanf(vi, "%t", buffer);
cout << "*IDN? -> " << buffer << endl;
if(stateGen.isChangeSigP || stateGen.isChangeGenP) {
#ifdef debug
cout << "start() -> generator state: isChangeSigP || isChangeGenP" << endl;
#endif
error = viPrintf(vi, ":ABORt\n");
do {
Sleep(50);
error = viPrintf(vi, "*OPC?\n");
error = viScanf(vi, "%t", buffer);
} while(strcmp(buffer,"1\n") != 0);
stateGen.isAborted = 1;
}
// if(stateGen.isChangeSigP) {
// //cout << "Reset instrument and setup waveform ... " << endl << endl;
// error = viPrintf(vi, "*RST\n");
// }
if(stateGen.isChangeGenP) {
#ifdef debug
cout << "start() -> generator state: isChangeGenP: -gVolt: " << genData.find("-gVolt")->second.c_str() << endl;
#endif
//error = viPrintf(vi, ":FREQuency:RASTer %s\n", gFreq.c_str());
error = viPrintf(vi, ":DAC:VOLTage %s\n", genData.find("-gVolt")->second.c_str());
do {
Sleep(50);
error = viPrintf(vi, "*OPC?\n");
error = viScanf(vi, "%t", buffer);
} while(strcmp(buffer,"1\n") != 0);
error = viPrintf(vi, ":DAC:VOLTage:OFFSet 0\n");
do {
Sleep(50);
error = viPrintf(vi, "*OPC?\n");
error = viScanf(vi, "%t", buffer);
} while(strcmp(buffer,"1\n") != 0);
error = viPrintf(vi, ":OUTPut1:ROUTe DAC\n");
do {
Sleep(50);
error = viPrintf(vi, "*OPC?\n");
error = viScanf(vi, "%t", buffer);
} while(strcmp(buffer,"1\n") != 0);
stateGen.isChangeGenP = 0;
}
if(stateGen.isChangeSigP) {
#ifdef debug
cout << "start() -> generator state: isChangeSigP" << endl;
#endif
//Common multiple of 48 and 64;
//long long sampleCount=0;
// Init sampleCount;
vector<ViByte> buffer1;
try {
sig->Calculate();
}
catch (string *error) {
cout << error->c_str();
delete error;
return;
}
catch (...) {
cout << "critical error\n";
return;
}
#ifdef debug
cout << "start() -> gFreq.c_str(): " << gFreq.c_str() << endl;
#endif
error = viPrintf(vi, ":FREQuency:RASTer %s\n", gFreq.c_str());
do {
Sleep(50);
error = viPrintf(vi, "*OPC?\n");
error = viScanf(vi, "%t", buffer);
} while(strcmp(buffer,"1\n") != 0);
error = viPrintf(vi, ":TRACe1:DELete:ALL\n");
do {
Sleep(50);
error = viPrintf(vi, "*OPC?\n");
error = viScanf(vi, "%t", buffer);
} while(strcmp(buffer,"1\n") != 0);
#ifdef debug
cout << "start() -> sampleCount: " << (long int)sig->sampleCount << endl;
#endif
error = viPrintf(vi, ":TRACe1:DEFine 1,%ld\n", (long int)sig->sampleCount);
do {
Sleep(50);
error = viPrintf(vi, "*OPC?\n");
error = viScanf(vi, "%t", buffer);
} while(strcmp(buffer,"1\n") != 0);
////////////////////////////////////////////////////
for (sig->n=1; sig->n <= sig->count; sig->n++) {
buffer1.clear();
sig->GenerateWaveformCommands(buffer1);
ViUInt32 writtenCount;
ViUInt32 NToWrite = (ViUInt32)buffer1.size();
error = viWrite(vi, &buffer1[0], (ViUInt32)buffer1.size(), &writtenCount);
while (writtenCount != NToWrite) {
cout << "writen: " << writtenCount << endl;
cout << "error: " << error << endl;
Sleep(50);
}
do {
Sleep(50);
error = viPrintf(vi, "*OPC?\n");
error = viScanf(vi, "%t", buffer);
} while(strcmp(buffer,"1\n") != 0);
error = viFlush(vi, VI_WRITE_BUF);
do {
Sleep(50);
error = viPrintf(vi, "*OPC?\n");
error = viScanf(vi, "%t", buffer);
} while(strcmp(buffer,"1\n") != 0);
}
// Switch on outputs
error = viPrintf(vi, ":OUTPut1 on\n");
// Select segments
error = viPrintf(vi, ":TRACe1:SELect 1\n");
stateGen.isChangeSigP = 0;
}
if (stateGen.isAborted) {
#ifdef debug
cout << "start() -> generator state: isAborted" << endl;
#endif
error = viPrintf(vi, ":INITiate:IMMediate\n");
// Wait until all commands have been executed
do {
Sleep(50);
error = viPrintf(vi, "*OPC?\n");
error = viScanf(vi, "%t", buffer);
} while(strcmp(buffer,"1\n") != 0);
// Capture errors from instrument
cout << "Check for errors ... " << endl;
do
{
error = viPrintf(vi, ":SYSTem:ERRor?\n");
error = viScanf(vi, "%t", buffer);
cout << " " << buffer;
}while(strcmp(buffer, "0,\"No error\"\n") != 0);
cout << endl << endl << "Finished." << endl << endl;
Sleep(5000); // milli seconds
stateGen.isAborted = 0;
}
}
int generator::openSession()
{
cout << "Open " << resrc << " ... ";
error = viOpenDefaultRM(&session);
error = viOpen(session, resrc, VI_NO_LOCK, VI_NULL, &vi);
if (error != VI_SUCCESS)
{
viClose(session);
cout
<< "failed!" << endl << endl
<< "Make sure that the AgM8190Firmware Application is started: " << endl
<< " Start Menu -> Keysight M8190 -> Keysight M8190" << endl << endl
;
Sleep(5000); // milli seconds
return 1;
}
error = viSetAttribute(vi, VI_ATTR_TMO_VALUE, (ViAttrState)0x1f40);
#ifdef debug
cout << endl << "open: error " << error << endl;
#endif
if (error < VI_SUCCESS) {
err_handler(vi, error);
viClose(session);
cout << "Timeout is too small" << endl << endl;
Sleep(5000); // milli seconds
return 1;
}
return 0;
}
void generator::err_handler(ViSession vi, ViStatus err)
{
char err_msg[1024]={0};
viStatusDesc (vi, err, err_msg);
printf ("ERROR = %s\n", err_msg);
return;
}
void generator::setSigData(string k, string v)
{
signal::sigData[k] = v;
}
generator::~generator()
{
delete sig;
if (stateGen.isCloseSes) {
error = viPrintf(vi, ":ABORt\n");
error = viPrintf(vi, "*RST\n");
error = viClose(vi);
error = viClose(session);
stateGen.isCloseSes=0;
stateGen.isOpenSes=1;
}
}
generator::signal::signal(string &gFreq)
{
gF=&gFreq; //Hz
commands.push_back("getAllP");
commands.push_back("setP");
commands.push_back("delP");
commands.push_back("commands");
commands.push_back("exit");
}
void generator::signal::execShell()
{
string command;
cout << "signal:";
while(getline(cin,command)) {
if (command == "") {
//cout << "=>";
} else if ((std::find(commands.begin(), commands.end(), command) == commands.end())) {
cout << command << " is not command" << endl;
} else if (command == "commands") {
for (std::list<string>::iterator it = commands.begin(); it!=commands.end(); ++it)
cout << *it << endl;
} else if (command == "exit") {
//code
break;
} else if (command == "getAllP") {
for (std::map<string,string>::iterator it=sigData.begin(); it!=sigData.end(); ++it)
cout << "key: " << it->first << "; value: " << it->second << endl;
} else if (command == "setP") {
cout << "key:";
string key, value; getline(cin,key);
std::map<string,string>::iterator it = sigData.find(key);
cout << "value:"; getline(cin,value);
sigData[key] = value;
if (it == sigData.end()) cout << "new 'key-value' added" << endl;
*isChangeSigP = 1;
} else if (command == "delP") {
cout << "key:";
string key; getline(cin,key);
std::map<string,string>::iterator it = sigData.find(key);
if (it == sigData.end()) { cout << "Key not find" << endl; }
else { sigData.erase(it); cout << "Key was delete" << endl; *isChangeSigP = 1; }
}
cout << "signal:";
}
}
void generator::signal::Calculate()
{
Fr = (double long)N*Fs;
int Chain = rangeCheck(Fr);
N = (Fr / Fs + Chain);
if (N<minN) {
throw new string("Error: Fr/Fs < 4\n");
} else if (N<384) {
sampleCount = N*192;
Fr=N*Fs;
} else {
long long remainder = N % 192;
long long quotient = N / 192;
if (remainder != 0)
N = (quotient + Chain) * 192;
sampleCount = N;
Fr=N*Fs;
}
////////////////////////////////////////
if (sampleCount > maxSampleCount) throw new string("Error: Sample Count > 2GSa\n");
long long remainder = sampleCount % maxPortion;
long long quotient = sampleCount / maxPortion;
if (remainder != 0) count = quotient + 1;
else count = quotient;
#ifdef debug
cout << "GenerateWaveformCommands() -> Fs: " << Fs << endl;
cout << "GenerateWaveformCommands() -> Fr: " << Fr << endl;
cout << "GenerateWaveformCommands() -> N: " << N << endl;
cout << "GenerateWaveformCommands() -> sampleCount: " << sampleCount << endl;
#endif
*gF = to_string((long long)Fr);
offset=0;
counter=0;
i=0;
}
void generator::signal::GenerateWaveformCommands(vector<ViByte> &buffer1)
{
// Generate a sine, LFM, impulse waves, ensure granularity (192) and minimum samples (384)
long long sampleCountCheck = 0;
vector<ViChar> binaryValues;
binaryValues.clear();
short way = 0;
long long barrier = n*maxPortion;
do
{
for (; i<N; ++i, ++counter)
{
if (counter == barrier || counter == sampleCount) { way = 1; break; }
const short dac = dacValue();
short value = (short)(dac << 4);
binaryValues.push_back((ViChar)value);
binaryValues.push_back((ViChar)(value >> 8));
}
if (way==1)
break;
i=0;
sampleCountCheck += N;
} while (sampleCount != sampleCountCheck);
// Encode the binary commands to download the waveform
#ifdef debug
cout << "offset: " << offset << endl;
#endif
string bytes1 = string(":trac1:data 1,") + to_string(offset) + string(",") + ScpiBlockPrefix(binaryValues.size());
offset+=binaryValues.size()/2;
#ifdef debug
cout << "n: " << n << endl;
cout << "offset: " << offset << endl;
cout << "binaryValues.size(): " << binaryValues.size() << endl;
#endif
buffer1.resize(bytes1.size() + binaryValues.size());
memcpy(&buffer1[0], bytes1.c_str(), bytes1.size());
memcpy(&buffer1[bytes1.size()], &binaryValues[0], binaryValues.size());
}
string generator::signal::ScpiBlockPrefix(size_t blocklen)
{
ostringstream blockLenSStr;
blockLenSStr << blocklen;
ostringstream resultSStr;
resultSStr << "#" << blockLenSStr.str().size() << blockLenSStr.str();
return resultSStr.str();
}
int generator::signal::rangeCheck(long double& Fr)
{
if (Fr < Fr_min) Fr = Fr_min;
if (Fr > Fr_max) Fr = Fr_max;
if ((Fr >= Fr_min) && (Fr < Fr_max/2)) return 1;
if ((Fr >= Fr_max/2) && (Fr <= Fr_max)) return 0;
}
void generator::signal_SIN::Calculate()
{
Fs = stold(sigData.find("-sF")->second); //in Hz;
minN=4; N=384;
signal::Calculate();
Tr = 1/Fr;
}
short generator::signal_SIN::dacValue()
{
return (short)(2047 * sin(2 * M_PI * Fs * i * Tr));
}
void generator::signal_LFM::Calculate()
{
F_min = stod(sigData.find("-sFmin")->second); //Hz
F_max = stod(sigData.find("-sFmax")->second); //Hz
Ts = stod(sigData.find("-sT")->second); //s
Fs = 1/Ts; //Hz
F_0 = (F_max + F_min)/2; //Hz
b = (F_max - F_min)/Ts; //Hz^2
double long n_12, n_2;
n_12 = (F_max+F_min)*Ts;
n_2 = n_12 * (3*F_max + F_min)/(4*F_max + 4*F_min);
double long t_21 = (-F_0-sqrtl(F_0*F_0 + b*(n_2-1)))/b;
if (t_21>Ts/2 || t_21<-Ts/2) t_21 = (-F_0+sqrtl(F_0*F_0 + b*(n_2-1)))/b;
double long t_22 = (-F_0-sqrtl(F_0*F_0 + b*(n_2-2)))/b;
if (t_22>Ts/2 || t_22<-Ts/2) t_22 = (-F_0+sqrtl(F_0*F_0 + b*(n_2-2)))/b;
double long dt = (t_21 - t_22)/4;
minN = Ts/dt;
dt = (t_21 - t_22)/10;
N = Ts/dt;
#ifdef debug
cout << "N...: " << N << endl;
cout << "Fs: " << Fs << endl;
#endif
signal::Calculate();
Tr = 1/Fr;
#ifdef debug
cout << "GenerateWaveformCommands() -> F_min: " << F_min << endl;
cout << "GenerateWaveformCommands() -> F_max: " << F_max << endl;
cout << "GenerateWaveformCommands() -> Ts: " << Ts << endl;
cout << "GenerateWaveformCommands() -> Fs: " << Fs << endl;
cout << "GenerateWaveformCommands() -> F_0: " << F_0 << endl;
cout << "GenerateWaveformCommands() -> b: " << b << endl;
#endif
}
short generator::signal_LFM::dacValue()
{
long double t = -Ts/2 + (double long)i*Tr;
return (short)(2047 * cos(2 * M_PI * (F_0 * t + b/2 * t * t)));
}
void generator::signal_IMP::Calculate()
{
Ts = stold(sigData.find("-sT")->second); //in s
Fs = (long double)1/Ts;
minN=4; N=384;
signal::Calculate();
}
short generator::signal_IMP::dacValue()
{
short sign;
if (i < N/2) sign = 2047; else sign = -2047;
return sign;
}
| [
"ialaev86@gmail.com"
] | ialaev86@gmail.com |
13f7a1b35f5215db5ecada6109eb70e7ce1b653b | 9ac313b5dc87f470eb45cdb2df71f470751d3f01 | /04.12/60 параграф/9.cpp | 37ef6221c4ce16d9bb4fd5b75a39abc9e8cf6a1c | [] | no_license | Maks3410/inf | 68b1c091fbf608c8c845acc3f62f8c61ef032cd0 | f391c99966b1c49d3c7a4ff0716c8ef797370d94 | refs/heads/master | 2023-04-03T15:21:04.227051 | 2021-04-22T17:11:11 | 2021-04-22T17:11:11 | 360,633,154 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | cpp | #include <iostream>
using namespace std;
int fibonacci(int n){
if (n <= 2) return 1;
else return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int a;
cin >> a;
cout << fibonacci(a);
} | [
"maksim.maksimum@gmail.com"
] | maksim.maksimum@gmail.com |
3711831852bf88a4ac7d44b01675ded262af0652 | 918923bd15593830b5b109fbbadaab0028091f81 | /sql_parser/ast_node/ast_insert_stmt.cpp | 6bdbac62a3bd1008e0b109e8d80a0143cfa09bab | [] | no_license | XLPE/Ginkgo | 6ddbc00a2d57eb08b74dcdf6f4b3e1248e78ce5b | b016b8d22dab9e8d58096bcd6fedc8843574dc6c | refs/heads/master | 2020-12-18T13:15:13.779015 | 2017-09-27T02:11:35 | 2017-09-27T02:11:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,045 | cpp | /*
* Copyright [2012-2015] DaSE@ECNU
*
* 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.
*
* /sql_parser/src/astnode/ast_insert_stmt.cpp
*
* Created on: Jul 23, 2015
* Author: fish
* Email: youngfish93@hotmail.com
* Copyright: Copyright (c) @ ECNU.DaSe
*
*/
#include "../ast_node/ast_insert_stmt.h"
#include <iostream> // NOLINT
#include <iomanip>
#include <string>
#include <bitset>
#include "../../common/error_define.h"
using namespace ginkgo::common; // NOLINT
using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::setw;
using std::bitset;
// namespace ginkgo {
// namespace sql_parser {
AstInsertStmt::AstInsertStmt(AstNodeType ast_node_type, int insert_opt,
string table_name, AstNode* col_list,
AstNode* insert_val_list,
AstNode* insert_assign_list,
AstNode* insert_assign_list_from_set,
AstNode* select_stmt)
: AstNode(ast_node_type),
insert_opt_(insert_opt),
table_name_(table_name),
col_list_(col_list),
insert_val_list_(insert_val_list),
select_stmt_(select_stmt),
insert_assign_list_(insert_assign_list),
insert_assign_list_from_set_(insert_assign_list_from_set) {}
AstInsertStmt::~AstInsertStmt() {
delete col_list_;
delete insert_val_list_;
delete select_stmt_;
delete insert_assign_list_;
delete insert_assign_list_from_set_;
}
void AstInsertStmt::Print(int level) const {
cout << setw(level * TAB_SIZE) << " "
<< "|Insert Statement|"
<< " Table Name:" << table_name_ << endl;
if (col_list_ != NULL) {
col_list_->Print(level + 1);
}
}
AstInsertValList::AstInsertValList(AstNodeType ast_node_type,
AstNode* insert_vals, AstNode* next)
: AstNode(ast_node_type), insert_vals_(insert_vals), next_(next) {}
AstInsertValList::~AstInsertValList() {
delete insert_vals_;
delete next_;
}
void AstInsertValList::Print(int level) const {
cout << setw(level * TAB_SIZE) << " "
<< "|Insert ValList|" << endl;
}
AstInsertVals::AstInsertVals(AstNodeType ast_node_type, int value_type,
AstNode* expr, AstNode* next)
: AstNode(ast_node_type),
value_type_(value_type),
expr_(expr),
next_(next) {}
AstInsertVals::~AstInsertVals() {
delete expr_;
delete next_;
}
void AstInsertVals::Print(int level) const {
cout << setw(level * TAB_SIZE) << " "
<< "|Insert Vals|" << endl;
}
AstInsertAssignList::AstInsertAssignList(AstNodeType ast_node_type,
string col_name, int value_type,
AstNode* expr, AstNode* next)
: AstNode(ast_node_type),
col_name_(col_name),
value_type_(value_type),
expr_(expr),
next_(next) {}
AstInsertAssignList::~AstInsertAssignList() {
delete expr_;
delete next_;
}
void AstInsertAssignList::Print(int level) const {
cout << setw(level * TAB_SIZE) << " "
<< "|Insert Assign List|" << endl;
if (expr_ != NULL) {
expr_->Print(level + 1);
}
if (next_ != NULL) {
next_->Print(level);
}
}
//} // namespace sql_parser
//} // namespace ginkgo
| [
"885626704@qq.com"
] | 885626704@qq.com |
12d2e43cbce39571be798b4093c034ab38949301 | 96c413b37babcb131afbbd16ed4106483d26c874 | /jhess.cpp | 0b41fa65b8e1f87dba4d325f7dbb95ca27250feb | [] | no_license | JonPizza/antfarm9002 | 63cebb69e1de640fa538d96924f91aca658d569d | 8aaf240e68c99b410e26f7b08f5aa3f12b7867ed | refs/heads/master | 2023-06-13T04:35:05.522469 | 2021-07-08T01:39:18 | 2021-07-08T01:39:18 | 383,969,251 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 68 | cpp | #include "board.cpp"
int main() {
Board b(640);
return 0;
} | [
"="
] | = |
226a0fb2c7cb6480ce1a91d20d6600d490518226 | eb2f8b3271e8ef9c9b092fcaeff3ff8307f7af86 | /Grade 10-12/2018 summer/二中集训/7.7 contest/t2.cpp | ce292338efba81a6da610d4676053eeea95ab95b | [] | no_license | Orion545/OI-Record | 0071ecde8f766c6db1f67b9c2adf07d98fd4634f | fa7d3a36c4a184fde889123d0a66d896232ef14c | refs/heads/master | 2022-01-13T19:39:22.590840 | 2019-05-26T07:50:17 | 2019-05-26T07:50:17 | 188,645,194 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,612 | cpp | #include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
inline int read(){
int re=0,flag=1;char ch=getchar();
while(ch>'9'||ch<'0'){
if(ch=='-') flag=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9') re=(re<<1)+(re<<3)+ch-'0',ch=getchar();
return re*flag;
}
int n,m;
int fa[300010],ch[300010][2],w[300010],a[300010];
bool rev[300010],rt[300010];
inline void _swap(int &x,int &y){x^=y;y^=x;x^=y;}
inline void update(int x){a[x]=w[x]+a[ch[x][0]]+a[ch[x][1]];}
inline void reverse(int x){_swap(ch[x][0],ch[x][1]);rev[x]^=1;}
inline void pushdown(int x){
if(rev[x]){
if(ch[x][0]) reverse(ch[x][0]);
if(ch[x][1]) reverse(ch[x][1]);
rev[x]=0;
}
}
inline void push(int x){if(!rt[x]) push(fa[x]);pushdown(x);}
inline bool get(int x){return x==ch[fa[x]][1];}
inline void rotate(int x){
int f=fa[x],ff=fa[f],son=get(x);
ch[f][son]=ch[x][son^1];
if(ch[f][son]) fa[ch[f][son]]=f;
fa[f]=x;ch[x][son^1]=f;
fa[x]=ff;
if(rt[f]) rt[x]=1,rt[f]=0;
else ch[ff][f==ch[ff][1]]=x;
update(f);update(x);
}
inline void splay(int x){
// cout<<"splay "<<x<<endl;
push(x);
for(int f;!rt[x];rotate(x)){
// cout<<x<<ends<<fa[x]<<endl;
if(!rt[f=fa[x]]) rotate((get(x)==get(f))?f:x);
}
update(x);
}
inline void access(int x){
// cout<<"access "<<x<<endl;
int y=0;
do{
splay(x);
rt[ch[x][1]]=1;
rt[ch[x][1]=y]=0;
x=fa[y=x];
update(x);
}while(x);
}
inline void mroot(int x){
access(x);splay(x);reverse(x);
}
inline bool judge(int x,int y){
while(fa[x]) x=fa[x];
while(fa[y]) y=fa[y];
return x==y;
}
inline void link(int x,int y){
if(judge(x,y)){
puts("no");
return;
}
puts("yes");
// cout<<"link "<<x<<ends<<y<<endl;
mroot(x);fa[x]=y;
}
inline void cut(int x,int y){
if(!judge(x,y)) return;
// cout<<"cut "<<x<<ends<<y<<endl;
mroot(x);splay(y);
fa[ch[y][0]]=fa[y];
rt[ch[y][0]]=1;
fa[y]=0;ch[y][0]=0;
}
inline void split(int x,int y){
mroot(x);access(y);splay(y);
}
int main(){
int i,t2,t3;char t1[20];
n=read();
for(i=1;i<=n;i++) w[i]=read(),a[i]=w[i],rt[i]=1;
m=read();
// for(i=1;i<=n;i++) cout<<i<<ends<<w[i]<<endl;
for(i=1;i<=m;i++){
scanf("%s",t1);t2=read();t3=read();
if(t1[0]=='e'){
if(!judge(t2,t3)) puts("impossible");
else split(t2,t3),printf("%d\n",a[t3]);
}
if(t1[0]=='b') link(t2,t3);
if(t1[0]=='p'){
access(t2);splay(t2);w[t2]=t3;update(t2);
}
}
// system("pause");
}
| [
"orion545@qq.com"
] | orion545@qq.com |
bd795b3edf0c8ec1724576b0427a10949660e3e1 | e2c4c567bc3117d79111ba3ba2a2c32befe913f8 | /src/masternode/masternodeman.h | c8738d445c4b43d3976a2486df05ff6faf4a6a90 | [
"MIT"
] | permissive | zyrkproject/zyrk-core | 989f264b44170d077e7929847fd1b8dfe16ff2b6 | e0daa7c6a270ac2db186734bba39079ddeb32bd2 | refs/heads/master | 2020-05-19T05:55:12.993218 | 2019-06-15T01:35:29 | 2019-06-15T01:35:29 | 184,860,119 | 4 | 2 | NOASSERTION | 2019-06-15T01:35:30 | 2019-05-04T06:26:38 | C | UTF-8 | C++ | false | false | 12,336 | h | // Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2019 The Zyrk Project developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MASTERNODEMAN_H
#define MASTERNODEMAN_H
#include "masternode.h"
#include "sync.h"
using namespace std;
class CMasternodeMan;
extern CMasternodeMan mnodeman;
/**
* Provides a forward and reverse index between MN vin's and integers.
*
* This mapping is normally add-only and is expected to be permanent
* It is only rebuilt if the size of the index exceeds the expected maximum number
* of MN's and the current number of known MN's.
*
* The external interface to this index is provided via delegation by CMasternodeMan
*/
class CMasternodeIndex
{
public: // Types
typedef std::map<CTxIn,int> index_m_t;
typedef index_m_t::iterator index_m_it;
typedef index_m_t::const_iterator index_m_cit;
typedef std::map<int,CTxIn> rindex_m_t;
typedef rindex_m_t::iterator rindex_m_it;
typedef rindex_m_t::const_iterator rindex_m_cit;
private:
int nSize;
index_m_t mapIndex;
rindex_m_t mapReverseIndex;
public:
CMasternodeIndex();
int GetSize() const {
return nSize;
}
/// Retrieve masternode vin by index
bool Get(int nIndex, CTxIn& vinMasternode) const;
/// Get index of a masternode vin
int GetMasternodeIndex(const CTxIn& vinMasternode) const;
void AddMasternodeVIN(const CTxIn& vinMasternode);
void Clear();
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
READWRITE(mapIndex);
if(ser_action.ForRead()) {
RebuildIndex();
}
}
private:
void RebuildIndex();
};
class CMasternodeMan
{
public:
typedef std::map<CTxIn,int> index_m_t;
typedef index_m_t::iterator index_m_it;
typedef index_m_t::const_iterator index_m_cit;
private:
static const int MAX_EXPECTED_INDEX_SIZE = 30000;
/// Only allow 1 index rebuild per hour
static const int64_t MIN_INDEX_REBUILD_TIME = 3600;
static const std::string SERIALIZATION_VERSION_STRING;
static const int DSEG_UPDATE_SECONDS = 3 * 60 * 60;
static const int LAST_PAID_SCAN_BLOCKS = 100;
static const int MIN_POSE_PROTO_VERSION = 70203;
static const int MAX_POSE_CONNECTIONS = 10;
static const int MAX_POSE_RANK = 10;
static const int MAX_POSE_BLOCKS = 10;
static const int MNB_RECOVERY_QUORUM_TOTAL = 10;
static const int MNB_RECOVERY_QUORUM_REQUIRED = 6;
static const int MNB_RECOVERY_MAX_ASK_ENTRIES = 10;
static const int MNB_RECOVERY_WAIT_SECONDS = 60;
static const int MNB_RECOVERY_RETRY_SECONDS = 3 * 60 * 60;
// Keep track of current block index
const CBlockIndex *pCurrentBlockIndex;
// map to hold all MNs
std::vector<CMasternode> vMasternodes;
// who's asked for the Masternode list and the last time
std::map<CNetAddr, int64_t> mAskedUsForMasternodeList;
// who we asked for the Masternode list and the last time
std::map<CNetAddr, int64_t> mWeAskedForMasternodeList;
// which Masternodes we've asked for
std::map<COutPoint, std::map<CNetAddr, int64_t> > mWeAskedForMasternodeListEntry;
// who we asked for the masternode verification
std::map<CNetAddr, CMasternodeVerification> mWeAskedForVerification;
// these maps are used for masternode recovery from MASTERNODE_NEW_START_REQUIRED state
std::map<uint256, std::pair< int64_t, std::set<CNetAddr> > > mMnbRecoveryRequests;
std::map<uint256, std::vector<CMasternodeBroadcast> > mMnbRecoveryGoodReplies;
std::list< std::pair<CService, uint256> > listScheduledMnbRequestConnections;
int64_t nLastIndexRebuildTime;
CMasternodeIndex indexMasternodes;
CMasternodeIndex indexMasternodesOld;
/// Set when index has been rebuilt, clear when read
bool fIndexRebuilt;
/// Set when masternodes are added, cleared when CGovernanceManager is notified
bool fMasternodesAdded;
/// Set when masternodes are removed, cleared when CGovernanceManager is notified
bool fMasternodesRemoved;
std::vector<uint256> vecDirtyGovernanceObjectHashes;
int64_t nLastWatchdogVoteTime;
friend class CMasternodeSync;
public:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
// Keep track of all broadcasts I've seen
std::map<uint256, std::pair<int64_t, CMasternodeBroadcast> > mapSeenMasternodeBroadcast;
// Keep track of all pings I've seen
std::map<uint256, CMasternodePing> mapSeenMasternodePing;
// Keep track of all verifications I've seen
std::map<uint256, CMasternodeVerification> mapSeenMasternodeVerification;
// keep track of dsq count to prevent masternodes from gaming darksend queue
int64_t nDsqCount;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
LOCK(cs);
std::string strVersion;
if(ser_action.ForRead()) {
READWRITE(strVersion);
}
else {
strVersion = SERIALIZATION_VERSION_STRING;
READWRITE(strVersion);
}
READWRITE(vMasternodes);
READWRITE(mAskedUsForMasternodeList);
READWRITE(mWeAskedForMasternodeList);
READWRITE(mWeAskedForMasternodeListEntry);
READWRITE(mMnbRecoveryRequests);
READWRITE(mMnbRecoveryGoodReplies);
READWRITE(nLastWatchdogVoteTime);
READWRITE(nDsqCount);
READWRITE(mapSeenMasternodeBroadcast);
READWRITE(mapSeenMasternodePing);
READWRITE(indexMasternodes);
if(ser_action.ForRead() && (strVersion != SERIALIZATION_VERSION_STRING)) {
Clear();
}
}
CMasternodeMan();
/// Add an entry
bool Add(CMasternode &mn);
/// Ask (source) node for mnb
void AskForMN(CNode *pnode, const CTxIn &vin);
void AskForMnb(CNode *pnode, const uint256 &hash);
/// Check all Masternodes
void Check();
/// Check all Masternodes and remove inactive
void CheckAndRemove();
/// Clear Masternode vector
void Clear();
/// Count Masternodes filtered by nProtocolVersion.
/// Masternode nProtocolVersion should match or be above the one specified in param here.
int CountMasternodes(int nProtocolVersion = -1);
/// Count enabled Masternodes filtered by nProtocolVersion.
/// Masternode nProtocolVersion should match or be above the one specified in param here.
int CountEnabled(int nProtocolVersion = -1);
/// Count Masternodes by network type - NET_IPV4, NET_IPV6, NET_TOR
// int CountByIP(int nNetworkType);
void DsegUpdate(CNode* pnode);
/// Find an entry
CMasternode* Find(const CScript &payee);
CMasternode* Find(const CTxIn& vin);
CMasternode* Find(const CPubKey& pubKeyMasternode);
/// Versions of Find that are safe to use from outside the class
bool Get(const CPubKey& pubKeyMasternode, CMasternode& masternode);
bool Get(const CTxIn& vin, CMasternode& masternode);
/// Retrieve masternode vin by index
bool Get(int nIndex, CTxIn& vinMasternode, bool& fIndexRebuiltOut) {
LOCK(cs);
fIndexRebuiltOut = fIndexRebuilt;
return indexMasternodes.Get(nIndex, vinMasternode);
}
bool GetIndexRebuiltFlag() {
LOCK(cs);
return fIndexRebuilt;
}
/// Get index of a masternode vin
int GetMasternodeIndex(const CTxIn& vinMasternode) {
LOCK(cs);
return indexMasternodes.GetMasternodeIndex(vinMasternode);
}
/// Get old index of a masternode vin
int GetMasternodeIndexOld(const CTxIn& vinMasternode) {
LOCK(cs);
return indexMasternodesOld.GetMasternodeIndex(vinMasternode);
}
/// Get masternode VIN for an old index value
bool GetMasternodeVinForIndexOld(int nMasternodeIndex, CTxIn& vinMasternodeOut) {
LOCK(cs);
return indexMasternodesOld.Get(nMasternodeIndex, vinMasternodeOut);
}
/// Get index of a masternode vin, returning rebuild flag
int GetMasternodeIndex(const CTxIn& vinMasternode, bool& fIndexRebuiltOut) {
LOCK(cs);
fIndexRebuiltOut = fIndexRebuilt;
return indexMasternodes.GetMasternodeIndex(vinMasternode);
}
void ClearOldMasternodeIndex() {
LOCK(cs);
indexMasternodesOld.Clear();
fIndexRebuilt = false;
}
bool Has(const CTxIn& vin);
masternode_info_t GetMasternodeInfo(const CTxIn& vin);
masternode_info_t GetMasternodeInfo(const CPubKey& pubKeyMasternode);
char* GetNotQualifyReason(CMasternode& mn, int nBlockHeight, bool fFilterSigTime, int nMnCount);
/// Find an entry in the masternode list that is next to be paid
CMasternode* GetNextMasternodeInQueueForPayment(int nBlockHeight, bool fFilterSigTime, int& nCount);
/// Same as above but use current block height
CMasternode* GetNextMasternodeInQueueForPayment(bool fFilterSigTime, int& nCount);
/// Find a random entry
CMasternode* FindRandomNotInVec(const std::vector<CTxIn> &vecToExclude, int nProtocolVersion = -1);
std::vector<CMasternode> GetFullMasternodeVector() { return vMasternodes; }
std::vector<std::pair<int, CMasternode> > GetMasternodeRanks(int nBlockHeight = -1, int nMinProtocol=0);
int GetMasternodeRank(const CTxIn &vin, int nBlockHeight, int nMinProtocol=0, bool fOnlyActive=true);
CMasternode* GetMasternodeByRank(int nRank, int nBlockHeight, int nMinProtocol=0, bool fOnlyActive=true);
void ProcessMasternodeConnections();
std::pair<CService, std::set<uint256> > PopScheduledMnbRequestConnection();
void ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
void DoFullVerificationStep();
void CheckSameAddr();
bool SendVerifyRequest(const CAddress& addr, const std::vector<CMasternode*>& vSortedByAddr);
void SendVerifyReply(CNode* pnode, CMasternodeVerification& mnv);
void ProcessVerifyReply(CNode* pnode, CMasternodeVerification& mnv);
void ProcessVerifyBroadcast(CNode* pnode, const CMasternodeVerification& mnv);
/// Return the number of (unique) Masternodes
int size() { return vMasternodes.size(); }
std::string ToString() const;
/// Update masternode list and maps using provided CMasternodeBroadcast
void UpdateMasternodeList(CMasternodeBroadcast mnb);
/// Perform complete check and only then update list and maps
bool CheckMnbAndUpdateMasternodeList(CNode* pfrom, CMasternodeBroadcast mnb, int& nDos);
bool IsMnbRecoveryRequested(const uint256& hash) { return mMnbRecoveryRequests.count(hash); }
void UpdateLastPaid();
void CheckAndRebuildMasternodeIndex();
void AddDirtyGovernanceObjectHash(const uint256& nHash)
{
LOCK(cs);
vecDirtyGovernanceObjectHashes.push_back(nHash);
}
std::vector<uint256> GetAndClearDirtyGovernanceObjectHashes()
{
LOCK(cs);
std::vector<uint256> vecTmp = vecDirtyGovernanceObjectHashes;
vecDirtyGovernanceObjectHashes.clear();
return vecTmp;;
}
bool IsWatchdogActive();
void UpdateWatchdogVoteTime(const CTxIn& vin);
bool AddGovernanceVote(const CTxIn& vin, uint256 nGovernanceObjectHash);
void RemoveGovernanceObject(uint256 nGovernanceObjectHash);
void CheckMasternode(const CTxIn& vin, bool fForce = false);
void CheckMasternode(const CPubKey& pubKeyMasternode, bool fForce = false);
int GetMasternodeState(const CTxIn& vin);
int GetMasternodeState(const CPubKey& pubKeyMasternode);
bool IsMasternodePingedWithin(const CTxIn& vin, int nSeconds, int64_t nTimeToCheckAt = -1);
void SetMasternodeLastPing(const CTxIn& vin, const CMasternodePing& mnp);
void UpdatedBlockTip(const CBlockIndex *pindex);
/**
* Called to notify CGovernanceManager that the masternode index has been updated.
* Must be called while not holding the CMasternodeMan::cs mutex
*/
void NotifyMasternodeUpdates();
};
#endif
| [
"admin@zyrk.io"
] | admin@zyrk.io |
cfdd020bf22f5895f28311970f295e30afb248ce | c06bc4e70e420f109c451374559a923d3a9fd122 | /libraries/PION/examples/CubeSat-SD-Card-Advanced/CubeSat-SD-Card-Advanced.ino | 66bd34d5bcf549d78e78c1f02cd8515a6bc192c9 | [
"MIT"
] | permissive | pion-labs/pion-educational-kits | 3661f6cff4dc3e86330a05314e80eaa89e87b01b | 1bea23f00040e386b44285f926b6871ba1bcd5fb | refs/heads/main | 2023-06-17T19:43:15.606933 | 2021-07-19T15:36:22 | 2021-07-19T15:36:22 | 362,965,932 | 20 | 13 | null | null | null | null | UTF-8 | C++ | false | false | 1,949 | ino | #include "PION_System.h"
#include "FS.h"
/*
Esse código demonstra como o subsistema de armazenamento de dados
pode ser modificado para que de acordo com a chamada da função
logOnSDFile() sejam armazenados os dados desejados.
*/
System cubeSat;
void setup(){
// Inicializa seu cubeSat, e seus periféricos
cubeSat.init();
// Cria o arquivo para armazenamento no cartão SD
cubeSat.createLogOnSD();
}
void loop(){
// Salva uma nova linha com dados no seu arquivo a cada 1000 millisegundos ou 1 segundo
cubeSat.logOnSDFile();
delay(1000);
}
// Declaração de funções que sobrescrevem as funcionalidades padrão
// Função Modificada
void createFileFirstLine(fs::FS &fs, const char * path){
// Mostra o nome do arquivo
Serial.printf("Escrevendo em: %s\n", path);
//Abre o arquivo do SD para a memória RAM
File file = fs.open(path, FILE_WRITE);
if(!file){
Serial.println("Falha ao abrir para escrita");
return;
}
// Cria a primeira linha modificada e separada por vírgulas do CSV.
const char * message = "tempo(ms),temperatura(C),umidade(%),co2(ppm),bateria(%)";
// Escreve a mensagem criada anteriormente
if(file.println(message)){
Serial.println("Escrita Começou");
} else {
Serial.println("Falha na escrita");
}
// Fecha o arquivo
file.close();
}
// Função Modicada para armazenamento
void appendFile(fs::FS &fs, const char * path, TickType_t time){
//Abre o arquivo do SD para a memória RAM
File file = fs.open(path, FILE_APPEND);
if(!file){
Serial.println("Falha ao abrir para gravacao");
return;
}
// Salva no CSV o dado, seguido de uma vírgula.
file.print(time);
file.write(',');
file.print(cubeSat.getTemperature());
file.write(',');
file.print(cubeSat.getHumidity());
file.write(',');
file.print(cubeSat.getCO2Level());
file.write(',');
file.println(cubeSat.getBattery());
// Fecha o arquivo
file.close();
} | [
"joaopedrovbs@gmail.com"
] | joaopedrovbs@gmail.com |
7d3fd5c8d19ad39ad50c34dff5dd74170225480a | dbd844bb6c9e2a2bfa3c1e45486fbe6c9f9f6b1b | /FelixiAtros/iatros-v1.0/iatros/htr/online/src/read.cc | f57b93eab1acb7534c3a1dba0a20a4aad898cbed | [
"MIT",
"LGPL-3.0-only"
] | permissive | MarioProjects/FelixRobot | 66ddaf62298de2273138600a7dc8284a3adb68ac | aeb6eaa329167b75c13d21c2c8de618af182c465 | refs/heads/master | 2022-02-15T23:03:27.438389 | 2020-06-26T16:54:04 | 2020-06-26T16:54:04 | 133,227,682 | 1 | 0 | MIT | 2022-02-03T18:06:13 | 2018-05-13T10:42:50 | CMake | WINDOWS-1250 | C++ | false | false | 1,951 | cc | /*
* read.cc
*
* Created on: Feb 12, 2006
* Author: moises@iti.upv.es
*/
#include <string>
#include <cstring>
#include "read.h"
int read_file_moto(istream &fd, sentence ** S, string filename) {
char linea[MAX_LIN];
static int line_counter=0;
while (fd.getline(linea,MAX_LIN)) {
line_counter++;
if (linea[0]!='#' && linea[0]!=' ' && strlen(linea)>0) break;
//if (linea[0]!=' ' && strlen(linea)>0) break;
}
if (fd.eof()) return false;
//if (!isalpha(linea[0])) {
if (!isgraph(linea[0])) {
cerr << "ERR 2: incorrect file format. " << filename.c_str()<< " Line " << line_counter << endl;
return false;
}
// nueva sentencia
int n_strokes;
fd >> n_strokes;
line_counter++;
sentence *sent=new sentence(linea,n_strokes);
// leemos las trazas
for (int s=0; s<n_strokes; s++) {
int num_points_stroke;
line_counter++;
fd >> num_points_stroke;
if (!fd.good()) {
cerr << "ERR 1: incorrect file format. " << filename.c_str()<<" Line: " << line_counter << endl;
return false;
}
int is_pen_down;
line_counter++;
fd >> is_pen_down;
if (!fd.good()) {
cerr << "ERR 1: incorrect file format. " << filename.c_str()<<" Line: " << line_counter << endl;
return false;
}
stroke st(num_points_stroke,is_pen_down);
// leemos los puntos de cada traza
for (int i=0; i<num_points_stroke; i++) {
int x, y;
line_counter++;
fd >> x >> y;
if (!fd.good()) {
cerr << "ERR 1: incorrect file format. " << filename.c_str()<< " Line: " << line_counter << endl;
return false;
}
Point p(x,y);
st.points.push_back(p);
}
// guardamos cada traza en la sentencia
if (st.points.size()>0) (*sent).strokes.push_back(st);
else if (n_strokes>0) (*sent).n_strokes--;
}
*S=sent;
// para el último salto de carro
fd.getline(linea,MAX_LIN);
return true;
}
| [
"maparla@inf.upv.es"
] | maparla@inf.upv.es |
83f78c65d52cf376a2d1827b83fbeec2775af49c | ee66e4a4fefe19257078c7f459bf4518d773dc75 | /src/rpcserver.cpp | 28b8e4cb02648bc70e0f52e1cdf16a44a7a04588 | [
"MIT"
] | permissive | htrcoin/htrcoin | 2b5ee6bff9afa7313c920424b54af9a841ae9f7e | 4540fa0bb5c459ee8893e8295dd27a31aca6d6b2 | refs/heads/master | 2020-03-07T09:33:03.262653 | 2018-08-06T17:34:58 | 2018-08-06T17:34:58 | 127,410,566 | 10 | 14 | null | 2018-06-07T12:52:59 | 2018-03-30T09:38:49 | C++ | UTF-8 | C++ | false | false | 34,676 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "base58.h"
#include "init.h"
#include "util.h"
#include "sync.h"
#include "base58.h"
#include "db.h"
#include "ui_interface.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#endif
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first, Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64_t AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > MAX_MONEY)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
CAmount nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64_t amount)
{
return (double)amount / (double)COIN;
}
//
// Utilities: convert hex-encoded Values
// (throws error if not hex).
//
uint256 ParseHashV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex)) // Note: IsHex("") is false
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
uint256 result;
result.SetHex(strHex);
return result;
}
uint256 ParseHashO(const Object& o, string strKey)
{
return ParseHashV(find_value(o, strKey), strKey);
}
vector<unsigned char> ParseHexV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex))
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
return ParseHex(strHex);
}
vector<unsigned char> ParseHexO(const Object& o, string strKey)
{
return ParseHexV(find_value(o, strKey), strKey);
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
#ifdef ENABLE_WALLET
if (pcmd->reqWallet && !pwalletMain)
continue;
#endif
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand);
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop HighTemperature server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "HighTemperature server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe reqWallet
// ------------------------ ----------------------- ---------- ---------- ---------
{ "help", &help, true, true, false },
{ "stop", &stop, true, true, false },
{ "getbestblockhash", &getbestblockhash, true, false, false },
{ "getblockcount", &getblockcount, true, false, false },
{ "getconnectioncount", &getconnectioncount, true, false, false },
{ "getpeerinfo", &getpeerinfo, true, false, false },
{ "addnode", &addnode, true, true, false },
{ "getaddednodeinfo", &getaddednodeinfo, true, true, false },
{ "ping", &ping, true, false, false },
{ "setban", &setban, true, false, false },
{ "listbanned", &listbanned, true, false, false },
{ "clearbanned", &clearbanned, true, false, false },
{ "getnettotals", &getnettotals, true, true, false },
{ "getdifficulty", &getdifficulty, true, false, false },
{ "getinfo", &getinfo, true, false, false },
{ "getrawmempool", &getrawmempool, true, false, false },
{ "getblock", &getblock, false, false, false },
{ "getblockbynumber", &getblockbynumber, false, false, false },
{ "getblockhash", &getblockhash, false, false, false },
{ "getrawtransaction", &getrawtransaction, false, false, false },
{ "createrawtransaction", &createrawtransaction, false, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false, false },
{ "decodescript", &decodescript, false, false, false },
{ "signrawtransaction", &signrawtransaction, false, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false, false },
{ "getcheckpoint", &getcheckpoint, true, false, false },
{ "sendalert", &sendalert, false, false, false },
{ "validateaddress", &validateaddress, true, false, false },
{ "validatepubkey", &validatepubkey, true, false, false },
{ "verifymessage", &verifymessage, false, false, false },
{ "searchrawtransactions", &searchrawtransactions, false, false, false },
/* Dark features */
{ "spork", &spork, true, false, false },
{ "masternode", &masternode, true, false, true },
{ "masternodelist", &masternodelist, true, false, false },
#ifdef ENABLE_WALLET
{ "darksend", &darksend, false, false, true },
{ "getmininginfo", &getmininginfo, true, false, false },
{ "getstakinginfo", &getstakinginfo, true, false, false },
{ "getnewaddress", &getnewaddress, true, false, true },
{ "getnewpubkey", &getnewpubkey, true, false, true },
{ "getaccountaddress", &getaccountaddress, true, false, true },
{ "setaccount", &setaccount, true, false, true },
{ "getaccount", &getaccount, false, false, true },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
{ "sendtoaddress", &sendtoaddress, false, false, true },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false, true },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false, true },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false, true },
{ "backupwallet", &backupwallet, true, false, true },
{ "keypoolrefill", &keypoolrefill, true, false, true },
{ "walletpassphrase", &walletpassphrase, true, false, true },
{ "walletpassphrasechange", &walletpassphrasechange, false, false, true },
{ "walletlock", &walletlock, true, false, true },
{ "encryptwallet", &encryptwallet, false, false, true },
{ "getbalance", &getbalance, false, false, true },
{ "move", &movecmd, false, false, true },
{ "sendfrom", &sendfrom, false, false, true },
{ "sendmany", &sendmany, false, false, true },
{ "addmultisigaddress", &addmultisigaddress, false, false, true },
{ "addredeemscript", &addredeemscript, false, false, true },
{ "gettransaction", &gettransaction, false, false, true },
{ "listtransactions", &listtransactions, false, false, true },
{ "listaddressgroupings", &listaddressgroupings, false, false, true },
{ "signmessage", &signmessage, false, false, true },
{ "getwork", &getwork, true, false, true },
{ "getworkex", &getworkex, true, false, true },
{ "listaccounts", &listaccounts, false, false, true },
{ "getblocktemplate", &getblocktemplate, true, false, false },
{ "submitblock", &submitblock, false, false, false },
{ "listsinceblock", &listsinceblock, false, false, true },
{ "dumpprivkey", &dumpprivkey, false, false, true },
{ "dumpwallet", &dumpwallet, true, false, true },
{ "importprivkey", &importprivkey, false, false, true },
{ "importwallet", &importwallet, false, false, true },
{ "importaddress", &importaddress, false, false, true },
{ "listunspent", &listunspent, false, false, true },
{ "settxfee", &settxfee, false, false, true },
{ "getsubsidy", &getsubsidy, true, true, false },
{ "getstakesubsidy", &getstakesubsidy, true, true, false },
{ "reservebalance", &reservebalance, false, true, true },
{ "createmultisig", &createmultisig, true, true, false },
{ "checkwallet", &checkwallet, false, true, true },
{ "repairwallet", &repairwallet, false, true, true },
{ "resendtx", &resendtx, false, true, true },
{ "makekeypair", &makekeypair, false, true, false },
{ "checkkernel", &checkkernel, true, false, true },
{ "getnewstealthaddress", &getnewstealthaddress, false, false, true },
{ "liststealthaddresses", &liststealthaddresses, false, false, true },
{ "scanforalltxns", &scanforalltxns, false, false, false },
{ "scanforstealthtxns", &scanforstealthtxns, false, false, false },
{ "importstealthaddress", &importstealthaddress, false, false, true },
{ "sendtostealthaddress", &sendtostealthaddress, false, false, true },
{ "smsgenable", &smsgenable, false, false, false },
{ "smsgdisable", &smsgdisable, false, false, false },
{ "smsglocalkeys", &smsglocalkeys, false, false, false },
{ "smsgoptions", &smsgoptions, false, false, false },
{ "smsgscanchain", &smsgscanchain, false, false, false },
{ "smsgscanbuckets", &smsgscanbuckets, false, false, false },
{ "smsgaddkey", &smsgaddkey, false, false, false },
{ "smsggetpubkey", &smsggetpubkey, false, false, false },
{ "smsgsend", &smsgsend, false, false, false },
{ "smsgsendanon", &smsgsendanon, false, false, false },
{ "smsginbox", &smsginbox, false, false, false },
{ "smsgoutbox", &smsgoutbox, false, false, false },
{ "smsgbuckets", &smsgbuckets, false, false, false },
#endif
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if (((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword())
{
unsigned char rand_pwd[32];
GetRandBytes(rand_pwd, 32);
string strWhatAmI = "To use HighTemperatured";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=ICrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"HighTemperature Alert\" admin@foo.com\n"),
strWhatAmI,
GetConfigFile().string(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32)),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl", false);
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2 | ssl::context::no_sslv3);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv3:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", Params().RPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
if (rpc_io_service == NULL) return;
deadlineTimers.clear();
rpc_io_service->stop();
if (rpc_worker_group != NULL)
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func)
{
if (!err)
func();
}
void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds)
{
assert(rpc_io_service != NULL);
if (deadlineTimers.count(name) == 0)
{
deadlineTimers.insert(make_pair(name,
boost::shared_ptr<deadline_timer>(new deadline_timer(*rpc_io_service))));
}
deadlineTimers[name]->expires_from_now(posix_time::seconds(nSeconds));
deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func));
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
LogPrint("rpc", "ThreadRPCServer method=%s\n", strMethod);
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto, MAX_SIZE);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string());
/* Deter brute-forcing short passwords.
If this results in a DoS the user really
shouldn't have their RPC port exposed. */
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
#ifdef ENABLE_WALLET
if (pcmd->reqWallet && !pwalletMain)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
#endif
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
#ifdef ENABLE_WALLET
else if (!pwalletMain) {
LOCK(cs_main);
result = pcmd->actor(params, false);
} else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
#else // ENABLE_WALLET
else {
LOCK(cs_main);
result = pcmd->actor(params, false);
}
#endif // !ENABLE_WALLET
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
std::string HelpExampleCli(string methodname, string args){
return "> HighTemperatured " + methodname + " " + args + "\n";
}
std::string HelpExampleRpc(string methodname, string args){
return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", "
"\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:9998/\n";
}
const CRPCTable tableRPC;
| [
"sarkawt909@gmail.com"
] | sarkawt909@gmail.com |
8a94110874b4c2f8c940debeccb2b4ecd1589de4 | bb014e36e83615621af5c48be1e1b346409d0339 | /covincrementhandlers.cpp | c4a4e16c1ad1edaab514c3323dd767b6c68b35b1 | [] | no_license | longcongduoi/proto-gateway | 38e3aff489a0a05979bcf225be7ef6eadba06e16 | bd20c78ede766c490fb4882263454aeae3f79520 | refs/heads/master | 2020-04-02T09:23:32.217039 | 2012-01-14T15:41:10 | 2012-01-14T15:41:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,796 | cpp | #include "covincrementhandlers.h"
#include "bacnetprimitivedata.h"
using namespace Bacnet;
template <class T, class V>
CovIncrementHandler<T, V>::CovIncrementHandler(T &covIncremenet):
_lastInformedValue(0),
_covIncrement(covIncremenet)
{
}
template <class T, class V>
CovIncrementHandler<T, V>::CovIncrementHandler():
_lastInformedValue(0)
{
_covIncrement.setValue(0);
}
template <class T, class V>
void CovIncrementHandler<T, V>::comparison_helper(V dataValue)
{
if (_lastInformedValue == dataValue)
_state = Equal;
else if ( (dataValue >= _lastInformedValue) ) {
if (_lastInformedValue + _covIncrement.value() > dataValue)
_state = EqualWithinInvrement;
else
_state = NotEqualWithinIncrement;
}
else if (dataValue <= _lastInformedValue) {
if (_lastInformedValue - _covIncrement.value() < dataValue)
_state = EqualWithinInvrement;
else
_state = NotEqualWithinIncrement;
}
//update remembered value
if (EqualWithinInvrement != _state)
_lastInformedValue = dataValue;
}
template <class T, class V>
void CovIncrementHandler<T, V>::visit(Real &data)
{
comparison_helper(data.value());
}
template <class T, class V>
void CovIncrementHandler<T, V>::visit(Double &data)
{
comparison_helper(data.value());
}
template <class T, class V>
void CovIncrementHandler<T, V>::visit(UnsignedInteger &data)
{
comparison_helper(data.value());
}
template <class T, class V>
void CovIncrementHandler<T, V>::visit(SignedInteger &data)
{
comparison_helper(data.value());
}
template <class T, class V>
void CovIncrementHandler<T, V>::visit(BacnetDataInterface &data)
{
Q_UNUSED(data);
qDebug("CovIncrementHandler<T, V>::visit(BacnetDataInterface&) always marks as not equal!");
//! \todo Or maybe we should compare qvariants?
_state = NotEqualWithinIncrement;
}
template <class T, class V>
qint32 CovIncrementHandler<T, V>::toRaw(quint8 *ptrStart, quint16 buffLength)
{
return _covIncrement.toRaw(ptrStart, buffLength);
}
template <class T, class V>
qint32 CovIncrementHandler<T, V>::toRaw(quint8 *ptrStart, quint16 buffLength, quint8 tagNumber)
{
return _covIncrement.toRaw(ptrStart, buffLength, tagNumber);
}
template <class T, class V>
qint32 CovIncrementHandler<T, V>::fromRaw(BacnetTagParser &parser)
{
return _covIncrement.fromRaw(parser);
}
template <class T, class V>
qint32 CovIncrementHandler<T, V>::fromRaw(BacnetTagParser &parser, quint8 tagNum)
{
return _covIncrement.fromRaw(parser, tagNum);
}
namespace Bacnet {//otherwise compilator complains there are specializations in a differenet namespace
template <class T, class V>
BacnetDataInterface *CovIncrementHandler<T, V>::createValue()
{
return new T(_covIncrement);
}
template <>
void CovIncrementHandler<Real, float>::visit(BacnetDataInterface &data)
{
QVariant dataValue = data.toInternal();
if (dataValue.canConvert(QVariant::Double)) {
bool ok;
float value = dataValue.toDouble(&ok);
Q_ASSERT(ok);
if (ok)
comparison_helper(value);
}
}
template <>
void CovIncrementHandler<Real, float>::visit(BacnetArray &data)
{
BacnetDataInterface *d = &data;
visit(*d);
}
template <class T, class V>
V CovIncrementHandler<T, V>::incrementValue()
{
return _covIncrement.value();
}
template <class T, class V>
void CovIncrementHandler<T, V>::setIncrementValue(V &covIncrement)
{
_covIncrement.setValue(covIncrement);
}
//template <>
//void CovIncrementHandler<double>::visit(BacnetDataInterface &data)
//{
// QVariant dataValue = data.toInternal();
// if (dataValue.canConvert(QVariant::Double)) {
// bool ok;
// double value = dataValue.toDouble(&ok);
// Q_ASSERT(ok);
// if (ok)
// comparison_helper(value);
// }
//}
//template <>
//void CovIncrementHandler<qint32>::visit(BacnetDataInterface &data)
//{
// QVariant dataValue = data.toInternal();
// if (dataValue.canConvert(QVariant::Int)) {
// bool ok;
// qint32 value = dataValue.toInt(&ok);
// Q_ASSERT(ok);
// if (ok)
// comparison_helper(value);
// }
//}
//template <>
//void CovIncrementHandler<quint32>::visit(BacnetDataInterface &data)
//{
// QVariant dataValue = data.toInternal();
// if (dataValue.canConvert(QVariant::Int)) {
// bool ok;
// quint32 value = dataValue.toInt(&ok);
// Q_ASSERT(ok);
// if (ok)
// comparison_helper(value);
// }
//}
}
////avoiding linking problems
template class CovIncrementHandler<Real, float>;
//template class CovIncrementHandler<double>;
//template class CovIncrementHandler<quint32>;
//template class CovIncrementHandler<qint32>;
| [
"krzysztow@gmail.com"
] | krzysztow@gmail.com |
8b3fe692f3a5e28869b762b1955d3c156adfe741 | 04c34025056a04c0c00f6c9c68061c84255d52b0 | /ch09/ex9_25.cpp | ae870e9fb8bd3101dbd35c68f7b577a9a1011cb3 | [] | no_license | AndroidHot/CppPrimer5 | 692af33f0cccca7b0f287e5b2755be50f2c92e9f | 6e0abd517e47913e726dbe80222738859d7a7e32 | refs/heads/master | 2021-06-26T15:53:21.259818 | 2021-01-30T02:34:56 | 2021-01-30T02:34:56 | 172,219,386 | 0 | 0 | null | 2020-10-24T09:02:26 | 2019-02-23T13:47:01 | C++ | UTF-8 | C++ | false | false | 575 | cpp | #include <iostream>
#include <list>
using std::list;
using std::cout;
using std::endl;
int main(int argc, char const *argv[])
{
list<int> values{1, 2, 3, 4};
values.erase(values.begin(), values.begin()); // if elem1 and elem2 are equal, nothing happened.
values.erase(values.end(), values.end()); // if elem1 and elem2 are equal, nothing happened.
values.erase(++values.begin(), values.end()); // if elem2 is the off-the-end iterator, it would delete from elem1 to the end.
for (auto i : values)
{
cout << i << " ";
}
return 0;
}
| [
"zhiwei.dev@gmail.com"
] | zhiwei.dev@gmail.com |
9dc47b764f3572a9fc59077f176b7bd300bae0ca | ceeea0d53535379db82373d4acf263dd98048065 | /util.h | 477518a214e006a79cc237f455fc86ff85f201ec | [
"MIT"
] | permissive | zwjnju/SystermMonitor | 6772e3ed0dde0ea48abff07cc8b58225d5ca11ec | 5833fb3dd8910fe346a75e0b4af44d9abdf4493d | refs/heads/master | 2020-06-21T21:37:43.993743 | 2019-08-08T13:54:47 | 2019-08-08T13:54:47 | 197,558,170 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,677 | h | #include <string>
#include <fstream>
// Classic helper function
class Util {
public:
static std::string convertToTime ( long int input_seconds );
static std::string getProgressBar(std::string percent);
//static void getStream(std::string path, std::ifstream& stream);
static std::ifstream getStream(std::string path);
};
std::string Util::convertToTime (long int input_seconds){
long minutes = input_seconds / 60;
long hours = minutes / 60;
long seconds = int(input_seconds%60);
minutes = int(minutes%60);
std::string result = std::to_string(hours) + ":" + std::to_string(minutes) + ":" + std::to_string(seconds);
return result;
}
// constructing string for given percentage
// 50 bars is uniformly streched 0 - 100 %
// meaning: every 2% is one bar(|)
std::string Util::getProgressBar(std::string percent){
std::string result = "0%% ";
int _size= 50;
int boundaries;
try {
boundaries = (stof(percent)/100)*_size;
} catch (...){
boundaries = 0;
}
for(int i=0;i<_size;i++){
if(i<=boundaries){
result +="|";
}
else{
result +=" ";
}
}
result +=" " + percent.substr(0,5) + " /100%%";
return result;
}
/*// wrapper for creating streams
void Util::getStream(std::string path, std::ifstream& stream){
stream.open (path, std::ifstream::in);
if (!stream && !stream.is_open()){
stream.close();
throw std::runtime_error("Non - existing PID");
}
//return stream;
}*/
std::ifstream Util::getStream(std::string path) {
std::ifstream stream(path);
if(!stream) {
throw std::runtime_error("Non existing pid");
}
return stream;
}
| [
"356533459@qq.com"
] | 356533459@qq.com |
9d6a89d6a9607f29cd6f3edcdfd1e189f4a85c60 | b5e00c7392791f982cc5a26d588d5ffc5cf9eb74 | /Breakout/Shader.cpp | bfbc4df8a5e6bbdd9b10e2e93f7278f4f7e8c8ac | [] | no_license | Gareton/OpenGL_Learning | 24643a4a2066158af16ed891dd54067fae8f8384 | eeb8086af2006e42a684c3f5a6e429963d1ffb55 | refs/heads/master | 2020-06-16T01:50:03.271263 | 2019-07-20T14:02:12 | 2019-07-20T14:02:12 | 195,448,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,922 | cpp | #include "Shader.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
Shader &Shader::Use()
{
glUseProgram(ID);
return *this;
}
void Shader::Compile(const GLchar *vertexSource, const GLchar *fragmentSource, const GLchar *geometrySource)
{
GLuint vShader, fShader, gShader;
vShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vShader, 1, &vertexSource, nullptr);
glCompileShader(vShader);
checkCompileErrors(vShader, "VERTEX");
fShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fShader, 1, &fragmentSource, nullptr);
glCompileShader(fShader);
checkCompileErrors(fShader, "FRAGMENT");
if (geometrySource != nullptr)
{
gShader = glCreateShader(GL_GEOMETRY_SHADER);
glShaderSource(gShader, 1, &geometrySource, nullptr);
glCompileShader(gShader);
checkCompileErrors(gShader, "GEOMETRY");
}
ID = glCreateProgram();
glAttachShader(ID, vShader);
glAttachShader(ID, fShader);
if(geometrySource != nullptr)
glAttachShader(ID, gShader);
glLinkProgram(ID);
checkCompileErrors(ID, "PROGRAM");
glDeleteShader(vShader);
glDeleteShader(fShader);
if (geometrySource != nullptr)
glDeleteShader(gShader);
}
void Shader::SetFloat(const GLchar *name, GLfloat value, GLboolean useShader)
{
if (useShader)
this->Use();
glUniform1f(glGetUniformLocation(ID, name), value);
}
void Shader::SetInteger(const GLchar *name, GLint value, GLboolean useShader)
{
if (useShader)
this->Use();
glUniform1i(glGetUniformLocation(ID, name), value);
}
void Shader::SetVector2f(const GLchar *name, GLfloat x, GLfloat y, GLboolean useShader)
{
if (useShader)
this->Use();
glUniform2f(glGetUniformLocation(ID, name), x, y);
}
void Shader::SetVector2f(const GLchar *name, const glm::vec2 &value, GLboolean useShader)
{
if (useShader)
this->Use();
glUniform2f(glGetUniformLocation(ID, name), value.x, value.y);
}
void Shader::SetVector3f(const GLchar *name, GLfloat x, GLfloat y, GLfloat z, GLboolean useShader)
{
if (useShader)
this->Use();
glUniform3f(glGetUniformLocation(ID, name), x, y, z);
}
void Shader::SetVector3f(const GLchar *name, const glm::vec3 &value, GLboolean useShader)
{
if (useShader)
this->Use();
glUniform3f(glGetUniformLocation(ID, name), value.x, value.y, value.z);
}
void Shader::SetVector4f(const GLchar *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w, GLboolean useShader)
{
if (useShader)
this->Use();
glUniform4f(glGetUniformLocation(ID, name), x, y, z, w);
}
void Shader::SetVector4f(const GLchar *name, const glm::vec4 &value, GLboolean useShader)
{
if (useShader)
this->Use();
glUniform4f(glGetUniformLocation(ID, name), value.x, value.y, value.z, value.w);
}
void Shader::SetMatrix4(const GLchar *name, const glm::mat4 &matrix, GLboolean useShader)
{
if (useShader)
this->Use();
glUniformMatrix4fv(glGetUniformLocation(ID, name), 1, GL_FALSE, glm::value_ptr(matrix));
}
GLuint Shader::GetID() const
{
return ID;
}
void Shader::checkCompileErrors(GLuint object, std::string type)
{
GLint success;
GLchar infoLog[1024];
if (type != "PROGRAM")
{
glGetShaderiv(object, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(object, 1024, NULL, infoLog);
std::cout << "| ERROR::SHADER: Compile-time error: Type: " << type << "\n"
<< infoLog << "\n -- --------------------------------------------------- -- "
<< std::endl;
}
}
else
{
glGetProgramiv(object, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(object, 1024, NULL, infoLog);
std::cout << "| ERROR::Shader: Link-time error: Type: " << type << "\n"
<< infoLog << "\n -- --------------------------------------------------- -- "
<< std::endl;
}
}
} | [
"fghftftrdrrdrdrdr65656hj56h@gmail.com"
] | fghftftrdrrdrdrdr65656hj56h@gmail.com |
a7c38c0f6d47655afdeebeaecec418e9d51b861f | ca7582b54871df2eaec79d591e1acd576aac54ba | /win32/srkbitmap.h | 6bbc5330f29b1ca920b62d3b931d05de9c1a46a6 | [] | no_license | matiasinsaurralde/sonork | 5da948610d7cccb58ba1a9e056bc049f8fa6c8d3 | 25514411bca36368fc2719b6fb8ab1367e1bb218 | refs/heads/master | 2021-01-20T18:01:59.504044 | 2016-06-17T01:03:44 | 2016-06-17T01:03:44 | 61,335,900 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,525 | h | #if !defined(SRKBITMAP_H)
#define SRKBITMAP_H
/*
Sonork Messaging System
Portions Copyright (C) 2001 Sonork SRL:
This program is free software; you can redistribute it and/or modify
it under the terms of the Sonork Source Code License (SSCL).
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
SSCL for more details.
You should have received a copy of the SSCL along with this program;
if not, write to sscl@sonork.com.
You may NOT use this source code before reading and accepting the
Sonork Source Code License (SSCL).
*/
class TSonorkBitmap
{
HDC dc;
HBITMAP bm,saved_dc_bm;
SIZE size;
void
DeleteBM();
public:
TSonorkBitmap();
~TSonorkBitmap();
HDC
DC() const
{ return dc; }
HBITMAP
Bitmap() const
{ return bm; }
const SIZE&
Size() const
{ return size;}
BOOL
Loaded() const
{ return bm!=NULL;}
BOOL
Initialized() const
{ return dc!=NULL;}
BOOL
InitHwnd(HWND);
BOOL
InitDc(HDC);
BOOL
LoadFile( SONORK_C_CSTR pFileName , DWORD cx, DWORD cy);
BOOL
Copy(HDC sDC, const RECT& rect);
BOOL
Copy(const TSonorkBitmap&);
BOOL
Transfer(TSonorkBitmap&);
BOOL
CreateBlank(DWORD cx, DWORD cy, HBRUSH init_brush);
BOOL
Save( SONORK_C_CSTR pFileName );
BOOL
BitBlt(HDC tDC, int tx, int ty, UINT op=SRCCOPY);
};
#endif
| [
"matias@insaurral.de"
] | matias@insaurral.de |
e5e6c2ce6ac6cb378f3b0659400cbd903ec08082 | 11eea8da1b414871e0f8608dd61ee543e81b4b19 | /P1803.cpp | b552b891709fb771548775c74e95854e2b9e0d15 | [] | no_license | Tomistong/MyLuoguRepo | 57ed57ad504978f7402bd1bbeba30b2f4ae32a22 | 5dfe5e99b0909f9fe5416d5eaad01f368a2bf891 | refs/heads/master | 2023-08-29T05:18:29.981970 | 2021-10-06T04:23:02 | 2021-10-06T04:23:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | cpp | #include <algorithm>
#include <cstdio>
#include <iostream>
using namespace std;
int sssz = 0;
struct ak {
int begin;
int end;
};
bool cmp(ak ioi, ak noi) { return ioi.end <= noi.end; }
int main() {
ak NOIP[100001];
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
cin >> NOIP[i].begin >> NOIP[i].end;
}
int ans = 0;
sort(NOIP, NOIP + n, cmp);
for (int i = 0; i < n; i++) {
if(sssz<=NOIP[i].begin){
ans++;
sssz = NOIP[i].end;
}
}
printf("%d",ans);
return 0;
} | [
"wumingyun2120@outlook.com"
] | wumingyun2120@outlook.com |
99357c7a7635fc35c65cd29c7aed08f89a5c4d3e | 97ce565e0720d326ba839c465b7b082377c3c199 | /lingao_bringup/include/flat_world_odom_node.h | e7b400e11a4a4458927df2b86b2b64bfc9f9b238 | [] | no_license | jkhou/UGV_ps4_control | a0cc95e62c30c77c4380bfa0d070042de8577f4c | 62a14caf1f94d6b8b3a3d32a0da15e20ae98c5bb | refs/heads/master | 2023-03-21T14:44:10.935472 | 2021-03-04T13:40:46 | 2021-03-04T13:40:46 | 344,472,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,187 | h | /*******************************************************************************
* Copyright 2018 ROBOTIS 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.
*******************************************************************************/
#ifndef FLAT_WORLD_ODOM_NODE_H_
#define FLAT_WORLD_ODOM_NODE_H_
#include <ros/ros.h>
#include <nav_msgs/Odometry.h>
class FlatWorldOdomNode
{
public:
FlatWorldOdomNode();
~FlatWorldOdomNode();
bool init();
private:
ros::NodeHandle nh_;
ros::Time last_published_time_;
ros::Publisher publisher_;
ros::Subscriber subscriber_;
void msgCallback(const nav_msgs::Odometry::ConstPtr odom_in);
};
#endif // FLAT_WORLD_IMU_NODE_H_ | [
"cquhjk@126.com"
] | cquhjk@126.com |
63e3254aaf4e2253640a4815a73db07843bd707a | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_patch_hunk_1044.cpp | d40a65c8ddaf674035c6a3045381527eef7dec3f | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,189 | cpp | if (head && !strcmp(ref->refname, head))
v->s = "*";
else
v->s = " ";
continue;
} else if (starts_with(name, "align")) {
- v->u.align = atom->u.align;
v->handler = align_atom_handler;
continue;
} else if (!strcmp(name, "end")) {
v->handler = end_atom_handler;
continue;
+ } else if (starts_with(name, "if")) {
+ const char *s;
+
+ if (skip_prefix(name, "if:", &s))
+ v->s = xstrdup(s);
+ v->handler = if_atom_handler;
+ continue;
+ } else if (!strcmp(name, "then")) {
+ v->handler = then_atom_handler;
+ continue;
+ } else if (!strcmp(name, "else")) {
+ v->handler = else_atom_handler;
+ continue;
} else
continue;
- formatp = strchr(name, ':');
- if (formatp) {
- const char *arg;
-
- formatp++;
- if (!strcmp(formatp, "short"))
- refname = shorten_unambiguous_ref(refname,
- warn_ambiguous_refs);
- else if (skip_prefix(formatp, "strip=", &arg))
- refname = strip_ref_components(refname, arg);
- else
- die(_("unknown %.*s format %s"),
- (int)(formatp - name), name, formatp);
- }
-
if (!deref)
v->s = refname;
else
v->s = xstrfmt("%s^{}", refname);
}
| [
"993273596@qq.com"
] | 993273596@qq.com |
74ad1d61fbc35bc6bdf9cb5a9636d730d599993b | 8b015bb56a29d2a9c5e6b0a286942291f64dc7cd | /libcaf_core/src/work_stealing.cpp | 87dcbdd8f70c3a37d4a21c9b49418d0772bf37bd | [
"BSL-1.0"
] | permissive | novaquark/actor-framework | 8c76b31618cf6d716674764492444790f2588015 | 08185596403b843a5fa50b56c22d2b2f2771b787 | refs/heads/master | 2021-06-01T12:27:33.206944 | 2017-12-11T09:23:43 | 2017-12-11T09:23:43 | 114,116,423 | 1 | 0 | NOASSERTION | 2019-05-15T12:24:41 | 2017-12-13T12:10:22 | C++ | UTF-8 | C++ | false | false | 1,606 | cpp | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/policy/work_stealing.hpp"
namespace caf {
namespace policy {
work_stealing::~work_stealing() {
// nop
}
} // namespace policy
} // namespace caf
| [
"dominik.charousset@haw-hamburg.de"
] | dominik.charousset@haw-hamburg.de |
b3c44e422dff36e3c4f5d4ffc7917be2350ad454 | 9440caccc16e90111775d1bf3b8f640217b6149b | /src/ExtractPartitions.cpp | f6b70f620e7139055b67c27a3ae07212df3ca1b4 | [] | no_license | dockratx/Recursive-Interlocking-3D-Puzzles | 4087bfe4fbb60d984715f882c7862a03e6c81bba | c424f5ee2d85d46e9995b73d9c062fbf0c08cebc | refs/heads/master | 2022-01-18T07:57:18.746659 | 2018-05-01T17:21:46 | 2018-05-01T17:21:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 73,529 | cpp | /**
CS591-W1 Final Project
ExtractPartitions.cpp
Purpose: For generating the partitions of a given voxel list
@author Ben Gaudiosi
@version 1.0 5/01/2018
*/
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <list>
#include <limits>
#include "../include/ExtractPartitions.h"
#include "../include/CompFab.h"
bool debug = false;
/**
Blank constructor for the Voxel class. Generates a voxel at the origin.
*/
Voxel::Voxel() {
x = 0;
y = 0;
z = 0;
}
/**
Constructor for the Voxel class.
@param x The x coordinate of the voxel.
@param y The y coordinate of the voxel.
@param z The z coordinate of the voxel.
*/
Voxel::Voxel(int x_val, int y_val, int z_val) {
x = x_val;
y = y_val;
z = z_val;
}
/**
Constructor for the VoxelPair class.
@param blockerVox The blocker voxel.
@param blockerScore The accessibility score of the blocker voxel.
@param blockeeVox The blockee voxel.
@param blockeeScore The accessibility score of the blockee voxel.
*/
VoxelPair::VoxelPair(Voxel blockerVox, double blockerScore, Voxel blockeeVox, double blockeeScore) {
blocker = blockerVox;
blocker_accessibility = blockerScore;
blockee = blockeeVox;
blockee_accessibility = blockeeScore;
}
/**
Constructor for the VoxelSort class.
@param vox The voxel to be sorted.
@param totalScore The score of the voxel in this class.
*/
VoxelSort::VoxelSort(Voxel vox, double totalScore) {
voxel = vox;
score = totalScore;
}
/**
String representation of the voxel class.
@return A human readable string of a voxel as (x, y, z).
*/
std::string Voxel::toString() {
std::string vox("(" + std::to_string(x) + "," + std::to_string(y) + "," + std::to_string(z) + ")");
return vox;
}
/**
String representation of the VoxelPair class.
@return A human readable string of a VoxelPair as (x1, y1, z1): score, (x2, y2, z2): score
*/
std::string VoxelPair::toString() {
return "(" + blocker.toString() + ":" + std::to_string(blocker_accessibility) + " ," + blockee.toString() + ": " + std::to_string(blockee_accessibility) + ")";
}
/**
Constructor for the AccessibilityStruct class.
@param lowerLeft A vector representing the lower left voxel in the grid. Usually is (0,0,0).
@param dimX The dimension of x.
@param dimY The dimension of y.
@param dimZ The dimension of z.
*/
AccessibilityStruct::AccessibilityStruct(CompFab::Vec3 lowerLeft, unsigned int dimX, unsigned int dimY, unsigned int dimZ) {
m_lowerLeft = lowerLeft;
m_dimX = dimX;
m_dimY = dimY;
m_dimZ = dimZ;
m_size = dimX*dimY*dimZ;
m_scoreArray = new double[m_size];
for(unsigned int i=0; i<m_size; ++i)
{
m_scoreArray[i] = 0.0;
}
}
/**
Destructor for the AccessibilityStruct class.
*/
AccessibilityStruct::~AccessibilityStruct()
{
delete[] m_scoreArray;
}
/**
Prints a list of voxels.
@param list The list of voxels to be printed.
*/
void printList(std::vector<Voxel> list) {
for (int i = 0; i < list.size(); i++) {
std::cout << "\t\t" << list[i].toString() << std::endl;
}
}
/**
Finds seeds for the key piece to start from.
@param voxel_list A VoxelGrid from which to generate the puzzle.
@return A list of potential seeds for the key piece
*/
std::vector<Voxel> findSeeds( CompFab::VoxelGrid * voxel_list ) {
std::vector<Voxel> seeds;
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int above = 0;
int one_side_adjacent;
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
for (int k = 0; k < nz; k++) {
if (voxel_list->isInside(i,j,k) == 1) {
// First check if any voxels above
for (int z = k+1 ; z < nz; z++) {
if (voxel_list->isInside(i,j,z) == 1) {
above = 1;
break;
}
}
if (above) {
above = 0;
continue;
}
//Now, check that only two other faces are open and (except bottom)
one_side_adjacent = 0;
if ( i != 0 ) {
if (voxel_list->isInside(i-1,j,k) == 1) {
one_side_adjacent++;
}
}
if ( i != nx-1 ) {
if (voxel_list->isInside(i+1,j,k) == 1) {
one_side_adjacent++;
}
}
if (j != 0) {
if (voxel_list->isInside(i,j-1,k) == 1) {
one_side_adjacent++;
}
}
if (j != ny-1) {
if (voxel_list->isInside(i,j+1,k) == 1) {
one_side_adjacent++;
}
}
if (one_side_adjacent == 3) {
seeds.push_back(Voxel(i, j, k));
}
}
}
}
}
return seeds;
}
/**
Finds the neighbors of a voxel.
@param voxel The voxel from which to find neighbors.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@return The neighbors of the voxel.
*/
std::vector<Voxel> getNeighbors(Voxel voxel, CompFab::VoxelGrid * voxel_list, int pieceId) {
std::vector<Voxel> neighbors;
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
if ( voxel.x != 0 ) {
if (voxel_list->isInside(voxel.x-1,voxel.y,voxel.z) == pieceId) {
neighbors.push_back(Voxel(voxel.x-1,voxel.y,voxel.z));
}
}
if ( voxel.x != nx-1 ) {
if (voxel_list->isInside(voxel.x+1,voxel.y,voxel.z) == pieceId) {
neighbors.push_back(Voxel(voxel.x+1,voxel.y,voxel.z));
}
}
if (voxel.y != 0) {
if (voxel_list->isInside(voxel.x,voxel.y-1,voxel.z) == pieceId) {
neighbors.push_back(Voxel(voxel.x,voxel.y-1,voxel.z));
}
}
if (voxel.y != ny-1) {
if (voxel_list->isInside(voxel.x,voxel.y+1,voxel.z) == pieceId) {
neighbors.push_back(Voxel(voxel.x,voxel.y+1,voxel.z));
}
}
if (voxel.z != 0) {
if (voxel_list->isInside(voxel.x,voxel.y,voxel.z-1) == pieceId) {
neighbors.push_back(Voxel(voxel.x,voxel.y,voxel.z-1));
}
}
if (voxel.z != nz-1) {
if (voxel_list->isInside(voxel.x,voxel.y,voxel.z+1) == pieceId) {
neighbors.push_back(Voxel(voxel.x,voxel.y,voxel.z+1));
}
}
return neighbors;
}
/**
Finds the accessibility scores of a VoxelGrid.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param alpha A double used as a param for how to generate the scores.
@param recurse How many layers of recursion to perform in score generation.
@param pieceId The id of the piece we are scoring. Is usually 1.
@return The accessiblity scores of each voxel in the form of an AccessibilityGrid.
*/
AccessibilityGrid * accessibilityScores( CompFab::VoxelGrid * voxel_list, double alpha, unsigned int recurse, int pieceId) {
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
CompFab::Vec3 start = CompFab::Vec3(0.0, 0.0, 0.0);
AccessibilityGrid * scores = new AccessibilityGrid(start, nx, ny, nz);
if (recurse == 0) {
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
for (int k = 0; k < nz; k++) {
scores->score(i, j, k) = getNeighbors(Voxel(i, j, k), voxel_list, pieceId).size();
}
}
}
} else {
double current_score;
double multiplier = pow(alpha, recurse);
std::vector<Voxel> neighbors;
AccessibilityGrid * old_scores = accessibilityScores( voxel_list, alpha, recurse-1, pieceId);
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
for (int k = 0; k < nz; k++) {
neighbors = getNeighbors(Voxel(i, j, k), voxel_list, pieceId);
current_score = 0;
for (int n = 0; n < neighbors.size(); n++) {
current_score += old_scores->score(neighbors[n].x, neighbors[n].y, neighbors[n].z);
}
current_score *= multiplier;
current_score += old_scores->score(i,j,k);
scores->score(i,j,k) = current_score;
}
}
}
}
return scores;
}
/**
Finds the direction of the exposed face of the key piece that isn't bad_normal.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param voxel The seed voxel.
@param bad_normal The direction which the key is going to be removed from.
@return The direction of the exposed face of the piece that isn't bad_normal.
*/
Voxel findNormal( CompFab::VoxelGrid * voxel_list, Voxel voxel, Voxel bad_normal) {
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
if ( bad_normal.x != -1 ) {
if (voxel.x == 0 || voxel_list->isInside(voxel.x-1,voxel.y,voxel.z) != 1) {
return Voxel(-1, 0, 0);
}
}
if ( bad_normal.x != 1 ) {
if (voxel.x == nx-1 || voxel_list->isInside(voxel.x+1,voxel.y,voxel.z) != 1) {
return Voxel(1, 0, 0);
}
}
if ( bad_normal.y != -1) {
if (voxel.y == 0 || voxel_list->isInside(voxel.x,voxel.y-1,voxel.z) != 1) {
return Voxel(0, -1, 0);
}
}
if ( bad_normal.y != 1) {
if (voxel.y == ny-1 || voxel_list->isInside(voxel.x,voxel.y+1,voxel.z) != 1) {
return Voxel(0, 1, 0);
}
}
if ( bad_normal.z != -1) {
if (voxel.z == 0 || voxel_list->isInside(voxel.x,voxel.y,voxel.z-1) != 1) {
return Voxel(0, 0, -1);
}
}
if ( bad_normal.z != 1) {
if (voxel.z == nz-1 || voxel_list->isInside(voxel.x,voxel.y,voxel.z+1) != 1) {
return Voxel(0, 0, 1);
}
}
std::cout << "error" << std::endl;
return Voxel(0,0,0);
}
/**
A sorting function for std::sort for the VoxelPair class.
@param i One of the VoxelPair being compared.
@param j One of the VoxelPair being compared.
@return true if i's blockee has a lower accessibility score than j's, false otherwise.
*/
bool accessSort(VoxelPair i, VoxelPair j) { return (i.blockee_accessibility < j.blockee_accessibility); }
/**
Performs breadth first search to find potential voxels to block removal in the specified direction.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param scores An AccessibilityStruct representing the current accesibility scores of the puzzle.
@param seed The seed voxel for the key piece.
@param bad_normal The direction which is being blocked.
@param nb_one The limit of VoxelPairs to find to block removal.
@param nb_two How many VoxelPairs to return after a sorting.
@return The top nb_two VoxelPairs to block removal in direction bad_direction.
*/
std::vector<VoxelPair> bfs(CompFab::VoxelGrid * voxel_list, AccessibilityGrid * scores, Voxel seed, Voxel bad_normal, int nb_one, int nb_two) {
std::vector<VoxelPair> potentials;
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
Voxel normal = findNormal(voxel_list, seed, bad_normal);
// Mark all the vertices as not visited
bool *visited = new bool[size];
for(unsigned int i=0; i<size; ++i) {
visited[i] = false;
}
// Create a queue for BFS
std::list<Voxel> queue;
std::vector<Voxel> neighbors;
Voxel blockee;
Voxel blocker;
//Mark the current node as visited and enqueue it
visited[seed.z*(nx*ny) + seed.y*ny + seed.x] = true;
queue.push_back(seed);
int count = 0;
while (!queue.empty() && potentials.size() < nb_one) {
count++;
blockee = queue.front();
blocker = blockee + normal;
if (blocker.x < 0 || blocker.x >= nx || blocker.y < 0 || blocker.y >= ny || blocker.z < 0 || blocker.z >= nz) {
;
} else if (voxel_list->isInside(blocker.x, blocker.y, blocker.z) == 1 && blocker != seed) {
potentials.push_back(VoxelPair(blocker, scores->score(blocker.x, blocker.y, blocker.z), blockee, scores->score(blockee.x, blockee.y, blockee.z)));
}
queue.pop_front();
neighbors = getNeighbors(blockee, voxel_list, 1);
for (int i = 0; i < neighbors.size(); i++) {
if ( !visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] ) {
visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] = true;
queue.push_back(neighbors[i]);
}
}
}
if (debug) {
std::cout << "in bfs, went through: " << count << std::endl;
}
std::sort (potentials.begin(), potentials.end(), accessSort);
std::vector<VoxelPair> accessible;
for (int i = 0; i< potentials.size() && i < nb_two; i++) {
accessible.push_back(potentials[i]);
}
delete[] visited;
return accessible;
}
/**
Uses breadth first search to find the shortest path from the seed to the blockee voxel specficied.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param seed The seed voxel from which the search starts.
@param goal The VoxelPair who's blockee voxel we're searching for.
@param anchors A list of forbidden voxels to ensure interlocking.
@param direction The direction which the piece is being removed.
@return The shortest path from seed to goal.blockee including all other pieces that must be included to ensure removability.
*/
std::vector<Voxel> shortestPath(CompFab::VoxelGrid * voxel_list, Voxel seed, VoxelPair goal, std::vector<Voxel> anchors, Voxel direction) {
if (debug) {
std::cout << "in shortestPath" << std::endl;
std::cout << "the seed is " << seed.toString() << std::endl;
std::cout << "the goal is" << goal.toString() << std::endl;
std::cout << "\tdirection of removal is " << direction.toString() << std::endl;
}
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
std::vector<Voxel> path;
// Mark all the vertices as not visited
bool *visited = new bool[size];
for(unsigned int i=0; i<size; ++i) {
visited[i] = false;
}
// Create a queue for BFS
std::list<std::vector<Voxel>> queue;
std::vector<Voxel> neighbors;
Voxel blockee = goal.blockee; // find the blockee
Voxel blocker = goal.blocker; // don't go under or through blocker
std::vector<Voxel> current;
//Mark the current node as visited and enqueue it
visited[seed.z*(nx*ny) + seed.y*ny + seed.x] = true;
path.push_back(seed);
queue.push_back(path);
std::vector<Voxel> final_path;
std::vector<Voxel> shortest_path;
// Add blocker and all things below it to visited
// generalize??
Voxel end = blocker;
Voxel neg_dir(direction.x*-1, direction.y*-1, direction.z*-1);
while (end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz) {
if (debug) {
std::cout << "\tsetting " << end.toString() << " to visited" <<std::endl;
}
visited[end.z*(nx*ny) + end.y*ny + end.x] = true;
end += neg_dir;
}
// add anchors
// ok so this is an issue, adding everything below anchors instead of general
for (int i = 0; i < anchors.size(); i++) {
end = anchors[i];
while (end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz) {
visited[end.z*(nx*ny) + end.y*ny + end.x] = true;
end += neg_dir;
}
}
int count = 0;
while ( !queue.empty() ) {
count++;
current = queue.front();
if (current.back() == blockee) {
shortest_path = current;
break;
}
queue.pop_front();
neighbors = getNeighbors(current.back(), voxel_list, 1);
if (debug) {
std::cout << "neighbors of " << current.back().toString() << ": " << std::endl;
printList(neighbors);
}
for (int i = 0; i < neighbors.size(); i++) {
if ( !visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] ) {
visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] = true;
std::vector<Voxel> new_path = current;
new_path.push_back(neighbors[i]);
queue.push_back(new_path);
}
}
}
if (debug) {
std::cout << "initial path is" << std::endl;
printList(shortest_path);
}
// add things in the direction
for (int i = 0; i < shortest_path.size(); i++) {
end = Voxel(shortest_path[i].x, shortest_path[i].y, shortest_path[i].z);
final_path.push_back(end);
end += direction;
while (end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz) {
if ( voxel_list->isInside(end.x, end.y, end.z) == 1 /*&& !visited[end.z*(nx*ny) + ny*end.y + end.x] */) {
final_path.push_back(end);
}
end += direction;
}
}
if (debug) {
std::cout << "final path:" << std::endl;
printList(final_path);
}
// Now... make sure that piece is connected after adding things. Otherwise need more path finding.
//final_path = ensurePieceConnectivity(voxel_list, final_path, direction);
delete[] visited;
return final_path;
}
/**
Finds the anchor voxels for the key piece.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param seed The chosen seed voxel.
@param normal_one The direction from which the piece is exposed, though cannot be removed.
@param normal_two The direction from which the piece is being removed.
@return A list of forbidden anchor voxels which search algorithms should not be allowed to access.
*/
std::vector<Voxel> findAnchors(CompFab::VoxelGrid * voxel_list, Voxel seed, Voxel normal_one, Voxel normal_two) {
std::vector<Voxel> anchors;
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
if ( normal_one.x != -1 && normal_two.x != -1) {
for (int i = 0; i < seed.x; i++) {
if (voxel_list->isInside(i, seed.y, seed.z) == 1) {
//check connectivity
anchors.push_back(Voxel(i, seed.y, seed.z));
break;
}
}
}
if ( normal_one.x != 1 && normal_two.x != 1) {
for (int i = nx-1; i > seed.x; i--) {
if (voxel_list->isInside(i, seed.y, seed.z) == 1) {
//check connectivity
anchors.push_back(Voxel(i, seed.y, seed.z));
break;
}
}
}
if ( normal_one.y != -1 && normal_two.y != -1) {
for (int i = 0; i < seed.y; i++) {
if (voxel_list->isInside(seed.x, i, seed.z) == 1) {
//check connectivity
anchors.push_back(Voxel(seed.x, i, seed.z));
break;
}
}
}
if ( normal_one.y != 1 && normal_two.y != 1) {
for (int i = ny-1; i > seed.y; i--) {
if (voxel_list->isInside(seed.x, i, seed.z) == 1) {
//check connectivity
anchors.push_back(Voxel(seed.x, i, seed.z));
break;
}
}
}
if ( normal_one.z != -1 && normal_two.z != -1) {
for (int i = 0; i < seed.z; i++) {
if (voxel_list->isInside(seed.x, seed.y, i) == 1) {
//check connectivity
anchors.push_back(Voxel(seed.x, seed.y, i));
break;
}
}
}
if ( normal_one.z != 1 && normal_two.z != 1) {
for (int i = nz-1; i > seed.z; i--) {
if (voxel_list->isInside(seed.x, seed.y, i) == 1) {
//check connectivity
anchors.push_back(Voxel(seed.x, seed.y, i));
break;
}
}
}
return anchors;
}
/**
Takes possible routes to block the key in direction normal_one and chooses the best.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param scores An AccessibilityStruct representing the current accesibility scores of the puzzle.
@param seed The chosen seed of the key.
@param candidates Potential VoxelPairs to block the key.
@param normal_one The direction from which to block the key.
@param normal_two The direction from which the piece will be removed.
@param index An integer pointer which gets set to the index of the chosen candidate.
@return The path from the seed to the chosen VoxelPair blockee, which is now the key.
*/
std::vector<Voxel> filterKey(CompFab::VoxelGrid * voxel_list, AccessibilityGrid * scores, Voxel seed,
std::vector<VoxelPair> candidates, Voxel normal_one, Voxel normal_two, int * index) {
if (debug) {
std::cout << "in filterKey" << std::endl;
}
std::vector<Voxel> chosen_path;
std::vector<Voxel> path;
std::vector<Voxel> anchors = findAnchors(voxel_list, seed, normal_one, normal_two);
double sum;
double max_score = std::numeric_limits<double>::max();
for (int i = 0; i<candidates.size(); i++) {
if (debug) {
std::cout << "finding path to " << candidates[i].blockee.toString() << ", blocker is " << candidates[i].blocker.toString() << std::endl;
}
path = shortestPath(voxel_list, seed, candidates[i], anchors, Voxel(0, 0, 1));
sum = 0;
for (int j = 0; j < path.size(); j++) {
sum += scores->score(path[j].x, path[j].y, path[j].z);
}
if (sum < max_score && sum > 0) {
chosen_path = path;
*index = i;
}
}
return chosen_path;
}
/**
Finds the final anchor voxel to block in the exposed direction
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param seed The chosen seed for the key.
@param normal The direction which the VoxelPair blocks.
@return The final anchor piece for the key.
*/
Voxel finalAnchor(CompFab::VoxelGrid * voxel_list, Voxel seed, VoxelPair blocks, Voxel normal) {
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
Voxel choice(-1, -1, -1);
while (!(seed.x <= 0 || seed.x >= nx-1 || seed.y <= 0 || seed.y >= ny-1 || seed.z <= 0 || seed.z >= nz-1)) {
seed += normal;
if (voxel_list->isInside(seed.x, seed.y, seed.z) == 1) {
choice = seed;
}
}
if (choice == Voxel(-1, -1, -1)) {
return blocks.blocker;
} else {
return choice;
}
}
/**
Expands a piece to have at least num_voxel voxels in it.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param scores An AccessibilityStruct representing the current accesibility scores of the puzzle.
@param key The piece being expanded.
@param anchors The anchor voxels which should not be added to the piece.
@param num_voxels The total number of voxels which should be in the piece.
@param normal The direction the piece is being removed.
@return An updated list of voxels that belong to this piece.
*/
std::vector<Voxel> expandPiece( CompFab::VoxelGrid * voxel_list, AccessibilityGrid * scores, std::vector<Voxel> key, std::vector<Voxel> anchors, int num_voxels, Voxel normal) {
if (debug) {
std::cout << "in expandPiece" << std::endl;
}
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int grid_size = nx*ny*nz;
std::vector<Voxel> path;
// Mark all the vertices as not visited
bool *visited = new bool[grid_size];
for(unsigned int i=0; i<grid_size; ++i) {
visited[i] = false;
}
// ERROR Z DETECTED
Voxel end;
Voxel neg_dir = Voxel(normal.x*-1, normal.y*-1, normal.z*-1);
for (int i = 0; i < anchors.size(); i++) {
end = anchors[i];
while (end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz) {
visited[end.z*(nx*ny) + end.y*ny + end.x] = true;
end += neg_dir;
}
}
for (int i = 0; i < key.size(); i++) {
visited[key[i].z*nx*ny + key[i].y*ny + key[i].x] = true;
}
int count = key.size();
int initial_count = count;
std::vector<Voxel> neighbors;
std::vector<Voxel> candidates;
double sum, dist, random, accum;
std::vector<double> probabilities;
int total;
std::vector<double> access_sums;
double B = -2.0;
int choice = -1;
std::vector<Voxel> tempPiece;
while (count < num_voxels) {
for (int i = 0; i< key.size(); i++) {
neighbors = getNeighbors(key[i], voxel_list, 1);
for (int j = 0; j < neighbors.size(); j++) {
if ( !visited[neighbors[j].z*nx*ny + neighbors[j].y*ny + neighbors[j].x] ) {
visited[neighbors[j].z*nx*ny + neighbors[j].y*ny + neighbors[j].x] = true;
candidates.push_back(neighbors[j]);
}
}
neighbors.clear();
}
if (candidates.size() == 0) {
break;
}
// Get score of candidate additions
for (int i = 0; i < candidates.size(); i++) {
tempPiece.clear();
visited[candidates[i].z*nx*ny + candidates[i].y*ny + candidates[i].x] = false;
sum = 0;
total = count;
// generalize to all
end = candidates[i];
while (end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz) {
if ((voxel_list->isInside(end.x, end.y, end.z) == 1) && (!visited[end.z*nx*ny + end.y*ny + end.x] )) {
tempPiece.push_back(end);
total++;
//sum += scores->score(end.x, end.y, end.z);
}
end += normal;
}
tempPiece = ensurePieceConnectivity(voxel_list, tempPiece, normal);
for (int j = 0; j < tempPiece.size(); j++) {
sum += scores->score(tempPiece[j].x, tempPiece[j].y, tempPiece[j].z);
}
if (total > num_voxels) {
continue;
}
access_sums.push_back(sum);
}
// Normalize scores
dist = 0;
for (int i = 0; i < access_sums.size(); i++) {
access_sums[i] = std::pow(access_sums[i], B);
dist += access_sums[i];
}
// Find probabilities
for (int i = 0; i < access_sums.size(); i++) {
probabilities.push_back( access_sums[i] / dist );
}
// Choose
random = (double) std::rand() / (RAND_MAX);
accum = 0.0;
for (int i = 0; i < probabilities.size(); i++) {
if ( random < accum + probabilities[i] || probabilities.size() == 1) {
choice = i;
break;
} else {
accum += probabilities[i];
}
}
// Add choice to the key
end = candidates[choice];
while (end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz) {
if ((voxel_list->isInside(end.x, end.y, end.z) == 1) && (!visited[end.z*nx*ny + end.y*ny + end.x] )) {
key.push_back(end);
visited[end.z*nx*ny + end.y*ny + end.x] = true;
}
end += normal;
}
for (int i = 0; i < key.size(); i++) {
visited[key[i].z*nx*ny + key[i].y*ny + key[i].x] = true;
}
candidates.clear();
access_sums.clear();
probabilities.clear();
count = key.size();
}
if (debug) {
std::cout << "added " << std::to_string(key.size() - initial_count) << " voxels. Piece size is now " << std::to_string(key.size()) << std::endl;
printList(key);
}
return key;
}
/**
Verifies that the remainder is simply connected, i.e. all voxels can be reached from a randomly chosen voxel in the remainder.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param piece The piece being verified.
@return true if the piece is connected, false otherwise.
*/
bool verifyPiece( CompFab::VoxelGrid * voxel_list, std::vector<Voxel> piece) {
if (debug) {
std::cout << "in verifyPiece" << std::endl;
}
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int grid_size = nx*ny*nz;
bool *visited = new bool[grid_size];
bool *inPiece = new bool[grid_size];
for(unsigned int i=0; i<grid_size; ++i) {
inPiece[i] = false;
visited[i] = false;
}
for (int i = 0; i < piece.size(); i++) {
inPiece[i] = true;
visited[piece[i].z*nx*ny + piece[i].y*ny + piece[i].x] = true;
}
// Find voxel to start bfs from
int x = -1;
int y = -1;
int z = -1;
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
for (int k = 0; k < nz; k++) {
if (voxel_list->isInside(i, j, k) == 1 && !visited[k*ny*nx + j*ny + i]) {
x = i;
y = j;
z = k;
break;
}
}
if (x != -1) {
break;
}
}
if (x != -1) {
break;
}
}
// Now, run bfs
Voxel current;
std::list<Voxel> queue;
std::vector<Voxel> neighbors;
visited[z*(nx*ny) + y*ny + x] = true;
queue.push_back(Voxel(x, y, z));
while (!queue.empty()) {
current = queue.front();
queue.pop_front();
neighbors = getNeighbors(current, voxel_list, 1);
for (int i = 0; i < neighbors.size(); i++) {
if ( !visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] ) {
visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] = true;
queue.push_back(neighbors[i]);
}
}
}
bool result = true;
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
for (int k = 0; k < nz; k++) {
if (voxel_list->isInside(i,j,k) == 1 && !visited[k*(ny*nx) + j*ny + i] ) {
if (debug) {
std::cout << "piece could not be verfied due to " << Voxel(i,j,k).toString() << std::endl;
}
result = false;
}
}
}
}
return result;
}
/**
Finds the normal direction from which to remove the next piece.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param voxel The voxel who's normal direction we're finding
@param piece The previous piece in the puzzle.
@return The direction from which the piece will be removed.
*/
Voxel findNormalDirection( CompFab::VoxelGrid * voxel_list, Voxel voxel, std::vector<Voxel> piece) {
if (debug) {
std::cout << "in findNormalDirection" << std::endl;
}
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
bool *visited = new bool[size];
for(unsigned int i=0; i<size; ++i) {
visited[i] = false;
}
// set voxels of piece to true
for (int i = 0; i < piece.size(); i++) {
visited[piece[i].z*ny*nx + piece[i].y*ny + piece[i].x] = true;
}
if (visited[voxel.z*ny*nx + voxel.y*ny + voxel.x-1]) {
return Voxel(-1, 0, 0);
} else if (visited[voxel.z*ny*nx + voxel.y*ny + voxel.x+1]) {
return Voxel(1, 0, 0);
} else if (visited[voxel.z*ny*nx + (voxel.y-1)*ny + voxel.x]) {
return Voxel(0, -1, 0);
} else if (visited[voxel.z*ny*nx + (voxel.y+1)*ny + voxel.x]) {
return Voxel(0, 1, 0);
} else if (visited[(voxel.z-1)*ny*nx + voxel.y*ny + voxel.x]) {
return Voxel(0, 0, -1);
} else if (visited[(voxel.z+1)*ny*nx + voxel.y*ny + voxel.x]) {
return Voxel(0, 0, 1);
} else {
std::cout << "Error finding normal" << std::endl;
return Voxel(-1,-1,-1);
}
}
/**
A sorting function for std::sort for the VoxelSort class.
@param i The VoxelSort being compared.
@param j The other VoxelSort being compared.
@return true if i's accessibility score is less than j's, false otherwise.
*/
bool voxelSortSorter(VoxelSort i, VoxelSort j) { return (i.score < j.score); }
/**
Sorts the potential seeds for a piece by their accessibility scores.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param scores An AccessibilityStruct representing the current accesibility scores of the puzzle.
@param seeds A list of potential seeds for a piece.
@param piece The previous piece.
@return A list of potential seeds sorted by their accessibility scores.
*/
std::vector<Voxel> seedSorter(CompFab::VoxelGrid * voxel_list, AccessibilityGrid * scores, std::vector<Voxel> seeds, std::vector<Voxel> piece) {
if (debug) {
std::cout << "in seedSorter" << std::endl;
}
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
std::vector<VoxelSort> voxels;
int max_distance = 0;
double max_dist_double = 0.0;
double max_access = 0.0;
int indiv_dist;
// find max distance
Voxel normal;
Voxel end;
for (int i = 0; i < seeds.size(); i++) {
normal = findNormalDirection( voxel_list, seeds[i], piece);
indiv_dist = 0;
end = Voxel(seeds[i].x, seeds[i].y, seeds[i].z);
for (int j = 0; end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz ; j++) {
if (voxel_list->isInside(end.x, end.y, end.z) == 1) {
indiv_dist = j;
}
end += normal;
}
if ( max_distance < indiv_dist) {
max_distance = indiv_dist;
}
}
max_dist_double = (double)max_distance;
// find max accessibilty score
for (int i = 0; i < seeds.size(); i++) {
if ( max_access < scores->score(seeds[i].x, seeds[i].y, seeds[i].z) ) {
max_access = scores->score( seeds[i].x, seeds[i].y, seeds[i].z );
}
}
// now, calculate score for each thing with normalized values
double this_score;
double this_dist;
for (int i = 0; i < seeds.size(); i++) {
this_score = scores->score( seeds[i].x, seeds[i].y, seeds[i].z ) / max_access;
normal = findNormalDirection( voxel_list, seeds[i], piece);
indiv_dist = 0;
for (int j = 0; end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz ; j++) {
if (voxel_list->isInside(end.x, end.y, end.z) == 1) {
indiv_dist = j;
}
end += normal;
}
this_dist = (double)indiv_dist / max_dist_double;
voxels.push_back(VoxelSort(seeds[i], this_score+this_dist));
}
std::sort (voxels.begin(), voxels.end(), voxelSortSorter);
std::vector<Voxel> finalVoxels;
for (int i = 0; i < voxels.size(); i++) {
finalVoxels.push_back(voxels[i].voxel);
}
return finalVoxels;
}
/**
Finds potential seeds for the next piece.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param scores An AccessibilityStruct representing the current accesibility scores of the puzzle.
@param piece The previous piece.
@param perpendicular The directions from which the next piece cannot be removed.
@return A list of potential seeds for the next piece.
*/
std::vector<Voxel> findCandidateSeeds(CompFab::VoxelGrid * voxel_list, AccessibilityGrid * scores, std::vector<Voxel> piece, Voxel perpendicular) {
if (debug) {
std::cout << "in findCandidateSeeds" << std::endl;
}
std::vector<Voxel> neighbors;
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
Voxel voxel;
// Mark all the vertices as not visited
bool *visited = new bool[size];
for(unsigned int i=0; i<size; ++i) {
visited[i] = false;
}
for (int i = 0; i < piece.size(); i++) {
visited[piece[i].z*ny*nx + piece[i].y*ny + piece[i].x] = true;
// mark all pieces in normal direction as visited too
voxel = piece[i] + Voxel(-1*perpendicular.x, -1*perpendicular.y, -1*perpendicular.z);
if ( voxel.x > -1 && voxel.x < nx && voxel.y > -1 && voxel.y < ny && voxel.z > -1 && voxel.z < nz ) {
visited[voxel.z*ny*nx + voxel.y*ny + voxel.x] = true;
}
}
for (int i = 0; i < piece.size(); i++) {
voxel = Voxel(piece[i].x, piece[i].y, piece[i].z);
if ( voxel.x != 0) {
if (voxel_list->isInside(voxel.x-1,voxel.y,voxel.z) == 1 && !visited[voxel.z*ny*nx + voxel.y*ny + voxel.x-1]) {
visited[voxel.z*ny*nx + voxel.y*ny + voxel.x-1] = true;
if (perpendicular.x == 0) {
neighbors.push_back(Voxel(voxel.x-1,voxel.y,voxel.z));
}
}
}
if ( voxel.x != nx-1) {
if (voxel_list->isInside(voxel.x+1,voxel.y,voxel.z) == 1 && !visited[voxel.z*ny*nx + voxel.y*ny + voxel.x+1]) {
visited[voxel.z*ny*nx + voxel.y*ny + voxel.x+1] = true;
if (perpendicular.x == 0) {
neighbors.push_back(Voxel(voxel.x+1,voxel.y,voxel.z));
}
}
}
if (voxel.y != 0) {
if (voxel_list->isInside(voxel.x,voxel.y-1,voxel.z) == 1 && !visited[voxel.z*ny*nx + (voxel.y-1)*ny + voxel.x]) {
visited[voxel.z*ny*nx + (voxel.y-1)*ny + voxel.x] = true;
if (perpendicular.y == 0) {
neighbors.push_back(Voxel(voxel.x,voxel.y-1,voxel.z));
}
}
}
if (voxel.y != ny-1) {
if (voxel_list->isInside(voxel.x,voxel.y+1,voxel.z) == 1 && !visited[voxel.z*ny*nx + (voxel.y+1)*ny + voxel.x]) {
visited[voxel.z*ny*nx + (voxel.y+1)*ny + voxel.x] = true;
if (perpendicular.y == 0) {
neighbors.push_back(Voxel(voxel.x,voxel.y+1,voxel.z));
}
}
}
if (voxel.z != 0) {
if (voxel_list->isInside(voxel.x,voxel.y,voxel.z-1) == 1 && !visited[(voxel.z-1)*ny*nx + voxel.y*ny + voxel.x]) {
visited[(voxel.z-1)*ny*nx + voxel.y*ny + voxel.x] = true;
if (perpendicular.z == 0) {
neighbors.push_back(Voxel(voxel.x,voxel.y,voxel.z-1));
}
}
}
if (voxel.z != nz-1) {
if (voxel_list->isInside(voxel.x,voxel.y,voxel.z+1) == 1 && !visited[(voxel.z+1)*ny*nx + voxel.y*ny + voxel.x]) {
visited[(voxel.z+1)*ny*nx + voxel.y*ny + voxel.x] = true;
if (perpendicular.z == 0) {
neighbors.push_back(Voxel(voxel.x,voxel.y,voxel.z+1));
}
}
}
}
if (neighbors.size() > 10) {
std::vector<Voxel> sorted = seedSorter(voxel_list, scores, neighbors, piece);
std::vector<Voxel> topX;
for (int i = 0; i < 10 && i < sorted.size(); i++) {
topX.push_back(sorted[i]);
}
if (debug) {
std::cout << "candidate seeds are: " << std::endl;
printList(topX);
}
return topX;
} else {
if (debug) {
std::cout << "candidate seeds are: " << std::endl;
printList(neighbors);
}
return neighbors;
}
}
/**
Finds teh shorest path from one voxel to another.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param start The voxel the path starts from.
@param goal The voxel to find.
@return The path from start voxel to goal voxel.
*/
std::vector<Voxel> shortestPathTwo(CompFab::VoxelGrid * voxel_list, Voxel start, Voxel goal) {
if (debug) {
std::cout << "in shortestPathTwo" << std::endl;
std::cout << "start is " << start.toString() << ", goal is " << goal.toString() << std::endl;
}
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
bool *visited = new bool[size];
for (int i = 0; i < size; i++) {
visited[i] = false;
}
std::list<std::vector<Voxel>> queue;
std::vector<Voxel> neighbors;
std::vector<Voxel> current;
std::vector<Voxel> path;
//Mark the current node as visited and enqueue it
visited[start.z*(nx*ny) + start.y*ny + start.x] = true;
path.push_back(start);
queue.push_back(path);
std::vector<Voxel> shortest_path;
while ( !queue.empty() ) {
current = queue.front();
if (current.back() == goal) {
shortest_path = current;
break;
}
queue.pop_front();
neighbors = getNeighbors(current.back(), voxel_list, 1);
for (int i = 0; i < neighbors.size(); i++) {
if ( !visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] ) {
visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] = true;
std::vector<Voxel> new_path = current;
new_path.push_back(neighbors[i]);
queue.push_back(new_path);
}
}
}
if (queue.empty()) {
std::cout << "\n\n\t\tFAILED FINDING PATH\n\t\tFAILED FINDING PATH\n\t\tFAILED FINDING PATH\n\n" << std::endl;
}
return shortest_path;
}
/**
From a list of potential seed voxels, creates the initial design of a potential piece.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param scores An AccessibilityStruct representing the current accesibility scores of the puzzle.
@param prevPiece The previous piece.
@param candidates A list of potential seeds for the next piece.
@param index An integer pointer that gets set to the index of the chosen candidate.
@return A list containing the initial construction of the next piece.
*/
std::vector<Voxel> createInitialPiece(CompFab::VoxelGrid * voxel_list, AccessibilityGrid * scores, std::vector<Voxel> prevPiece, std::vector<Voxel> candidates, int * index) {
if (debug) {
std::cout << "in createInitialPiece" << std::endl;
}
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
std::vector<Voxel> bestChoice;
std::vector<Voxel> currentChoice;
std::vector<Voxel> toRemove;
double bestScore = std::numeric_limits<double>::max();
double currentScore;
Voxel normal;
Voxel end;
bool *visited = new bool[size];
std::vector<Voxel> shortestPath;
std::vector<Voxel> finalPath;
bool in;
for (int i = 0; i < candidates.size(); i++) {
//std::cout << "checking candidate " << candidates[i].toString() << std::endl;
// Reset everything
currentChoice.clear();
toRemove.clear();
shortestPath.clear();
finalPath.clear();
// Find the normal
normal = findNormalDirection( voxel_list, candidates[i], prevPiece);
end = candidates[i] + normal;
//std::cout << "\tnormal is " << normal.toString() << std::endl;
// Figure out what voxels must be added in the normal direction
//std::cout << "\tfinding the voxels to add" << std::endl;
for (int j = 0; end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz ; j++) {
//std::cout << "\tchecking " << end.toString() << std::endl;
if (voxel_list->isInside(end.x, end.y, end.z) == 1) {
//std::cout << "\t\t" << end.toString() << " must be removed" << std::endl;
toRemove.push_back(end);
}
end += normal;
}
if (toRemove.size() == 0) {
currentScore = scores->score(candidates[i].x, candidates[i].y, candidates[i].z);
currentChoice.push_back(candidates[i]);
/*if (currentScore < bestScore) {
bestScore = currentScore;
currentChoice.push_back(candidates[i]);
std::cout << "\t\t\tsetting bestChoice with nothing to remove with current score =" << std::to_string(currentScore)<< std::endl;
bestChoice = currentChoice;
}*/
}
//std::cout << "\tvoxels to remove: " << std::endl;
//printList(toRemove);
// Now, find shortest path to each of these and add said path to the piece
for (int j = 0; j < toRemove.size(); j++) {
shortestPath = shortestPathTwo(voxel_list, candidates[i], toRemove[j]);
//std::cout << "\tpath to " << toRemove[j].toString() << " is: " << std::endl;
if (shortestPath.size() == 0) {
std::cout << "Something went wrong" << std::endl;
}
if (debug) {
printList(shortestPath);
}
// add all voxels in normal direction
for (int k = 0; k < shortestPath.size(); k++) {
end = shortestPath[k];
for (int l = 0; end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz ; l++) {
if (voxel_list->isInside(end.x, end.y, end.z) == 1) {
finalPath.push_back(end);
}
end += normal;
}
}
// add path to the piece
for (int k = 0; k < finalPath.size(); k++) {
// Check if it's already in there
in = false;
for (int l = 0; l < currentChoice.size(); l++) {
if (finalPath[k] == currentChoice[l]) {
in = true;
break;
}
}
if ( !in ) {
currentChoice.push_back(finalPath[k]);
}
}
}
// Now, decide if this one is better
if (currentScore != 0.0) {
currentScore = 0.0;
}
for (int j = 0; j < currentChoice.size(); j++) {
currentScore += scores->score(currentChoice[j].x, currentChoice[j].y, currentChoice[j].z);
}
if (currentScore < bestScore && currentScore > 0.0) {
//std::cout << "\t\t\tsetting bestChoice with current score =" << std::to_string(currentScore) << std::endl;
bestScore = currentScore;
bestChoice = currentChoice;
*index = i;
}
}
if (debug) {
std::cout << "best choice is:" << std::endl;
printList(bestChoice);
}
return bestChoice;
}
/**
Finds a blocker for the next piece in direction toBlock
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param scores An AccessibilityStruct representing the current accesibility scores of the puzzle.
@param seed A seed for the next piece.
@param toBlock The direction that must be blocked.
@param normal The direction the piece is being released in.
@param nb_one The number of blocking pairs to find.
@param nb_two The number of blocking pairs to choose amongst.
@param anchor A Voxel pointer that gets set to the blocker to be an anchor later on.
@param anchorList A list of anchors which any path finding is not allowed to go through.
@return An update of the piece blocked in the direction toBlock.
*/
std::vector<Voxel> bfsTwo(CompFab::VoxelGrid * voxel_list, AccessibilityGrid * scores, Voxel seed, Voxel toBlock, Voxel normal, int nb_one, int nb_two, Voxel * anchor, std::vector<Voxel> anchorList){
if (debug) {
std::cout << "in bfsTwo" << std::endl;
}
std::vector<VoxelPair> potentials;
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
// Mark all the vertices as not visited
bool *visited = new bool[size];
for(unsigned int i=0; i<size; ++i) {
visited[i] = false;
}
// Create a queue for BFS
std::list<Voxel> queue;
std::vector<Voxel> neighbors;
Voxel blockee;
Voxel blocker;
//Mark the current node as visited and enqueue it
visited[seed.z*(nx*ny) + seed.y*ny + seed.x] = true;
queue.push_back(seed);
int count = 0;
while (!queue.empty() && potentials.size() < nb_one) {
count++;
blockee = queue.front();
blocker = blockee + toBlock;
if (blocker.x < 0 || blocker.x >= nx || blocker.y < 0 || blocker.y >= ny || blocker.z < 0 || blocker.z >= nz) {
;
} else if (voxel_list->isInside(blocker.x, blocker.y, blocker.z) == 1 && blocker != seed) {
potentials.push_back(VoxelPair(blocker, scores->score(blocker.x, blocker.y, blocker.z), blockee, scores->score(blockee.x, blockee.y, blockee.z)));
}
queue.pop_front();
neighbors = getNeighbors(blockee, voxel_list, 1);
for (int i = 0; i < neighbors.size(); i++) {
if ( !visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] ) {
visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] = true;
queue.push_back(neighbors[i]);
}
}
}
if (debug) {
std::cout << "in bfsTwo, went through: " << count << std::endl;
}
std::sort (potentials.begin(), potentials.end(), accessSort);
std::vector<VoxelPair> accessible;
for (int i = 0; i< potentials.size() && nb_two < accessible.size(); i++) {
if (debug) {
std::cout << "\t" << potentials[i].toString() << " could block" << std::endl;
}
accessible.push_back(potentials[i]);
}
std::vector<Voxel> currentPiece;
std::vector<Voxel> bestPiece;
double currentScore;
double bestScore = std::numeric_limits<double>::max();
Voxel bestBlocker;
Voxel current;
bool skip;
for (int i = 0; i < accessible.size(); i++) {
currentPiece = shortestPath(voxel_list, seed, accessible[i], anchorList, normal);
if (debug) {
std::cout<< "path from " << seed.toString() << " to " << accessible[i].blockee.toString() << std::endl;
}
// Verify that the blocker isn't isolated, i.e. that it can access rest of puzzle not through the piece
for(unsigned int j=0; j<size; ++j) {
visited[j] = false;
}
for (int j = 0; j < currentPiece.size(); j++) {
visited[ currentPiece[j].z*(ny*nx) + currentPiece[j].y*ny + currentPiece[j].x ] = true;
}
queue.clear();
queue.push_back(accessible[i].blocker);
while (!queue.empty()) {
current = queue.front();
queue.pop_front();
neighbors = getNeighbors(current, voxel_list, 1);
for (int k = 0; k < neighbors.size(); k++) {
if ( !visited[ neighbors[k].z*(nx*ny) + neighbors[k].y*ny + neighbors[k].x ] ) {
visited[ neighbors[k].z*(nx*ny) + neighbors[k].y*ny + neighbors[k].x ] = true;
queue.push_back(neighbors[k]);
}
}
}
// Finally, make sure everything in puzzle was visited
skip = false;
for (int x = 0; x < nx; x++) {
for (int y = 0; y < ny; y++) {
for (int z = 0; z < nz; z++) {
if ((voxel_list->isInside(x, y, z) == 1) && !visited[z*(ny*nx) + y*ny + x]) {
skip = true;
if (debug) {
std::cout << "bad blocker is " << accessible[i].blocker.toString() << std::endl;
}
}
}
}
}
if (skip) continue;
//printList(currentPiece);
if (currentPiece.size() == 0) {
std::cout << "Could not find path?" << std::endl;
continue;
}
currentScore = 0.0;
for (int j = 0; j < currentPiece.size(); j++) {
currentScore += scores->score(currentPiece[j].x, currentPiece[j].y, currentPiece[j].z);
}
//std::cout << "\tthe score is " << std::to_string(currentScore) << std::endl;
if (currentScore < bestScore) {
bestScore = currentScore;
bestPiece = currentPiece;
bestBlocker = accessible[i].blocker;
}
}
if (debug) {
std::cout << "returning: " << std::endl;
printList(bestPiece);
}
*anchor = bestBlocker;
return bestPiece;
}
/**
Ensures that the piece isn't mobile in a direction.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param scores An AccessibilityStruct representing the current accesibility scores of the puzzle.
@param prevPiece The previous piece.
@param currentPiece The piece currently being built.
@param prevPieceId The value which voxel_list->(x,y,z) is set to for the previous piece.
@param dir The direction for which we're checking mobility.
@param normal The direction the current piece is being removed in.
@param prevNormal The direction the previous piece was removed in.
@param anchor A Voxel pointer which gets set to the anchor for this direction.
@param anchorList A list of anchors which the piece cannot travel through.
@return An updated version of the current piece, only changed if it was not blocked in direction dir.
*/
std::vector<Voxel> mobilityCheck(CompFab::VoxelGrid * voxel_list, AccessibilityGrid * scores, std::vector<Voxel> prevPiece, std::vector<Voxel> currentPiece, int prevPieceId, Voxel dir, Voxel normal, Voxel prevNormal, Voxel * anchor, std::vector<Voxel> anchorList) {
if (debug) {
std::cout << "checking mobility in dir " << dir.toString() << std::endl;
}
int count = currentPiece.size();
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
bool *isCurrent = new bool[size];
for(unsigned int i=0; i<size; ++i) {
isCurrent[i] = false;
}
for (int i = 0; i < currentPiece.size(); i++) {
isCurrent[currentPiece[i].z*(ny*nx) + currentPiece[i].y*ny + currentPiece[i].x] = true;
}
bool blocked = false;
bool in;
Voxel end;
std::vector<Voxel> path;
for (int i = 0; i < currentPiece.size(); i++) {
end = currentPiece[i];
while (end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz && !blocked) {
if (voxel_list->isInside(end.x, end.y, end.z) == 1 || ((voxel_list->isInside(end.x, end.y, end.z) == prevPieceId) && (dir != prevNormal)) ) {
if (!isCurrent[end.z*(ny*nx) + end.y*ny + end.x]) {
//*anchor = end;
blocked = true;
}
}
end += dir;
}
if (blocked) {
break;
}
}
if (!blocked) {
// add blockee voxel
//std::cout << "NEED TO BLOCK" << std::endl;
path = bfsTwo(voxel_list, scores, currentPiece[0], dir, normal, 50, 10, anchor, anchorList);
//std::cout << "BEST CHOICE IS " << std::endl;
//printList(path);
for (int i = 0; i < path.size(); i++) {
in = false;
//std::cout << "\tchecking if " << path[i].toString() << "is already in piece" << std::endl;
for (int j = 0; j < currentPiece.size(); j++) {
if (path[i] == currentPiece[j]) {
//std::cout << "\t\t" << path[i].toString() << " is in current piece already" << std::endl;
in = true;
break;
}
}
if ( !in ) {
currentPiece.push_back(path[i]);
}
}
}
if (currentPiece.size() == count) {
if (debug) {
std::cout << "no change" << std::endl;
}
} else {
if (debug) {
std::cout << "twas change" << std::endl;
}
}
return currentPiece;
}
/**
Ensures the piece is only mobile in one direction.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param scores An AccessibilityStruct representing the current accesibility scores of the puzzle.
@param prevPiece The previous piece.
@param currentPiece The piece which is being checked.
@param prevPieceId The value which voxel_list->(x,y,z) is set to for the previous piece.
@param prevNormal The direction the previous piece was removed in.
@param theAnchors A pointer to a voxel vector that gets updated with the voxels that cannot be added to this piece.
@return An udpated version of the piece that is only mobile in one direction.
*/
std::vector<Voxel> ensureInterlocking(CompFab::VoxelGrid * voxel_list, AccessibilityGrid * scores, std::vector<Voxel> prevPiece, std::vector<Voxel> currentPiece, int prevPieceId, Voxel prevNormal, std::vector<Voxel> * theAnchors) {
if (debug) {
std::cout << "in ensureInterlocking" << std::endl;
}
Voxel normal = findNormalDirection( voxel_list, currentPiece[0], prevPiece);
Voxel dir;
if (debug) {
std::cout << "normal for this whole piece starting at" << currentPiece[0].toString() << " is " << normal.toString() << std::endl;
}
// Perform mobility check in each of the other 5 directions
Voxel anchor;
std::vector<Voxel> anchorList;
if (normal.x != -1) {
dir = Voxel(-1, 0, 0);
anchor = Voxel(-1, -1, -1);
currentPiece = mobilityCheck(voxel_list, scores, prevPiece, currentPiece, prevPieceId, dir, normal, prevNormal, &anchor, anchorList);
if (anchor != Voxel(-1, -1, -1)) {
anchorList.push_back(anchor);
}
}
if (normal.x != 1) {
dir = Voxel(1, 0, 0);
anchor = Voxel(-1, -1, -1);
currentPiece = mobilityCheck(voxel_list, scores, prevPiece, currentPiece, prevPieceId, dir, normal, prevNormal, &anchor, anchorList);
if (anchor != Voxel(-1, -1, -1)) {
anchorList.push_back(anchor);
}
}
if (normal.y != -1) {
dir = Voxel(0, -1, 0);
anchor = Voxel(-1, -1, -1);
currentPiece = mobilityCheck(voxel_list, scores, prevPiece, currentPiece, prevPieceId, dir, normal, prevNormal, &anchor, anchorList);
if (anchor != Voxel(-1, -1, -1)) {
anchorList.push_back(anchor);
}
}
if (normal.y != 1) {
dir = Voxel(0, 1, 0);
anchor = Voxel(-1, -1, -1);
currentPiece = mobilityCheck(voxel_list, scores, prevPiece, currentPiece, prevPieceId, dir, normal, prevNormal, &anchor, anchorList);
if (anchor != Voxel(-1, -1, -1)) {
anchorList.push_back(anchor);
}
}
if (normal.z != -1) {
dir = Voxel(0, 0, -1);
currentPiece = mobilityCheck(voxel_list, scores, prevPiece, currentPiece, prevPieceId, dir, normal, prevNormal, &anchor, anchorList);
if (anchor != Voxel(-1, -1, -1)) {
anchorList.push_back(anchor);
}
}
if (normal.z != 1) {
dir = Voxel(0, 0, 1);
currentPiece = mobilityCheck(voxel_list, scores, prevPiece, currentPiece, prevPieceId, dir, normal, prevNormal, &anchor, anchorList);
if (anchor != Voxel(-1, -1, -1)) {
anchorList.push_back(anchor);
}
}
*theAnchors = anchorList;
return currentPiece;
}
/**
Finds the shortest path from a voxel to another piece.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param start The voxel the path starts on.
@param goals The piece we're finding a path to.
@return The path from voxel start to a piece.
*/
std::vector<Voxel> shortestPathThree(CompFab::VoxelGrid * voxel_list, Voxel start, std::vector<Voxel> goals) {
if (debug) {
std::cout << "in shortestPathThree" << std::endl;
std::cout << "starting from " << start.toString() << std::endl;
}
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
bool *visited = new bool[size];
for (int i = 0; i < size; i++) {
visited[i] = false;
}
bool *piece = new bool[size];
for (int i =0; i < size; i++) {
piece[i] = false;
}
for (int i = 0; i < goals.size(); i++) {
piece[goals[i].z*(ny*nx) + goals[i].y*ny + goals[i].x] = true;
}
piece[start.z*(nx*ny) + start.y*ny + start.x] = false;
std::list<std::vector<Voxel>> queue;
std::vector<Voxel> neighbors;
std::vector<Voxel> current;
std::vector<Voxel> path;
//Mark the current node as visited and enqueue it
visited[start.z*(nx*ny) + start.y*ny + start.x] = true;
path.push_back(start);
queue.push_back(path);
std::vector<Voxel> shortest_path;
Voxel back;
while ( !queue.empty() ) {
current = queue.front();
back = current.back();
if ( piece[back.z*(ny*nx) + back.y*ny + back.x] ) {
shortest_path = current;
break;
}
queue.pop_front();
neighbors = getNeighbors(current.back(), voxel_list, 1);
for (int i = 0; i < neighbors.size(); i++) {
if ( !visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] ) {
visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] = true;
std::vector<Voxel> new_path = current;
new_path.push_back(neighbors[i]);
queue.push_back(new_path);
}
}
}
if (queue.empty()) {
std::cout << "\n\n\t\tFAILED FINDING PATH (3)\n\t\tFAILED FINDING PATH (3)\n\t\tFAILED FINDING PATH (3)\n\n" << std::endl;
}
return shortest_path;
}
/**
Ensures that a piece is connected to itself.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param piece The piece being checking.
@param normal The direction the piece is being removed in.
@return Updates the piece if it's not connected, otherwise leave it alone.
*/
std::vector<Voxel> ensurePieceConnectivity(CompFab::VoxelGrid * voxel_list, std::vector<Voxel> piece, Voxel normal) {
if (debug) {
std::cout << "in ensurePieceConnectivity" << std::endl;
std::cout << "piece is: " << std::endl;
printList(piece);
}
if (piece.size() == 0) {
return piece;
}
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
bool *visited = new bool[size];
bool *inPiece = new bool[size];
bool connected = false;
std::list<Voxel> newQueue;
Voxel start = piece[0];
Voxel current;
bool in;
Voxel end;
std::vector<Voxel> path;
std::vector<Voxel> neighbors;
std::vector<Voxel> disconnected;
//while (!connected) {
for(unsigned int i=0; i<size; ++i) {
visited[i] = false;
inPiece[i] = false;
}
for (int i = 0; i < piece.size(); i++) {
inPiece[piece[i].z*(ny*nx) + piece[i].y*ny + piece[i].x] = true;
}
newQueue.clear();
//Mark the current node as visited and enqueue it
visited[start.z*(nx*ny) + start.y*ny + start.x] = true;
newQueue.push_back(start);
if (debug) {
std::cout << "checking connection" << std::endl;
}
while ( !newQueue.empty() ) {
current = newQueue.front();
newQueue.pop_front();
neighbors = getNeighbors(current, voxel_list, 1);
if (debug) {
std::cout << "current is " << current.toString() << ", it's neighbors are:" << std::endl;
printList(neighbors);
}
for (int i = 0; i < neighbors.size(); i++) {
if ( !visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] && inPiece[neighbors[i].z*(ny*nx) + neighbors[i].y*ny + neighbors[i].x] ) {
if (debug) {
std::cout << "REACHED " << neighbors[i].toString() << " FROM " << current.toString() << std::endl;
}
visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] = true;
newQueue.push_back(neighbors[i]);
}
}
}
if (debug) {
std::cout << "thru there" << std::endl;
}
// okay so now make sure that all pieces have been visited
disconnected.clear();
for (int i = 0; i < piece.size(); i++) {
if (!visited[piece[i].z*(ny*nx) + piece[i].y*ny + piece[i].x]) {
disconnected.push_back(piece[i]);
} else {
if (debug) {
std::cout << "visited " << piece[i].toString() << " somewhere" << std::endl;
}
}
}
// GUCCI
if (disconnected.size() == 0) {
connected = true;
}
if (debug) {
std::cout << "now, finding paths " << std::endl;
}
path.clear();
for (int i = 0; i < disconnected.size(); i++) {
if (debug) {
std::cout << "\tdelinquent:" << start.toString() << ", path is (starting from " << disconnected[i].toString()<< "):" << std::endl;
}
path = shortestPathThree(voxel_list, disconnected[i], piece);
if (debug) {
printList(path);
}
for (int j = 0; j < path.size(); j++) {
end = path[j];
end += normal;
while (end.x < nx && end.x > -1 && end.y > -1 && end.y < ny && end.z > -1 && end.z < nz) {
if ( voxel_list->isInside(end.x, end.y, end.z) == 1) {
in = false;
for (int k = 0; k < piece.size(); k++) {
if (piece[k] == end) {
in = true;
}
}
if (!in) {
if (debug) {
std::cout << "adding to piece " << end.toString() << std::endl;
}
piece.push_back(end);
} else {
if (debug) {
std::cout << end.toString() << " is already in" << std::endl;
}
}
}
end += normal;
}
}
}
//}
if (debug) {
std::cout << "escaped ensurePieceConnectivity" << std::endl;
}
return piece;
}
/**
Ensures that a piece is connected to itself during partition process.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param piece The piece being partitioned.
@param pieceId The ID of the piece as it's set to in voxel_list
@return true if the piece is connected, false otherwise.
*/
bool checkPieceConnectivity(CompFab::VoxelGrid * voxel_list, std::vector<Voxel> piece, int pieceId) {
if (debug) {
std::cout << "in checkPieceConnectivity" << std::endl;
}
bool connected = true;
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
bool *visited = new bool[size];
for (int i = 0; i < size; i++) {
visited[i] = false;
}
std::list<Voxel> queue;
std::vector<Voxel> neighbors;
Voxel current;
Voxel start = Voxel(-1,-1,-1);
for (int i = 0; i < piece.size(); i++) {
if (voxel_list->isInside(piece[i].x, piece[i].y, piece[i].z) == pieceId) {
start = piece[i];
break;
}
}
if (start == Voxel(-1,-1,-1)) {
std::cout << "Error in checkPieceConnectivity" << std::endl;
}
//Mark the current node as visited and enqueue it
visited[start.z*(nx*ny) + start.y*ny + start.x] = true;
queue.push_back(start);
while ( !queue.empty() ) {
current = queue.front();
queue.pop_front();
neighbors = getNeighbors(current, voxel_list, pieceId);
for (int i = 0; i < neighbors.size(); i++) {
if ( !visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] ) {
visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] = true;
queue.push_back(neighbors[i]);
}
}
}
for (int i = 0; i < piece.size(); i++) {
if (voxel_list->isInside(piece[i].x, piece[i].y, piece[i].z) == pieceId && !visited[piece[i].z*(ny*nx) + piece[i].y*ny + piece[i].x]) {
connected = false;
break;
}
}
return connected;
}
/**
Partitions a piece into 2 pieces.
@param voxel_list A VoxelGrid representing the current state of the puzzle.
@param scores An AccessibilityStruct representing the current accesibility scores of the puzzle.
@param piece The piece being partitioned.
@param numPartition The piece ID as set in voxel_list
@param pieceSize The size of the partition
@return The partitioned piece.
*/
std::vector<Voxel> partitionPiece(CompFab::VoxelGrid * voxel_list, AccessibilityGrid * scores, std::vector<Voxel> piece, int numPartition, int pieceSize) {
//if (debug) {
std::cout << "in partitionPiece" << std::endl;
std::cout << "piece size is " << std::to_string(pieceSize) << std::endl;
//}
int nx = voxel_list->m_dimX;
int ny = voxel_list->m_dimY;
int nz = voxel_list->m_dimZ;
int size = nx*ny*nz;
//first, sort piece by accessibility
std::vector<VoxelSort> sorted;
for (int i = 0; i < piece.size(); i++) {
sorted.push_back(VoxelSort(piece[i], scores->score(piece[i].x, piece[i].y, piece[i].z)));
}
std::sort (sorted.begin(), sorted.end(), voxelSortSorter);
piece.clear();
for (int i = 0; i < sorted.size(); i++) {
piece.push_back(sorted[i].voxel);
}
bool *visited = new bool[size];
for (int i = 0; i < size; i++) {
visited[i] = false;
}
std::list<Voxel> queue;
std::vector<Voxel> neighbors;
Voxel current;
Voxel start = piece[0];
//Mark the current node as visited and enqueue it
visited[start.z*(nx*ny) + start.y*ny + start.x] = true;
queue.push_back(start);
std::vector<Voxel> partition;
std::vector<Voxel> temp;
while ( !queue.empty() ) {
std::cout << "partition size is " << std::to_string(partition.size()) << std::endl;
current = queue.front();
if (partition.size() >= pieceSize ) {
break;
}
queue.pop_front();
neighbors = getNeighbors(current, voxel_list, numPartition);
for (int i = 0; i < neighbors.size(); i++) {
if ( !visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] ) {
// Ensure adding piece doesn't disconnect the partitions
temp = partition;
temp.push_back(neighbors[i]);
for (int j = 0; j< temp.size(); j++) {
voxel_list->isInside(temp[j].x, temp[j].y, temp[j].z) = 0;
}
if (checkPieceConnectivity(voxel_list, piece, numPartition)) {
partition = temp;
}
for (int j = 0; j< temp.size(); j++) {
voxel_list->isInside(temp[j].x, temp[j].y, temp[j].z) = numPartition;
}
visited[ neighbors[i].z*(nx*ny) + neighbors[i].y*ny + neighbors[i].x ] = true;
queue.push_back(neighbors[i]);
}
}
}
delete[] visited;
return partition;
}
| [
"bgaudiosi531@gmail.com"
] | bgaudiosi531@gmail.com |
81c04a30052d84b399686b57a14731c0fcd91b1f | abf24191265fb9e6648cf1de7ed848fbe291da7c | /cugl/lib/math/polygon/CUPathExtruder.cpp | 626bf40afe8eca57997fda16b985433752af59df | [] | no_license | onewordstudios/sweetspace | 4ecc3fe27fb794fac6e8b2e8402f9b010f5553a4 | 5d071cd68eb925b9ae1b004ce5d6080cc3261d30 | refs/heads/master | 2023-02-04T11:13:34.287462 | 2023-02-03T04:03:24 | 2023-02-03T04:03:24 | 241,430,856 | 9 | 2 | null | 2023-02-03T04:03:26 | 2020-02-18T18:00:44 | C++ | UTF-8 | C++ | false | false | 24,622 | cpp | //
// CUPathExtruder.cpp
// Cornell University Game Library (CUGL)
//
// This module is a factory for extruding a path polgyon into a stroke with
// width. It has support for joints and end caps.
//
// The code in this factory is ported from the Kivy implementation of Line in
// package kivy.vertex_instructions. We believe that this port is acceptable
// within the scope of the Kivy license. There are no specific credits in that
// file, so there is no one specific to credit. However, thanks to the Kivy
// team for doing the heavy lifting on this method.
//
// Because they did all the hard work, we will recommend their picture of how
// joints and end caps work:
//
// http://kivy.org/docs/_images/line-instruction.png
//
// Since math objects are intended to be on the stack, we do not provide
// any shared pointer support in this class.
//
// CUGL MIT License:
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
// Author: Walker White
// Version: 6/22/16
#include <cugl/math/polygon/CUPathExtruder.h>
#include <cugl/util/CUDebug.h>
#include <iterator>
/** The number of segments to use in a rounded joint */
#define JOINT_PRECISION 10
/** The number of segments to use in a rounded cap */
#define CAP_PRECISION 10
namespace cugl {
/**
* Data necessary for a single iteration of the Kivy algorithm
*
* The Kivy algorithm is great, but it is a tangled mess. There is a lot of
* information that needs to be carried across iterations. At each step, we
* need to know the index position from the previous iteration, as well as from
* two iterations ago.
*
* All of the data means that it is very hard to break the algorithm up
* into multiple functions. The component functions would take larger numbers
* of arguments, all passed by reference. However, a function that long is a
* sin. So we use this class to encapsulate the data we need.
*
* We are not even going to try to explain why all these are necessary.
*/
class KivyData {
public:
/** The current algorithm iteraction */
unsigned int index;
/** The path stroke */
float stroke;
/** The path joint */
PathJoint joint;
/** The path cap */
PathCap cap;
/** The vector for the current segement */
Vec2 c;
/** The vector for the previous segement */
Vec2 pc;
/** The first side of the segment rectangle */
Vec2 v1;
/** The second side of the segment rectangle */
Vec2 v2;
/** The third side of the segment rectangle */
Vec2 v3;
/** The fourth side of the segment rectangle */
Vec2 v4;
/** The first side of the previous segment rectangle */
Vec2 p1;
/** The second side of the previous segment rectangle */
Vec2 p2;
/** The third side of the previous segment rectangle */
Vec2 p3;
/** The fourth side of the previous segment rectangle */
Vec2 p4;
/** The top edge of the current segement */
Vec2 s1;
/** The bottom edge of the current segement */
Vec2 s4;
/** The current angle */
float angle;
/** The current segment angle */
float sangle;
/** The previous angle */
float pangle;
/** The previous previous angle */
float pangle2;
/** The current vertex index */
unsigned int pos;
/** The previous vertex index */
unsigned int ppos;
/** The previous previous vertex index */
unsigned int p2pos;
};
}
using namespace cugl;
#pragma mark -
#pragma mark Initialization
/**
* Sets the vertex data for this extruder.
*
* The extrusion only uses the vertex data from the polygon. It ignores any
* existing indices. The method assumes the polygon is closed if the
* number of indices is twice the number of vertices.
*
* The vertex data is copied. The extruder does not retain any references
* to the original data.
*
* This method resets all interal data. You will need to reperform the
* calculation before accessing data.
*
* @param poly The vertices to extrude
*/
void PathExtruder::set(const Poly2& poly) {
CUAssertLog(poly.getType() == Poly2::Type::PATH,
"The polygon is not a path");
reset();
_input = poly._vertices;
_closed = poly._indices.size() == poly._vertices.size()*2;
}
#pragma mark -
#pragma mark Calculation
/**
* Performs a extrusion of the current vertex data.
*
* An extrusion of a polygon is a second polygon that follows the path of
* the first one, but gives it width. Hence it takes a path and turns it
* into a solid shape. This is more complicated than simply triangulating
* the original polygon. The new polygon has more vertices, depending on
* the choice of joint (shape at the corners) and cap (shape at the end).
*
* CREDITS: This code is ported from the Kivy implementation of Line in
* package kivy.vertex_instructions. My belief is that this port is
* acceptable within the scope of the Kivy license. There are no specific
* credits in that file, so there is no one specific to credit. However,
* thanks to the Kivy team for doing the heavy lifting on this method.
*
* Because they did all the hard work, we will plug their picture of how
* joints and end caps work:
*
* http://kivy.org/docs/_images/line-instruction.png
*
* @param stroke The stroke width of the extrusion
* @param joint The extrusion joint type.
* @param cap The extrusion cap type.
*/
void PathExtruder::calculate(float stroke, PathJoint joint, PathCap cap) {
if (_input.size() == 0) {
_calculated = true;
return;
}
_outverts.clear();
_outindx.clear();
// Closed paths have no cap;
if (_closed && _input.size() > 2) {
cap = PathCap::NONE;
}
// Determine how large the new polygon is
unsigned int vcount, icount;
unsigned int count = computeSize(joint, cap, &vcount, &icount);
_outverts.reserve(vcount*2);
_outindx.reserve(icount);
// Thanks Kivy guys for all the hard work.
KivyData data;
// Initialize the data
data.stroke = stroke;
data.joint = joint;
data.cap = cap;
// Iterate through the path
data.angle = data.sangle = 0;
data.pangle = data.pangle2 = 0;
data.pos = data.ppos = data.p2pos = 0;
int mod = (int)_input.size();
for(int ii = 0; ii < count-1; ii++) {
Vec2 a = _input[ ii % mod];
Vec2 b = _input[(ii+1) % mod];
data.index = ii;
makeSegment(a, b, &data);
makeJoint(a, &data);
}
// Process the caps
makeCaps(count, &data);
// If closed, make one last joint
if (_closed && mod > 2) {
makeLastJoint(&data);
}
_calculated = true;
}
/**
* Computes the number of vertices and indices necessary for the extrusion.
*
* The number of vertices is put in vcount, while the number of indices
* is put in icount. The method returns the total number of points
* generating the extruded path, which may be more than the input size when
* the path is closed.
*
* @param joint The extrusion joint type.
* @param cap The extrusion cap type.
* @param vcount Pointer to store the number of vertices needed.
* @param icount Pointer to store the number of vertices needed.
*
* @return the total number of points generating the extruded path
*/
unsigned int PathExtruder::computeSize(PathJoint joint, PathCap cap,
unsigned int* vcount, unsigned int* icount) {
unsigned int count = (int)_input.size();
if (_closed && _input.size() > 2) {
count += 1;
}
// Determine the number of vertices and indices we need.
*vcount = (count - 1) * 4;
*icount = (count - 1) * 6;
switch (joint) {
case PathJoint::BEVEL:
*icount += (count - 2) * 3;
*vcount += (count - 2);
break;
case PathJoint::ROUND:
*icount += (JOINT_PRECISION * 3) * (count - 2);
*vcount += (JOINT_PRECISION) * (count - 2);
break;
case PathJoint::MITRE:
*icount += (count - 2) * 6;
*vcount += (count - 2) * 2;
break;
case PathJoint::NONE:
// Nothing to do.
break;
}
switch (cap) {
case PathCap::SQUARE:
*icount += 12;
*vcount += 4;
break;
case PathCap::ROUND:
*icount += (CAP_PRECISION * 3) * 2;
*vcount += (CAP_PRECISION) * 2;
break;
case PathCap::NONE:
// Nothing to do.
break;
}
return count;
}
/**
* Creates the extruded line segment from a to b.
*
* The new vertices are appended to _outvert, while the new _indices are
* appended to _outindx.
*
* @param a The start of the line segment
* @param b The end of the line segment.
* @param data The data necessary to run the Kivy algorithm.
*/
void PathExtruder::makeSegment(const Vec2& a, const Vec2& b, KivyData* data) {
if (data->index > 0 && data->joint != PathJoint::NONE) {
data->pc = data->c;
data->p1 = data->v1; data->p2 = data->v2;
data->p3 = data->v3; data->p4 = data->v4;
}
data->p2pos = data->ppos; data->ppos = data->pos;
data->pangle2 = data->pangle; data->pangle = data->angle;
// Calculate the orientation of the segment, between pi and -pi
data->c = b - a;
data->angle = atan2(data->c.y, data->c.x);
float a1 = data->angle - M_PI_2;
float a2 = data->angle + M_PI_2;
// Calculate the position of the segment
Vec2 temp1 = Vec2(cos(a1) * data->stroke, sin(a1) * data->stroke);
Vec2 temp2 = Vec2(cos(a2) * data->stroke, sin(a2) * data->stroke);
data->v1 = a+temp1;
data->v4 = a+temp2;
data->v2 = b+temp1;
data->v3 = b+temp2;
if (data->index == 0) {
data->s1 = data->v1; data->s4 = data->v4;
data->sangle = data->angle;
}
// Add the indices
_outindx.push_back(data->pos );
_outindx.push_back(data->pos+1);
_outindx.push_back(data->pos+2);
_outindx.push_back(data->pos );
_outindx.push_back(data->pos+2);
_outindx.push_back(data->pos+3);
// Add the vertices
_outverts.push_back(data->v1);
_outverts.push_back(data->v2);
_outverts.push_back(data->v3);
_outverts.push_back(data->v4);
data->pos += 4;
}
/**
* Creates a joint immediately before point a.
*
* The new vertices are appended to _outvert, while the new _indices are
* appended to _outindx.
*
* @param a The generating point after the joint.
* @param data The data necessary to run the Kivy algorithm.
*
* @return true if a joint was successfully created.
*/
bool PathExtruder::makeJoint(const Vec2& a, KivyData* data) {
if (data->index == 0 || data->joint == PathJoint::NONE) {
return false;
}
// calculate the angle of the previous and current segment
float jangle = atan2(data->c.x * data->pc.y - data->c.y * data->pc.x,
data->c.x * data->pc.x + data->c.y * data->pc.y);
// in case of the angle is NULL, avoid the generation
if (jangle == 0) {
return false;
}
// Send to the specific joints
switch (data->joint) {
case PathJoint::BEVEL:
return makeBevelJoint(a, jangle, data);
case PathJoint::MITRE:
return makeMitreJoint(a,jangle,data);
case PathJoint::ROUND:
return makeRoundJoint(a,jangle,data);
case PathJoint::NONE:
// Nothing to do
break;
}
return true;
}
/**
* Creates a mitre joint immediately before point a.
*
* The new vertices are appended to _outvert, while the new _indices are
* appended to _outindx.
*
* @param a The generating point after the joint.
* @param jangle The joint angle
* @param data The data necessary to run the Kivy algorithm.
*
* @return true if a joint was successfully created.
*/
bool PathExtruder::makeMitreJoint(const Vec2& a, float jangle, KivyData* data) {
_outverts.push_back(a);
// Indices depend on angle
if (jangle < 0) {
float s, t;
if (Vec2::doesLineIntersect(data->p1, data->p2, data->v1, data->v2, &s,&t)) {
Vec2 temp = data->p1 + s*(data->p2-data->p1);
_outverts.push_back(temp);
_outindx.push_back(data->pos );
_outindx.push_back(data->pos+1 );
_outindx.push_back(data->p2pos+1);
_outindx.push_back(data->pos );
_outindx.push_back(data->ppos );
_outindx.push_back(data->pos+1 );
data->pos += 2;
return true;
}
} else {
float s, t;
if (Vec2::doesLineIntersect(data->p3, data->p4, data->v3, data->v4, &s, &t)) {
Vec2 temp = data->p3 + s*(data->p4-data->p3);
_outverts.push_back(temp);
_outindx.push_back(data->pos );
_outindx.push_back(data->pos+1 );
_outindx.push_back(data->p2pos+2);
_outindx.push_back(data->pos );
_outindx.push_back(data->ppos+3 );
_outindx.push_back(data->pos+1 );
data->pos += 2;
return true;
}
}
return false;
}
/**
* Creates a bevel joint immediately before point a.
*
* The new vertices are appended to _outvert, while the new _indices are
* appended to _outindx.
*
* @param a The generating point after the joint.
* @param jangle The joint angle
* @param data The data necessary to run the Kivy algorithm.
*
* @return true if a joint was successfully created.
*/
bool PathExtruder::makeBevelJoint(const Vec2& a, float jangle, KivyData* data) {
_outverts.push_back(a);
// Indices depend on angle
if (jangle < 0) {
_outindx.push_back(data->p2pos+1);
_outindx.push_back(data->ppos );
_outindx.push_back(data->pos );
} else {
_outindx.push_back(data->p2pos+2);
_outindx.push_back(data->ppos +3);
_outindx.push_back(data->pos );
}
data->pos += 1;
return true;
}
/**
* Creates a round joint immediately before point a.
*
* The new vertices are appended to _outvert, while the new _indices are
* appended to _outindx.
*
* @param a The generating point after the joint.
* @param jangle The joint angle
* @param data The data necessary to run the Kivy algorithm.
*
* @return true if a joint was successfully created.
*/
bool PathExtruder::makeRoundJoint(const Vec2& a, float jangle, KivyData* data) {
float a0, step;
unsigned int s_pos, e_pos;
if (jangle < 0) {
a0 = data->angle + M_PI_2;
step = (fabsf(jangle)) / (float)JOINT_PRECISION;
s_pos = data->ppos + 3;
e_pos = data->p2pos + 1;
} else {
a0 = data->angle - M_PI_2;
step = -(fabsf(jangle)) / (float)JOINT_PRECISION;
s_pos = data->ppos;
e_pos = data->p2pos + 2;
}
unsigned int opos = data->pos;
_outverts.push_back(a);
data->pos += 1;
for(int j = 0; j < JOINT_PRECISION - 1; j++) {
_outverts.push_back(a-Vec2(cos(a0 - step * j) * data->stroke,
sin(a0 - step * j) * data->stroke));
if (j == 0) {
_outindx.push_back(opos );
_outindx.push_back(s_pos);
_outindx.push_back(data->pos);
} else {
_outindx.push_back(opos );
_outindx.push_back(data->pos-1);
_outindx.push_back(data->pos);
}
data->pos += 1;
}
_outindx.push_back(opos );
_outindx.push_back(data->pos-1);
_outindx.push_back(e_pos);
return true;
}
/**
* Creates the caps on the two ends of the open path.
*
* The new vertices are appended to _outvert, while the new _indices are
* appended to _outindx.
*
* @param count The number of generating points in the path.
* @param data The data necessary to run the Kivy algorithm.
*
* @return true if a joint was successfully created.
*/
void PathExtruder::makeCaps(int count, KivyData* data) {
switch (data->cap) {
case PathCap::SQUARE:
makeSquareCaps(count, data);
break;
case PathCap::ROUND:
makeRoundCaps(count, data);
break;
case PathCap::NONE:
// Nothing to do.
break;
}
}
/**
* Creates square caps on the two ends of the open path.
*
* The new vertices are appended to _outvert, while the new _indices are
* appended to _outindx.
*
* @param count The number of generating points in the path.
* @param data The data necessary to run the Kivy algorithm.
*
* @return true if a joint was successfully created.
*/
void PathExtruder::makeSquareCaps(int count, KivyData* data) {
// cap end
Vec2 temp = Vec2(cos(data->angle) * data->stroke,
sin(data->angle) * data->stroke);
_outverts.push_back(data->v2+temp);
_outverts.push_back(data->v3+temp);
_outindx.push_back(data->ppos + 1);
_outindx.push_back(data->ppos + 2);
_outindx.push_back(data->pos + 1);
_outindx.push_back(data->ppos + 1);
_outindx.push_back(data->pos);
_outindx.push_back(data->pos + 1);
data->pos += 2;
// cap start
temp = Vec2(cos(data->sangle) * data->stroke,
sin(data->sangle) * data->stroke);
_outverts.push_back(data->s1-temp);
_outverts.push_back(data->s4-temp);
_outindx.push_back(0);
_outindx.push_back(3);
_outindx.push_back(data->pos + 1 );
_outindx.push_back(0);
_outindx.push_back(data->pos);
_outindx.push_back(data->pos + 1 );
data->pos += 2;
}
/**
* Creates round caps on the two ends of the open path.
*
* The new vertices are appended to _outvert, while the new _indices are
* appended to _outindx.
*
* @param count The number of generating points in the path.
* @param data The data necessary to run the Kivy algorithm.
*
* @return true if a joint was successfully created.
*/
void PathExtruder::makeRoundCaps(int count, KivyData* data) {
// cap start
float a1 = data->sangle - M_PI_2;
float a2 = data->sangle + M_PI_2;
float step = (a1 - a2) / (float)CAP_PRECISION;
unsigned int opos = data->pos;
data->c = _input[0];
_outverts.push_back(data->c);
data->pos += 1;
for(int i = 0; i < CAP_PRECISION - 1; i++) {
Vec2 temp = Vec2(cos(a1 + step * i) * data->stroke,
sin(a1 + step * i) * data->stroke);
_outverts.push_back(data->c+temp);
if (i == 0) {
_outindx.push_back(opos);
_outindx.push_back(0);
_outindx.push_back(data->pos);
} else {
_outindx.push_back(opos);
_outindx.push_back(data->pos-1);
_outindx.push_back(data->pos);
}
data->pos += 1;
}
_outindx.push_back(opos );
_outindx.push_back(data->pos-1);
_outindx.push_back(3);
// cap end
a1 = data->angle - M_PI_2;
a2 = data->angle + M_PI_2;
step = (a2 - a1) / (float)CAP_PRECISION;
opos = data->pos;
data->c = _input[count-1];
_outverts.push_back(data->c);
data->pos += 1;
for(int i = 0; i < CAP_PRECISION - 1; i++) {
Vec2 temp = Vec2(cos(a1 + step * i) * data->stroke,
sin(a1 + step * i) * data->stroke);
_outverts.push_back(data->c+temp);
if (i == 0) {
_outindx.push_back(opos );
_outindx.push_back(data->ppos+1);
_outindx.push_back(data->pos);
} else {
_outindx.push_back(opos );
_outindx.push_back(data->pos-1);
_outindx.push_back(data->pos);
}
data->pos += 1;
}
_outindx.push_back(opos);
_outindx.push_back(data->pos-1);
_outindx.push_back(data->ppos+2);
}
/**
* Creates the final joint at the end of a closed path.
*
* The new vertices are appended to _outvert, while the new _indices are
* appended to _outindx.
*
* @param data The data necessary to run the Kivy algorithm.
*
* @return true if a joint was successfully created.
*/
bool PathExtruder::makeLastJoint(KivyData* data) {
Vec2 a = _input[0];
Vec2 b = _input[1];
data->pc = data->c; data->c = b-a;
data->angle = atan2(data->c.y, data->c.x);
float a1 = data->angle - M_PI_2;
float a2 = data->angle + M_PI_2;
Vec2 temp1, temp2;
data->ppos = 0;
float jangle = atan2(data->c.x * data->pc.y - data->c.y * data->pc.x,
data->c.x * data->pc.x + data->c.y * data->pc.y);
switch (data->joint) {
case PathJoint::BEVEL:
data->p2pos = data->pos-5;
return makeBevelJoint(a, jangle, data);
case PathJoint::MITRE:
data->p1 = data->v1; data->p2 = data->v2;
data->p3 = data->v3; data->p4 = data->v4;
// Calculate the position of the segment
temp1 = Vec2(cos(a1) * data->stroke, sin(a1) * data->stroke);
temp2 = Vec2(cos(a2) * data->stroke, sin(a2) * data->stroke);
data->v1 = a+temp1; data->v4 = a+temp2;
data->v2 = b+temp1; data->v3 = b+temp2;
data->p2pos = data->pos-6;
return makeMitreJoint(a, jangle, data);
case PathJoint::ROUND:
data->p2pos = data->pos-JOINT_PRECISION-4;
return makeRoundJoint(a, jangle, data);
case PathJoint::NONE:
// Nothing to do
break;
}
return true;
}
#pragma mark -
#pragma mark Materialization
/**
* Returns a polygon representing the path extrusion.
*
* The polygon contains the original vertices together with the new
* indices defining the wireframe path. The extruder does not maintain
* references to this polygon and it is safe to modify it.
*
* If the calculation is not yet performed, this method will return the
* empty polygon.
*
* @return a polygon representing the path extrusion.
*/
Poly2 PathExtruder::getPolygon() {
Poly2 poly;
if (_calculated) {
poly._vertices = _outverts;
poly._indices = _outindx;
poly._type = Poly2::Type::SOLID;
poly.computeBounds();
}
return poly;
}
/**
* Stores the path extrusion in the given buffer.
*
* This method will add both the original vertices, and the corresponding
* indices to the new buffer. If the buffer is not empty, the indices
* will be adjusted accordingly. You should clear the buffer first if
* you do not want to preserve the original data.
*
* If the calculation is not yet performed, this method will do nothing.
*
* @param buffer The buffer to store the extruded polygon
*
* @return a reference to the buffer for chaining.
*/
Poly2* PathExtruder::getPolygon(Poly2* buffer) {
CUAssertLog(buffer, "Destination buffer is null");
if (_calculated) {
if (buffer->_vertices.size() == 0) {
buffer->_vertices = _outverts;
buffer->_indices = _outindx;
} else {
int offset = (int)buffer->_vertices.size();
buffer->_vertices.reserve(offset+_outverts.size());
std::copy(_outverts.begin(),_outverts.end(),std::back_inserter(buffer->_vertices));
buffer->_indices.reserve(buffer->_indices.size()+_outindx.size());
for(auto it = _outindx.begin(); it != _outindx.end(); ++it) {
buffer->_indices.push_back(offset+*it);
}
}
buffer->_type = Poly2::Type::SOLID;
buffer->computeBounds();
}
return buffer;
}
| [
"mt-xing@users.noreply.github.com"
] | mt-xing@users.noreply.github.com |
5cd56e7712c45e8ffee7411ad70fb204de7c8926 | 20d024bd04ace59987ba05f864d6d9dece72fbab | /CQU Summer/8-8 动态规划 V/I - 悼念512汶川大地震遇难同胞――珍惜现在,感恩生活.cpp | 21c1fec7968644e196045ebfe651719c16d7846c | [] | no_license | Yeluorag/ACM-ICPC-Code-Library | 8837688c23bf487d4374a76cf0656cb7adc751b0 | 77751c79549ea8ab6f790d55fac3738d5b615488 | refs/heads/master | 2021-01-20T20:18:43.366920 | 2016-08-12T08:08:38 | 2016-08-12T08:08:38 | 64,487,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,324 | cpp | #include <iostream>
#include <sstream>
#include <cstdio>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
#define mem(a, n) memset(a, n, sizeof(a))
#define rep(i, n) for(int i = 0; i < (n); i ++)
#define REP(i, t, n) for(int i = (t); i < (n); i ++)
#define REPD(i, t, n) for(int i = (n); i >= t; i --)
#define FOR(i, t, n) for(int i = (t); i <= (n); i ++)
#define ALL(v) v.begin(), v.end()
#define si(a) scanf("%d", &a)
#define ss(a) scanf("%s", a)
#define sii(a, b) scanf("%d%d", &a, &b)
#define VI vector<int>
#define PII pair<int, int>
#define pb push_back
#define ET puts("")
const int inf = 1 << 30, N = 4e2 + 5, MOD = 1e9 + 7;
int T, cas = 0;
int n, m, p[N], h[N], c[N], dp[105][N];
int main(){
#ifdef LOCAL
freopen("/Users/apple/input.txt", "r", stdin);
// freopen("/Users/apple/out.txt", "w", stdout);
#endif
si(T);
while(T --) {
sii(n, m);
rep(i, m) { si(p[i]), sii(h[i], c[i]); }
mem(dp, 0);
rep(i, m) {
for(int j = 0; j <= n; j ++) {
FOR(k, 0, c[i]) {
if(k * p[i] > j) break;
dp[i+1][j] = max(dp[i+1][j], dp[i][j-k*p[i]] + k * h[i]);
}
}
}
printf("%d\n", dp[m][n]);
}
return 0;
} | [
"yeluorag@gmail.com"
] | yeluorag@gmail.com |
49b12b66e157d673917191e218a8e5b89585bedb | 29affb727777af19c8a3f53f1706630c61051304 | /parser/ParserVersion.h | f2c5f407fe81f27761378a9c6f7d9cf3ca7d7987 | [] | no_license | wipkirill/sputnik-sdk | 7cd26f6bbd2e8b1b46ecf43c64b26c48eef72862 | 926b46f73e6c1eb08b675d59891589161d6db611 | refs/heads/master | 2021-08-19T07:39:04.740902 | 2017-11-25T07:30:44 | 2017-11-25T07:30:44 | 111,981,751 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,076 | h | #pragma once
#include <string>
#ifdef PARSER_VERSION_STRING
# undef PARSER_VERSION_STRING
#endif
#ifdef PARSER_VERSION_NUMBER
# undef PARSER_VERSION_NUMBER
#endif
/*
** Compile-Time Library Version Numbers
**
** ^(The [PARSER_VERSION] C preprocessor macro in the header
** evaluates to a string literal that is the libsputnik version in the
** format "X.Y.Z" where X is the major version number
** and Y is the minor version number and Z is the release number.)^
** ^(The [PARSER_VERSION_NUMBER] C preprocessor macro resolves to an integer
** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
** numbers used in [PARSER_VERSION].)^
*/
#define PARSER_VERSION_STRING "1.0.0"
#define PARSER_VERSION_NUMBER 1
#define PARSER_SOURCE_ID "2017-03-11 22:49:17.433"
#define PARSER_REVISION_ID "083c07a6c2f8c21f640d5c47b1165d1e27df532e"
std::string parser_version() {
return PARSER_VERSION_STRING;
}
std::string parser_source_id() {
return PARSER_SOURCE_ID " " PARSER_REVISION_ID;
}
int parser_version_number() {
return PARSER_VERSION_NUMBER;
}
| [
"wipkirill@gmail.com"
] | wipkirill@gmail.com |
3373732d89145b573af0ae4f22be72db2902daab | 23c6e6f35680bee885ee071ee123870c3dbc1e3d | /test/libcxx/forwardlist/emplace_after.pass.cpp | 025547b845fa4c1250e938883b87247fa56d77d3 | [] | no_license | paradise-fi/divine | 3a354c00f39ad5788e08eb0e33aff9d2f5919369 | d47985e0b5175a7b4ee506fb05198c4dd9eeb7ce | refs/heads/master | 2021-07-09T08:23:44.201902 | 2021-03-21T14:24:02 | 2021-03-21T14:24:02 | 95,647,518 | 15 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,203 | cpp | /* TAGS: c++ */
/* VERIFY_OPTS: -o nofail:malloc */
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <forward_list>
// template <class... Args>
// iterator emplace_after(const_iterator p, Args&&... args);
#include <forward_list>
#include <cassert>
#include "Emplaceable.h"
#include "min_allocator.h"
int main()
{
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
{
typedef Emplaceable T;
typedef std::forward_list<T> C;
typedef C::iterator I;
C c;
I i = c.emplace_after(c.cbefore_begin());
assert(i == c.begin());
assert(c.front() == Emplaceable());
assert(distance(c.begin(), c.end()) == 1);
i = c.emplace_after(c.cbegin(), 1, 2.5);
assert(i == next(c.begin()));
assert(c.front() == Emplaceable());
assert(*next(c.begin()) == Emplaceable(1, 2.5));
assert(distance(c.begin(), c.end()) == 2);
i = c.emplace_after(next(c.cbegin()), 2, 3.5);
assert(i == next(c.begin(), 2));
assert(c.front() == Emplaceable());
assert(*next(c.begin()) == Emplaceable(1, 2.5));
assert(*next(c.begin(), 2) == Emplaceable(2, 3.5));
assert(distance(c.begin(), c.end()) == 3);
i = c.emplace_after(c.cbegin(), 3, 4.5);
assert(i == next(c.begin()));
assert(c.front() == Emplaceable());
assert(*next(c.begin(), 1) == Emplaceable(3, 4.5));
assert(*next(c.begin(), 2) == Emplaceable(1, 2.5));
assert(*next(c.begin(), 3) == Emplaceable(2, 3.5));
assert(distance(c.begin(), c.end()) == 4);
}
#if __cplusplus >= 201103L
{
typedef Emplaceable T;
typedef std::forward_list<T, min_allocator<T>> C;
typedef C::iterator I;
C c;
I i = c.emplace_after(c.cbefore_begin());
assert(i == c.begin());
assert(c.front() == Emplaceable());
assert(distance(c.begin(), c.end()) == 1);
i = c.emplace_after(c.cbegin(), 1, 2.5);
assert(i == next(c.begin()));
assert(c.front() == Emplaceable());
assert(*next(c.begin()) == Emplaceable(1, 2.5));
assert(distance(c.begin(), c.end()) == 2);
i = c.emplace_after(next(c.cbegin()), 2, 3.5);
assert(i == next(c.begin(), 2));
assert(c.front() == Emplaceable());
assert(*next(c.begin()) == Emplaceable(1, 2.5));
assert(*next(c.begin(), 2) == Emplaceable(2, 3.5));
assert(distance(c.begin(), c.end()) == 3);
i = c.emplace_after(c.cbegin(), 3, 4.5);
assert(i == next(c.begin()));
assert(c.front() == Emplaceable());
assert(*next(c.begin(), 1) == Emplaceable(3, 4.5));
assert(*next(c.begin(), 2) == Emplaceable(1, 2.5));
assert(*next(c.begin(), 3) == Emplaceable(2, 3.5));
assert(distance(c.begin(), c.end()) == 4);
}
#endif
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
}
| [
"me@mornfall.net"
] | me@mornfall.net |
eaf4707f58f094ad3a00adb56c30d3687a33fe09 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-sagemaker/source/model/DeleteWorkforceRequest.cpp | d04dfc8ec0b506b657e6ed3ba6d088b653ec7835 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 924 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/sagemaker/model/DeleteWorkforceRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::SageMaker::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DeleteWorkforceRequest::DeleteWorkforceRequest() :
m_workforceNameHasBeenSet(false)
{
}
Aws::String DeleteWorkforceRequest::SerializePayload() const
{
JsonValue payload;
if(m_workforceNameHasBeenSet)
{
payload.WithString("WorkforceName", m_workforceName);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DeleteWorkforceRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "SageMaker.DeleteWorkforce"));
return headers;
}
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
559a79a8dfa02f330468def1a3c3b6c800416c00 | b8691935656ec9ce1466160d101be469f1fde46c | /driver.hpp | 40b8ade4b9845cc0587716a1c3e4b0f058c8d623 | [] | no_license | nyeung97/Image_Transformation | 4fa5a56ddd3ca31379f69c92537eaf7a4270edca | a7cbe2a3f2f020a7ec28902f60017b883bf06165 | refs/heads/master | 2022-02-18T16:51:10.261127 | 2019-08-24T14:01:59 | 2019-08-24T14:01:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | hpp | #include <iostream>
#include <stdlib.h>
#include <fstream>
using namespace std;
int checkfiles(ifstream& input, ofstream& output) {
if(input.is_open() == false) {
cout << "Input file failed to open";
exit(1);
}
if(output.is_open() == false) {
cout << "Output file failed to open";
exit(1);
}
cout << "Files opened successfully!";
return(0);
}
| [
"nelsonyeung97@gmail.com"
] | nelsonyeung97@gmail.com |
e6e350bde0e34d114737149b8080bec7e0362d6d | 057b5c42a7357cc3b9add37c159511758322a3f9 | /lab_03/inc/managers/base_manager.h | b05441d0a88360b8c9d249af787a7388cf7630f6 | [] | no_license | Pangolierchick/IU7-OOP | 85551cb9873356c48ed925c7183f70d7bec83590 | ef56a80d48ee770538771c2a3c4085574a2e08c1 | refs/heads/master | 2023-05-15T00:34:20.079985 | 2021-06-05T15:29:10 | 2021-06-05T15:29:10 | 343,880,849 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 113 | h | #pragma once
class BaseManager {
public:
BaseManager() = default;
~BaseManager() = default;
};
| [
"gogofun@bk.ru"
] | gogofun@bk.ru |
57afb3a0c8b77dca182b2645a6eb055d518f9595 | 6cddc32efeef73a5176419a645f500f18cace88c | /1.1/default/NfcClientCallback.h | 774df2b770978264300478c67b43827af6bcdbec | [] | no_license | DirtyUnicorns/android_vendor_nxp_opensource_hidlimpl | 3342d44ab80494fce4ab0badffcb5d0cf6c72d77 | bd5d8628be7b3bb0fa186d424b3c9f15856b90f3 | refs/heads/q10x | 2020-04-23T14:12:34.581275 | 2019-11-15T13:09:58 | 2019-11-15T13:09:58 | 171,223,713 | 0 | 3 | null | 2019-11-26T21:35:46 | 2019-02-18T05:59:38 | C++ | UTF-8 | C++ | false | false | 3,127 | h | /*
* Copyright (c) 2018, The Linux Foundation. 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 The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* 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.
*/
#ifndef ANDROID_HARDWARE_NFC_V1_1_NFCCLIENTCALLBACK_H
#define ANDROID_HARDWARE_NFC_V1_1_NFCCLIENTCALLBACK_H
#include <android/hardware/nfc/1.1/INfcClientCallback.h>
#include <hidl/MQDescriptor.h>
#include <hidl/Status.h>
namespace android {
namespace hardware {
namespace nfc {
namespace V1_1 {
namespace implementation {
using ::android::hardware::hidl_array;
using ::android::hardware::hidl_memory;
using ::android::hardware::hidl_string;
using ::android::hardware::hidl_vec;
using ::android::hardware::Return;
using ::android::hardware::Void;
using ::android::sp;
struct NfcClientCallback : public INfcClientCallback {
// Methods from ::android::hardware::nfc::V1_0::INfcClientCallback follow.
Return<void> sendEvent(::android::hardware::nfc::V1_0::NfcEvent event, ::android::hardware::nfc::V1_0::NfcStatus status) override;
Return<void> sendData(const hidl_vec<uint8_t>& data) override;
// Methods from ::android::hardware::nfc::V1_1::INfcClientCallback follow.
Return<void> sendEvent_1_1(::android::hardware::nfc::V1_1::NfcEvent event, ::android::hardware::nfc::V1_0::NfcStatus status) override;
// Methods from ::android::hidl::base::V1_0::IBase follow.
};
// FIXME: most likely delete, this is only for passthrough implementations
// extern "C" INfcClientCallback* HIDL_FETCH_INfcClientCallback(const char* name);
} // namespace implementation
} // namespace V1_1
} // namespace nfc
} // namespace hardware
} // namespace android
#endif // ANDROID_HARDWARE_NFC_V1_1_NFCCLIENTCALLBACK_H
| [
"rrangwan@codeaurora.org"
] | rrangwan@codeaurora.org |
34cc7db22e5815ea8b1f035e288c797c63727560 | 050ebbbc7d5f89d340fd9f2aa534eac42d9babb7 | /grupa2/pkramarski/p1/cza.cpp | 7c85f840ceb828888a0b681717b2c677d088dc00 | [] | no_license | anagorko/zpk2015 | 83461a25831fa4358366ec15ab915a0d9b6acdf5 | 0553ec55d2617f7bea588d650b94828b5f434915 | refs/heads/master | 2020-04-05T23:47:55.299547 | 2016-09-14T11:01:46 | 2016-09-14T11:01:46 | 52,429,626 | 0 | 13 | null | 2016-03-22T09:35:25 | 2016-02-24T09:19:07 | C++ | UTF-8 | C++ | false | false | 215 | cpp | #include<iostream>
using namespace std;
int main (){
int a, g, m, s;
cin >> a;
g = a/3600;
m = (a - g*3600)/60;
s = (a - g*3600 - m*60);
cout << g << "g" << m << "m" << s << "s" << endl;
}
| [
"pawel.kramarski@student.uw.edu.pl"
] | pawel.kramarski@student.uw.edu.pl |
2a2e011a3ea5c05add7877eeaff9d0cb1b338487 | 1af49694004c6fbc31deada5618dae37255ce978 | /chrome/browser/notifications/notification_display_service_impl.cc | f82d310e49b5ea33283330b521d3ed2e07ef8992 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 12,845 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/notification_display_service_impl.h"
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/feature_list.h"
#include "base/logging.h"
#include "build/build_config.h"
#include "build/buildflag.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_features.h"
#include "chrome/browser/notifications/non_persistent_notification_handler.h"
#include "chrome/browser/notifications/notification_display_service_factory.h"
#include "chrome/browser/notifications/persistent_notification_handler.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/updates/announcement_notification/announcement_notification_handler.h"
#include "chrome/common/pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/buildflags/buildflags.h"
#include "ui/message_center/public/cpp/notification.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/api/notifications/extension_notification_handler.h"
#endif
#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_MAC) || \
defined(OS_WIN)
#include "chrome/browser/send_tab_to_self/desktop_notification_handler.h"
#include "chrome/browser/sharing/sharing_notification_handler.h"
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/nearby_sharing/common/nearby_share_features.h"
#include "chrome/browser/nearby_sharing/nearby_notification_handler.h"
#endif
#if !defined(OS_ANDROID)
#include "chrome/browser/notifications/muted_notification_handler.h"
#include "chrome/browser/notifications/screen_capture_notification_blocker.h"
#endif
namespace {
void OperationCompleted() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}
} // namespace
// static
NotificationDisplayServiceImpl* NotificationDisplayServiceImpl::GetForProfile(
Profile* profile) {
return static_cast<NotificationDisplayServiceImpl*>(
NotificationDisplayServiceFactory::GetForProfile(profile));
}
// static
void NotificationDisplayServiceImpl::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
// of lacros-chrome is complete.
#if defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
registry->RegisterBooleanPref(prefs::kAllowNativeNotifications, true);
#endif
}
NotificationDisplayServiceImpl::NotificationDisplayServiceImpl(Profile* profile)
: profile_(profile) {
// TODO(peter): Move these to the NotificationDisplayServiceFactory.
if (profile_) {
AddNotificationHandler(
NotificationHandler::Type::WEB_NON_PERSISTENT,
std::make_unique<NonPersistentNotificationHandler>());
AddNotificationHandler(NotificationHandler::Type::WEB_PERSISTENT,
std::make_unique<PersistentNotificationHandler>());
#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_MAC) || \
defined(OS_WIN)
AddNotificationHandler(
NotificationHandler::Type::SEND_TAB_TO_SELF,
std::make_unique<send_tab_to_self::DesktopNotificationHandler>(
profile_));
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
AddNotificationHandler(
NotificationHandler::Type::EXTENSION,
std::make_unique<extensions::ExtensionNotificationHandler>());
#endif
#if !defined(OS_ANDROID)
AddNotificationHandler(NotificationHandler::Type::SHARING,
std::make_unique<SharingNotificationHandler>());
AddNotificationHandler(NotificationHandler::Type::ANNOUNCEMENT,
std::make_unique<AnnouncementNotificationHandler>());
if (base::FeatureList::IsEnabled(
features::kMuteNotificationsDuringScreenShare)) {
auto screen_capture_blocker =
std::make_unique<ScreenCaptureNotificationBlocker>(this);
AddNotificationHandler(NotificationHandler::Type::NOTIFICATIONS_MUTED,
std::make_unique<MutedNotificationHandler>(
screen_capture_blocker.get()));
notification_queue_.AddNotificationBlocker(
std::move(screen_capture_blocker));
}
#endif
#if BUILDFLAG(IS_CHROMEOS_ASH)
if (base::FeatureList::IsEnabled(features::kNearbySharing)) {
AddNotificationHandler(NotificationHandler::Type::NEARBY_SHARE,
std::make_unique<NearbyNotificationHandler>());
}
#endif
}
bridge_delegator_ = std::make_unique<NotificationPlatformBridgeDelegator>(
profile_,
base::BindOnce(
&NotificationDisplayServiceImpl::OnNotificationPlatformBridgeReady,
weak_factory_.GetWeakPtr()));
}
NotificationDisplayServiceImpl::~NotificationDisplayServiceImpl() {
for (auto& obs : observers_)
obs.OnNotificationDisplayServiceDestroyed(this);
}
void NotificationDisplayServiceImpl::ProcessNotificationOperation(
NotificationCommon::Operation operation,
NotificationHandler::Type notification_type,
const GURL& origin,
const std::string& notification_id,
const base::Optional<int>& action_index,
const base::Optional<base::string16>& reply,
const base::Optional<bool>& by_user) {
NotificationHandler* handler = GetNotificationHandler(notification_type);
DCHECK(handler);
if (!handler) {
LOG(ERROR) << "Unable to find a handler for "
<< static_cast<int>(notification_type);
return;
}
// TODO(crbug.com/766854): Plumb this through from the notification platform
// bridges so they can report completion of the operation as needed.
base::OnceClosure completed_closure = base::BindOnce(&OperationCompleted);
switch (operation) {
case NotificationCommon::OPERATION_CLICK:
handler->OnClick(profile_, origin, notification_id, action_index, reply,
std::move(completed_closure));
break;
case NotificationCommon::OPERATION_CLOSE:
DCHECK(by_user.has_value());
handler->OnClose(profile_, origin, notification_id, by_user.value(),
std::move(completed_closure));
for (auto& observer : observers_)
observer.OnNotificationClosed(notification_id);
break;
case NotificationCommon::OPERATION_DISABLE_PERMISSION:
handler->DisableNotifications(profile_, origin);
break;
case NotificationCommon::OPERATION_SETTINGS:
handler->OpenSettings(profile_, origin);
break;
}
}
void NotificationDisplayServiceImpl::AddNotificationHandler(
NotificationHandler::Type notification_type,
std::unique_ptr<NotificationHandler> handler) {
DCHECK(handler);
DCHECK_EQ(notification_handlers_.count(notification_type), 0u);
notification_handlers_[notification_type] = std::move(handler);
}
NotificationHandler* NotificationDisplayServiceImpl::GetNotificationHandler(
NotificationHandler::Type notification_type) {
auto found = notification_handlers_.find(notification_type);
if (found != notification_handlers_.end())
return found->second.get();
return nullptr;
}
void NotificationDisplayServiceImpl::Shutdown() {
bridge_delegator_->DisplayServiceShutDown();
}
void NotificationDisplayServiceImpl::Display(
NotificationHandler::Type notification_type,
const message_center::Notification& notification,
std::unique_ptr<NotificationCommon::Metadata> metadata) {
// TODO(estade): in the future, the reverse should also be true: a
// non-TRANSIENT type implies no delegate.
if (notification_type == NotificationHandler::Type::TRANSIENT)
DCHECK(notification.delegate());
CHECK(profile_ || notification_type == NotificationHandler::Type::TRANSIENT);
if (!bridge_delegator_initialized_) {
actions_.push(base::BindOnce(&NotificationDisplayServiceImpl::Display,
weak_factory_.GetWeakPtr(), notification_type,
notification, std::move(metadata)));
return;
}
for (auto& observer : observers_)
observer.OnNotificationDisplayed(notification, metadata.get());
if (notification_queue_.ShouldEnqueueNotification(notification_type,
notification)) {
notification_queue_.EnqueueNotification(notification_type, notification,
std::move(metadata));
} else {
bridge_delegator_->Display(notification_type, notification,
std::move(metadata));
}
NotificationHandler* handler = GetNotificationHandler(notification_type);
if (handler)
handler->OnShow(profile_, notification.id());
}
void NotificationDisplayServiceImpl::Close(
NotificationHandler::Type notification_type,
const std::string& notification_id) {
CHECK(profile_ || notification_type == NotificationHandler::Type::TRANSIENT);
if (!bridge_delegator_initialized_) {
actions_.push(base::BindOnce(&NotificationDisplayServiceImpl::Close,
weak_factory_.GetWeakPtr(), notification_type,
notification_id));
return;
}
notification_queue_.RemoveQueuedNotification(notification_id);
bridge_delegator_->Close(notification_type, notification_id);
}
void NotificationDisplayServiceImpl::GetDisplayed(
DisplayedNotificationsCallback callback) {
if (!bridge_delegator_initialized_) {
actions_.push(base::BindOnce(&NotificationDisplayServiceImpl::GetDisplayed,
weak_factory_.GetWeakPtr(),
std::move(callback)));
return;
}
bridge_delegator_->GetDisplayed(
base::BindOnce(&NotificationDisplayServiceImpl::OnGetDisplayed,
weak_factory_.GetWeakPtr(), std::move(callback)));
}
void NotificationDisplayServiceImpl::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void NotificationDisplayServiceImpl::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
// Callback to run once the profile has been loaded in order to perform a
// given |operation| in a notification.
void NotificationDisplayServiceImpl::ProfileLoadedCallback(
NotificationCommon::Operation operation,
NotificationHandler::Type notification_type,
const GURL& origin,
const std::string& notification_id,
const base::Optional<int>& action_index,
const base::Optional<base::string16>& reply,
const base::Optional<bool>& by_user,
Profile* profile) {
if (!profile) {
// TODO(miguelg): Add UMA for this condition.
// Perhaps propagate this through PersistentNotificationStatus.
LOG(WARNING) << "Profile not loaded correctly";
return;
}
NotificationDisplayServiceImpl* display_service =
NotificationDisplayServiceImpl::GetForProfile(profile);
display_service->ProcessNotificationOperation(operation, notification_type,
origin, notification_id,
action_index, reply, by_user);
}
void NotificationDisplayServiceImpl::SetBlockersForTesting(
NotificationDisplayQueue::NotificationBlockers blockers) {
notification_queue_.SetNotificationBlockers(std::move(blockers));
}
void NotificationDisplayServiceImpl::
SetNotificationPlatformBridgeDelegatorForTesting(
std::unique_ptr<NotificationPlatformBridgeDelegator> bridge_delegator) {
bridge_delegator_ = std::move(bridge_delegator);
OnNotificationPlatformBridgeReady();
}
void NotificationDisplayServiceImpl::OverrideNotificationHandlerForTesting(
NotificationHandler::Type notification_type,
std::unique_ptr<NotificationHandler> handler) {
DCHECK(handler);
DCHECK_EQ(1u, notification_handlers_.count(notification_type));
notification_handlers_[notification_type] = std::move(handler);
}
void NotificationDisplayServiceImpl::OnNotificationPlatformBridgeReady() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
bridge_delegator_initialized_ = true;
// Flush any pending actions that have yet to execute.
while (!actions_.empty()) {
std::move(actions_.front()).Run();
actions_.pop();
}
}
void NotificationDisplayServiceImpl::OnGetDisplayed(
DisplayedNotificationsCallback callback,
std::set<std::string> notification_ids,
bool supports_synchronization) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
std::set<std::string> queued = notification_queue_.GetQueuedNotificationIds();
notification_ids.insert(queued.begin(), queued.end());
std::move(callback).Run(std::move(notification_ids),
supports_synchronization);
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
380d2d12cbeeae0fe577bd2da0ebb7b6634be3b1 | c0fbe5034244b314fc218364e83540eee0e11132 | /SceneParams.h | 11c56b3a76dc2594864603832973cef947f7af14 | [] | no_license | studentwb/wisualisation_ISS | d2eaf1a1eabfec2705313e2fb8c6fb270dfc9088 | 75775f26a5cf7a44578d19a5cab774420d9e07ad | refs/heads/master | 2022-10-10T05:25:02.203260 | 2020-06-13T23:27:54 | 2020-06-13T23:27:54 | 264,520,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | h | #ifndef SCENEPARAMS_H
#define SCENEPARAMS_H
/*!
* \brief SceneParams
* Klasa odpowiada za ustawienia prametrów sceny, na której rozkładane jest tło
*/
class SceneParams {
double _AngleX_deg;
double _X_Light_deg = 0;
double _Y_Light_deg = 0;
double _Z_Light_deg = 0;
public:
SceneParams()
{ _AngleX_deg = 0; }
void SetAngleX_deg(double AngleX_deg) { _AngleX_deg = AngleX_deg; }
double GetAngleX_deg() const { return _AngleX_deg; }
void SetZ_Light_deg(double Z_Light_deg) { _Z_Light_deg = Z_Light_deg; }
double GetZ_Light_deg() const { return _Z_Light_deg; }
void SetY_Light_deg(double Y_Light_deg) { _Y_Light_deg = Y_Light_deg; }
double GetY_Light_deg() const { return _Y_Light_deg; }
void SetX_Light_deg(double X_Light_deg) { _X_Light_deg = X_Light_deg; }
double GetX_Light_deg() const { return _X_Light_deg; }
};
extern SceneParams ScnParams;
#endif // SCENEPARAMS_H
| [
"wabaron98@gmail.com"
] | wabaron98@gmail.com |
1c0c2ea3305b8b39be38c2abc3feff9186fa763f | 945ba1aa3d720a454237ffe2d785d7416d70753f | /src/php_v8_try_catch.cc | 9858ac444a36db102215612144b1175a78f0df4f | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | rawhitr/php-v8 | 2e29f8d256a30eed93625792efdf3902070edf97 | 051d1006a9f74ba8fc678306ba992baa679a9aef | refs/heads/master | 2020-03-21T04:53:12.011735 | 2018-04-25T13:54:32 | 2018-04-25T13:54:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,295 | cc | /*
* This file is part of the pinepain/php-v8 PHP extension.
*
* Copyright (c) 2015-2018 Bogdan Padalko <pinepain@gmail.com>
*
* Licensed under the MIT license: http://opensource.org/licenses/MIT
*
* For the full copyright and license information, please view the
* LICENSE file that was distributed with this source or visit
* http://opensource.org/licenses/MIT
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_v8_try_catch.h"
#include "php_v8_message.h"
#include "php_v8_value.h"
#include "php_v8.h"
zend_class_entry* php_v8_try_catch_class_entry;
#define this_ce php_v8_try_catch_class_entry
void php_v8_try_catch_create_from_try_catch(zval *return_value, php_v8_isolate_t *php_v8_isolate, php_v8_context_t *php_v8_context, v8::TryCatch *try_catch) {
zval isolate_zv;
zval context_zv;
object_init_ex(return_value, this_ce);
PHP_V8_DECLARE_ISOLATE(php_v8_isolate);
v8::Local<v8::Context> context = isolate->GetEnteredContext();
ZVAL_OBJ(&isolate_zv, &php_v8_isolate->std);
ZVAL_OBJ(&context_zv, &php_v8_context->std);
zend_update_property(this_ce, return_value, ZEND_STRL("isolate"), &isolate_zv);
zend_update_property(this_ce, return_value, ZEND_STRL("context"), &context_zv);
zend_update_property_bool(this_ce, return_value, ZEND_STRL("can_continue"), static_cast<zend_long>(try_catch && try_catch->CanContinue()));
zend_update_property_bool(this_ce, return_value, ZEND_STRL("has_terminated"), static_cast<zend_long>(try_catch && try_catch->HasTerminated()));
if (try_catch && !try_catch->Exception().IsEmpty()) {
zval exception_zv;
php_v8_value_t * php_v8_value = php_v8_get_or_create_value(&exception_zv, try_catch->Exception(), php_v8_isolate);
zend_update_property(this_ce, return_value, ZEND_STRL("exception"), &exception_zv);
if (!Z_ISUNDEF(php_v8_value->exception)) {
zend_update_property(this_ce, return_value, ZEND_STRL("external_exception"), &php_v8_value->exception);
zval_ptr_dtor(&php_v8_value->exception);
ZVAL_UNDEF(&php_v8_value->exception);
}
zval_ptr_dtor(&exception_zv);
}
if (try_catch && !try_catch->StackTrace(context).IsEmpty()) {
zval stack_trace_zv;
php_v8_get_or_create_value(&stack_trace_zv, try_catch->StackTrace(context).ToLocalChecked(), php_v8_isolate);
zend_update_property(this_ce, return_value, ZEND_STRL("stack_trace"), &stack_trace_zv);
zval_ptr_dtor(&stack_trace_zv);
}
if (try_catch && !try_catch->Message().IsEmpty()) {
zval message_zv;
php_v8_message_create_from_message(&message_zv, php_v8_isolate, try_catch->Message());
zend_update_property(this_ce, return_value, ZEND_STRL("message"), &message_zv);
zval_ptr_dtor(&message_zv);
}
}
static PHP_METHOD(TryCatch, __construct) {
zval *php_v8_isolate_zv;
zval *php_v8_context_zv;
zval *php_v8_exception_zv = NULL;
zval *php_v8_stack_trace_zv = NULL;
zval *php_v8_message_zv = NULL;
zval *external_exception_zv = NULL;
zend_bool can_continue = '\0';
zend_bool has_terminated = '\0';
if (zend_parse_parameters(ZEND_NUM_ARGS(), "oo|o!o!o!bbo!",
&php_v8_isolate_zv,
&php_v8_context_zv,
&php_v8_exception_zv,
&php_v8_stack_trace_zv,
&php_v8_message_zv,
&can_continue,
&has_terminated,
&external_exception_zv) == FAILURE) {
return;
}
PHP_V8_ISOLATE_FETCH_WITH_CHECK(php_v8_isolate_zv, php_v8_isolate);
PHP_V8_CONTEXT_FETCH_WITH_CHECK(php_v8_context_zv, php_v8_context);
PHP_V8_DATA_ISOLATES_CHECK_USING(php_v8_context, php_v8_isolate);
zend_update_property(this_ce, getThis(), ZEND_STRL("isolate"), php_v8_isolate_zv);
zend_update_property(this_ce, getThis(), ZEND_STRL("context"), php_v8_context_zv);
if (php_v8_exception_zv != NULL) {
PHP_V8_VALUE_FETCH_WITH_CHECK(php_v8_exception_zv, php_v8_exception_value);
PHP_V8_DATA_ISOLATES_CHECK_USING(php_v8_exception_value, php_v8_isolate);
zend_update_property(this_ce, getThis(), ZEND_STRL("exception"), php_v8_exception_zv);
}
if (php_v8_stack_trace_zv != NULL) {
PHP_V8_VALUE_FETCH_WITH_CHECK(php_v8_stack_trace_zv, php_v8_stack_trace_value);
PHP_V8_DATA_ISOLATES_CHECK_USING(php_v8_stack_trace_value, php_v8_isolate);
zend_update_property(this_ce, getThis(), ZEND_STRL("stack_trace"), php_v8_stack_trace_zv);
}
if (php_v8_message_zv != NULL) {
zend_update_property(this_ce, getThis(), ZEND_STRL("message"), php_v8_message_zv);
}
zend_update_property_bool(this_ce, getThis(), ZEND_STRL("can_continue"), can_continue);
zend_update_property_bool(this_ce, getThis(), ZEND_STRL("has_terminated"), has_terminated);
if (external_exception_zv != NULL) {
zend_update_property(this_ce, getThis(), ZEND_STRL("external_exception"), external_exception_zv);
}
}
static PHP_METHOD(TryCatch, getIsolate)
{
zval rv;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETVAL_ZVAL(zend_read_property(this_ce, getThis(), ZEND_STRL("isolate"), 0, &rv), 1, 0);
}
static PHP_METHOD(TryCatch, getContext)
{
zval rv;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETVAL_ZVAL(zend_read_property(this_ce, getThis(), ZEND_STRL("context"), 0, &rv), 1, 0);
}
static PHP_METHOD(TryCatch, getException)
{
zval rv;
zval *prop;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
prop = zend_read_property(this_ce, getThis(), ZEND_STRL("exception"), 0, &rv);
RETVAL_ZVAL(prop, 1, 0);
}
static PHP_METHOD(TryCatch, getStackTrace)
{
zval rv;
zval *prop;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
prop = zend_read_property(this_ce, getThis(), ZEND_STRL("stack_trace"), 0, &rv);
RETVAL_ZVAL(prop, 1, 0);
}
static PHP_METHOD(TryCatch, getMessage)
{
zval rv;
zval *prop;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
prop = zend_read_property(this_ce, getThis(), ZEND_STRL("message"), 0, &rv);
RETVAL_ZVAL(prop, 1, 0);
}
static PHP_METHOD(TryCatch, canContinue)
{
zval rv;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETVAL_ZVAL(zend_read_property(this_ce, getThis(), ZEND_STRL("can_continue"), 0, &rv), 1, 0);
}
static PHP_METHOD(TryCatch, hasTerminated)
{
zval rv;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETVAL_ZVAL(zend_read_property(this_ce, getThis(), ZEND_STRL("has_terminated"), 0, &rv), 1, 0);
}
static PHP_METHOD(TryCatch, getExternalException)
{
zval rv;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETVAL_ZVAL(zend_read_property(this_ce, getThis(), ZEND_STRL("external_exception"), 0, &rv), 1, 0);
}
PHP_V8_ZEND_BEGIN_ARG_WITH_CONSTRUCTOR_INFO_EX(arginfo___construct, 2)
ZEND_ARG_OBJ_INFO(0, isolate, V8\\Isolate, 0)
ZEND_ARG_OBJ_INFO(0, context, V8\\Context, 0)
ZEND_ARG_OBJ_INFO(0, exception, V8\\Value, 1)
ZEND_ARG_OBJ_INFO(0, stack_trace, V8\\Value, 1)
ZEND_ARG_OBJ_INFO(0, message, V8\\Message, 1)
ZEND_ARG_TYPE_INFO(0, can_continue, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, has_terminated, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, external_exception, Throwable, 1)
ZEND_END_ARG_INFO()
PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_getIsolate, ZEND_RETURN_VALUE, 0, V8\\Isolate, 0)
ZEND_END_ARG_INFO()
PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_getContext, ZEND_RETURN_VALUE, 0, V8\\Context, 0)
ZEND_END_ARG_INFO()
PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_getException, ZEND_RETURN_VALUE, 0, V8\\Value, 1)
ZEND_END_ARG_INFO()
PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_getStackTrace, ZEND_RETURN_VALUE, 0, V8\\Value, 1)
ZEND_END_ARG_INFO()
PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_getMessage, ZEND_RETURN_VALUE, 0, V8\\Message, 1)
ZEND_END_ARG_INFO()
PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_canContinue, ZEND_RETURN_VALUE, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_hasTerminated, ZEND_RETURN_VALUE, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
PHP_V8_ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_getExternalException, ZEND_RETURN_VALUE, 0, Throwable, 1)
ZEND_END_ARG_INFO()
static const zend_function_entry php_v8_try_catch_methods[] = {
PHP_V8_ME(TryCatch, __construct, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR)
PHP_V8_ME(TryCatch, getIsolate, ZEND_ACC_PUBLIC)
PHP_V8_ME(TryCatch, getContext, ZEND_ACC_PUBLIC)
PHP_V8_ME(TryCatch, getException, ZEND_ACC_PUBLIC)
PHP_V8_ME(TryCatch, getStackTrace, ZEND_ACC_PUBLIC)
PHP_V8_ME(TryCatch, getMessage, ZEND_ACC_PUBLIC)
PHP_V8_ME(TryCatch, canContinue, ZEND_ACC_PUBLIC)
PHP_V8_ME(TryCatch, hasTerminated, ZEND_ACC_PUBLIC)
PHP_V8_ME(TryCatch, getExternalException, ZEND_ACC_PUBLIC)
PHP_FE_END
};
PHP_MINIT_FUNCTION (php_v8_try_catch) {
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce, PHP_V8_NS, "TryCatch", php_v8_try_catch_methods);
this_ce = zend_register_internal_class(&ce);
zend_declare_property_null(this_ce, ZEND_STRL("isolate"), ZEND_ACC_PRIVATE);
zend_declare_property_null(this_ce, ZEND_STRL("context"), ZEND_ACC_PRIVATE);
zend_declare_property_null(this_ce, ZEND_STRL("exception"), ZEND_ACC_PRIVATE);
zend_declare_property_null(this_ce, ZEND_STRL("stack_trace"), ZEND_ACC_PRIVATE);
zend_declare_property_null(this_ce, ZEND_STRL("message"), ZEND_ACC_PRIVATE);
zend_declare_property_null(this_ce, ZEND_STRL("can_continue"), ZEND_ACC_PRIVATE);
zend_declare_property_null(this_ce, ZEND_STRL("has_terminated"), ZEND_ACC_PRIVATE);
zend_declare_property_null(this_ce, ZEND_STRL("external_exception"), ZEND_ACC_PRIVATE);
return SUCCESS;
}
| [
"pinepain@gmail.com"
] | pinepain@gmail.com |
4031b34ac8fdfdf98db0f77b5c2a10c7d3983208 | 28b93971a99bdc488ad2e96f52373e8c045dd45b | /YTE/Graphics/Precompiled.cpp | 23233676eb029c4abf0a503a33d702da5bc5bee8 | [] | no_license | rodrigobmg/Yours-Truly-Engine | 8d10e6944d256e07ecfa5ac4f1973fa12d7204ef | 8bdea121201b26689f8d180fe0b7ebc542e1ca83 | refs/heads/master | 2020-05-18T10:57:30.276549 | 2017-11-04T01:30:14 | 2017-11-04T01:30:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39 | cpp | #include "YTE/Graphics/Precompiled.hpp" | [
"playmer@gmail.com"
] | playmer@gmail.com |
33aa906d779d054ce1dd66aaa4846316b0a334dd | b012b15ec5edf8a52ecf3d2f390adc99633dfb82 | /branches-public/moos-ivp-12.2mit/ivp/src/pSearchGrid/main.cpp | e485998ea32fcff15824f444409fb7b0afba3ba8 | [] | no_license | crosslore/moos-ivp-aro | cbe697ba3a842961d08b0664f39511720102342b | cf2f1abe0e27ccedd0bbc66e718be950add71d9b | refs/heads/master | 2022-12-06T08:14:18.641803 | 2020-08-18T06:39:14 | 2020-08-18T06:39:14 | 263,586,714 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,577 | cpp | /****************************************************************/
/* NAME: Michael Benjamin, Henrik Schmidt, and John Leonard */
/* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */
/* FILE: main.cpp */
/* DATE: Dec 10th 2011 */
/****************************************************************/
#include <iostream>
#include "MBUtils.h"
#include "ColorParse.h"
#include "SearchGrid.h"
#include "SearchGrid_Info.h"
using namespace std;
int main(int argc, char *argv[])
{
string mission_file;
string run_command = argv[0];
for(int i=1; i<argc; i++) {
string argi = argv[i];
if((argi=="-v") || (argi=="--version") || (argi=="-version"))
showReleaseInfoAndExit();
else if((argi=="-e") || (argi=="--example") || (argi=="-example"))
showExampleConfigAndExit();
else if((argi == "-h") || (argi == "--help") || (argi=="-help"))
showHelpAndExit();
else if((argi == "-i") || (argi == "--interface"))
showInterfaceAndExit();
else if(strEnds(argi, ".moos") || strEnds(argi, ".moos++"))
mission_file = argv[i];
else if(strBegins(argi, "--alias="))
run_command = argi.substr(8);
else if(i==2)
run_command = argi;
}
if(mission_file == "")
showHelpAndExit();
cout << termColor("green");
cout << "pSearchGrid launching as " << run_command << endl;
cout << termColor() << endl;
SearchGrid search_grid;
search_grid.Run(run_command.c_str(), mission_file.c_str());
return(0);
}
| [
"zouxueson@hotmail.com"
] | zouxueson@hotmail.com |
733f709d215dc870ceb2a4004d6561ff58edf77a | c1f9c8c023b0910060fe1e3fe25ef3dfec316df9 | /src/main.cpp | 54f819ea22290b8ece8d8a5ecfff2dad4d3b7c2a | [
"MIT"
] | permissive | get9/dvsim | 6dadcb17e5b87d88359430c105868fe3d56757f7 | 404aca4bdbac5bd1722a82f876b9a7851f44f4f7 | refs/heads/master | 2021-01-10T11:22:58.239569 | 2015-12-04T01:05:12 | 2015-12-04T01:05:12 | 47,088,369 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 807 | cpp | #include "util.h"
#include "node.h"
#include <iostream>
#include <cstdlib>
int main(int argc, char** argv)
{
// CLI argument verification
if (argc < 2) {
std::cerr << "Usage:" << std::endl;
std::cerr << " " << argv[0] << " config.txt" << std::endl;
std::exit(1);
}
// Parse config file (either from stdin or from file)
NodeConfig config;
if (std::string(argv[1]) == "<") {
std::cout << "getting config from stdin" << std::endl;
config = parse_config_file(std::cin);
} else {
std::ifstream infile(argv[1], std::ifstream::in);
std::cout << "getting config from " << argv[1] << std::endl;
config = parse_config_file(infile);
}
// Start a node
DVSim::Node this_node(config);
this_node.start();
}
| [
"skarlage@get9.io"
] | skarlage@get9.io |
21f276307d27875b70910c064158cd046e36bb7e | 0897560a7ebde50481f950c9a441e2fc3c34ba04 | /10.0.15042.0/winrt/internal/Windows.Web.Http.Diagnostics.3.h | d5ff2448262ff649e647aa7ad7f5fa1724bf2704 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | dngoins/cppwinrt | 338f01171153cbca14a723217129ed36b6ce2c9d | 0bb7a57392673f793ba99978738490100a9684ec | refs/heads/master | 2021-01-19T19:14:59.993078 | 2017-03-01T22:14:18 | 2017-03-01T22:14:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,746 | h | // C++ for the Windows Runtime v1.0.private
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Web.Http.Diagnostics.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::Web::Http::Diagnostics {
struct WINRT_EBO HttpDiagnosticProvider :
Windows::Web::Http::Diagnostics::IHttpDiagnosticProvider
{
HttpDiagnosticProvider(std::nullptr_t) noexcept {}
static Windows::Web::Http::Diagnostics::HttpDiagnosticProvider CreateFromProcessDiagnosticInfo(const Windows::System::Diagnostics::ProcessDiagnosticInfo & processDiagnosticInfo);
};
struct WINRT_EBO HttpDiagnosticProviderRequestResponseCompletedEventArgs :
Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestResponseCompletedEventArgs
{
HttpDiagnosticProviderRequestResponseCompletedEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO HttpDiagnosticProviderRequestResponseTimestamps :
Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestResponseTimestamps
{
HttpDiagnosticProviderRequestResponseTimestamps(std::nullptr_t) noexcept {}
};
struct WINRT_EBO HttpDiagnosticProviderRequestSentEventArgs :
Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderRequestSentEventArgs
{
HttpDiagnosticProviderRequestSentEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO HttpDiagnosticProviderResponseReceivedEventArgs :
Windows::Web::Http::Diagnostics::IHttpDiagnosticProviderResponseReceivedEventArgs
{
HttpDiagnosticProviderResponseReceivedEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO HttpDiagnosticSourceLocation :
Windows::Web::Http::Diagnostics::IHttpDiagnosticSourceLocation
{
HttpDiagnosticSourceLocation(std::nullptr_t) noexcept {}
};
}
}
| [
"kwelton@microsoft.com"
] | kwelton@microsoft.com |
5c729d46dcd252ddca24cbd194c46d6eb7f8353c | d14b5d78b72711e4614808051c0364b7bd5d6d98 | /third_party/llvm-10.0/llvm/lib/Target/RISCV/RISCVInstrInfo.h | 625b6187513330d538edfe6e4e37b1ca983707e9 | [
"Apache-2.0"
] | permissive | google/swiftshader | 76659addb1c12eb1477050fded1e7d067f2ed25b | 5be49d4aef266ae6dcc95085e1e3011dad0e7eb7 | refs/heads/master | 2023-07-21T23:19:29.415159 | 2023-07-21T19:58:29 | 2023-07-21T20:50:19 | 62,297,898 | 1,981 | 306 | Apache-2.0 | 2023-07-05T21:29:34 | 2016-06-30T09:25:24 | C++ | UTF-8 | C++ | false | false | 5,680 | h | //===-- RISCVInstrInfo.h - RISCV Instruction Information --------*- C++ -*-===//
//
// 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 RISCV implementation of the TargetInstrInfo class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_TARGET_RISCV_RISCVINSTRINFO_H
#define LLVM_LIB_TARGET_RISCV_RISCVINSTRINFO_H
#include "RISCVRegisterInfo.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#define GET_INSTRINFO_HEADER
#include "RISCVGenInstrInfo.inc"
namespace llvm {
class RISCVSubtarget;
class RISCVInstrInfo : public RISCVGenInstrInfo {
public:
explicit RISCVInstrInfo(RISCVSubtarget &STI);
unsigned isLoadFromStackSlot(const MachineInstr &MI,
int &FrameIndex) const override;
unsigned isStoreToStackSlot(const MachineInstr &MI,
int &FrameIndex) const override;
void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
const DebugLoc &DL, MCRegister DstReg, MCRegister SrcReg,
bool KillSrc) const override;
void storeRegToStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI, unsigned SrcReg,
bool IsKill, int FrameIndex,
const TargetRegisterClass *RC,
const TargetRegisterInfo *TRI) const override;
void loadRegFromStackSlot(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI, unsigned DstReg,
int FrameIndex, const TargetRegisterClass *RC,
const TargetRegisterInfo *TRI) const override;
// Materializes the given integer Val into DstReg.
void movImm(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
const DebugLoc &DL, Register DstReg, uint64_t Val,
MachineInstr::MIFlag Flag = MachineInstr::NoFlags) const;
unsigned getInstSizeInBytes(const MachineInstr &MI) const override;
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
MachineBasicBlock *&FBB,
SmallVectorImpl<MachineOperand> &Cond,
bool AllowModify) const override;
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
MachineBasicBlock *FBB, ArrayRef<MachineOperand> Cond,
const DebugLoc &dl,
int *BytesAdded = nullptr) const override;
unsigned insertIndirectBranch(MachineBasicBlock &MBB,
MachineBasicBlock &NewDestBB,
const DebugLoc &DL, int64_t BrOffset,
RegScavenger *RS = nullptr) const override;
unsigned removeBranch(MachineBasicBlock &MBB,
int *BytesRemoved = nullptr) const override;
bool
reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const override;
MachineBasicBlock *getBranchDestBlock(const MachineInstr &MI) const override;
bool isBranchOffsetInRange(unsigned BranchOpc,
int64_t BrOffset) const override;
bool isAsCheapAsAMove(const MachineInstr &MI) const override;
bool verifyInstruction(const MachineInstr &MI,
StringRef &ErrInfo) const override;
bool getMemOperandWithOffsetWidth(const MachineInstr &LdSt,
const MachineOperand *&BaseOp,
int64_t &Offset, unsigned &Width,
const TargetRegisterInfo *TRI) const;
bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa,
const MachineInstr &MIb) const override;
std::pair<unsigned, unsigned>
decomposeMachineOperandsTargetFlags(unsigned TF) const override;
ArrayRef<std::pair<unsigned, const char *>>
getSerializableDirectMachineOperandTargetFlags() const override;
// Return true if the function can safely be outlined from.
virtual bool
isFunctionSafeToOutlineFrom(MachineFunction &MF,
bool OutlineFromLinkOnceODRs) const override;
// Return true if MBB is safe to outline from, and return any target-specific
// information in Flags.
virtual bool isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
unsigned &Flags) const override;
// Calculate target-specific information for a set of outlining candidates.
outliner::OutlinedFunction getOutliningCandidateInfo(
std::vector<outliner::Candidate> &RepeatedSequenceLocs) const override;
// Return if/how a given MachineInstr should be outlined.
virtual outliner::InstrType
getOutliningType(MachineBasicBlock::iterator &MBBI,
unsigned Flags) const override;
// Insert a custom frame for outlined functions.
virtual void
buildOutlinedFrame(MachineBasicBlock &MBB, MachineFunction &MF,
const outliner::OutlinedFunction &OF) const override;
// Insert a call to an outlined function into a given basic block.
virtual MachineBasicBlock::iterator
insertOutlinedCall(Module &M, MachineBasicBlock &MBB,
MachineBasicBlock::iterator &It, MachineFunction &MF,
const outliner::Candidate &C) const override;
protected:
const RISCVSubtarget &STI;
};
}
#endif
| [
"bclayton@google.com"
] | bclayton@google.com |
ea4b94d8ff3326906002f1ae0bd4c1b43bce61b8 | 42ca994494c59edf535ebd5b561eddf53154087a | /module13/events.cpp | d98c36c10f8d93d655976620ca60dad8d88deb28 | [] | no_license | patmclaughlin94/EN605.417.FA | 9024776c5ff41308af538160fab9ac00f9b00e01 | 0d0f213df7a36cdc0ac19890f840bcb41d0a2e17 | refs/heads/master | 2021-09-14T16:21:29.143957 | 2018-05-16T03:18:21 | 2018-05-16T03:18:21 | 119,475,429 | 0 | 0 | null | 2018-01-30T03:13:09 | 2018-01-30T03:13:09 | null | UTF-8 | C++ | false | false | 23,161 | cpp | #include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#ifdef __APPLE__
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
#if !defined(CL_CALLBACK)
#define CL_CALLBACK
#endif
// Constant
const int ARRAY_SIZE = 1000;
// Function to check and handle OpenCL errors
inline void
checkErr(cl_int err, const char * name)
{
if (err != CL_SUCCESS) {
std::cerr << "ERROR: " << name << " (" << err << ")" << std::endl;
exit(EXIT_FAILURE);
}
}
void CL_CALLBACK contextCallback(
const char * errInfo,
const void * private_info,
size_t cb,
void * user_data)
{
std::cout << "Error occured during context use: " << errInfo << std::endl;
// should really perform any clearup and so on at this point
// but for simplicitly just exit.
exit(1);
}
cl_uint getNumPlatforms() {
cl_uint errNum;
cl_uint numPlatforms;
errNum = clGetPlatformIDs(0, NULL, &numPlatforms);
checkErr((errNum != CL_SUCCESS) ? errNum : (numPlatforms <= 0 ? -1 : CL_SUCCESS),
"clGetPlatformIDs");
return numPlatforms;
}
// Get first platform you find
// TODO: Return all platforms
void getPlatform(cl_platform_id * platform) {
cl_int errNum;
cl_uint numPlatforms;
cl_platform_id * platformIDs;
// Get Number of platforms
errNum = clGetPlatformIDs(0, NULL, &numPlatforms);
checkErr((errNum != CL_SUCCESS) ? errNum : (numPlatforms <= 0 ? -1 : CL_SUCCESS),
"clGetPlatformIDs");
// Get Platform IDs
platformIDs = (cl_platform_id *) malloc(sizeof(cl_platform_id) * numPlatforms);
errNum = clGetPlatformIDs(numPlatforms, platformIDs, NULL);
checkErr((errNum != CL_SUCCESS) ? errNum: (numPlatforms <= 0 ? -1 : CL_SUCCESS), "clGetPlatformIDs");
// Use the first platform
*platform = platformIDs[0];
// Clean up your mess...
delete [] platformIDs;
}
// Get first device you find
// TODO: Return all devices and assess which device makes the most sense for each context
void getDevice(cl_platform_id platform, cl_device_id * device) {
cl_int errNum;
cl_uint numDevices;
cl_device_id * deviceIDs;
errNum = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices);
if(errNum != CL_SUCCESS && errNum != CL_DEVICE_NOT_FOUND) {
checkErr(errNum, "clGetDeviceIDs");
} else if(numDevices > 0) {
deviceIDs = (cl_device_id *) malloc(sizeof(cl_device_id) * numDevices);
errNum = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, numDevices, deviceIDs, NULL);
checkErr(errNum, "clGetDeviceIDs");
}
// Use first device
*device = deviceIDs[0];
// Clean up your mess...
delete [] deviceIDs;
}
// Create context given 1 platform and a set of devices
cl_context createContext(cl_platform_id platform, cl_device_id * deviceIDs, cl_uint numDevices){
cl_int errNum;
cl_context context = NULL;
cl_context_properties contextProperties[] =
{
CL_CONTEXT_PLATFORM,
(cl_context_properties)platform,
0
};
context = clCreateContext(
contextProperties,
numDevices,
deviceIDs,
&contextCallback,
NULL,
&errNum);
checkErr(errNum, "clCreateContext");
return context;
}
// Create a program for the given context and given kernel file
cl_program createProgram(const char * fileName, cl_context context,
cl_device_id * deviceIDs, cl_uint numDevices) {
cl_int errNum;
cl_program program;
std::ifstream kernelFile(fileName, std::ios::in);
if (!kernelFile.is_open())
{
std::cerr << "Failed to open file for reading: " << fileName << std::endl;
return NULL;
}
std::ostringstream oss;
oss << kernelFile.rdbuf();
std::string srcStdStr = oss.str();
const char *srcStr = srcStdStr.c_str();
program = clCreateProgramWithSource(context, 1,
(const char**)&srcStr,
NULL, NULL);
if (program == NULL)
{
std::cerr << "Failed to create CL program from source." << std::endl;
return NULL;
}
errNum = clBuildProgram(program, numDevices, deviceIDs, NULL, NULL, NULL);
if (errNum != CL_SUCCESS)
{
// Determine the reason for the error
char buildLog[16384];
clGetProgramBuildInfo(program, deviceIDs[0], CL_PROGRAM_BUILD_LOG,
sizeof(buildLog), buildLog, NULL);
std::cerr << "Error in kernel: " << std::endl;
std::cerr << buildLog;
clReleaseProgram(program);
return NULL;
}
return program;
}
void createKernels(cl_kernel * kernels, cl_program program) {
cl_int errNum;
kernels[0] = clCreateKernel(program, "add", &errNum);
kernels[1] = clCreateKernel(program, "sub", &errNum);
kernels[2] = clCreateKernel(program, "mult", &errNum);
kernels[3] = clCreateKernel(program, "div", &errNum);
checkErr(errNum, "clCreateKernel");
}
bool createMemReadOnly(cl_context context, cl_mem * memObjects,
float ** hostObjects, int numObjects, int array_size) {
for (int i = 0; i < numObjects; i++) {
memObjects[i] = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(float) * array_size, hostObjects[i], NULL);
if(memObjects[i] == NULL) {
std::cerr << "Error creating memory objects." << std::endl;
return false;
}
}
return true;
}
bool createMemReadWrite(cl_context context, cl_mem * memObjects,
int numObjects, int array_size) {
for (int i = 0; i < numObjects; i++) {
memObjects[i] = clCreateBuffer(context, CL_MEM_READ_WRITE,
sizeof(float) * array_size, NULL, NULL);
if(memObjects[i] == NULL) {
std::cerr << "Error creating memory objects." << std::endl;
return false;
}
}
return true;
}
///
// Create memory objects used as the arguments to the kernel
// The kernel takes three arguments: result (output), a (input),
// and b (input)
//
bool CreateMemObjects(cl_context context, cl_mem memObjects[3],
float *a, float *b, int array_size)
{
memObjects[0] = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(float) * array_size, a, NULL);
memObjects[1] = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(float) * array_size, b, NULL);
memObjects[2] = clCreateBuffer(context, CL_MEM_READ_WRITE,
sizeof(float) * array_size, NULL, NULL);
if (memObjects[0] == NULL || memObjects[1] == NULL || memObjects[2] == NULL)
{
std::cerr << "Error creating memory objects." << std::endl;
return false;
}
return true;
}
// Sets arguments but reuses kernel argument results computed from previous computations
// in the next computation
// e.g. result from add used as argument to subtract
void setArgsBlocking(cl_kernel * kernels, cl_mem * memReadOnly, cl_mem * memReadWrite) {
// "add" kernel args
checkErr(clSetKernelArg(kernels[0], 0, sizeof(cl_mem), &memReadOnly[0]), "set kernel arg");
checkErr(clSetKernelArg(kernels[0], 1, sizeof(cl_mem), &memReadOnly[1]), "set kernel arg");
checkErr(clSetKernelArg(kernels[0], 2, sizeof(cl_mem), &memReadWrite[0]), "set kernel arg");
// "sub" kernel args
checkErr(clSetKernelArg(kernels[1], 0, sizeof(cl_mem), &memReadWrite[0]), "set kernel arg");
checkErr(clSetKernelArg(kernels[1], 1, sizeof(cl_mem), &memReadOnly[1]), "set kernel arg");
checkErr(clSetKernelArg(kernels[1], 2, sizeof(cl_mem), &memReadWrite[1]), "set kernel arg");
// "mult" kernel args
checkErr(clSetKernelArg(kernels[2], 0, sizeof(cl_mem), &memReadWrite[1]), "set kernel arg");
checkErr(clSetKernelArg(kernels[2], 1, sizeof(cl_mem), &memReadOnly[1]), "set kernel arg");
checkErr(clSetKernelArg(kernels[2], 2, sizeof(cl_mem), &memReadWrite[2]), "set kernel arg");
// "div" kernel args
checkErr(clSetKernelArg(kernels[3], 0, sizeof(cl_mem), &memReadWrite[2]), "set kernel arg");
checkErr(clSetKernelArg(kernels[3], 1, sizeof(cl_mem), &memReadOnly[1]), "set kernel arg");
checkErr(clSetKernelArg(kernels[3], 2, sizeof(cl_mem), &memReadWrite[3]), "set kernel arg");
}
// Sets arguments and reuses "a" and "b" for each operation
// No independence between operations
void setArgsNonBlocking(cl_kernel * kernels, cl_mem * memReadOnly, cl_mem * memReadWrite) {
// "add" kernel args
checkErr(clSetKernelArg(kernels[0], 0, sizeof(cl_mem), &memReadOnly[0]), "set kernel arg");
checkErr(clSetKernelArg(kernels[0], 1, sizeof(cl_mem), &memReadOnly[1]), "set kernel arg");
checkErr(clSetKernelArg(kernels[0], 2, sizeof(cl_mem), &memReadWrite[0]), "set kernel arg");
// "sub" kernel args
checkErr(clSetKernelArg(kernels[1], 0, sizeof(cl_mem), &memReadOnly[0]), "set kernel arg");
checkErr(clSetKernelArg(kernels[1], 1, sizeof(cl_mem), &memReadOnly[1]), "set kernel arg");
checkErr(clSetKernelArg(kernels[1], 2, sizeof(cl_mem), &memReadWrite[1]), "set kernel arg");
// "mult" kernel args
checkErr(clSetKernelArg(kernels[2], 0, sizeof(cl_mem), &memReadOnly[0]), "set kernel arg");
checkErr(clSetKernelArg(kernels[2], 1, sizeof(cl_mem), &memReadOnly[1]), "set kernel arg");
checkErr(clSetKernelArg(kernels[2], 2, sizeof(cl_mem), &memReadWrite[2]), "set kernel arg");
// "div" kernel args
checkErr(clSetKernelArg(kernels[3], 0, sizeof(cl_mem), &memReadOnly[0]), "set kernel arg");
checkErr(clSetKernelArg(kernels[3], 1, sizeof(cl_mem), &memReadOnly[1]), "set kernel arg");
checkErr(clSetKernelArg(kernels[3], 2, sizeof(cl_mem), &memReadWrite[3]), "set kernel arg");
}
// setArgsNonBlocking this will be different from above because we will re-use a and b for all inputs
void setKernelArgs(cl_kernel kernel, cl_mem memObjects[3]) {
checkErr(clSetKernelArg(kernel, 0, sizeof(cl_mem), &memObjects[0]), "set kernel arg 0");
checkErr(clSetKernelArg(kernel, 1, sizeof(cl_mem), &memObjects[1]), "set kernel arg 1");
checkErr(clSetKernelArg(kernel, 2, sizeof(cl_mem), &memObjects[2]), "set kernel arg 2");
}
///
// Cleanup any created OpenCL resources
//
void Cleanup(cl_context context, cl_command_queue commandQueue,
cl_program program, cl_mem memObjects[3])
{
for (int i = 0; i < 3; i++)
{
if (memObjects[i] != 0)
clReleaseMemObject(memObjects[i]);
}
if (commandQueue != 0)
clReleaseCommandQueue(commandQueue);
/*if (kernel != 0)
clReleaseKernel(kernel);*/
if (program != 0)
clReleaseProgram(program);
if (context != 0)
clReleaseContext(context);
}
void populateInputs(float * a, float * b, int array_size) {
for(int i = 0; i < array_size; i++) {
a[i] = (float)(i + 1);
b[i] = (float)((i + 1) * 2);
}
printf("populated arrays!\n");
}
// Options:
// 1) Blocking: all kernels wait for the previous kernel to conclude
// 2) Non Blocking: no kernels wait for previous kernel to conclude... all just execute when they can
// 3) Semi-blocking: 2 kernels execute, 2nd 2 kernels wait for first 2 to conclude
void runKernelBlocking(cl_command_queue queue, cl_kernel * kernels, int array_size) {
size_t globalWorkSize[1];
globalWorkSize[0] = array_size;
size_t localWorkSize[1] = {1};
// Events to enforce blocking
cl_event events[4];
cl_ulong ev_start_time;
cl_ulong ev_end_time;
size_t return_bytes;
// Queue the kernel up for execution across the array
/*
cl_int clEnqueueNDRangeKernel (
cl_command_queue command_queue,
cl_kernel kernel,
cl_uint work_dim,
const size_t *global_work_offset,
const size_t *global_work_size,
const size_t *local_work_size,
cl_uint num_events_in_wait_list,
const cl_event *event_wait_list,
cl_event *event)
*/
// execute add
checkErr(clEnqueueNDRangeKernel(queue, kernels[0], 1, NULL,
globalWorkSize, localWorkSize,
0, NULL, &events[0]), "enqueue kernel");
printf("executed add\n");
// execute sub with result from add
checkErr(clEnqueueNDRangeKernel(queue, kernels[1], 1, NULL,
globalWorkSize, localWorkSize,
1, &events[0], &events[1]), "enqueue kernel");
printf("executed sub\n");
// execute mult with result from sub
checkErr(clEnqueueNDRangeKernel(queue, kernels[2], 1, NULL,
globalWorkSize, localWorkSize,
1, &events[1], &events[2]), "enqueue kernel");
printf("executed mult\n");
// execute div with result from mult
checkErr(clEnqueueNDRangeKernel(queue, kernels[3], 1, NULL,
globalWorkSize, localWorkSize,
1, &events[2], &events[3]), "enqueue kernel");
printf("executed div\n");
clWaitForEvents(1, &events[0] );
clWaitForEvents(1, &events[3] );
checkErr(clGetEventProfilingInfo(events[0], CL_PROFILING_COMMAND_QUEUED, sizeof(cl_ulong), &ev_start_time, &return_bytes), "evt prfiling");
checkErr(clGetEventProfilingInfo(events[3], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &ev_end_time, &return_bytes), "evt prfiling");
double run_time =(double)(ev_end_time - ev_start_time);
printf("Blocking kernel runs on arrays of length %d took %f ms\n",array_size, run_time*1e-6);
// read sub result back
// read mult result back
// read div result back
}
void runKernelNonBlocking(cl_command_queue queue, cl_kernel * kernels, int array_size) {
size_t globalWorkSize[1];
globalWorkSize[0] = array_size;
size_t localWorkSize[1] = {1};
// Events for profiling
cl_event events[2];
cl_ulong ev_start_time;
cl_ulong ev_end_time;
size_t return_bytes;
// execute add
checkErr(clEnqueueNDRangeKernel(queue, kernels[0], 1, NULL,
globalWorkSize, localWorkSize,
0, NULL, &events[0]), "enqueue kernel");
printf("executed add\n");
// execute sub with result from add
checkErr(clEnqueueNDRangeKernel(queue, kernels[1], 1, NULL,
globalWorkSize, localWorkSize,
0, NULL, NULL), "enqueue kernel");
printf("executed sub\n");
// execute mult with result from sub
checkErr(clEnqueueNDRangeKernel(queue, kernels[2], 1, NULL,
globalWorkSize, localWorkSize,
0, NULL, NULL), "enqueue kernel");
printf("executed mult\n");
// execute div with result from mult
checkErr(clEnqueueNDRangeKernel(queue, kernels[3], 1, NULL,
globalWorkSize, localWorkSize,
0, NULL, &events[1]), "enqueue kernel");
printf("executed div\n");
clWaitForEvents(1, &events[0] );
clWaitForEvents(1, &events[1] );
checkErr(clGetEventProfilingInfo(events[0], CL_PROFILING_COMMAND_QUEUED, sizeof(cl_ulong), &ev_start_time, &return_bytes), "evt prfiling");
checkErr(clGetEventProfilingInfo(events[1], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &ev_end_time, &return_bytes), "evt prfiling");
double run_time =(double)(ev_end_time - ev_start_time);
printf("Non Blocking kernel runs on arrays of length %d took %f ms\n",array_size, run_time*1e-6);
}
void getResults(cl_command_queue queue, cl_mem * memReadWrite, float ** readWrites, int array_size) {
// read add result back
checkErr(clEnqueueReadBuffer(queue, memReadWrite[0], CL_TRUE,
0, array_size * sizeof(float), readWrites[0],
0, NULL, NULL), "reading buffer");
// read sub result back
checkErr(clEnqueueReadBuffer(queue, memReadWrite[1], CL_TRUE,
0, array_size * sizeof(float), readWrites[1],
0, NULL, NULL), "reading buffer");
// read mult result back
checkErr(clEnqueueReadBuffer(queue, memReadWrite[2], CL_TRUE,
0, array_size * sizeof(float), readWrites[2],
0, NULL, NULL), "reading buffer");
// read div result back
checkErr(clEnqueueReadBuffer(queue, memReadWrite[3], CL_TRUE,
0, array_size * sizeof(float), readWrites[3],
0, NULL, NULL), "reading buffer");
}
// Specify 0, 1, 2, 3 for "add", "subtract", "multiply", "divide"
int main(int argc, char** argv) {
// Default variables that can be specified by command line
int blocking = 1;
int array_size = 1000;
if(argc == 3) {
blocking = atoi(argv[1]);
array_size = atoi(argv[2]);
}
// Host boilerplate vars
float * a = new float[array_size];
float * b = new float[array_size];
float * result = new float[array_size];
float * result2 = new float[array_size];
float * result3 = new float[array_size];
float * result4 = new float[array_size];
float ** readOnlys = new float*[2];
float ** readWrites = new float*[4];
// allocate memory for read only host memory
for (int i = 0; i < 2; i++) {
readOnlys[i] = new float[array_size];
}
// allocate memory for read/write host memory
for (int i = 0; i < 4; i++) {
readWrites[i] = new float[array_size];
}
cl_int errNum;
// OpenCL boilerplate vars
cl_platform_id platform = 0;
cl_device_id device = 0;
cl_context context = NULL;
cl_program program = NULL;
cl_mem memObjects[3] = {0, 0, 0};
cl_mem * memReadOnly = new cl_mem[2];
cl_mem * memReadWrite = new cl_mem[4];
cl_uint num_events_in_waitlist = 0;
cl_command_queue queue;
cl_kernel * kernels = new cl_kernel[3];
// Choose first platform you find
getPlatform(&platform);
// Choose first device on first platform
getDevice(platform, &device);
// Create context on first platform/device discovered
context = createContext(platform, &device, (cl_uint) 1);
// create program for simple kernel operations "add", "sub", etc...
program = createProgram("simple_ops.cl", context, &device, (cl_uint) 1);
// Create Kernel Objects for add, sub, mult, div
createKernels(kernels, program);
printf("Set up platform, device, context, program and kernels\n");
// populate host memory objects
populateInputs(a, b, array_size);
for (int i = 0; i < array_size; i++) {
readOnlys[0][i] = a[i];
readOnlys[1][i] = b[i];
}
/*readOnlys[0] = a;
readOnlys[1] = b;*/
// Create mem objects
/*cl_context context, cl_mem * memObjects,
float ** hostObjects, int numObjects, int array_size*/
bool success = createMemReadOnly(context, memReadOnly, readOnlys, 2, array_size);
success = createMemReadWrite(context, memReadWrite, 4, array_size);
if(!success) {
clReleaseKernel(kernels[0]);
clReleaseKernel(kernels[1]);
clReleaseKernel(kernels[2]);
clReleaseKernel(kernels[3]);
return 1;
}
/*if(!CreateMemObjects(context, memObjects, a, b, array_size)) {
clReleaseKernel(kernels[0]);
clReleaseKernel(kernels[1]);
clReleaseKernel(kernels[2]);
clReleaseKernel(kernels[3]);
return 1;
}*/
// Pick the first device and create command queue
queue = clCreateCommandQueue(
context,
device,
CL_QUEUE_PROFILING_ENABLE,
&errNum);
checkErr(errNum, "clCreateCommandQueue");
// Set kernel arguments for add, sub, mult, div
if(blocking == 1) {
setArgsBlocking(kernels, memReadOnly, memReadWrite);
runKernelBlocking(queue, kernels, array_size);
} else if(blocking == 0) {
setArgsNonBlocking(kernels, memReadOnly, memReadWrite);
runKernelNonBlocking(queue, kernels, array_size);
}
// Set kernel arguments
//setKernelArgs(kernels[0], memObjects2)
// PUT RUN KERNEL FUNCTION HERE
getResults(queue, memReadWrite, readWrites, array_size);
/*size_t globalWorkSize[1];
globalWorkSize[0] = array_size;
size_t localWorkSize[1] = {1};
printf("BLAHHH\n");
cl_event prof_event;
// Queue the kernel up for execution across the array
checkErr(clEnqueueNDRangeKernel(queue, kernels[0], 1, NULL,
globalWorkSize, localWorkSize,
0, NULL, &prof_event), "enqueue kernel");
printf("enqueued kernel\n");
checkErr(clWaitForEvents(1, &prof_event), "wait for events");
cl_ulong ev_start_time = (cl_ulong)0;
cl_ulong ev_end_time = (cl_ulong)0;
size_t return_bytes;
checkErr(clGetEventProfilingInfo(prof_event, CL_PROFILING_COMMAND_QUEUED, sizeof(cl_ulong), &ev_start_time, &return_bytes), "evt prfiling");
checkErr(clGetEventProfilingInfo(prof_event, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &ev_end_time, &return_bytes), "evt prfiling");
double run_time =(double)(ev_end_time - ev_start_time);
// Read the output buffer back to the Host
// Initialize timing mechanism with cl_event
checkErr(clEnqueueReadBuffer(queue, memObjects[2], CL_TRUE,
0, array_size * sizeof(float), result,
0, NULL, &prof_event), "reading buffer");*/
/*for(int i = 0; i < 4; i++) {
for(int j = 0; j < array_size; j++) {
printf("%f ", readWrites[i][j]);
}
printf("\n");
}*/
Cleanup(context, queue, program, memObjects);
clReleaseKernel(kernels[0]);
clReleaseKernel(kernels[1]);
clReleaseKernel(kernels[2]);
clReleaseKernel(kernels[3]);
delete [] a;
delete [] b;
delete [] result;
delete [] result2;
delete [] result3;
delete [] result4;
for(int i = 0; i < 2; i++) {
delete [] readOnlys[i];
}
delete [] readOnlys;
for(int i = 0; i < 4; i++) {
delete [] readWrites[i];
}
delete [] readWrites;
delete [] kernels;
printf("all done!\n");
} | [
"pat.mclaughlin94@gmail.com"
] | pat.mclaughlin94@gmail.com |
98760f1cdb8ff6f45c9d435c92ab481ba7b6c03a | 0c0088fdb45a5069e1304de9a85162ea713a4558 | /DecomposeForPacking/DecomposeForPacking/Arcball.cpp | 7dcce0d0b351b16be919f9a5c6e7c078340a7eb8 | [] | no_license | orperel/DecomposeForPacking | cda2ae35efd9b2ade24ec87d7005a7d6caea802d | 7d92e97942835288bf4c00f7adf957a383f99e68 | refs/heads/master | 2021-05-08T16:48:27.561656 | 2015-03-25T23:58:43 | 2015-03-25T23:58:43 | 120,173,070 | 1 | 0 | null | 2018-02-04T09:57:56 | 2018-02-04T09:57:55 | null | UTF-8 | C++ | false | false | 2,456 | cpp | #include "Arcball.h"
#include <algorithm>
Arcball::Arcball() : _isArcballOn(false), _lastXPos(0), _lastYPos(0), _currXPos(0), _currYPos(0), _angle(0)
{
_axis_in_camera_coord = VECTOR_3D(1.0f);
_prevModelRotationMatrix = _lastModelRotationMatrix = std::make_shared<MATRIX_4X4>();
}
Arcball::~Arcball()
{
}
void Arcball::handleMousePress(bool isLeftMousePressed, int x, int y)
{
if (isLeftMousePressed)
{
if (!_isArcballOn)
{
_isArcballOn = true;
_lastXPos = _currXPos = x;
_lastYPos = _currYPos = y;
}
}
else
{
_isArcballOn = false;
_prevModelRotationMatrix = _lastModelRotationMatrix;
// Make sure subsequent rotations while arcball is off cause no new rotation
_angle = 0;
_axis_in_camera_coord = VECTOR_3D(1.0f);
}
}
void Arcball::handleMouseMove(int x, int y)
{
if (_isArcballOn) { // if left button is pressed
_currXPos = x;
_currYPos = y;
// Calculate vectors from the ball's center to the press point (a) and current point (b)
VECTOR_3D va = getArcballVector(_lastXPos, _lastYPos);
VECTOR_3D vb = getArcballVector(_currXPos, _currYPos);
// Angle between va and vb is calculated using the dot product (va and vb are assumed to be of length 1)
// We use min to fix small precision errors and make sure we cap at 1.0
_angle = acos(std::min(1.0f, glm::dot(va, vb)));
_axis_in_camera_coord = VECTOR_3D(glm::cross(va, vb));
}
}
void Arcball::updateScreenSize(int screenWidth, int screenHeight)
{
_screenWidth = screenWidth;
_screenHeight = screenHeight;
}
VECTOR_3D Arcball::getArcballVector(int x, int y)
{
// Screen coordinates to [-1,1] coordinates
VECTOR_3D p = VECTOR_3D(1.0*x / _screenWidth * 2 - 1.0,
1.0*y / _screenHeight * 2 - 1.0,
0);
p.y = -p.y; // Normalize y axis because it is inverted for OpenGL
float vecOPLengthsquared = p.x * p.x + p.y * p.y;
if (vecOPLengthsquared <= 1 * 1)
p.z = sqrt(1 * 1 - vecOPLengthsquared); // Pythagore
else
p = glm::normalize(p); // Nearest point
return p;
}
shared_ptr<MATRIX_4X4> Arcball::modelRotationMatrix(shared_ptr<MATRIX_4X4> model, shared_ptr<MATRIX_4X4> view)
{
VECTOR_3D rotationAxis = glm::inverse(glm::mat3(*view) * glm::inverse(glm::mat3(*model))) * _axis_in_camera_coord;
MATRIX_4X4 rotationMatrix = glm::rotate(glm::degrees(_angle) / 10.0f, rotationAxis);
_lastModelRotationMatrix = std::make_shared<MATRIX_4X4>(rotationMatrix * (*_prevModelRotationMatrix));
return _lastModelRotationMatrix;
} | [
"or_perel@hotmail.com"
] | or_perel@hotmail.com |
a94f21724241ef93a6aeba442ad9d31d9a328e7f | 7d0f47b50f1b29cd9fbb368f03f7f95dcc736200 | /module06/ex00/Value.hpp | 7ae47296e3965193db64076d36c6056b5c2b8b50 | [] | no_license | msamual/CPP_Piscine | 9761e161497d1a98ace34c8679938963a581a46f | 57882d341e7b9472a754fd501ac416dd793e08bb | refs/heads/main | 2023-06-30T21:54:59.653230 | 2021-08-11T11:37:41 | 2021-08-11T11:37:41 | 394,963,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 919 | hpp | #ifndef VALUE_HPP
# define VALUE_HPP
# define CHAR 1
# define INT 2
# define FLOAT 3
# define DOUBLE 4
# define NaN 5
# define NaNF 6
# define INF 7
# define INF_NEG 8
# define INF_POS 9
# define CHARQ 10
# define RED "\033[0;31m"
# define WHITE "\033[0m"
# include <iostream>
# include <ostream>
class Value
{
private:
Value();
std::string _input;
int _type;
double _double;
int _int;
float _float;
char _char;
double _value;
public:
Value(std::string input);
Value(const Value& value);
~Value();
Value& operator=(const Value& value);
void printInput();
void printDouble();
void trimInput();
int defType();
int getType();
bool isNumber();
void printResult();
void toInt();
void toFloat();
void toDouble();
void toChar();
void startChar();
void startInt();
void startFloat();
void startDouble();
};
#endif | [
"msamual@er-c5.kzn.21-school.ru"
] | msamual@er-c5.kzn.21-school.ru |
7bd88ab1758d0a69b526828afc8d24a9334ea6f6 | b456bd3db80eb5b9a3eb566871f080bbf677b567 | /processing.h | 503ce3a3b69f6f7a0053baa792b74c705308cb3d | [] | no_license | VolDonets/ws_devices_mul_threads | e121f1973e4be761e878ce2ca8c93282b2a624a9 | 720df0460fa35a05cf66b4e7f1a368059cfcb950 | refs/heads/master | 2022-04-18T06:10:04.873575 | 2020-04-08T01:15:10 | 2020-04-08T01:15:10 | 251,255,404 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 720 | h | //
// Created by vovan on 25.03.2020.
//
#ifndef WS_DEVICES_2_PROCESSING_H
#define WS_DEVICES_2_PROCESSING_H
#include "lib_mpu6050/mpu6050_drive.h"
#include "web_sockets/WebServer.h"
#include "lib_bme280/bme280.h"
class Processing {
public:
Processing(i2c_init_func_def, i2c_read_func_def, i2c_write_func_def, i2c_read_func_def, i2c_write_func_def);
void start();
private:
MPU6050_Drive *mpu6050_drive;
BME280 *bme280_drive;
thread server_thread;
shared_ptr<PrintfLogger> logger;
shared_ptr<MyServer> ws_server;
shared_ptr<MyHandler> handler;
void init_server();
void processing_data_to_websocket();
std::string to_json_process();
};
#endif //WS_DEVICES_2_PROCESSING_H
| [
"vovan.s.marsa@gmail.com"
] | vovan.s.marsa@gmail.com |
360f8a3eee7d24ea2276414d147b693c1d6db58f | 028d79ad6dd6bb4114891b8f4840ef9f0e9d4a32 | /src/drawgfx.cpp | 67614a712737acacb8fa3cbe1b3cd858f4df86b3 | [] | no_license | neonichu/iMame4All-for-iPad | 72f56710d2ed7458594838a5152e50c72c2fb67f | 4eb3d4ed2e5ccb5c606fcbcefcb7c5a662ace611 | refs/heads/master | 2020-04-21T07:26:37.595653 | 2011-11-26T12:21:56 | 2011-11-26T12:21:56 | 2,855,022 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 120,544 | cpp | #ifndef DECLARE
#include "driver.h"
/* LBO */
#ifdef LSB_FIRST
#define BL0 0
#define BL1 1
#define BL2 2
#define BL3 3
#define WL0 0
#define WL1 1
#else
#define BL0 3
#define BL1 2
#define BL2 1
#define BL3 0
#define WL0 1
#define WL1 0
#endif
UINT8 gfx_drawmode_table[256];
plot_pixel_proc plot_pixel;
read_pixel_proc read_pixel;
plot_box_proc plot_box;
static UINT8 is_raw[TRANSPARENCY_MODES];
#ifdef ALIGN_INTS /* GSL 980108 read/write nonaligned dword routine for ARM processor etc */
#define write_dword_aligned(address,data) *(UINT32 *)address = data
#ifdef LSB_FIRST
#define write_dword_unaligned(address,data) \
*(address) = data; \
*(address+1) = (data >> 8); \
*(address+2) = (data >> 16); \
*(address+3) = (data >> 24)
#else
#define write_dword_unaligned(address,data) \
*(address+3) = data; \
*(address+2) = (data >> 8); \
*(address+1) = (data >> 16); \
*(address) = (data >> 24)
#endif
#else
#define write_dword(address,data) *address=data
#endif
INLINE int readbit(const UINT8 *src,int bitnum)
{
return (src[bitnum / 8] >> (7 - bitnum % 8)) & 1;
}
void decodechar(struct GfxElement *gfx,int num,const UINT8 *src,const struct GfxLayout *gl)
{
int plane,x,y;
UINT8 *dp;
int offs;
offs = num * gl->charincrement;
dp = gfx->gfxdata + num * gfx->char_modulo;
for (y = 0;y < gfx->height;y++)
{
int yoffs;
yoffs = y;
#ifdef PREROTATE_GFX
if (Machine->orientation & ORIENTATION_FLIP_Y)
yoffs = gfx->height-1 - yoffs;
#endif
for (x = 0;x < gfx->width;x++)
{
int xoffs;
xoffs = x;
#ifdef PREROTATE_GFX
if (Machine->orientation & ORIENTATION_FLIP_X)
xoffs = gfx->width-1 - xoffs;
#endif
dp[x] = 0;
if (Machine->orientation & ORIENTATION_SWAP_XY)
{
for (plane = 0;plane < gl->planes;plane++)
{
if (readbit(src,offs + gl->planeoffset[plane] + gl->yoffset[xoffs] + gl->xoffset[yoffs]))
dp[x] |= (1 << (gl->planes-1-plane));
}
}
else
{
for (plane = 0;plane < gl->planes;plane++)
{
if (readbit(src,offs + gl->planeoffset[plane] + gl->yoffset[yoffs] + gl->xoffset[xoffs]))
dp[x] |= (1 << (gl->planes-1-plane));
}
}
}
dp += gfx->line_modulo;
}
if (gfx->pen_usage)
{
/* fill the pen_usage array with info on the used pens */
gfx->pen_usage[num] = 0;
dp = gfx->gfxdata + num * gfx->char_modulo;
for (y = 0;y < gfx->height;y++)
{
for (x = 0;x < gfx->width;x++)
{
gfx->pen_usage[num] |= 1 << dp[x];
}
dp += gfx->line_modulo;
}
}
}
struct GfxElement *decodegfx(const UINT8 *src,const struct GfxLayout *gl)
{
int c;
struct GfxElement *gfx;
if ((gfx = (GfxElement *) malloc(sizeof(struct GfxElement))) == 0)
return 0;
memset(gfx,0,sizeof(struct GfxElement));
if (Machine->orientation & ORIENTATION_SWAP_XY)
{
gfx->width = gl->height;
gfx->height = gl->width;
}
else
{
gfx->width = gl->width;
gfx->height = gl->height;
}
gfx->line_modulo = gfx->width;
gfx->char_modulo = gfx->line_modulo * gfx->height;
if ((gfx->gfxdata = (unsigned char *) malloc(gl->total * gfx->char_modulo * sizeof(UINT8))) == 0)
{
free(gfx);
return 0;
}
gfx->total_elements = gl->total;
gfx->color_granularity = 1 << gl->planes;
gfx->pen_usage = 0; /* need to make sure this is NULL if the next test fails) */
if (gfx->color_granularity <= 32) /* can't handle more than 32 pens */
gfx->pen_usage = (unsigned int *) malloc(gfx->total_elements * sizeof(int));
/* no need to check for failure, the code can work without pen_usage */
for (c = 0;c < gl->total;c++)
decodechar(gfx,c,src,gl);
return gfx;
}
void freegfx(struct GfxElement *gfx)
{
if (gfx)
{
free(gfx->pen_usage);
free(gfx->gfxdata);
free(gfx);
}
}
INLINE void blockmove_NtoN_transpen_noremap8(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
UINT8 *dstdata,int dstmodulo,
int transpen)
{
UINT8 *end;
int trans4;
UINT32 *sd4;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
trans4 = transpen * 0x01010101;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = *(srcdata++);
if (col != transpen) *dstdata = col;
dstdata++;
}
sd4 = (UINT32 *)srcdata;
#ifdef ALIGN_INTS /* GSL 980108 read/write nonaligned dword routine for ARM processor etc */
if ((long)dstdata & 3)
{
while (dstdata <= end - 4)
{
UINT32 col4;
if ((col4 = *(sd4++)) != trans4)
{
UINT32 xod4;
xod4 = col4 ^ trans4;
if( (xod4&0x000000ff) && (xod4&0x0000ff00) &&
(xod4&0x00ff0000) && (xod4&0xff000000) )
{
write_dword_unaligned(dstdata,col4);
}
else
{
if (xod4 & 0xff000000) dstdata[BL3] = col4 >> 24;
if (xod4 & 0x00ff0000) dstdata[BL2] = col4 >> 16;
if (xod4 & 0x0000ff00) dstdata[BL1] = col4 >> 8;
if (xod4 & 0x000000ff) dstdata[BL0] = col4;
}
}
dstdata += 4;
}
}
else
{
while (dstdata <= end - 4)
{
UINT32 col4;
if ((col4 = *(sd4++)) != trans4)
{
UINT32 xod4;
xod4 = col4 ^ trans4;
if( (xod4&0x000000ff) && (xod4&0x0000ff00) &&
(xod4&0x00ff0000) && (xod4&0xff000000) )
{
write_dword_aligned((UINT32 *)dstdata,col4);
}
else
{
if (xod4 & 0xff000000) dstdata[BL3] = col4 >> 24;
if (xod4 & 0x00ff0000) dstdata[BL2] = col4 >> 16;
if (xod4 & 0x0000ff00) dstdata[BL1] = col4 >> 8;
if (xod4 & 0x000000ff) dstdata[BL0] = col4;
}
}
dstdata += 4;
}
}
#else
while (dstdata <= end - 4)
{
UINT32 col4;
if ((col4 = *(sd4++)) != trans4)
{
UINT32 xod4;
xod4 = col4 ^ trans4;
if( (xod4&0x000000ff) && (xod4&0x0000ff00) &&
(xod4&0x00ff0000) && (xod4&0xff000000) )
{
write_dword((UINT32 *)dstdata,col4);
}
else
{
if (xod4 & 0xff000000) dstdata[BL3] = col4 >> 24;
if (xod4 & 0x00ff0000) dstdata[BL2] = col4 >> 16;
if (xod4 & 0x0000ff00) dstdata[BL1] = col4 >> 8;
if (xod4 & 0x000000ff) dstdata[BL0] = col4;
}
}
dstdata += 4;
}
#endif
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = *(srcdata++);
if (col != transpen) *dstdata = col;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
}
INLINE void blockmove_NtoN_transpen_noremap_flipx8(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
UINT8 *dstdata,int dstmodulo,
int transpen)
{
UINT8 *end;
int trans4;
UINT32 *sd4;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
srcdata -= 3;
trans4 = transpen * 0x01010101;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = srcdata[3];
srcdata--;
if (col != transpen) *dstdata = col;
dstdata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
UINT32 col4;
if ((col4 = *(sd4--)) != trans4)
{
UINT32 xod4;
xod4 = col4 ^ trans4;
if (xod4 & 0x000000ff) dstdata[BL3] = col4;
if (xod4 & 0x0000ff00) dstdata[BL2] = col4 >> 8;
if (xod4 & 0x00ff0000) dstdata[BL1] = col4 >> 16;
if (xod4 & 0xff000000) dstdata[BL0] = col4 >> 24;
}
dstdata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = srcdata[3];
srcdata--;
if (col != transpen) *dstdata = col;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
}
INLINE void blockmove_NtoN_transpen_noremap16(
const UINT16 *srcdata,int srcwidth,int srcheight,int srcmodulo,
UINT16 *dstdata,int dstmodulo,
int transpen)
{
UINT16 *end;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
int col;
col = *(srcdata++);
if (col != transpen) *dstdata = col;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
}
INLINE void blockmove_NtoN_transpen_noremap_flipx16(
const UINT16 *srcdata,int srcwidth,int srcheight,int srcmodulo,
UINT16 *dstdata,int dstmodulo,
int transpen)
{
UINT16 *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
int col;
col = *(srcdata--);
if (col != transpen) *dstdata = col;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
}
#define DATA_TYPE UINT8
#define DECLARE(function,args,body) INLINE void function##8 args body
#define BLOCKMOVE(function,flipx,args) \
if (flipx) blockmove_##function##_flipx##8 args ; \
else blockmove_##function##8 args
#include "drawgfx.cpp"
#undef DATA_TYPE
#undef DECLARE
#undef BLOCKMOVE
#define DATA_TYPE UINT16
#define DECLARE(function,args,body) INLINE void function##16 args body
#define BLOCKMOVE(function,flipx,args) \
if (flipx) blockmove_##function##_flipx##16 args ; \
else blockmove_##function##16 args
#include "drawgfx.cpp"
#undef DATA_TYPE
#undef DECLARE
#undef BLOCKMOVE
/***************************************************************************
Draw graphic elements in the specified bitmap.
transparency == TRANSPARENCY_NONE - no transparency.
transparency == TRANSPARENCY_PEN - bits whose _original_ value is == transparent_color
are transparent. This is the most common kind of
transparency.
transparency == TRANSPARENCY_PENS - as above, but transparent_color is a mask of
transparent pens.
transparency == TRANSPARENCY_COLOR - bits whose _remapped_ palette index (taken from
Machine->game_colortable) is == transparent_color
transparency == TRANSPARENCY_THROUGH - if the _destination_ pixel is == transparent_color,
the source pixel is drawn over it. This is used by
e.g. Jr. Pac Man to draw the sprites when the background
has priority over them.
transparency == TRANSPARENCY_PEN_TABLE - the transparency condition is same as TRANSPARENCY_PEN
A special drawing is done according to gfx_drawmode_table[source pixel].
DRAWMODE_NONE transparent
DRAWMODE_SOURCE normal, draw source pixel.
DRAWMODE_SHADOW destination is changed through palette_shadow_table[]
***************************************************************************/
INLINE void common_drawgfx(struct osd_bitmap *dest,const struct GfxElement *gfx,
unsigned int code,unsigned int color,int flipx,int flipy,int sx,int sy,
const struct rectangle *clip,int transparency,int transparent_color,
struct osd_bitmap *pri_buffer,UINT32 pri_mask)
{
struct rectangle myclip;
if (!gfx)
{
usrintf_showmessage("drawgfx() gfx == 0");
return;
}
if (!gfx->colortable && !is_raw[transparency])
{
usrintf_showmessage("drawgfx() gfx->colortable == 0");
return;
}
code %= gfx->total_elements;
if (!is_raw[transparency])
color %= gfx->total_colors;
if (gfx->pen_usage && (transparency == TRANSPARENCY_PEN || transparency == TRANSPARENCY_PENS))
{
int transmask = 0;
if (transparency == TRANSPARENCY_PEN)
{
transmask = 1 << transparent_color;
}
else /* transparency == TRANSPARENCY_PENS */
{
transmask = transparent_color;
}
if ((gfx->pen_usage[code] & ~transmask) == 0)
/* character is totally transparent, no need to draw */
return;
else if ((gfx->pen_usage[code] & transmask) == 0)
/* character is totally opaque, can disable transparency */
transparency = TRANSPARENCY_NONE;
}
if (Machine->orientation & ORIENTATION_SWAP_XY)
{
int temp;
temp = sx;
sx = sy;
sy = temp;
temp = flipx;
flipx = flipy;
flipy = temp;
if (clip)
{
/* clip and myclip might be the same, so we need a temporary storage */
temp = clip->min_x;
myclip.min_x = clip->min_y;
myclip.min_y = temp;
temp = clip->max_x;
myclip.max_x = clip->max_y;
myclip.max_y = temp;
clip = &myclip;
}
}
if (Machine->orientation & ORIENTATION_FLIP_X)
{
sx = dest->width - gfx->width - sx;
if (clip)
{
int temp;
/* clip and myclip might be the same, so we need a temporary storage */
temp = clip->min_x;
myclip.min_x = dest->width-1 - clip->max_x;
myclip.max_x = dest->width-1 - temp;
myclip.min_y = clip->min_y;
myclip.max_y = clip->max_y;
clip = &myclip;
}
#ifndef PREROTATE_GFX
flipx = !flipx;
#endif
}
if (Machine->orientation & ORIENTATION_FLIP_Y)
{
sy = dest->height - gfx->height - sy;
if (clip)
{
int temp;
myclip.min_x = clip->min_x;
myclip.max_x = clip->max_x;
/* clip and myclip might be the same, so we need a temporary storage */
temp = clip->min_y;
myclip.min_y = dest->height-1 - clip->max_y;
myclip.max_y = dest->height-1 - temp;
clip = &myclip;
}
#ifndef PREROTATE_GFX
flipy = !flipy;
#endif
}
if (dest->depth != 16)
drawgfx_core8(dest,gfx,code,color,flipx,flipy,sx,sy,clip,transparency,transparent_color,pri_buffer,pri_mask);
else
drawgfx_core16(dest,gfx,code,color,flipx,flipy,sx,sy,clip,transparency,transparent_color,pri_buffer,pri_mask);
}
void drawgfx(struct osd_bitmap *dest,const struct GfxElement *gfx,
unsigned int code,unsigned int color,int flipx,int flipy,int sx,int sy,
const struct rectangle *clip,int transparency,int transparent_color)
{
profiler_mark(PROFILER_DRAWGFX);
common_drawgfx(dest,gfx,code,color,flipx,flipy,sx,sy,clip,transparency,transparent_color,NULL,0);
profiler_mark(PROFILER_END);
}
void pdrawgfx(struct osd_bitmap *dest,const struct GfxElement *gfx,
unsigned int code,unsigned int color,int flipx,int flipy,int sx,int sy,
const struct rectangle *clip,int transparency,int transparent_color,UINT32 priority_mask)
{
profiler_mark(PROFILER_DRAWGFX);
common_drawgfx(dest,gfx,code,color,flipx,flipy,sx,sy,clip,transparency,transparent_color,priority_bitmap,priority_mask);
profiler_mark(PROFILER_END);
}
/***************************************************************************
Use drawgfx() to copy a bitmap onto another at the given position.
This function will very likely change in the future.
***************************************************************************/
void copybitmap(struct osd_bitmap *dest,struct osd_bitmap *src,int flipx,int flipy,int sx,int sy,
const struct rectangle *clip,int transparency,int transparent_color)
{
/* translate to proper transparency here */
if (transparency == TRANSPARENCY_NONE)
transparency = TRANSPARENCY_NONE_RAW;
else if (transparency == TRANSPARENCY_PEN)
transparency = TRANSPARENCY_PEN_RAW;
else if (transparency == TRANSPARENCY_COLOR)
{
transparent_color = Machine->pens[transparent_color];
transparency = TRANSPARENCY_PEN_RAW;
}
else if (transparency == TRANSPARENCY_THROUGH)
transparency = TRANSPARENCY_THROUGH_RAW;
copybitmap_remap(dest,src,flipx,flipy,sx,sy,clip,transparency,transparent_color);
}
void copybitmap_remap(struct osd_bitmap *dest,struct osd_bitmap *src,int flipx,int flipy,int sx,int sy,
const struct rectangle *clip,int transparency,int transparent_color)
{
struct rectangle myclip;
profiler_mark(PROFILER_COPYBITMAP);
if (Machine->orientation & ORIENTATION_SWAP_XY)
{
int temp;
temp = sx;
sx = sy;
sy = temp;
temp = flipx;
flipx = flipy;
flipy = temp;
if (clip)
{
/* clip and myclip might be the same, so we need a temporary storage */
temp = clip->min_x;
myclip.min_x = clip->min_y;
myclip.min_y = temp;
temp = clip->max_x;
myclip.max_x = clip->max_y;
myclip.max_y = temp;
clip = &myclip;
}
}
if (Machine->orientation & ORIENTATION_FLIP_X)
{
sx = dest->width - src->width - sx;
if (clip)
{
int temp;
/* clip and myclip might be the same, so we need a temporary storage */
temp = clip->min_x;
myclip.min_x = dest->width-1 - clip->max_x;
myclip.max_x = dest->width-1 - temp;
myclip.min_y = clip->min_y;
myclip.max_y = clip->max_y;
clip = &myclip;
}
}
if (Machine->orientation & ORIENTATION_FLIP_Y)
{
sy = dest->height - src->height - sy;
if (clip)
{
int temp;
myclip.min_x = clip->min_x;
myclip.max_x = clip->max_x;
/* clip and myclip might be the same, so we need a temporary storage */
temp = clip->min_y;
myclip.min_y = dest->height-1 - clip->max_y;
myclip.max_y = dest->height-1 - temp;
clip = &myclip;
}
}
if (dest->depth != 16)
copybitmap_core8(dest,src,flipx,flipy,sx,sy,clip,transparency,transparent_color);
else
copybitmap_core16(dest,src,flipx,flipy,sx,sy,clip,transparency,transparent_color);
profiler_mark(PROFILER_END);
}
/***************************************************************************
Copy a bitmap onto another with scroll and wraparound.
This function supports multiple independently scrolling rows/columns.
"rows" is the number of indepentently scrolling rows. "rowscroll" is an
array of integers telling how much to scroll each row. Same thing for
"cols" and "colscroll".
If the bitmap cannot scroll in one direction, set rows or columns to 0.
If the bitmap scrolls as a whole, set rows and/or cols to 1.
Bidirectional scrolling is, of course, supported only if the bitmap
scrolls as a whole in at least one direction.
***************************************************************************/
void copyscrollbitmap(struct osd_bitmap *dest,struct osd_bitmap *src,
int rows,const int *rowscroll,int cols,const int *colscroll,
const struct rectangle *clip,int transparency,int transparent_color)
{
/* translate to proper transparency here */
if (transparency == TRANSPARENCY_NONE)
transparency = TRANSPARENCY_NONE_RAW;
else if (transparency == TRANSPARENCY_PEN)
transparency = TRANSPARENCY_PEN_RAW;
else if (transparency == TRANSPARENCY_COLOR)
{
transparent_color = Machine->pens[transparent_color];
transparency = TRANSPARENCY_PEN_RAW;
}
else if (transparency == TRANSPARENCY_THROUGH)
transparency = TRANSPARENCY_THROUGH_RAW;
copyscrollbitmap_remap(dest,src,rows,rowscroll,cols,colscroll,clip,transparency,transparent_color);
}
void copyscrollbitmap_remap(struct osd_bitmap *dest,struct osd_bitmap *src,
int rows,const int *rowscroll,int cols,const int *colscroll,
const struct rectangle *clip,int transparency,int transparent_color)
{
int srcwidth,srcheight,destwidth,destheight;
if (rows == 0 && cols == 0)
{
copybitmap(dest,src,0,0,0,0,clip,transparency,transparent_color);
return;
}
profiler_mark(PROFILER_COPYBITMAP);
if (Machine->orientation & ORIENTATION_SWAP_XY)
{
srcwidth = src->height;
srcheight = src->width;
destwidth = dest->height;
destheight = dest->width;
}
else
{
srcwidth = src->width;
srcheight = src->height;
destwidth = dest->width;
destheight = dest->height;
}
if (rows == 0)
{
/* scrolling columns */
int col,colwidth;
struct rectangle myclip;
colwidth = srcwidth / cols;
myclip.min_y = clip->min_y;
myclip.max_y = clip->max_y;
col = 0;
while (col < cols)
{
int cons,scroll;
/* count consecutive columns scrolled by the same amount */
scroll = colscroll[col];
cons = 1;
while (col + cons < cols && colscroll[col + cons] == scroll)
cons++;
if (scroll < 0) scroll = srcheight - (-scroll) % srcheight;
else scroll %= srcheight;
myclip.min_x = col * colwidth;
if (myclip.min_x < clip->min_x) myclip.min_x = clip->min_x;
myclip.max_x = (col + cons) * colwidth - 1;
if (myclip.max_x > clip->max_x) myclip.max_x = clip->max_x;
copybitmap(dest,src,0,0,0,scroll,&myclip,transparency,transparent_color);
copybitmap(dest,src,0,0,0,scroll - srcheight,&myclip,transparency,transparent_color);
col += cons;
}
}
else if (cols == 0)
{
/* scrolling rows */
int row,rowheight;
struct rectangle myclip;
rowheight = srcheight / rows;
myclip.min_x = clip->min_x;
myclip.max_x = clip->max_x;
row = 0;
while (row < rows)
{
int cons,scroll;
/* count consecutive rows scrolled by the same amount */
scroll = rowscroll[row];
cons = 1;
while (row + cons < rows && rowscroll[row + cons] == scroll)
cons++;
if (scroll < 0) scroll = srcwidth - (-scroll) % srcwidth;
else scroll %= srcwidth;
myclip.min_y = row * rowheight;
if (myclip.min_y < clip->min_y) myclip.min_y = clip->min_y;
myclip.max_y = (row + cons) * rowheight - 1;
if (myclip.max_y > clip->max_y) myclip.max_y = clip->max_y;
copybitmap(dest,src,0,0,scroll,0,&myclip,transparency,transparent_color);
copybitmap(dest,src,0,0,scroll - srcwidth,0,&myclip,transparency,transparent_color);
row += cons;
}
}
else if (rows == 1 && cols == 1)
{
/* XY scrolling playfield */
int scrollx,scrolly,sx,sy;
if (rowscroll[0] < 0) scrollx = srcwidth - (-rowscroll[0]) % srcwidth;
else scrollx = rowscroll[0] % srcwidth;
if (colscroll[0] < 0) scrolly = srcheight - (-colscroll[0]) % srcheight;
else scrolly = colscroll[0] % srcheight;
for (sx = scrollx - srcwidth;sx < destwidth;sx += srcwidth)
for (sy = scrolly - srcheight;sy < destheight;sy += srcheight)
copybitmap(dest,src,0,0,sx,sy,clip,transparency,transparent_color);
}
else if (rows == 1)
{
/* scrolling columns + horizontal scroll */
int col,colwidth;
int scrollx;
struct rectangle myclip;
if (rowscroll[0] < 0) scrollx = srcwidth - (-rowscroll[0]) % srcwidth;
else scrollx = rowscroll[0] % srcwidth;
colwidth = srcwidth / cols;
myclip.min_y = clip->min_y;
myclip.max_y = clip->max_y;
col = 0;
while (col < cols)
{
int cons,scroll;
/* count consecutive columns scrolled by the same amount */
scroll = colscroll[col];
cons = 1;
while (col + cons < cols && colscroll[col + cons] == scroll)
cons++;
if (scroll < 0) scroll = srcheight - (-scroll) % srcheight;
else scroll %= srcheight;
myclip.min_x = col * colwidth + scrollx;
if (myclip.min_x < clip->min_x) myclip.min_x = clip->min_x;
myclip.max_x = (col + cons) * colwidth - 1 + scrollx;
if (myclip.max_x > clip->max_x) myclip.max_x = clip->max_x;
copybitmap(dest,src,0,0,scrollx,scroll,&myclip,transparency,transparent_color);
copybitmap(dest,src,0,0,scrollx,scroll - srcheight,&myclip,transparency,transparent_color);
myclip.min_x = col * colwidth + scrollx - srcwidth;
if (myclip.min_x < clip->min_x) myclip.min_x = clip->min_x;
myclip.max_x = (col + cons) * colwidth - 1 + scrollx - srcwidth;
if (myclip.max_x > clip->max_x) myclip.max_x = clip->max_x;
copybitmap(dest,src,0,0,scrollx - srcwidth,scroll,&myclip,transparency,transparent_color);
copybitmap(dest,src,0,0,scrollx - srcwidth,scroll - srcheight,&myclip,transparency,transparent_color);
col += cons;
}
}
else if (cols == 1)
{
/* scrolling rows + vertical scroll */
int row,rowheight;
int scrolly;
struct rectangle myclip;
if (colscroll[0] < 0) scrolly = srcheight - (-colscroll[0]) % srcheight;
else scrolly = colscroll[0] % srcheight;
rowheight = srcheight / rows;
myclip.min_x = clip->min_x;
myclip.max_x = clip->max_x;
row = 0;
while (row < rows)
{
int cons,scroll;
/* count consecutive rows scrolled by the same amount */
scroll = rowscroll[row];
cons = 1;
while (row + cons < rows && rowscroll[row + cons] == scroll)
cons++;
if (scroll < 0) scroll = srcwidth - (-scroll) % srcwidth;
else scroll %= srcwidth;
myclip.min_y = row * rowheight + scrolly;
if (myclip.min_y < clip->min_y) myclip.min_y = clip->min_y;
myclip.max_y = (row + cons) * rowheight - 1 + scrolly;
if (myclip.max_y > clip->max_y) myclip.max_y = clip->max_y;
copybitmap(dest,src,0,0,scroll,scrolly,&myclip,transparency,transparent_color);
copybitmap(dest,src,0,0,scroll - srcwidth,scrolly,&myclip,transparency,transparent_color);
myclip.min_y = row * rowheight + scrolly - srcheight;
if (myclip.min_y < clip->min_y) myclip.min_y = clip->min_y;
myclip.max_y = (row + cons) * rowheight - 1 + scrolly - srcheight;
if (myclip.max_y > clip->max_y) myclip.max_y = clip->max_y;
copybitmap(dest,src,0,0,scroll,scrolly - srcheight,&myclip,transparency,transparent_color);
copybitmap(dest,src,0,0,scroll - srcwidth,scrolly - srcheight,&myclip,transparency,transparent_color);
row += cons;
}
}
profiler_mark(PROFILER_END);
}
/* notes:
- startx and starty MUST be UINT32 for calculations to work correctly
- srcbitmap->width and height are assumed to be a power of 2 to speed up wraparound
*/
void copyrozbitmap(struct osd_bitmap *dest,struct osd_bitmap *src,
UINT32 startx,UINT32 starty,int incxx,int incxy,int incyx,int incyy,int wraparound,
const struct rectangle *clip,int transparency,int transparent_color,UINT32 priority)
{
profiler_mark(PROFILER_COPYBITMAP);
/* cheat, the core doesn't support TRANSPARENCY_NONE yet */
if (transparency == TRANSPARENCY_NONE)
{
transparency = TRANSPARENCY_PEN;
transparent_color = -1;
}
/* if necessary, remap the transparent color */
if (transparency == TRANSPARENCY_COLOR)
{
transparency = TRANSPARENCY_PEN;
transparent_color = Machine->pens[transparent_color];
}
if (transparency != TRANSPARENCY_PEN)
{
usrintf_showmessage("copyrozbitmap unsupported trans %02x",transparency);
return;
}
if (dest->depth != 16)
copyrozbitmap_core8(dest,src,startx,starty,incxx,incxy,incyx,incyy,wraparound,clip,transparency,transparent_color,priority);
else
copyrozbitmap_core16(dest,src,startx,starty,incxx,incxy,incyx,incyy,wraparound,clip,transparency,transparent_color,priority);
profiler_mark(PROFILER_END);
}
/* fill a bitmap using the specified pen */
void fillbitmap(struct osd_bitmap *dest,int pen,const struct rectangle *clip)
{
int sx,sy,ex,ey,y;
struct rectangle myclip;
if (Machine->orientation & ORIENTATION_SWAP_XY)
{
if (clip)
{
myclip.min_x = clip->min_y;
myclip.max_x = clip->max_y;
myclip.min_y = clip->min_x;
myclip.max_y = clip->max_x;
clip = &myclip;
}
}
if (Machine->orientation & ORIENTATION_FLIP_X)
{
if (clip)
{
int temp;
temp = clip->min_x;
myclip.min_x = dest->width-1 - clip->max_x;
myclip.max_x = dest->width-1 - temp;
myclip.min_y = clip->min_y;
myclip.max_y = clip->max_y;
clip = &myclip;
}
}
if (Machine->orientation & ORIENTATION_FLIP_Y)
{
if (clip)
{
int temp;
myclip.min_x = clip->min_x;
myclip.max_x = clip->max_x;
temp = clip->min_y;
myclip.min_y = dest->height-1 - clip->max_y;
myclip.max_y = dest->height-1 - temp;
clip = &myclip;
}
}
sx = 0;
ex = dest->width - 1;
sy = 0;
ey = dest->height - 1;
if (clip && sx < clip->min_x) sx = clip->min_x;
if (clip && ex > clip->max_x) ex = clip->max_x;
if (sx > ex) return;
if (clip && sy < clip->min_y) sy = clip->min_y;
if (clip && ey > clip->max_y) ey = clip->max_y;
if (sy > ey) return;
osd_mark_dirty (sx,sy,ex,ey,0); /* ASG 971011 */
/* ASG 980211 */
if (dest->depth == 16)
{
if ((pen >> 8) == (pen & 0xff))
{
for (y = sy;y <= ey;y++)
memset(&dest->line[y][sx*2],pen&0xff,(ex-sx+1)*2);
}
else
{
UINT16 *sp = (UINT16 *)dest->line[sy];
int x;
for (x = sx;x <= ex;x++)
sp[x] = pen;
sp+=sx;
for (y = sy+1;y <= ey;y++)
memcpy(&dest->line[y][sx*2],sp,(ex-sx+1)*2);
}
}
else
{
for (y = sy;y <= ey;y++)
memset(&dest->line[y][sx],pen,ex-sx+1);
}
}
INLINE void common_drawgfxzoom( struct osd_bitmap *dest_bmp,const struct GfxElement *gfx,
unsigned int code,unsigned int color,int flipx,int flipy,int sx,int sy,
const struct rectangle *clip,int transparency,int transparent_color,
int scalex, int scaley,struct osd_bitmap *pri_buffer,UINT32 pri_mask)
{
struct rectangle myclip;
if (!scalex || !scaley) return;
if (scalex == 0x10000 && scaley == 0x10000)
{
common_drawgfx(dest_bmp,gfx,code,color,flipx,flipy,sx,sy,clip,transparency,transparent_color,pri_buffer,pri_mask);
return;
}
pri_mask |= (1<<31);
if (transparency != TRANSPARENCY_PEN && transparency != TRANSPARENCY_PEN_RAW
&& transparency != TRANSPARENCY_PENS && transparency != TRANSPARENCY_COLOR
&& transparency != TRANSPARENCY_PEN_TABLE && transparency != TRANSPARENCY_PEN_TABLE_RAW)
{
usrintf_showmessage("drawgfxzoom unsupported trans %02x",transparency);
return;
}
if (transparency == TRANSPARENCY_COLOR)
transparent_color = Machine->pens[transparent_color];
/*
scalex and scaley are 16.16 fixed point numbers
1<<15 : shrink to 50%
1<<16 : uniform scale
1<<17 : double to 200%
*/
if (Machine->orientation & ORIENTATION_SWAP_XY)
{
int temp;
temp = sx;
sx = sy;
sy = temp;
temp = flipx;
flipx = flipy;
flipy = temp;
temp = scalex;
scalex = scaley;
scaley = temp;
if (clip)
{
/* clip and myclip might be the same, so we need a temporary storage */
temp = clip->min_x;
myclip.min_x = clip->min_y;
myclip.min_y = temp;
temp = clip->max_x;
myclip.max_x = clip->max_y;
myclip.max_y = temp;
clip = &myclip;
}
}
if (Machine->orientation & ORIENTATION_FLIP_X)
{
sx = dest_bmp->width - ((gfx->width * scalex + 0x7fff) >> 16) - sx;
if (clip)
{
int temp;
/* clip and myclip might be the same, so we need a temporary storage */
temp = clip->min_x;
myclip.min_x = dest_bmp->width-1 - clip->max_x;
myclip.max_x = dest_bmp->width-1 - temp;
myclip.min_y = clip->min_y;
myclip.max_y = clip->max_y;
clip = &myclip;
}
#ifndef PREROTATE_GFX
flipx = !flipx;
#endif
}
if (Machine->orientation & ORIENTATION_FLIP_Y)
{
sy = dest_bmp->height - ((gfx->height * scaley + 0x7fff) >> 16) - sy;
if (clip)
{
int temp;
myclip.min_x = clip->min_x;
myclip.max_x = clip->max_x;
/* clip and myclip might be the same, so we need a temporary storage */
temp = clip->min_y;
myclip.min_y = dest_bmp->height-1 - clip->max_y;
myclip.max_y = dest_bmp->height-1 - temp;
clip = &myclip;
}
#ifndef PREROTATE_GFX
flipy = !flipy;
#endif
}
/* KW 991012 -- Added code to force clip to bitmap boundary */
if(clip)
{
myclip.min_x = clip->min_x;
myclip.max_x = clip->max_x;
myclip.min_y = clip->min_y;
myclip.max_y = clip->max_y;
if (myclip.min_x < 0) myclip.min_x = 0;
if (myclip.max_x >= dest_bmp->width) myclip.max_x = dest_bmp->width-1;
if (myclip.min_y < 0) myclip.min_y = 0;
if (myclip.max_y >= dest_bmp->height) myclip.max_y = dest_bmp->height-1;
clip=&myclip;
}
/* ASG 980209 -- added 16-bit version */
if (dest_bmp->depth != 16)
{
if( gfx && gfx->colortable )
{
const UINT16 *pal = &gfx->colortable[gfx->color_granularity * (color % gfx->total_colors)]; /* ASG 980209 */
int source_base = (code % gfx->total_elements) * gfx->height;
int sprite_screen_height = (scaley*gfx->height+0x8000)>>16;
int sprite_screen_width = (scalex*gfx->width+0x8000)>>16;
/* compute sprite increment per screen pixel */
int dx = (gfx->width<<16)/sprite_screen_width;
int dy = (gfx->height<<16)/sprite_screen_height;
int ex = sx+sprite_screen_width;
int ey = sy+sprite_screen_height;
int x_index_base;
int y_index;
if( flipx )
{
x_index_base = (sprite_screen_width-1)*dx;
dx = -dx;
}
else
{
x_index_base = 0;
}
if( flipy )
{
y_index = (sprite_screen_height-1)*dy;
dy = -dy;
}
else
{
y_index = 0;
}
if( clip )
{
if( sx < clip->min_x)
{ /* clip left */
int pixels = clip->min_x-sx;
sx += pixels;
x_index_base += pixels*dx;
}
if( sy < clip->min_y )
{ /* clip top */
int pixels = clip->min_y-sy;
sy += pixels;
y_index += pixels*dy;
}
/* NS 980211 - fixed incorrect clipping */
if( ex > clip->max_x+1 )
{ /* clip right */
int pixels = ex-clip->max_x-1;
ex -= pixels;
}
if( ey > clip->max_y+1 )
{ /* clip bottom */
int pixels = ey-clip->max_y-1;
ey -= pixels;
}
}
if( ex>sx )
{ /* skip if inner loop doesn't draw anything */
int y;
/* case 1: TRANSPARENCY_PEN */
if (transparency == TRANSPARENCY_PEN)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
if (((1 << pri[x]) & pri_mask) == 0)
dest[x] = pal[c];
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color ) dest[x] = pal[c];
x_index += dx;
}
y_index += dy;
}
}
}
/* case 1b: TRANSPARENCY_PEN_RAW */
if (transparency == TRANSPARENCY_PEN_RAW)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
if (((1 << pri[x]) & pri_mask) == 0)
dest[x] = color + c;
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color ) dest[x] = color + c;
x_index += dx;
}
y_index += dy;
}
}
}
/* case 2: TRANSPARENCY_PENS */
if (transparency == TRANSPARENCY_PENS)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if (((1 << c) & transparent_color) == 0)
{
if (((1 << pri[x]) & pri_mask) == 0)
dest[x] = pal[c];
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if (((1 << c) & transparent_color) == 0)
dest[x] = pal[c];
x_index += dx;
}
y_index += dy;
}
}
}
/* case 3: TRANSPARENCY_COLOR */
else if (transparency == TRANSPARENCY_COLOR)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = pal[source[x_index>>16]];
if( c != transparent_color )
{
if (((1 << pri[x]) & pri_mask) == 0)
dest[x] = c;
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = pal[source[x_index>>16]];
if( c != transparent_color ) dest[x] = c;
x_index += dx;
}
y_index += dy;
}
}
}
/* case 4: TRANSPARENCY_PEN_TABLE */
if (transparency == TRANSPARENCY_PEN_TABLE)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
if (((1 << pri[x]) & pri_mask) == 0)
{
switch(gfx_drawmode_table[c])
{
case DRAWMODE_SOURCE:
dest[x] = pal[c];
break;
case DRAWMODE_SHADOW:
dest[x] = palette_shadow_table[dest[x]];
break;
}
}
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
switch(gfx_drawmode_table[c])
{
case DRAWMODE_SOURCE:
dest[x] = pal[c];
break;
case DRAWMODE_SHADOW:
dest[x] = palette_shadow_table[dest[x]];
break;
}
}
x_index += dx;
}
y_index += dy;
}
}
}
/* case 4b: TRANSPARENCY_PEN_TABLE_RAW */
if (transparency == TRANSPARENCY_PEN_TABLE_RAW)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
if (((1 << pri[x]) & pri_mask) == 0)
{
switch(gfx_drawmode_table[c])
{
case DRAWMODE_SOURCE:
dest[x] = color + c;
break;
case DRAWMODE_SHADOW:
dest[x] = palette_shadow_table[dest[x]];
break;
}
}
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT8 *dest = dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
switch(gfx_drawmode_table[c])
{
case DRAWMODE_SOURCE:
dest[x] = color + c;
break;
case DRAWMODE_SHADOW:
dest[x] = palette_shadow_table[dest[x]];
break;
}
}
x_index += dx;
}
y_index += dy;
}
}
}
}
}
}
/* ASG 980209 -- new 16-bit part */
else
{
if( gfx && gfx->colortable )
{
const UINT16 *pal = &gfx->colortable[gfx->color_granularity * (color % gfx->total_colors)]; /* ASG 980209 */
int source_base = (code % gfx->total_elements) * gfx->height;
int sprite_screen_height = (scaley*gfx->height+0x8000)>>16;
int sprite_screen_width = (scalex*gfx->width+0x8000)>>16;
/* compute sprite increment per screen pixel */
int dx = (gfx->width<<16)/sprite_screen_width;
int dy = (gfx->height<<16)/sprite_screen_height;
int ex = sx+sprite_screen_width;
int ey = sy+sprite_screen_height;
int x_index_base;
int y_index;
if( flipx )
{
x_index_base = (sprite_screen_width-1)*dx;
dx = -dx;
}
else
{
x_index_base = 0;
}
if( flipy )
{
y_index = (sprite_screen_height-1)*dy;
dy = -dy;
}
else
{
y_index = 0;
}
if( clip )
{
if( sx < clip->min_x)
{ /* clip left */
int pixels = clip->min_x-sx;
sx += pixels;
x_index_base += pixels*dx;
}
if( sy < clip->min_y )
{ /* clip top */
int pixels = clip->min_y-sy;
sy += pixels;
y_index += pixels*dy;
}
/* NS 980211 - fixed incorrect clipping */
if( ex > clip->max_x+1 )
{ /* clip right */
int pixels = ex-clip->max_x-1;
ex -= pixels;
}
if( ey > clip->max_y+1 )
{ /* clip bottom */
int pixels = ey-clip->max_y-1;
ey -= pixels;
}
}
if( ex>sx )
{ /* skip if inner loop doesn't draw anything */
int y;
/* case 1: TRANSPARENCY_PEN */
if (transparency == TRANSPARENCY_PEN)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
if (((1 << pri[x]) & pri_mask) == 0)
dest[x] = pal[c];
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color ) dest[x] = pal[c];
x_index += dx;
}
y_index += dy;
}
}
}
/* case 1b: TRANSPARENCY_PEN_RAW */
if (transparency == TRANSPARENCY_PEN_RAW)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
if (((1 << pri[x]) & pri_mask) == 0)
dest[x] = color + c;
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color ) dest[x] = color + c;
x_index += dx;
}
y_index += dy;
}
}
}
/* case 2: TRANSPARENCY_PENS */
if (transparency == TRANSPARENCY_PENS)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if (((1 << c) & transparent_color) == 0)
{
if (((1 << pri[x]) & pri_mask) == 0)
dest[x] = pal[c];
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if (((1 << c) & transparent_color) == 0)
dest[x] = pal[c];
x_index += dx;
}
y_index += dy;
}
}
}
/* case 3: TRANSPARENCY_COLOR */
else if (transparency == TRANSPARENCY_COLOR)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = pal[source[x_index>>16]];
if( c != transparent_color )
{
if (((1 << pri[x]) & pri_mask) == 0)
dest[x] = c;
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = pal[source[x_index>>16]];
if( c != transparent_color ) dest[x] = c;
x_index += dx;
}
y_index += dy;
}
}
}
/* case 4: TRANSPARENCY_PEN_TABLE */
if (transparency == TRANSPARENCY_PEN_TABLE)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
if (((1 << pri[x]) & pri_mask) == 0)
{
switch(gfx_drawmode_table[c])
{
case DRAWMODE_SOURCE:
dest[x] = pal[c];
break;
case DRAWMODE_SHADOW:
dest[x] = palette_shadow_table[dest[x]];
break;
}
}
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
switch(gfx_drawmode_table[c])
{
case DRAWMODE_SOURCE:
dest[x] = pal[c];
break;
case DRAWMODE_SHADOW:
dest[x] = palette_shadow_table[dest[x]];
break;
}
}
x_index += dx;
}
y_index += dy;
}
}
}
/* case 4b: TRANSPARENCY_PEN_TABLE_RAW */
if (transparency == TRANSPARENCY_PEN_TABLE_RAW)
{
if (pri_buffer)
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
UINT8 *pri = pri_buffer->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
if (((1 << pri[x]) & pri_mask) == 0)
{
switch(gfx_drawmode_table[c])
{
case DRAWMODE_SOURCE:
dest[x] = color + c;
break;
case DRAWMODE_SHADOW:
dest[x] = palette_shadow_table[dest[x]];
break;
}
}
pri[x] = 31;
}
x_index += dx;
}
y_index += dy;
}
}
else
{
for( y=sy; y<ey; y++ )
{
UINT8 *source = gfx->gfxdata + (source_base+(y_index>>16)) * gfx->line_modulo;
UINT16 *dest = (UINT16 *)dest_bmp->line[y];
int x, x_index = x_index_base;
for( x=sx; x<ex; x++ )
{
int c = source[x_index>>16];
if( c != transparent_color )
{
switch(gfx_drawmode_table[c])
{
case DRAWMODE_SOURCE:
dest[x] = color + c;
break;
case DRAWMODE_SHADOW:
dest[x] = palette_shadow_table[dest[x]];
break;
}
}
x_index += dx;
}
y_index += dy;
}
}
}
}
}
}
}
void drawgfxzoom( struct osd_bitmap *dest_bmp,const struct GfxElement *gfx,
unsigned int code,unsigned int color,int flipx,int flipy,int sx,int sy,
const struct rectangle *clip,int transparency,int transparent_color,int scalex, int scaley)
{
profiler_mark(PROFILER_DRAWGFX);
common_drawgfxzoom(dest_bmp,gfx,code,color,flipx,flipy,sx,sy,
clip,transparency,transparent_color,scalex,scaley,NULL,0);
profiler_mark(PROFILER_END);
}
void pdrawgfxzoom( struct osd_bitmap *dest_bmp,const struct GfxElement *gfx,
unsigned int code,unsigned int color,int flipx,int flipy,int sx,int sy,
const struct rectangle *clip,int transparency,int transparent_color,int scalex, int scaley,
UINT32 priority_mask)
{
profiler_mark(PROFILER_DRAWGFX);
common_drawgfxzoom(dest_bmp,gfx,code,color,flipx,flipy,sx,sy,
clip,transparency,transparent_color,scalex,scaley,priority_bitmap,priority_mask);
profiler_mark(PROFILER_END);
}
void plot_pixel2(struct osd_bitmap *bitmap1,struct osd_bitmap *bitmap2,int x,int y,int pen)
{
plot_pixel(bitmap1, x, y, pen);
plot_pixel(bitmap2, x, y, pen);
}
static void pp_8_nd(struct osd_bitmap *b,int x,int y,int p) { b->line[y][x] = p; }
static void pp_8_nd_fx(struct osd_bitmap *b,int x,int y,int p) { b->line[y][b->width-1-x] = p; }
static void pp_8_nd_fy(struct osd_bitmap *b,int x,int y,int p) { b->line[b->height-1-y][x] = p; }
static void pp_8_nd_fxy(struct osd_bitmap *b,int x,int y,int p) { b->line[b->height-1-y][b->width-1-x] = p; }
static void pp_8_nd_s(struct osd_bitmap *b,int x,int y,int p) { b->line[x][y] = p; }
static void pp_8_nd_fx_s(struct osd_bitmap *b,int x,int y,int p) { b->line[x][b->width-1-y] = p; }
static void pp_8_nd_fy_s(struct osd_bitmap *b,int x,int y,int p) { b->line[b->height-1-x][y] = p; }
static void pp_8_nd_fxy_s(struct osd_bitmap *b,int x,int y,int p) { b->line[b->height-1-x][b->width-1-y] = p; }
static void pp_8_d(struct osd_bitmap *b,int x,int y,int p) { b->line[y][x] = p; osd_mark_dirty (x,y,x,y,0); }
static void pp_8_d_fx(struct osd_bitmap *b,int x,int y,int p) { x = b->width-1-x; b->line[y][x] = p; osd_mark_dirty (x,y,x,y,0); }
static void pp_8_d_fy(struct osd_bitmap *b,int x,int y,int p) { y = b->height-1-y; b->line[y][x] = p; osd_mark_dirty (x,y,x,y,0); }
static void pp_8_d_fxy(struct osd_bitmap *b,int x,int y,int p) { x = b->width-1-x; y = b->height-1-y; b->line[y][x] = p; osd_mark_dirty (x,y,x,y,0); }
static void pp_8_d_s(struct osd_bitmap *b,int x,int y,int p) { b->line[x][y] = p; osd_mark_dirty (y,x,y,x,0); }
static void pp_8_d_fx_s(struct osd_bitmap *b,int x,int y,int p) { y = b->width-1-y; b->line[x][y] = p; osd_mark_dirty (y,x,y,x,0); }
static void pp_8_d_fy_s(struct osd_bitmap *b,int x,int y,int p) { x = b->height-1-x; b->line[x][y] = p; osd_mark_dirty (y,x,y,x,0); }
static void pp_8_d_fxy_s(struct osd_bitmap *b,int x,int y,int p) { x = b->height-1-x; y = b->width-1-y; b->line[x][y] = p; osd_mark_dirty (y,x,y,x,0); }
static void pp_16_nd(struct osd_bitmap *b,int x,int y,int p) { ((UINT16 *)b->line[y])[x] = p; }
static void pp_16_nd_fx(struct osd_bitmap *b,int x,int y,int p) { ((UINT16 *)b->line[y])[b->width-1-x] = p; }
static void pp_16_nd_fy(struct osd_bitmap *b,int x,int y,int p) { ((UINT16 *)b->line[b->height-1-y])[x] = p; }
static void pp_16_nd_fxy(struct osd_bitmap *b,int x,int y,int p) { ((UINT16 *)b->line[b->height-1-y])[b->width-1-x] = p; }
static void pp_16_nd_s(struct osd_bitmap *b,int x,int y,int p) { ((UINT16 *)b->line[x])[y] = p; }
static void pp_16_nd_fx_s(struct osd_bitmap *b,int x,int y,int p) { ((UINT16 *)b->line[x])[b->width-1-y] = p; }
static void pp_16_nd_fy_s(struct osd_bitmap *b,int x,int y,int p) { ((UINT16 *)b->line[b->height-1-x])[y] = p; }
static void pp_16_nd_fxy_s(struct osd_bitmap *b,int x,int y,int p) { ((UINT16 *)b->line[b->height-1-x])[b->width-1-y] = p; }
static void pp_16_d(struct osd_bitmap *b,int x,int y,int p) { ((UINT16 *)b->line[y])[x] = p; osd_mark_dirty (x,y,x,y,0); }
static void pp_16_d_fx(struct osd_bitmap *b,int x,int y,int p) { x = b->width-1-x; ((UINT16 *)b->line[y])[x] = p; osd_mark_dirty (x,y,x,y,0); }
static void pp_16_d_fy(struct osd_bitmap *b,int x,int y,int p) { y = b->height-1-y; ((UINT16 *)b->line[y])[x] = p; osd_mark_dirty (x,y,x,y,0); }
static void pp_16_d_fxy(struct osd_bitmap *b,int x,int y,int p) { x = b->width-1-x; y = b->height-1-y; ((UINT16 *)b->line[y])[x] = p; osd_mark_dirty (x,y,x,y,0); }
static void pp_16_d_s(struct osd_bitmap *b,int x,int y,int p) { ((UINT16 *)b->line[x])[y] = p; osd_mark_dirty (y,x,y,x,0); }
static void pp_16_d_fx_s(struct osd_bitmap *b,int x,int y,int p) { y = b->width-1-y; ((UINT16 *)b->line[x])[y] = p; osd_mark_dirty (y,x,y,x,0); }
static void pp_16_d_fy_s(struct osd_bitmap *b,int x,int y,int p) { x = b->height-1-x; ((UINT16 *)b->line[x])[y] = p; osd_mark_dirty (y,x,y,x,0); }
static void pp_16_d_fxy_s(struct osd_bitmap *b,int x,int y,int p) { x = b->height-1-x; y = b->width-1-y; ((UINT16 *)b->line[x])[y] = p; osd_mark_dirty (y,x,y,x,0); }
static int rp_8(struct osd_bitmap *b,int x,int y) { return b->line[y][x]; }
static int rp_8_fx(struct osd_bitmap *b,int x,int y) { return b->line[y][b->width-1-x]; }
static int rp_8_fy(struct osd_bitmap *b,int x,int y) { return b->line[b->height-1-y][x]; }
static int rp_8_fxy(struct osd_bitmap *b,int x,int y) { return b->line[b->height-1-y][b->width-1-x]; }
static int rp_8_s(struct osd_bitmap *b,int x,int y) { return b->line[x][y]; }
static int rp_8_fx_s(struct osd_bitmap *b,int x,int y) { return b->line[x][b->width-1-y]; }
static int rp_8_fy_s(struct osd_bitmap *b,int x,int y) { return b->line[b->height-1-x][y]; }
static int rp_8_fxy_s(struct osd_bitmap *b,int x,int y) { return b->line[b->height-1-x][b->width-1-y]; }
static int rp_16(struct osd_bitmap *b,int x,int y) { return ((UINT16 *)b->line[y])[x]; }
static int rp_16_fx(struct osd_bitmap *b,int x,int y) { return ((UINT16 *)b->line[y])[b->width-1-x]; }
static int rp_16_fy(struct osd_bitmap *b,int x,int y) { return ((UINT16 *)b->line[b->height-1-y])[x]; }
static int rp_16_fxy(struct osd_bitmap *b,int x,int y) { return ((UINT16 *)b->line[b->height-1-y])[b->width-1-x]; }
static int rp_16_s(struct osd_bitmap *b,int x,int y) { return ((UINT16 *)b->line[x])[y]; }
static int rp_16_fx_s(struct osd_bitmap *b,int x,int y) { return ((UINT16 *)b->line[x])[b->width-1-y]; }
static int rp_16_fy_s(struct osd_bitmap *b,int x,int y) { return ((UINT16 *)b->line[b->height-1-x])[y]; }
static int rp_16_fxy_s(struct osd_bitmap *b,int x,int y) { return ((UINT16 *)b->line[b->height-1-x])[b->width-1-y]; }
static void pb_8_nd(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; while(h-->0){ int c=w; x=t; while(c-->0){ b->line[y][x] = p; x++; } y++; } }
static void pb_8_nd_fx(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->width-1-x; while(h-->0){ int c=w; x=t; while(c-->0){ b->line[y][x] = p; x--; } y++; } }
static void pb_8_nd_fy(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; y = b->height-1-y; while(h-->0){ int c=w; x=t; while(c-->0){ b->line[y][x] = p; x++; } y--; } }
static void pb_8_nd_fxy(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->width-1-x; y = b->height-1-y; while(h-->0){ int c=w; x=t; while(c-->0){ b->line[y][x] = p; x--; } y--; } }
static void pb_8_nd_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; while(h-->0){ int c=w; x=t; while(c-->0){ b->line[x][y] = p; x++; } y++; } }
static void pb_8_nd_fx_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; y = b->width-1-y; while(h-->0){ int c=w; x=t; while(c-->0){ b->line[x][y] = p; x++; } y--; } }
static void pb_8_nd_fy_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->height-1-x; while(h-->0){ int c=w; x=t; while(c-->0){ b->line[x][y] = p; x--; } y++; } }
static void pb_8_nd_fxy_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->height-1-x; y = b->width-1-y; while(h-->0){ int c=w; x=t; while(c-->0){ b->line[x][y] = p; x--; } y--; } }
static void pb_8_d(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; osd_mark_dirty (t,y,t+w-1,y+h-1,0); while(h-->0){ int c=w; x=t; while(c-->0){ b->line[y][x] = p; x++; } y++; } }
static void pb_8_d_fx(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->width-1-x; osd_mark_dirty (t-w+1,y,t,y+h-1,0); while(h-->0){ int c=w; x=t; while(c-->0){ b->line[y][x] = p; x--; } y++; } }
static void pb_8_d_fy(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; y = b->height-1-y; osd_mark_dirty (t,y-h+1,t+w-1,y,0); while(h-->0){ int c=w; x=t; while(c-->0){ b->line[y][x] = p; x++; } y--; } }
static void pb_8_d_fxy(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->width-1-x; y = b->height-1-y; osd_mark_dirty (t-w+1,y-h+1,t,y,0); while(h-->0){ int c=w; x=t; while(c-->0){ b->line[y][x] = p; x--; } y--; } }
static void pb_8_d_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; osd_mark_dirty (y,t,y+h-1,t+w-1,0); while(h-->0){ int c=w; x=t; while(c-->0){ b->line[x][y] = p; x++; } y++; } }
static void pb_8_d_fx_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; y = b->width-1-y; osd_mark_dirty (y-h+1,t,y,t+w-1,0); while(h-->0){ int c=w; x=t; while(c-->0){ b->line[x][y] = p; x++; } y--; } }
static void pb_8_d_fy_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->height-1-x; osd_mark_dirty (y,t-w+1,y+h-1,t,0); while(h-->0){ int c=w; x=t; while(c-->0){ b->line[x][y] = p; x--; } y++; } }
static void pb_8_d_fxy_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->height-1-x; y = b->width-1-y; osd_mark_dirty (y-h+1,t-w+1,y,t,0); while(h-->0){ int c=w; x=t; while(c-->0){ b->line[x][y] = p; x--; } y--; } }
static void pb_16_nd(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[y])[x] = p; x++; } y++; } }
static void pb_16_nd_fx(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->width-1-x; while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[y])[x] = p; x--; } y++; } }
static void pb_16_nd_fy(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; y = b->height-1-y; while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[y])[x] = p; x++; } y--; } }
static void pb_16_nd_fxy(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->width-1-x; y = b->height-1-y; while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[y])[x] = p; x--; } y--; } }
static void pb_16_nd_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[x])[y] = p; x++; } y++; } }
static void pb_16_nd_fx_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; y = b->width-1-y; while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[x])[y] = p; x++; } y--; } }
static void pb_16_nd_fy_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->height-1-x; while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[x])[y] = p; x--; } y++; } }
static void pb_16_nd_fxy_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->height-1-x; y = b->width-1-y; while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[x])[y] = p; x--; } y--; } }
static void pb_16_d(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; osd_mark_dirty (t,y,t+w-1,y+h-1,0); while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[y])[x] = p; x++; } y++; } }
static void pb_16_d_fx(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->width-1-x; osd_mark_dirty (t-w+1,y,t,y+h-1,0); while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[y])[x] = p; x--; } y++; } }
static void pb_16_d_fy(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; y = b->height-1-y; osd_mark_dirty (t,y-h+1,t+w-1,y,0); while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[y])[x] = p; x++; } y--; } }
static void pb_16_d_fxy(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->width-1-x; y = b->height-1-y; osd_mark_dirty (t-w+1,y-h+1,t,y,0); while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[y])[x] = p; x--; } y--; } }
static void pb_16_d_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; osd_mark_dirty (y,t,y+h-1,t+w-1,0); while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[x])[y] = p; x++; } y++; } }
static void pb_16_d_fx_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=x; y = b->width-1-y; osd_mark_dirty (y-h+1,t,y,t+w-1,0); while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[x])[y] = p; x++; } y--; } }
static void pb_16_d_fy_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->height-1-x; osd_mark_dirty (y,t-w+1,y+h-1,t,0); while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[x])[y] = p; x--; } y++; } }
static void pb_16_d_fxy_s(struct osd_bitmap *b,int x,int y,int w,int h,int p) { int t=b->height-1-x; y = b->width-1-y; osd_mark_dirty (y-h+1,t-w+1,y,t,0); while(h-->0){ int c=w; x=t; while(c-->0){ ((UINT16 *)b->line[x])[y] = p; x--; } y--; } }
static plot_pixel_proc pps_8_nd[] =
{ pp_8_nd, pp_8_nd_fx, pp_8_nd_fy, pp_8_nd_fxy,
pp_8_nd_s, pp_8_nd_fx_s, pp_8_nd_fy_s, pp_8_nd_fxy_s };
static plot_pixel_proc pps_8_d[] =
{ pp_8_d, pp_8_d_fx, pp_8_d_fy, pp_8_d_fxy,
pp_8_d_s, pp_8_d_fx_s, pp_8_d_fy_s, pp_8_d_fxy_s };
static plot_pixel_proc pps_16_nd[] =
{ pp_16_nd, pp_16_nd_fx, pp_16_nd_fy, pp_16_nd_fxy,
pp_16_nd_s, pp_16_nd_fx_s, pp_16_nd_fy_s, pp_16_nd_fxy_s };
static plot_pixel_proc pps_16_d[] =
{ pp_16_d, pp_16_d_fx, pp_16_d_fy, pp_16_d_fxy,
pp_16_d_s, pp_16_d_fx_s, pp_16_d_fy_s, pp_16_d_fxy_s };
static read_pixel_proc rps_8[] =
{ rp_8, rp_8_fx, rp_8_fy, rp_8_fxy,
rp_8_s, rp_8_fx_s, rp_8_fy_s, rp_8_fxy_s };
static read_pixel_proc rps_16[] =
{ rp_16, rp_16_fx, rp_16_fy, rp_16_fxy,
rp_16_s, rp_16_fx_s, rp_16_fy_s, rp_16_fxy_s };
static plot_box_proc pbs_8_nd[] =
{ pb_8_nd, pb_8_nd_fx, pb_8_nd_fy, pb_8_nd_fxy,
pb_8_nd_s, pb_8_nd_fx_s, pb_8_nd_fy_s, pb_8_nd_fxy_s };
static plot_box_proc pbs_8_d[] =
{ pb_8_d, pb_8_d_fx, pb_8_d_fy, pb_8_d_fxy,
pb_8_d_s, pb_8_d_fx_s, pb_8_d_fy_s, pb_8_d_fxy_s };
static plot_box_proc pbs_16_nd[] =
{ pb_16_nd, pb_16_nd_fx, pb_16_nd_fy, pb_16_nd_fxy,
pb_16_nd_s, pb_16_nd_fx_s, pb_16_nd_fy_s, pb_16_nd_fxy_s };
static plot_box_proc pbs_16_d[] =
{ pb_16_d, pb_16_d_fx, pb_16_d_fy, pb_16_d_fxy,
pb_16_d_s, pb_16_d_fx_s, pb_16_d_fy_s, pb_16_d_fxy_s };
void set_pixel_functions(void)
{
if (Machine->color_depth == 8)
{
read_pixel = rps_8[Machine->orientation];
if (Machine->drv->video_attributes & VIDEO_SUPPORTS_DIRTY)
{
plot_pixel = pps_8_d[Machine->orientation];
plot_box = pbs_8_d[Machine->orientation];
}
else
{
plot_pixel = pps_8_nd[Machine->orientation];
plot_box = pbs_8_nd[Machine->orientation];
}
}
else
{
read_pixel = rps_16[Machine->orientation];
if (Machine->drv->video_attributes & VIDEO_SUPPORTS_DIRTY)
{
plot_pixel = pps_16_d[Machine->orientation];
plot_box = pbs_16_d[Machine->orientation];
}
else
{
plot_pixel = pps_16_nd[Machine->orientation];
plot_box = pbs_16_nd[Machine->orientation];
}
}
/* while we're here, fill in the raw drawing mode table as well */
is_raw[TRANSPARENCY_NONE_RAW] = 1;
is_raw[TRANSPARENCY_PEN_RAW] = 1;
is_raw[TRANSPARENCY_PENS_RAW] = 1;
is_raw[TRANSPARENCY_THROUGH_RAW] = 1;
is_raw[TRANSPARENCY_PEN_TABLE_RAW] = 1;
is_raw[TRANSPARENCY_BLEND_RAW] = 1;
}
#else /* DECLARE */
/* -------------------- included inline section --------------------- */
/* don't put this file in the makefile, it is #included by common.c to */
/* generate 8-bit and 16-bit versions */
DECLARE(blockmove_8toN_opaque,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata),
{
DATA_TYPE *end;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
dstdata[0] = paldata[srcdata[0]];
dstdata[1] = paldata[srcdata[1]];
dstdata[2] = paldata[srcdata[2]];
dstdata[3] = paldata[srcdata[3]];
dstdata[4] = paldata[srcdata[4]];
dstdata[5] = paldata[srcdata[5]];
dstdata[6] = paldata[srcdata[6]];
dstdata[7] = paldata[srcdata[7]];
dstdata += 8;
srcdata += 8;
}
while (dstdata < end)
*(dstdata++) = paldata[*(srcdata++)];
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_opaque_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata),
{
DATA_TYPE *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
srcdata -= 8;
dstdata[0] = paldata[srcdata[8]];
dstdata[1] = paldata[srcdata[7]];
dstdata[2] = paldata[srcdata[6]];
dstdata[3] = paldata[srcdata[5]];
dstdata[4] = paldata[srcdata[4]];
dstdata[5] = paldata[srcdata[3]];
dstdata[6] = paldata[srcdata[2]];
dstdata[7] = paldata[srcdata[1]];
dstdata += 8;
}
while (dstdata < end)
*(dstdata++) = paldata[*(srcdata--)];
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_opaque_pri,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,UINT8 *pridata,UINT32 pmask),
{
DATA_TYPE *end;
pmask |= (1<<31);
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
if (((1 << pridata[0]) & pmask) == 0) dstdata[0] = paldata[srcdata[0]];
if (((1 << pridata[1]) & pmask) == 0) dstdata[1] = paldata[srcdata[1]];
if (((1 << pridata[2]) & pmask) == 0) dstdata[2] = paldata[srcdata[2]];
if (((1 << pridata[3]) & pmask) == 0) dstdata[3] = paldata[srcdata[3]];
if (((1 << pridata[4]) & pmask) == 0) dstdata[4] = paldata[srcdata[4]];
if (((1 << pridata[5]) & pmask) == 0) dstdata[5] = paldata[srcdata[5]];
if (((1 << pridata[6]) & pmask) == 0) dstdata[6] = paldata[srcdata[6]];
if (((1 << pridata[7]) & pmask) == 0) dstdata[7] = paldata[srcdata[7]];
memset(pridata,31,8);
srcdata += 8;
dstdata += 8;
pridata += 8;
}
while (dstdata < end)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[*srcdata];
*pridata = 31;
srcdata++;
dstdata++;
pridata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
pridata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_opaque_pri_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,UINT8 *pridata,UINT32 pmask),
{
DATA_TYPE *end;
pmask |= (1<<31);
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
srcdata -= 8;
if (((1 << pridata[0]) & pmask) == 0) dstdata[0] = paldata[srcdata[8]];
if (((1 << pridata[1]) & pmask) == 0) dstdata[1] = paldata[srcdata[7]];
if (((1 << pridata[2]) & pmask) == 0) dstdata[2] = paldata[srcdata[6]];
if (((1 << pridata[3]) & pmask) == 0) dstdata[3] = paldata[srcdata[5]];
if (((1 << pridata[4]) & pmask) == 0) dstdata[4] = paldata[srcdata[4]];
if (((1 << pridata[5]) & pmask) == 0) dstdata[5] = paldata[srcdata[3]];
if (((1 << pridata[6]) & pmask) == 0) dstdata[6] = paldata[srcdata[2]];
if (((1 << pridata[7]) & pmask) == 0) dstdata[7] = paldata[srcdata[1]];
memset(pridata,31,8);
dstdata += 8;
pridata += 8;
}
while (dstdata < end)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[*srcdata];
*pridata = 31;
srcdata--;
dstdata++;
pridata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
pridata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_opaque_raw,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
unsigned int colorbase),
{
DATA_TYPE *end;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
dstdata[0] = colorbase + srcdata[0];
dstdata[1] = colorbase + srcdata[1];
dstdata[2] = colorbase + srcdata[2];
dstdata[3] = colorbase + srcdata[3];
dstdata[4] = colorbase + srcdata[4];
dstdata[5] = colorbase + srcdata[5];
dstdata[6] = colorbase + srcdata[6];
dstdata[7] = colorbase + srcdata[7];
dstdata += 8;
srcdata += 8;
}
while (dstdata < end)
*(dstdata++) = colorbase + *(srcdata++);
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_opaque_raw_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
unsigned int colorbase),
{
DATA_TYPE *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
srcdata -= 8;
dstdata[0] = colorbase + srcdata[8];
dstdata[1] = colorbase + srcdata[7];
dstdata[2] = colorbase + srcdata[6];
dstdata[3] = colorbase + srcdata[5];
dstdata[4] = colorbase + srcdata[4];
dstdata[5] = colorbase + srcdata[3];
dstdata[6] = colorbase + srcdata[2];
dstdata[7] = colorbase + srcdata[1];
dstdata += 8;
}
while (dstdata < end)
*(dstdata++) = colorbase + *(srcdata--);
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transpen,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transpen),
{
DATA_TYPE *end;
int trans4;
UINT32 *sd4;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
trans4 = transpen * 0x01010101;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = *(srcdata++);
if (col != transpen) *dstdata = paldata[col];
dstdata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
UINT32 col4;
if ((col4 = *(sd4++)) != trans4)
{
UINT32 xod4;
xod4 = col4 ^ trans4;
if (xod4 & 0x000000ff) dstdata[BL0] = paldata[(col4) & 0xff];
if (xod4 & 0x0000ff00) dstdata[BL1] = paldata[(col4 >> 8) & 0xff];
if (xod4 & 0x00ff0000) dstdata[BL2] = paldata[(col4 >> 16) & 0xff];
if (xod4 & 0xff000000) dstdata[BL3] = paldata[col4 >> 24];
}
dstdata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = *(srcdata++);
if (col != transpen) *dstdata = paldata[col];
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transpen_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transpen),
{
DATA_TYPE *end;
int trans4;
UINT32 *sd4;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
srcdata -= 3;
trans4 = transpen * 0x01010101;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = srcdata[3];
srcdata--;
if (col != transpen) *dstdata = paldata[col];
dstdata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
UINT32 col4;
if ((col4 = *(sd4--)) != trans4)
{
UINT32 xod4;
xod4 = col4 ^ trans4;
if (xod4 & 0xff000000) dstdata[BL0] = paldata[col4 >> 24];
if (xod4 & 0x00ff0000) dstdata[BL1] = paldata[(col4 >> 16) & 0xff];
if (xod4 & 0x0000ff00) dstdata[BL2] = paldata[(col4 >> 8) & 0xff];
if (xod4 & 0x000000ff) dstdata[BL3] = paldata[col4 & 0xff];
}
dstdata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = srcdata[3];
srcdata--;
if (col != transpen) *dstdata = paldata[col];
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transpen_pri,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transpen,UINT8 *pridata,UINT32 pmask),
{
DATA_TYPE *end;
int trans4;
UINT32 *sd4;
pmask |= (1<<31);
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
trans4 = transpen * 0x01010101;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = *(srcdata++);
if (col != transpen)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[col];
*pridata = 31;
}
dstdata++;
pridata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
UINT32 col4;
if ((col4 = *(sd4++)) != trans4)
{
UINT32 xod4;
xod4 = col4 ^ trans4;
if (xod4 & 0x000000ff)
{
if (((1 << pridata[BL0]) & pmask) == 0)
dstdata[BL0] = paldata[(col4) & 0xff];
pridata[BL0] = 31;
}
if (xod4 & 0x0000ff00)
{
if (((1 << pridata[BL1]) & pmask) == 0)
dstdata[BL1] = paldata[(col4 >> 8) & 0xff];
pridata[BL1] = 31;
}
if (xod4 & 0x00ff0000)
{
if (((1 << pridata[BL2]) & pmask) == 0)
dstdata[BL2] = paldata[(col4 >> 16) & 0xff];
pridata[BL2] = 31;
}
if (xod4 & 0xff000000)
{
if (((1 << pridata[BL3]) & pmask) == 0)
dstdata[BL3] = paldata[col4 >> 24];
pridata[BL3] = 31;
}
}
dstdata += 4;
pridata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = *(srcdata++);
if (col != transpen)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[col];
*pridata = 31;
}
dstdata++;
pridata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
pridata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transpen_pri_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transpen,UINT8 *pridata,UINT32 pmask),
{
DATA_TYPE *end;
int trans4;
UINT32 *sd4;
pmask |= (1<<31);
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
srcdata -= 3;
trans4 = transpen * 0x01010101;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = srcdata[3];
srcdata--;
if (col != transpen)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[col];
*pridata = 31;
}
dstdata++;
pridata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
UINT32 col4;
if ((col4 = *(sd4--)) != trans4)
{
UINT32 xod4;
xod4 = col4 ^ trans4;
if (xod4 & 0xff000000)
{
if (((1 << pridata[BL0]) & pmask) == 0)
dstdata[BL0] = paldata[col4 >> 24];
pridata[BL0] = 31;
}
if (xod4 & 0x00ff0000)
{
if (((1 << pridata[BL1]) & pmask) == 0)
dstdata[BL1] = paldata[(col4 >> 16) & 0xff];
pridata[BL1] = 31;
}
if (xod4 & 0x0000ff00)
{
if (((1 << pridata[BL2]) & pmask) == 0)
dstdata[BL2] = paldata[(col4 >> 8) & 0xff];
pridata[BL2] = 31;
}
if (xod4 & 0x000000ff)
{
if (((1 << pridata[BL3]) & pmask) == 0)
dstdata[BL3] = paldata[col4 & 0xff];
pridata[BL3] = 31;
}
}
dstdata += 4;
pridata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = srcdata[3];
srcdata--;
if (col != transpen)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[col];
*pridata = 31;
}
dstdata++;
pridata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
pridata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transpen_raw,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
unsigned int colorbase,int transpen),
{
DATA_TYPE *end;
int trans4;
UINT32 *sd4;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
trans4 = transpen * 0x01010101;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = *(srcdata++);
if (col != transpen) *dstdata = colorbase + col;
dstdata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
UINT32 col4;
if ((col4 = *(sd4++)) != trans4)
{
UINT32 xod4;
xod4 = col4 ^ trans4;
if (xod4 & 0x000000ff) dstdata[BL0] = colorbase + ((col4) & 0xff);
if (xod4 & 0x0000ff00) dstdata[BL1] = colorbase + ((col4 >> 8) & 0xff);
if (xod4 & 0x00ff0000) dstdata[BL2] = colorbase + ((col4 >> 16) & 0xff);
if (xod4 & 0xff000000) dstdata[BL3] = colorbase + (col4 >> 24);
}
dstdata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = *(srcdata++);
if (col != transpen) *dstdata = colorbase + col;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transpen_raw_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
unsigned int colorbase, int transpen),
{
DATA_TYPE *end;
int trans4;
UINT32 *sd4;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
srcdata -= 3;
trans4 = transpen * 0x01010101;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = srcdata[3];
srcdata--;
if (col != transpen) *dstdata = colorbase + col;
dstdata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
UINT32 col4;
if ((col4 = *(sd4--)) != trans4)
{
UINT32 xod4;
xod4 = col4 ^ trans4;
if (xod4 & 0xff000000) dstdata[BL0] = colorbase + (col4 >> 24);
if (xod4 & 0x00ff0000) dstdata[BL1] = colorbase + ((col4 >> 16) & 0xff);
if (xod4 & 0x0000ff00) dstdata[BL2] = colorbase + ((col4 >> 8) & 0xff);
if (xod4 & 0x000000ff) dstdata[BL3] = colorbase + (col4 & 0xff);
}
dstdata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = srcdata[3];
srcdata--;
if (col != transpen) *dstdata = colorbase + col;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
#define PEN_IS_OPAQUE ((1<<col)&transmask) == 0
DECLARE(blockmove_8toN_transmask,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transmask),
{
DATA_TYPE *end;
UINT32 *sd4;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = *(srcdata++);
if (PEN_IS_OPAQUE) *dstdata = paldata[col];
dstdata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
int col;
UINT32 col4;
col4 = *(sd4++);
col = (col4 >> 0) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL0] = paldata[col];
col = (col4 >> 8) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL1] = paldata[col];
col = (col4 >> 16) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL2] = paldata[col];
col = (col4 >> 24) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL3] = paldata[col];
dstdata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = *(srcdata++);
if (PEN_IS_OPAQUE) *dstdata = paldata[col];
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transmask_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transmask),
{
DATA_TYPE *end;
UINT32 *sd4;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
srcdata -= 3;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = srcdata[3];
srcdata--;
if (PEN_IS_OPAQUE) *dstdata = paldata[col];
dstdata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
int col;
UINT32 col4;
col4 = *(sd4--);
col = (col4 >> 24) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL0] = paldata[col];
col = (col4 >> 16) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL1] = paldata[col];
col = (col4 >> 8) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL2] = paldata[col];
col = (col4 >> 0) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL3] = paldata[col];
dstdata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = srcdata[3];
srcdata--;
if (PEN_IS_OPAQUE) *dstdata = paldata[col];
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transmask_pri,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transmask,UINT8 *pridata,UINT32 pmask),
{
DATA_TYPE *end;
UINT32 *sd4;
pmask |= (1<<31);
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = *(srcdata++);
if (PEN_IS_OPAQUE)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[col];
*pridata = 31;
}
dstdata++;
pridata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
int col;
UINT32 col4;
col4 = *(sd4++);
col = (col4 >> 0) & 0xff;
if (PEN_IS_OPAQUE)
{
if (((1 << pridata[BL0]) & pmask) == 0)
dstdata[BL0] = paldata[col];
pridata[BL0] = 31;
}
col = (col4 >> 8) & 0xff;
if (PEN_IS_OPAQUE)
{
if (((1 << pridata[BL1]) & pmask) == 0)
dstdata[BL1] = paldata[col];
pridata[BL1] = 31;
}
col = (col4 >> 16) & 0xff;
if (PEN_IS_OPAQUE)
{
if (((1 << pridata[BL2]) & pmask) == 0)
dstdata[BL2] = paldata[col];
pridata[BL2] = 31;
}
col = (col4 >> 24) & 0xff;
if (PEN_IS_OPAQUE)
{
if (((1 << pridata[BL3]) & pmask) == 0)
dstdata[BL3] = paldata[col];
pridata[BL3] = 31;
}
dstdata += 4;
pridata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = *(srcdata++);
if (PEN_IS_OPAQUE)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[col];
*pridata = 31;
}
dstdata++;
pridata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
pridata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transmask_pri_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transmask,UINT8 *pridata,UINT32 pmask),
{
DATA_TYPE *end;
UINT32 *sd4;
pmask |= (1<<31);
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
srcdata -= 3;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = srcdata[3];
srcdata--;
if (PEN_IS_OPAQUE)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[col];
*pridata = 31;
}
dstdata++;
pridata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
int col;
UINT32 col4;
col4 = *(sd4--);
col = (col4 >> 24) & 0xff;
if (PEN_IS_OPAQUE)
{
if (((1 << pridata[BL0]) & pmask) == 0)
dstdata[BL0] = paldata[col];
pridata[BL0] = 31;
}
col = (col4 >> 16) & 0xff;
if (PEN_IS_OPAQUE)
{
if (((1 << pridata[BL1]) & pmask) == 0)
dstdata[BL1] = paldata[col];
pridata[BL1] = 31;
}
col = (col4 >> 8) & 0xff;
if (PEN_IS_OPAQUE)
{
if (((1 << pridata[BL2]) & pmask) == 0)
dstdata[BL2] = paldata[col];
pridata[BL2] = 31;
}
col = (col4 >> 0) & 0xff;
if (PEN_IS_OPAQUE)
{
if (((1 << pridata[BL3]) & pmask) == 0)
dstdata[BL3] = paldata[col];
pridata[BL3] = 31;
}
dstdata += 4;
pridata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = srcdata[3];
srcdata--;
if (PEN_IS_OPAQUE)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[col];
*pridata = 31;
}
dstdata++;
pridata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
pridata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transmask_raw,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
unsigned int colorbase,int transmask),
{
DATA_TYPE *end;
UINT32 *sd4;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = *(srcdata++);
if (PEN_IS_OPAQUE) *dstdata = colorbase + col;
dstdata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
int col;
UINT32 col4;
col4 = *(sd4++);
col = (col4 >> 0) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL0] = colorbase + col;
col = (col4 >> 8) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL1] = colorbase + col;
col = (col4 >> 16) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL2] = colorbase + col;
col = (col4 >> 24) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL3] = colorbase + col;
dstdata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = *(srcdata++);
if (PEN_IS_OPAQUE) *dstdata = colorbase + col;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transmask_raw_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
unsigned int colorbase,int transmask),
{
DATA_TYPE *end;
UINT32 *sd4;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
srcdata -= 3;
while (srcheight)
{
end = dstdata + srcwidth;
while (((long)srcdata & 3) && dstdata < end) /* longword align */
{
int col;
col = srcdata[3];
srcdata--;
if (PEN_IS_OPAQUE) *dstdata = colorbase + col;
dstdata++;
}
sd4 = (UINT32 *)srcdata;
while (dstdata <= end - 4)
{
int col;
UINT32 col4;
col4 = *(sd4--);
col = (col4 >> 24) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL0] = colorbase + col;
col = (col4 >> 16) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL1] = colorbase + col;
col = (col4 >> 8) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL2] = colorbase + col;
col = (col4 >> 0) & 0xff;
if (PEN_IS_OPAQUE) dstdata[BL3] = colorbase + col;
dstdata += 4;
}
srcdata = (UINT8 *)sd4;
while (dstdata < end)
{
int col;
col = srcdata[3];
srcdata--;
if (PEN_IS_OPAQUE) *dstdata = colorbase + col;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transcolor,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transcolor),
{
DATA_TYPE *end;
const UINT16 *lookupdata = Machine->game_colortable + (paldata - Machine->remapped_colortable);
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
if (lookupdata[*srcdata] != transcolor) *dstdata = paldata[*srcdata];
srcdata++;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transcolor_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transcolor),
{
DATA_TYPE *end;
const UINT16 *lookupdata = Machine->game_colortable + (paldata - Machine->remapped_colortable);
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
if (lookupdata[*srcdata] != transcolor) *dstdata = paldata[*srcdata];
srcdata--;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transcolor_pri,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transcolor,UINT8 *pridata,UINT32 pmask),
{
DATA_TYPE *end;
const UINT16 *lookupdata = Machine->game_colortable + (paldata - Machine->remapped_colortable);
pmask |= (1<<31);
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
if (lookupdata[*srcdata] != transcolor)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[*srcdata];
*pridata = 31;
}
srcdata++;
dstdata++;
pridata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
pridata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transcolor_pri_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transcolor,UINT8 *pridata,UINT32 pmask),
{
DATA_TYPE *end;
const UINT16 *lookupdata = Machine->game_colortable + (paldata - Machine->remapped_colortable);
pmask |= (1<<31);
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
if (lookupdata[*srcdata] != transcolor)
{
if (((1 << *pridata) & pmask) == 0)
*dstdata = paldata[*srcdata];
*pridata = 31;
}
srcdata--;
dstdata++;
pridata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
pridata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transthrough,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transcolor),
{
DATA_TYPE *end;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
if (*dstdata == transcolor) *dstdata = paldata[*srcdata];
srcdata++;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transthrough_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transcolor),
{
DATA_TYPE *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
if (*dstdata == transcolor) *dstdata = paldata[*srcdata];
srcdata--;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transthrough_raw,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
unsigned int colorbase,int transcolor),
{
DATA_TYPE *end;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
if (*dstdata == transcolor) *dstdata = colorbase + *srcdata;
srcdata++;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_transthrough_raw_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
unsigned int colorbase,int transcolor),
{
DATA_TYPE *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
if (*dstdata == transcolor) *dstdata = colorbase + *srcdata;
srcdata--;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_pen_table,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transcolor),
{
DATA_TYPE *end;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
int col;
col = *(srcdata++);
if (col != transcolor)
{
switch(gfx_drawmode_table[col])
{
case DRAWMODE_SOURCE:
*dstdata = paldata[col];
break;
case DRAWMODE_SHADOW:
*dstdata = palette_shadow_table[*dstdata];
break;
}
}
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_pen_table_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int transcolor),
{
DATA_TYPE *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
int col;
col = *(srcdata--);
if (col != transcolor)
{
switch(gfx_drawmode_table[col])
{
case DRAWMODE_SOURCE:
*dstdata = paldata[col];
break;
case DRAWMODE_SHADOW:
*dstdata = palette_shadow_table[*dstdata];
break;
}
}
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_pen_table_raw,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
unsigned int colorbase,int transcolor),
{
DATA_TYPE *end;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
int col;
col = *(srcdata++);
if (col != transcolor)
{
switch(gfx_drawmode_table[col])
{
case DRAWMODE_SOURCE:
*dstdata = colorbase + col;
break;
case DRAWMODE_SHADOW:
*dstdata = palette_shadow_table[*dstdata];
break;
}
}
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_8toN_pen_table_raw_flipx,(
const UINT8 *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
unsigned int colorbase,int transcolor),
{
DATA_TYPE *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
int col;
col = *(srcdata--);
if (col != transcolor)
{
switch(gfx_drawmode_table[col])
{
case DRAWMODE_SOURCE:
*dstdata = colorbase + col;
break;
case DRAWMODE_SHADOW:
*dstdata = palette_shadow_table[*dstdata];
break;
}
}
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_NtoN_opaque_noremap,(
const DATA_TYPE *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo),
{
while (srcheight)
{
memcpy(dstdata,srcdata,srcwidth * sizeof(DATA_TYPE));
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_NtoN_opaque_noremap_flipx,(
const DATA_TYPE *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo),
{
DATA_TYPE *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
srcdata -= 8;
dstdata[0] = srcdata[8];
dstdata[1] = srcdata[7];
dstdata[2] = srcdata[6];
dstdata[3] = srcdata[5];
dstdata[4] = srcdata[4];
dstdata[5] = srcdata[3];
dstdata[6] = srcdata[2];
dstdata[7] = srcdata[1];
dstdata += 8;
}
while (dstdata < end)
*(dstdata++) = *(srcdata--);
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_NtoN_opaque_remap,(
const DATA_TYPE *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata),
{
DATA_TYPE *end;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
dstdata[0] = paldata[srcdata[0]];
dstdata[1] = paldata[srcdata[1]];
dstdata[2] = paldata[srcdata[2]];
dstdata[3] = paldata[srcdata[3]];
dstdata[4] = paldata[srcdata[4]];
dstdata[5] = paldata[srcdata[5]];
dstdata[6] = paldata[srcdata[6]];
dstdata[7] = paldata[srcdata[7]];
dstdata += 8;
srcdata += 8;
}
while (dstdata < end)
*(dstdata++) = paldata[*(srcdata++)];
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_NtoN_opaque_remap_flipx,(
const DATA_TYPE *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata),
{
DATA_TYPE *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
srcdata -= 8;
dstdata[0] = paldata[srcdata[8]];
dstdata[1] = paldata[srcdata[7]];
dstdata[2] = paldata[srcdata[6]];
dstdata[3] = paldata[srcdata[5]];
dstdata[4] = paldata[srcdata[4]];
dstdata[5] = paldata[srcdata[3]];
dstdata[6] = paldata[srcdata[2]];
dstdata[7] = paldata[srcdata[1]];
dstdata += 8;
}
while (dstdata < end)
*(dstdata++) = paldata[*(srcdata--)];
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_NtoN_transthrough_noremap,(
const DATA_TYPE *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
int transcolor),
{
DATA_TYPE *end;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
if (*dstdata == transcolor) *dstdata = *srcdata;
srcdata++;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_NtoN_transthrough_noremap_flipx,(
const DATA_TYPE *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
int transcolor),
{
DATA_TYPE *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata < end)
{
if (*dstdata == transcolor) *dstdata = *srcdata;
srcdata--;
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_NtoN_blend_noremap,(
const DATA_TYPE *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
int srcshift),
{
DATA_TYPE *end;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
dstdata[0] |= srcdata[0] << srcshift;
dstdata[1] |= srcdata[1] << srcshift;
dstdata[2] |= srcdata[2] << srcshift;
dstdata[3] |= srcdata[3] << srcshift;
dstdata[4] |= srcdata[4] << srcshift;
dstdata[5] |= srcdata[5] << srcshift;
dstdata[6] |= srcdata[6] << srcshift;
dstdata[7] |= srcdata[7] << srcshift;
dstdata += 8;
srcdata += 8;
}
while (dstdata < end)
*(dstdata++) |= *(srcdata++) << srcshift;
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_NtoN_blend_noremap_flipx,(
const DATA_TYPE *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
int srcshift),
{
DATA_TYPE *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
srcdata -= 8;
dstdata[0] |= srcdata[8] << srcshift;
dstdata[1] |= srcdata[7] << srcshift;
dstdata[2] |= srcdata[6] << srcshift;
dstdata[3] |= srcdata[5] << srcshift;
dstdata[4] |= srcdata[4] << srcshift;
dstdata[5] |= srcdata[3] << srcshift;
dstdata[6] |= srcdata[2] << srcshift;
dstdata[7] |= srcdata[1] << srcshift;
dstdata += 8;
}
while (dstdata < end)
*(dstdata++) |= *(srcdata--) << srcshift;
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_NtoN_blend_remap,(
const DATA_TYPE *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int srcshift),
{
DATA_TYPE *end;
srcmodulo -= srcwidth;
dstmodulo -= srcwidth;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
dstdata[0] = paldata[dstdata[0] | (srcdata[0] << srcshift)];
dstdata[1] = paldata[dstdata[1] | (srcdata[1] << srcshift)];
dstdata[2] = paldata[dstdata[2] | (srcdata[2] << srcshift)];
dstdata[3] = paldata[dstdata[3] | (srcdata[3] << srcshift)];
dstdata[4] = paldata[dstdata[4] | (srcdata[4] << srcshift)];
dstdata[5] = paldata[dstdata[5] | (srcdata[5] << srcshift)];
dstdata[6] = paldata[dstdata[6] | (srcdata[6] << srcshift)];
dstdata[7] = paldata[dstdata[7] | (srcdata[7] << srcshift)];
dstdata += 8;
srcdata += 8;
}
while (dstdata < end)
{
*dstdata = paldata[*dstdata | (*(srcdata++) << srcshift)];
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(blockmove_NtoN_blend_remap_flipx,(
const DATA_TYPE *srcdata,int srcwidth,int srcheight,int srcmodulo,
DATA_TYPE *dstdata,int dstmodulo,
const UINT16 *paldata,int srcshift),
{
DATA_TYPE *end;
srcmodulo += srcwidth;
dstmodulo -= srcwidth;
//srcdata += srcwidth-1;
while (srcheight)
{
end = dstdata + srcwidth;
while (dstdata <= end - 8)
{
srcdata -= 8;
dstdata[0] = paldata[dstdata[0] | (srcdata[8] << srcshift)];
dstdata[1] = paldata[dstdata[1] | (srcdata[7] << srcshift)];
dstdata[2] = paldata[dstdata[2] | (srcdata[6] << srcshift)];
dstdata[3] = paldata[dstdata[3] | (srcdata[5] << srcshift)];
dstdata[4] = paldata[dstdata[4] | (srcdata[4] << srcshift)];
dstdata[5] = paldata[dstdata[5] | (srcdata[3] << srcshift)];
dstdata[6] = paldata[dstdata[6] | (srcdata[2] << srcshift)];
dstdata[7] = paldata[dstdata[7] | (srcdata[1] << srcshift)];
dstdata += 8;
}
while (dstdata < end)
{
*dstdata = paldata[*dstdata | (*(srcdata--) << srcshift)];
dstdata++;
}
srcdata += srcmodulo;
dstdata += dstmodulo;
srcheight--;
}
})
DECLARE(drawgfx_core,(
struct osd_bitmap *dest,const struct GfxElement *gfx,
unsigned int code,unsigned int color,int flipx,int flipy,int sx,int sy,
const struct rectangle *clip,int transparency,int transparent_color,
struct osd_bitmap *pri_buffer,UINT32 pri_mask),
{
int ox;
int oy;
int ex;
int ey;
/* check bounds */
ox = sx;
oy = sy;
ex = sx + gfx->width-1;
if (sx < 0) sx = 0;
if (clip && sx < clip->min_x) sx = clip->min_x;
if (ex >= dest->width) ex = dest->width-1;
if (clip && ex > clip->max_x) ex = clip->max_x;
if (sx > ex) return;
ey = sy + gfx->height-1;
if (sy < 0) sy = 0;
if (clip && sy < clip->min_y) sy = clip->min_y;
if (ey >= dest->height) ey = dest->height-1;
if (clip && ey > clip->max_y) ey = clip->max_y;
if (sy > ey) return;
osd_mark_dirty (sx,sy,ex,ey,0); /* ASG 971011 */
{
UINT8 *sd = gfx->gfxdata + code * gfx->char_modulo; /* source data */
int sw = ex-sx+1; /* source width */
int sh = ey-sy+1; /* source height */
int sm = gfx->line_modulo; /* source modulo */
DATA_TYPE *dd = ((DATA_TYPE *)dest->line[sy]) + sx; /* dest data */
int dm = ((DATA_TYPE *)dest->line[1])-((DATA_TYPE *)dest->line[0]); /* dest modulo */
const UINT16 *paldata = &gfx->colortable[gfx->color_granularity * color];
UINT8 *pribuf = (pri_buffer) ? pri_buffer->line[sy] + sx : NULL;
if (flipx)
{
//if ((sx-ox) == 0) sd += gfx->width - sw;
sd += gfx->width -1 -(sx-ox);
}
else
sd += (sx-ox);
if (flipy)
{
//if ((sy-oy) == 0) sd += sm * (gfx->height - sh);
//dd += dm * (sh - 1);
//dm = -dm;
sd += sm * (gfx->height -1 -(sy-oy));
sm = -sm;
}
else
sd += sm * (sy-oy);
switch (transparency)
{
case TRANSPARENCY_NONE:
if (pribuf)
BLOCKMOVE(8toN_opaque_pri,flipx,(sd,sw,sh,sm,dd,dm,paldata,pribuf,pri_mask));
else
BLOCKMOVE(8toN_opaque,flipx,(sd,sw,sh,sm,dd,dm,paldata));
break;
case TRANSPARENCY_PEN:
if (pribuf)
BLOCKMOVE(8toN_transpen_pri,flipx,(sd,sw,sh,sm,dd,dm,paldata,transparent_color,pribuf,pri_mask));
else
BLOCKMOVE(8toN_transpen,flipx,(sd,sw,sh,sm,dd,dm,paldata,transparent_color));
break;
case TRANSPARENCY_PENS:
if (pribuf)
BLOCKMOVE(8toN_transmask_pri,flipx,(sd,sw,sh,sm,dd,dm,paldata,transparent_color,pribuf,pri_mask));
else
BLOCKMOVE(8toN_transmask,flipx,(sd,sw,sh,sm,dd,dm,paldata,transparent_color));
break;
case TRANSPARENCY_COLOR:
if (pribuf)
BLOCKMOVE(8toN_transcolor_pri,flipx,(sd,sw,sh,sm,dd,dm,paldata,transparent_color,pribuf,pri_mask));
else
BLOCKMOVE(8toN_transcolor,flipx,(sd,sw,sh,sm,dd,dm,paldata,transparent_color));
break;
case TRANSPARENCY_THROUGH:
if (pribuf)
usrintf_showmessage("pdrawgfx TRANS_THROUGH not supported");
// BLOCKMOVE(8toN_transthrough,flipx,(sd,sw,sh,sm,dd,dm,paldata,transparent_color));
else
BLOCKMOVE(8toN_transthrough,flipx,(sd,sw,sh,sm,dd,dm,paldata,transparent_color));
break;
case TRANSPARENCY_PEN_TABLE:
if (pribuf)
usrintf_showmessage("pdrawgfx TRANS_PEN_TABLE not supported");
// BLOCKMOVE(8toN_pen_table_pri,flipx,(sd,sw,sh,sm,dd,dm,paldata,transparent_color));
else
BLOCKMOVE(8toN_pen_table,flipx,(sd,sw,sh,sm,dd,dm,paldata,transparent_color));
break;
case TRANSPARENCY_PEN_TABLE_RAW:
if (pribuf)
usrintf_showmessage("pdrawgfx TRANS_PEN_TABLE_RAW not supported");
// BLOCKMOVE(8toN_pen_table_pri_raw,flipx,(sd,sw,sh,sm,dd,dm,color,transparent_color));
else
BLOCKMOVE(8toN_pen_table_raw,flipx,(sd,sw,sh,sm,dd,dm,color,transparent_color));
break;
case TRANSPARENCY_NONE_RAW:
if (pribuf)
usrintf_showmessage("pdrawgfx TRANS_NONE_RAW not supported");
// BLOCKMOVE(8toN_opaque_pri_raw,flipx,(sd,sw,sh,sm,dd,dm,paldata,pribuf,pri_mask));
else
BLOCKMOVE(8toN_opaque_raw,flipx,(sd,sw,sh,sm,dd,dm,color));
break;
case TRANSPARENCY_PEN_RAW:
if (pribuf)
usrintf_showmessage("pdrawgfx TRANS_PEN_RAW not supported");
// BLOCKMOVE(8toN_transpen_pri_raw,flipx,(sd,sw,sh,sm,dd,dm,paldata,pribuf,pri_mask));
else
BLOCKMOVE(8toN_transpen_raw,flipx,(sd,sw,sh,sm,dd,dm,color,transparent_color));
break;
case TRANSPARENCY_PENS_RAW:
if (pribuf)
usrintf_showmessage("pdrawgfx TRANS_PENS_RAW not supported");
// BLOCKMOVE(8toN_transmask_pri_raw,flipx,(sd,sw,sh,sm,dd,dm,paldata,pribuf,pri_mask));
else
BLOCKMOVE(8toN_transmask_raw,flipx,(sd,sw,sh,sm,dd,dm,color,transparent_color));
break;
case TRANSPARENCY_THROUGH_RAW:
if (pribuf)
usrintf_showmessage("pdrawgfx TRANS_PEN_RAW not supported");
// BLOCKMOVE(8toN_transpen_pri_raw,flipx,(sd,sw,sh,sm,dd,dm,paldata,pribuf,pri_mask));
else
BLOCKMOVE(8toN_transthrough_raw,flipx,(sd,sw,sh,sm,dd,dm,color,transparent_color));
break;
default:
if (pribuf)
usrintf_showmessage("pdrawgfx pen mode not supported");
else
usrintf_showmessage("drawgfx pen mode not supported");
break;
}
}
})
DECLARE(copybitmap_core,(
struct osd_bitmap *dest,struct osd_bitmap *src,
int flipx,int flipy,int sx,int sy,
const struct rectangle *clip,int transparency,int transparent_color),
{
int ox;
int oy;
int ex;
int ey;
/* check bounds */
ox = sx;
oy = sy;
ex = sx + src->width-1;
if (sx < 0) sx = 0;
if (clip && sx < clip->min_x) sx = clip->min_x;
if (ex >= dest->width) ex = dest->width-1;
if (clip && ex > clip->max_x) ex = clip->max_x;
if (sx > ex) return;
ey = sy + src->height-1;
if (sy < 0) sy = 0;
if (clip && sy < clip->min_y) sy = clip->min_y;
if (ey >= dest->height) ey = dest->height-1;
if (clip && ey > clip->max_y) ey = clip->max_y;
if (sy > ey) return;
{
DATA_TYPE *sd = ((DATA_TYPE *)src->line[0]); /* source data */
int sw = ex-sx+1; /* source width */
int sh = ey-sy+1; /* source height */
int sm = ((DATA_TYPE *)src->line[1])-((DATA_TYPE *)src->line[0]); /* source modulo */
DATA_TYPE *dd = ((DATA_TYPE *)dest->line[sy]) + sx; /* dest data */
int dm = ((DATA_TYPE *)dest->line[1])-((DATA_TYPE *)dest->line[0]); /* dest modulo */
if (flipx)
{
//if ((sx-ox) == 0) sd += gfx->width - sw;
sd += src->width -1 -(sx-ox);
}
else
sd += (sx-ox);
if (flipy)
{
//if ((sy-oy) == 0) sd += sm * (gfx->height - sh);
//dd += dm * (sh - 1);
//dm = -dm;
sd += sm * (src->height -1 -(sy-oy));
sm = -sm;
}
else
sd += sm * (sy-oy);
switch (transparency)
{
case TRANSPARENCY_NONE:
BLOCKMOVE(NtoN_opaque_remap,flipx,(sd,sw,sh,sm,dd,dm,Machine->pens));
break;
case TRANSPARENCY_NONE_RAW:
BLOCKMOVE(NtoN_opaque_noremap,flipx,(sd,sw,sh,sm,dd,dm));
break;
case TRANSPARENCY_PEN_RAW:
BLOCKMOVE(NtoN_transpen_noremap,flipx,(sd,sw,sh,sm,dd,dm,transparent_color));
break;
case TRANSPARENCY_THROUGH_RAW:
BLOCKMOVE(NtoN_transthrough_noremap,flipx,(sd,sw,sh,sm,dd,dm,transparent_color));
break;
case TRANSPARENCY_BLEND:
BLOCKMOVE(NtoN_blend_remap,flipx,(sd,sw,sh,sm,dd,dm,Machine->pens,transparent_color));
break;
case TRANSPARENCY_BLEND_RAW:
BLOCKMOVE(NtoN_blend_noremap,flipx,(sd,sw,sh,sm,dd,dm,transparent_color));
break;
default:
usrintf_showmessage("copybitmap pen mode not supported");
break;
}
}
})
DECLARE(copyrozbitmap_core,(struct osd_bitmap *bitmap,struct osd_bitmap *srcbitmap,
UINT32 startx,UINT32 starty,int incxx,int incxy,int incyx,int incyy,int wraparound,
const struct rectangle *clip,int transparency,int transparent_color,UINT32 priority),
{
UINT32 cx;
UINT32 cy;
int x;
int sx;
int sy;
int ex;
int ey;
const int xmask = srcbitmap->width-1;
const int ymask = srcbitmap->height-1;
const int widthshifted = srcbitmap->width << 16;
const int heightshifted = srcbitmap->height << 16;
DATA_TYPE *dest;
if (clip)
{
startx += clip->min_x * incxx + clip->min_y * incyx;
starty += clip->min_x * incxy + clip->min_y * incyy;
sx = clip->min_x;
sy = clip->min_y;
ex = clip->max_x;
ey = clip->max_y;
}
else
{
sx = 0;
sy = 0;
ex = bitmap->width-1;
ey = bitmap->height-1;
}
if (Machine->orientation & ORIENTATION_SWAP_XY)
{
int t;
t = startx; startx = starty; starty = t;
t = sx; sx = sy; sy = t;
t = ex; ex = ey; ey = t;
t = incxx; incxx = incyy; incyy = t;
t = incxy; incxy = incyx; incyx = t;
}
if (Machine->orientation & ORIENTATION_FLIP_X)
{
int w = ex - sx;
incxy = -incxy;
incyx = -incyx;
startx = widthshifted - startx - 1;
startx -= incxx * w;
starty -= incxy * w;
w = sx;
sx = bitmap->width-1 - ex;
ex = bitmap->width-1 - w;
}
if (Machine->orientation & ORIENTATION_FLIP_Y)
{
int h = ey - sy;
incxy = -incxy;
incyx = -incyx;
starty = heightshifted - starty - 1;
startx -= incyx * h;
starty -= incyy * h;
h = sy;
sy = bitmap->height-1 - ey;
ey = bitmap->height-1 - h;
}
if (incxy == 0 && incyx == 0 && !wraparound)
{
/* optimized loop for the not rotated case */
if (incxx == 0x10000)
{
/* optimized loop for the not zoomed case */
/* startx is unsigned */
startx = ((INT32)startx) >> 16;
if (startx >= srcbitmap->width)
{
sx += -startx;
startx = 0;
}
if (sx <= ex)
{
while (sy <= ey)
{
if (starty < heightshifted)
{
x = sx;
cx = startx;
cy = starty >> 16;
dest = ((DATA_TYPE *)bitmap->line[sy]) + sx;
if (priority)
{
UINT8 *pri = &priority_bitmap->line[sy][sx];
DATA_TYPE *src = (DATA_TYPE *)srcbitmap->line[cy];
while (x <= ex && cx < srcbitmap->width)
{
int c = src[cx];
if (c != transparent_color)
{
*dest = c;
*pri |= priority;
}
cx++;
x++;
dest++;
pri++;
}
}
else
{
DATA_TYPE *src = (DATA_TYPE *)srcbitmap->line[cy];
while (x <= ex && cx < srcbitmap->width)
{
int c = src[cx];
if (c != transparent_color)
*dest = c;
cx++;
x++;
dest++;
}
}
}
starty += incyy;
sy++;
}
}
}
else
{
while (startx >= widthshifted && sx <= ex)
{
startx += incxx;
sx++;
}
if (sx <= ex)
{
while (sy <= ey)
{
if (starty < heightshifted)
{
x = sx;
cx = startx;
cy = starty >> 16;
dest = ((DATA_TYPE *)bitmap->line[sy]) + sx;
if (priority)
{
UINT8 *pri = &priority_bitmap->line[sy][sx];
DATA_TYPE *src = (DATA_TYPE *)srcbitmap->line[cy];
while (x <= ex && cx < widthshifted)
{
int c = src[cx >> 16];
if (c != transparent_color)
{
*dest = c;
*pri |= priority;
}
cx += incxx;
x++;
dest++;
pri++;
}
}
else
{
DATA_TYPE *src = (DATA_TYPE *)srcbitmap->line[cy];
while (x <= ex && cx < widthshifted)
{
int c = src[cx >> 16];
if (c != transparent_color)
*dest = c;
cx += incxx;
x++;
dest++;
}
}
}
starty += incyy;
sy++;
}
}
}
}
else
{
if (wraparound)
{
/* plot with wraparound */
while (sy <= ey)
{
x = sx;
cx = startx;
cy = starty;
dest = ((DATA_TYPE *)bitmap->line[sy]) + sx;
if (priority)
{
UINT8 *pri = &priority_bitmap->line[sy][sx];
while (x <= ex)
{
int c = ((DATA_TYPE *)srcbitmap->line[(cy >> 16) & xmask])[(cx >> 16) & ymask];
if (c != transparent_color)
{
*dest = c;
*pri |= priority;
}
cx += incxx;
cy += incxy;
x++;
dest++;
pri++;
}
}
else
{
while (x <= ex)
{
int c = ((DATA_TYPE *)srcbitmap->line[(cy >> 16) & xmask])[(cx >> 16) & ymask];
if (c != transparent_color)
*dest = c;
cx += incxx;
cy += incxy;
x++;
dest++;
}
}
startx += incyx;
starty += incyy;
sy++;
}
}
else
{
while (sy <= ey)
{
x = sx;
cx = startx;
cy = starty;
dest = ((DATA_TYPE *)bitmap->line[sy]) + sx;
if (priority)
{
UINT8 *pri = &priority_bitmap->line[sy][sx];
while (x <= ex)
{
if (cx < widthshifted && cy < heightshifted)
{
int c = ((DATA_TYPE *)srcbitmap->line[cy >> 16])[cx >> 16];
if (c != transparent_color)
{
*dest = c;
*pri |= priority;
}
}
cx += incxx;
cy += incxy;
x++;
dest++;
pri++;
}
}
else
{
while (x <= ex)
{
if (cx < widthshifted && cy < heightshifted)
{
int c = ((DATA_TYPE *)srcbitmap->line[cy >> 16])[cx >> 16];
if (c != transparent_color)
*dest = c;
}
cx += incxx;
cy += incxy;
x++;
dest++;
}
}
startx += incyx;
starty += incyy;
sy++;
}
}
}
})
#endif /* DECLARE */
| [
"boris@icculus.org"
] | boris@icculus.org |
c6efaa28cbcc579e8dd21f71fda9d80e771b6a3b | bb7fea5089fadf7c2e992df907f296bd8ceab47f | /V8/src/ic/ic.cc | 897c317844870d94ff806e5060b7fc6e8e1028b7 | [
"BSD-3-Clause",
"SunPro",
"bzip2-1.0.6"
] | permissive | sdoa5335717/V8 | 201227820a2ad32ce12040e8f810156c1ea4a175 | 28ebc7bca486ec432ad30b3d66088acb6cf0a583 | refs/heads/master | 2020-03-29T11:06:27.134908 | 2018-09-22T01:50:21 | 2018-09-22T01:50:21 | 149,836,229 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 124,117 | cc | // Copyright 2012 the V8 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.
#include "src/ic/ic.h"
#include <iostream>
#include "src/accessors.h"
#include "src/api-arguments-inl.h"
#include "src/api.h"
#include "src/arguments.h"
#include "src/base/bits.h"
#include "src/codegen.h"
#include "src/conversions.h"
#include "src/execution.h"
#include "src/field-type.h"
#include "src/frames-inl.h"
#include "src/ic/call-optimization.h"
#include "src/ic/handler-compiler.h"
#include "src/ic/handler-configuration-inl.h"
#include "src/ic/ic-compiler.h"
#include "src/ic/ic-inl.h"
#include "src/ic/stub-cache.h"
#include "src/isolate-inl.h"
#include "src/macro-assembler.h"
#include "src/prototype.h"
#include "src/runtime-profiler.h"
#include "src/runtime/runtime-utils.h"
#include "src/runtime/runtime.h"
#include "src/tracing/trace-event.h"
namespace v8 {
namespace internal {
char IC::TransitionMarkFromState(IC::State state) {
switch (state) {
case UNINITIALIZED:
return '0';
case PREMONOMORPHIC:
return '.';
case MONOMORPHIC:
return '1';
case RECOMPUTE_HANDLER:
return '^';
case POLYMORPHIC:
return 'P';
case MEGAMORPHIC:
return 'N';
case GENERIC:
return 'G';
}
UNREACHABLE();
return 0;
}
const char* GetTransitionMarkModifier(KeyedAccessStoreMode mode) {
if (mode == STORE_NO_TRANSITION_HANDLE_COW) return ".COW";
if (mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
return ".IGNORE_OOB";
}
if (IsGrowStoreMode(mode)) return ".GROW";
return "";
}
#ifdef DEBUG
#define TRACE_GENERIC_IC(isolate, type, reason) \
do { \
if (FLAG_trace_ic) { \
PrintF("[%s patching generic stub in ", type); \
JavaScriptFrame::PrintTop(isolate, stdout, false, true); \
PrintF(" (%s)]\n", reason); \
} \
} while (false)
#else
#define TRACE_GENERIC_IC(isolate, type, reason) \
do { \
if (FLAG_trace_ic) { \
PrintF("[%s patching generic stub in ", type); \
PrintF("(see below) (%s)]\n", reason); \
} \
} while (false)
#endif // DEBUG
void IC::TraceIC(const char* type, Handle<Object> name) {
if (FLAG_trace_ic) {
if (AddressIsDeoptimizedCode()) return;
DCHECK(UseVector());
State new_state = nexus()->StateFromFeedback();
TraceIC(type, name, state(), new_state);
}
}
void IC::TraceIC(const char* type, Handle<Object> name, State old_state,
State new_state) {
if (!FLAG_trace_ic) return;
PrintF("[%s%s in ", is_keyed() ? "Keyed" : "", type);
// TODO(jkummerow): Add support for "apply". The logic is roughly:
// marker = [fp_ + kMarkerOffset];
// if marker is smi and marker.value == INTERNAL and
// the frame's code == builtin(Builtins::kFunctionApply):
// then print "apply from" and advance one frame
Object* maybe_function =
Memory::Object_at(fp_ + JavaScriptFrameConstants::kFunctionOffset);
if (maybe_function->IsJSFunction()) {
JSFunction* function = JSFunction::cast(maybe_function);
int code_offset = 0;
if (function->IsInterpreted()) {
code_offset = InterpretedFrame::GetBytecodeOffset(fp());
} else {
code_offset =
static_cast<int>(pc() - function->code()->instruction_start());
}
JavaScriptFrame::PrintFunctionAndOffset(function, function->abstract_code(),
code_offset, stdout, true);
}
const char* modifier = "";
if (kind() == Code::KEYED_STORE_IC) {
KeyedAccessStoreMode mode =
casted_nexus<KeyedStoreICNexus>()->GetKeyedAccessStoreMode();
modifier = GetTransitionMarkModifier(mode);
}
Map* map = nullptr;
if (!receiver_map().is_null()) {
map = *receiver_map();
}
PrintF(" (%c->%c%s) map=(%p", TransitionMarkFromState(old_state),
TransitionMarkFromState(new_state), modifier,
reinterpret_cast<void*>(map));
if (map != nullptr) {
PrintF(" dict=%u own=%u type=", map->is_dictionary_map(),
map->NumberOfOwnDescriptors());
std::cout << map->instance_type();
}
PrintF(") ");
name->ShortPrint(stdout);
PrintF("]\n");
}
#define TRACE_IC(type, name) TraceIC(type, name)
IC::IC(FrameDepth depth, Isolate* isolate, FeedbackNexus* nexus)
: isolate_(isolate),
vector_set_(false),
target_maps_set_(false),
nexus_(nexus) {
// To improve the performance of the (much used) IC code, we unfold a few
// levels of the stack frame iteration code. This yields a ~35% speedup when
// running DeltaBlue and a ~25% speedup of gbemu with the '--nouse-ic' flag.
const Address entry = Isolate::c_entry_fp(isolate->thread_local_top());
Address* constant_pool = NULL;
if (FLAG_enable_embedded_constant_pool) {
constant_pool = reinterpret_cast<Address*>(
entry + ExitFrameConstants::kConstantPoolOffset);
}
Address* pc_address =
reinterpret_cast<Address*>(entry + ExitFrameConstants::kCallerPCOffset);
Address fp = Memory::Address_at(entry + ExitFrameConstants::kCallerFPOffset);
// If there's another JavaScript frame on the stack or a
// StubFailureTrampoline, we need to look one frame further down the stack to
// find the frame pointer and the return address stack slot.
if (depth == EXTRA_CALL_FRAME) {
if (FLAG_enable_embedded_constant_pool) {
constant_pool = reinterpret_cast<Address*>(
fp + StandardFrameConstants::kConstantPoolOffset);
}
const int kCallerPCOffset = StandardFrameConstants::kCallerPCOffset;
pc_address = reinterpret_cast<Address*>(fp + kCallerPCOffset);
fp = Memory::Address_at(fp + StandardFrameConstants::kCallerFPOffset);
}
#ifdef DEBUG
StackFrameIterator it(isolate);
for (int i = 0; i < depth + 1; i++) it.Advance();
StackFrame* frame = it.frame();
DCHECK(fp == frame->fp() && pc_address == frame->pc_address());
#endif
// For interpreted functions, some bytecode handlers construct a
// frame. We have to skip the constructed frame to find the interpreted
// function's frame. Check if the there is an additional frame, and if there
// is skip this frame. However, the pc should not be updated. The call to
// ICs happen from bytecode handlers.
Object* frame_type =
Memory::Object_at(fp + TypedFrameConstants::kFrameTypeOffset);
if (frame_type == Smi::FromInt(StackFrame::STUB)) {
fp = Memory::Address_at(fp + TypedFrameConstants::kCallerFPOffset);
}
fp_ = fp;
if (FLAG_enable_embedded_constant_pool) {
constant_pool_address_ = constant_pool;
}
pc_address_ = StackFrame::ResolveReturnAddressLocation(pc_address);
Code* target = this->target();
kind_ = target->kind();
state_ = UseVector() ? nexus->StateFromFeedback() : StateFromCode(target);
old_state_ = state_;
extra_ic_state_ = target->extra_ic_state();
}
// The ICs that don't pass slot and vector through the stack have to
// save/restore them in the dispatcher.
bool IC::ShouldPushPopSlotAndVector(Code::Kind kind) {
if (kind == Code::LOAD_IC || kind == Code::LOAD_GLOBAL_IC ||
kind == Code::KEYED_LOAD_IC || kind == Code::CALL_IC) {
return true;
}
if (kind == Code::STORE_IC || kind == Code::KEYED_STORE_IC) {
return !StoreWithVectorDescriptor::kPassLastArgsOnStack;
}
return false;
}
InlineCacheState IC::StateFromCode(Code* code) {
Isolate* isolate = code->GetIsolate();
switch (code->kind()) {
case Code::BINARY_OP_IC: {
BinaryOpICState state(isolate, code->extra_ic_state());
return state.GetICState();
}
case Code::COMPARE_IC: {
CompareICStub stub(isolate, code->extra_ic_state());
return stub.GetICState();
}
case Code::TO_BOOLEAN_IC: {
ToBooleanICStub stub(isolate, code->extra_ic_state());
return stub.GetICState();
}
default:
if (code->is_debug_stub()) return UNINITIALIZED;
UNREACHABLE();
return UNINITIALIZED;
}
}
SharedFunctionInfo* IC::GetSharedFunctionInfo() const {
// Compute the JavaScript frame for the frame pointer of this IC
// structure. We need this to be able to find the function
// corresponding to the frame.
StackFrameIterator it(isolate());
while (it.frame()->fp() != this->fp()) it.Advance();
JavaScriptFrame* frame = JavaScriptFrame::cast(it.frame());
// Find the function on the stack and both the active code for the
// function and the original code.
JSFunction* function = frame->function();
return function->shared();
}
Code* IC::GetCode() const {
HandleScope scope(isolate());
Handle<SharedFunctionInfo> shared(GetSharedFunctionInfo(), isolate());
Code* code = shared->code();
return code;
}
static void LookupForRead(LookupIterator* it) {
for (; it->IsFound(); it->Next()) {
switch (it->state()) {
case LookupIterator::NOT_FOUND:
case LookupIterator::TRANSITION:
UNREACHABLE();
case LookupIterator::JSPROXY:
return;
case LookupIterator::INTERCEPTOR: {
// If there is a getter, return; otherwise loop to perform the lookup.
Handle<JSObject> holder = it->GetHolder<JSObject>();
if (!holder->GetNamedInterceptor()->getter()->IsUndefined(
it->isolate())) {
return;
}
break;
}
case LookupIterator::ACCESS_CHECK:
// PropertyHandlerCompiler::CheckPrototypes() knows how to emit
// access checks for global proxies.
if (it->GetHolder<JSObject>()->IsJSGlobalProxy() && it->HasAccess()) {
break;
}
return;
case LookupIterator::ACCESSOR:
case LookupIterator::INTEGER_INDEXED_EXOTIC:
case LookupIterator::DATA:
return;
}
}
}
bool IC::ShouldRecomputeHandler(Handle<String> name) {
if (!RecomputeHandlerForName(name)) return false;
DCHECK(UseVector());
maybe_handler_ = nexus()->FindHandlerForMap(receiver_map());
// This is a contextual access, always just update the handler and stay
// monomorphic.
if (kind() == Code::LOAD_GLOBAL_IC) return true;
// The current map wasn't handled yet. There's no reason to stay monomorphic,
// *unless* we're moving from a deprecated map to its replacement, or
// to a more general elements kind.
// TODO(verwaest): Check if the current map is actually what the old map
// would transition to.
if (maybe_handler_.is_null()) {
if (!receiver_map()->IsJSObjectMap()) return false;
Map* first_map = FirstTargetMap();
if (first_map == NULL) return false;
Handle<Map> old_map(first_map);
if (old_map->is_deprecated()) return true;
return IsMoreGeneralElementsKindTransition(old_map->elements_kind(),
receiver_map()->elements_kind());
}
return true;
}
bool IC::RecomputeHandlerForName(Handle<Object> name) {
if (is_keyed()) {
// Determine whether the failure is due to a name failure.
if (!name->IsName()) return false;
DCHECK(UseVector());
Name* stub_name = nexus()->FindFirstName();
if (*name != stub_name) return false;
}
return true;
}
void IC::UpdateState(Handle<Object> receiver, Handle<Object> name) {
update_receiver_map(receiver);
if (!name->IsString()) return;
if (state() != MONOMORPHIC && state() != POLYMORPHIC) return;
if (receiver->IsUndefined(isolate()) || receiver->IsNull(isolate())) return;
// Remove the target from the code cache if it became invalid
// because of changes in the prototype chain to avoid hitting it
// again.
if (ShouldRecomputeHandler(Handle<String>::cast(name))) {
MarkRecomputeHandler(name);
}
}
MaybeHandle<Object> IC::TypeError(MessageTemplate::Template index,
Handle<Object> object, Handle<Object> key) {
HandleScope scope(isolate());
THROW_NEW_ERROR(isolate(), NewTypeError(index, key, object), Object);
}
MaybeHandle<Object> IC::ReferenceError(Handle<Name> name) {
HandleScope scope(isolate());
THROW_NEW_ERROR(
isolate(), NewReferenceError(MessageTemplate::kNotDefined, name), Object);
}
static void ComputeTypeInfoCountDelta(IC::State old_state, IC::State new_state,
int* polymorphic_delta,
int* generic_delta) {
switch (old_state) {
case UNINITIALIZED:
case PREMONOMORPHIC:
if (new_state == UNINITIALIZED || new_state == PREMONOMORPHIC) break;
if (new_state == MONOMORPHIC || new_state == POLYMORPHIC) {
*polymorphic_delta = 1;
} else if (new_state == MEGAMORPHIC || new_state == GENERIC) {
*generic_delta = 1;
}
break;
case MONOMORPHIC:
case POLYMORPHIC:
if (new_state == MONOMORPHIC || new_state == POLYMORPHIC) break;
*polymorphic_delta = -1;
if (new_state == MEGAMORPHIC || new_state == GENERIC) {
*generic_delta = 1;
}
break;
case MEGAMORPHIC:
case GENERIC:
if (new_state == MEGAMORPHIC || new_state == GENERIC) break;
*generic_delta = -1;
if (new_state == MONOMORPHIC || new_state == POLYMORPHIC) {
*polymorphic_delta = 1;
}
break;
case RECOMPUTE_HANDLER:
UNREACHABLE();
}
}
// static
void IC::OnTypeFeedbackChanged(Isolate* isolate, Code* host) {
if (host->kind() != Code::FUNCTION) return;
TypeFeedbackInfo* info = TypeFeedbackInfo::cast(host->type_feedback_info());
info->change_own_type_change_checksum();
host->set_profiler_ticks(0);
isolate->runtime_profiler()->NotifyICChanged();
// TODO(2029): When an optimized function is patched, it would
// be nice to propagate the corresponding type information to its
// unoptimized version for the benefit of later inlining.
}
void IC::PostPatching(Address address, Code* target, Code* old_target) {
// Type vector based ICs update these statistics at a different time because
// they don't always patch on state change.
if (ICUseVector(target->kind())) return;
DCHECK(old_target->is_inline_cache_stub());
DCHECK(target->is_inline_cache_stub());
State old_state = StateFromCode(old_target);
State new_state = StateFromCode(target);
Isolate* isolate = target->GetIsolate();
Code* host =
isolate->inner_pointer_to_code_cache()->GetCacheEntry(address)->code;
if (host->kind() != Code::FUNCTION) return;
// Not all Code objects have TypeFeedbackInfo.
if (host->type_feedback_info()->IsTypeFeedbackInfo()) {
if (FLAG_type_info_threshold > 0) {
int polymorphic_delta = 0; // "Polymorphic" here includes monomorphic.
int generic_delta = 0; // "Generic" here includes megamorphic.
ComputeTypeInfoCountDelta(old_state, new_state, &polymorphic_delta,
&generic_delta);
TypeFeedbackInfo* info =
TypeFeedbackInfo::cast(host->type_feedback_info());
info->change_ic_with_type_info_count(polymorphic_delta);
info->change_ic_generic_count(generic_delta);
}
TypeFeedbackInfo* info = TypeFeedbackInfo::cast(host->type_feedback_info());
info->change_own_type_change_checksum();
}
host->set_profiler_ticks(0);
isolate->runtime_profiler()->NotifyICChanged();
// TODO(2029): When an optimized function is patched, it would
// be nice to propagate the corresponding type information to its
// unoptimized version for the benefit of later inlining.
}
void IC::Clear(Isolate* isolate, Address address, Address constant_pool) {
Code* target = GetTargetAtAddress(address, constant_pool);
// Don't clear debug break inline cache as it will remove the break point.
if (target->is_debug_stub()) return;
if (target->kind() == Code::COMPARE_IC) {
CompareIC::Clear(isolate, address, target, constant_pool);
}
}
void KeyedLoadIC::Clear(Isolate* isolate, Code* host, KeyedLoadICNexus* nexus) {
if (IsCleared(nexus)) return;
// Make sure to also clear the map used in inline fast cases. If we
// do not clear these maps, cached code can keep objects alive
// through the embedded maps.
nexus->ConfigurePremonomorphic();
OnTypeFeedbackChanged(isolate, host);
}
void CallIC::Clear(Isolate* isolate, Code* host, CallICNexus* nexus) {
// Determine our state.
Object* feedback = nexus->vector()->Get(nexus->slot());
State state = nexus->StateFromFeedback();
if (state != UNINITIALIZED && !feedback->IsAllocationSite()) {
nexus->ConfigureUninitialized();
// The change in state must be processed.
OnTypeFeedbackChanged(isolate, host);
}
}
void LoadIC::Clear(Isolate* isolate, Code* host, LoadICNexus* nexus) {
if (IsCleared(nexus)) return;
nexus->ConfigurePremonomorphic();
OnTypeFeedbackChanged(isolate, host);
}
void LoadGlobalIC::Clear(Isolate* isolate, Code* host,
LoadGlobalICNexus* nexus) {
if (IsCleared(nexus)) return;
nexus->ConfigureUninitialized();
OnTypeFeedbackChanged(isolate, host);
}
void StoreIC::Clear(Isolate* isolate, Code* host, StoreICNexus* nexus) {
if (IsCleared(nexus)) return;
nexus->ConfigurePremonomorphic();
OnTypeFeedbackChanged(isolate, host);
}
void KeyedStoreIC::Clear(Isolate* isolate, Code* host,
KeyedStoreICNexus* nexus) {
if (IsCleared(nexus)) return;
nexus->ConfigurePremonomorphic();
OnTypeFeedbackChanged(isolate, host);
}
void CompareIC::Clear(Isolate* isolate, Address address, Code* target,
Address constant_pool) {
DCHECK(CodeStub::GetMajorKey(target) == CodeStub::CompareIC);
CompareICStub stub(target->stub_key(), isolate);
// Only clear CompareICs that can retain objects.
if (stub.state() != CompareICState::KNOWN_RECEIVER) return;
SetTargetAtAddress(address, GetRawUninitialized(isolate, stub.op()),
constant_pool);
PatchInlinedSmiCode(isolate, address, DISABLE_INLINED_SMI_CHECK);
}
static bool MigrateDeprecated(Handle<Object> object) {
if (!object->IsJSObject()) return false;
Handle<JSObject> receiver = Handle<JSObject>::cast(object);
if (!receiver->map()->is_deprecated()) return false;
JSObject::MigrateInstance(Handle<JSObject>::cast(object));
return true;
}
void IC::ConfigureVectorState(IC::State new_state, Handle<Object> key) {
DCHECK(UseVector());
if (new_state == PREMONOMORPHIC) {
nexus()->ConfigurePremonomorphic();
} else if (new_state == MEGAMORPHIC) {
if (kind() == Code::LOAD_IC || kind() == Code::STORE_IC) {
nexus()->ConfigureMegamorphic();
} else if (kind() == Code::KEYED_LOAD_IC) {
KeyedLoadICNexus* nexus = casted_nexus<KeyedLoadICNexus>();
nexus->ConfigureMegamorphicKeyed(key->IsName() ? PROPERTY : ELEMENT);
} else {
DCHECK(kind() == Code::KEYED_STORE_IC);
KeyedStoreICNexus* nexus = casted_nexus<KeyedStoreICNexus>();
nexus->ConfigureMegamorphicKeyed(key->IsName() ? PROPERTY : ELEMENT);
}
} else {
UNREACHABLE();
}
vector_set_ = true;
OnTypeFeedbackChanged(isolate(), get_host());
}
void IC::ConfigureVectorState(Handle<Name> name, Handle<Map> map,
Handle<Object> handler) {
DCHECK(UseVector());
if (kind() == Code::LOAD_IC) {
LoadICNexus* nexus = casted_nexus<LoadICNexus>();
nexus->ConfigureMonomorphic(map, handler);
} else if (kind() == Code::LOAD_GLOBAL_IC) {
LoadGlobalICNexus* nexus = casted_nexus<LoadGlobalICNexus>();
nexus->ConfigureHandlerMode(Handle<Code>::cast(handler));
} else if (kind() == Code::KEYED_LOAD_IC) {
KeyedLoadICNexus* nexus = casted_nexus<KeyedLoadICNexus>();
nexus->ConfigureMonomorphic(name, map, handler);
} else if (kind() == Code::STORE_IC) {
StoreICNexus* nexus = casted_nexus<StoreICNexus>();
nexus->ConfigureMonomorphic(map, handler);
} else {
DCHECK(kind() == Code::KEYED_STORE_IC);
KeyedStoreICNexus* nexus = casted_nexus<KeyedStoreICNexus>();
nexus->ConfigureMonomorphic(name, map, handler);
}
vector_set_ = true;
OnTypeFeedbackChanged(isolate(), get_host());
}
void IC::ConfigureVectorState(Handle<Name> name, MapHandleList* maps,
List<Handle<Object>>* handlers) {
DCHECK(UseVector());
if (kind() == Code::LOAD_IC) {
LoadICNexus* nexus = casted_nexus<LoadICNexus>();
nexus->ConfigurePolymorphic(maps, handlers);
} else if (kind() == Code::KEYED_LOAD_IC) {
KeyedLoadICNexus* nexus = casted_nexus<KeyedLoadICNexus>();
nexus->ConfigurePolymorphic(name, maps, handlers);
} else if (kind() == Code::STORE_IC) {
StoreICNexus* nexus = casted_nexus<StoreICNexus>();
nexus->ConfigurePolymorphic(maps, handlers);
} else {
DCHECK(kind() == Code::KEYED_STORE_IC);
KeyedStoreICNexus* nexus = casted_nexus<KeyedStoreICNexus>();
nexus->ConfigurePolymorphic(name, maps, handlers);
}
vector_set_ = true;
OnTypeFeedbackChanged(isolate(), get_host());
}
void IC::ConfigureVectorState(MapHandleList* maps,
MapHandleList* transitioned_maps,
CodeHandleList* handlers) {
DCHECK(UseVector());
DCHECK(kind() == Code::KEYED_STORE_IC);
KeyedStoreICNexus* nexus = casted_nexus<KeyedStoreICNexus>();
nexus->ConfigurePolymorphic(maps, transitioned_maps, handlers);
vector_set_ = true;
OnTypeFeedbackChanged(isolate(), get_host());
}
MaybeHandle<Object> LoadIC::Load(Handle<Object> object, Handle<Name> name) {
// If the object is undefined or null it's illegal to try to get any
// of its properties; throw a TypeError in that case.
if (object->IsUndefined(isolate()) || object->IsNull(isolate())) {
return TypeError(MessageTemplate::kNonObjectPropertyLoad, object, name);
}
bool use_ic = MigrateDeprecated(object) ? false : FLAG_use_ic;
if (state() != UNINITIALIZED) {
JSObject::MakePrototypesFast(object, kStartAtReceiver, isolate());
update_receiver_map(object);
}
// Named lookup in the object.
LookupIterator it(object, name);
LookupForRead(&it);
if (it.IsFound() || !ShouldThrowReferenceError()) {
// Update inline cache and stub cache.
if (use_ic) UpdateCaches(&it);
// Get the property.
Handle<Object> result;
ASSIGN_RETURN_ON_EXCEPTION(isolate(), result, Object::GetProperty(&it),
Object);
if (it.IsFound()) {
return result;
} else if (!ShouldThrowReferenceError()) {
LOG(isolate(), SuspectReadEvent(*name, *object));
return result;
}
}
return ReferenceError(name);
}
MaybeHandle<Object> LoadGlobalIC::Load(Handle<Name> name) {
Handle<JSGlobalObject> global = isolate()->global_object();
if (name->IsString()) {
// Look up in script context table.
Handle<String> str_name = Handle<String>::cast(name);
Handle<ScriptContextTable> script_contexts(
global->native_context()->script_context_table());
ScriptContextTable::LookupResult lookup_result;
if (ScriptContextTable::Lookup(script_contexts, str_name, &lookup_result)) {
Handle<Object> result =
FixedArray::get(*ScriptContextTable::GetContext(
script_contexts, lookup_result.context_index),
lookup_result.slot_index, isolate());
if (result->IsTheHole(isolate())) {
// Do not install stubs and stay pre-monomorphic for
// uninitialized accesses.
return ReferenceError(name);
}
if (FLAG_use_ic && LoadScriptContextFieldStub::Accepted(&lookup_result)) {
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadScriptContextFieldStub);
LoadScriptContextFieldStub stub(isolate(), &lookup_result);
PatchCache(name, stub.GetCode());
TRACE_IC("LoadGlobalIC", name);
}
return result;
}
}
return LoadIC::Load(global, name);
}
static bool AddOneReceiverMapIfMissing(MapHandleList* receiver_maps,
Handle<Map> new_receiver_map) {
DCHECK(!new_receiver_map.is_null());
for (int current = 0; current < receiver_maps->length(); ++current) {
if (!receiver_maps->at(current).is_null() &&
receiver_maps->at(current).is_identical_to(new_receiver_map)) {
return false;
}
}
receiver_maps->Add(new_receiver_map);
return true;
}
bool IC::UpdatePolymorphicIC(Handle<Name> name, Handle<Object> handler) {
DCHECK(IsHandler(*handler));
if (is_keyed() && state() != RECOMPUTE_HANDLER) return false;
Handle<Map> map = receiver_map();
MapHandleList maps;
List<Handle<Object>> handlers;
TargetMaps(&maps);
int number_of_maps = maps.length();
int deprecated_maps = 0;
int handler_to_overwrite = -1;
for (int i = 0; i < number_of_maps; i++) {
Handle<Map> current_map = maps.at(i);
if (current_map->is_deprecated()) {
// Filter out deprecated maps to ensure their instances get migrated.
++deprecated_maps;
} else if (map.is_identical_to(current_map)) {
// If the receiver type is already in the polymorphic IC, this indicates
// there was a prototoype chain failure. In that case, just overwrite the
// handler.
handler_to_overwrite = i;
} else if (handler_to_overwrite == -1 &&
IsTransitionOfMonomorphicTarget(*current_map, *map)) {
handler_to_overwrite = i;
}
}
int number_of_valid_maps =
number_of_maps - deprecated_maps - (handler_to_overwrite != -1);
if (number_of_valid_maps >= 4) return false;
if (number_of_maps == 0 && state() != MONOMORPHIC && state() != POLYMORPHIC) {
return false;
}
DCHECK(UseVector());
if (!nexus()->FindHandlers(&handlers, maps.length())) return false;
number_of_valid_maps++;
if (number_of_valid_maps > 1 && is_keyed()) return false;
if (number_of_valid_maps == 1) {
ConfigureVectorState(name, receiver_map(), handler);
} else {
if (handler_to_overwrite >= 0) {
handlers.Set(handler_to_overwrite, handler);
if (!map.is_identical_to(maps.at(handler_to_overwrite))) {
maps.Set(handler_to_overwrite, map);
}
} else {
maps.Add(map);
handlers.Add(handler);
}
ConfigureVectorState(name, &maps, &handlers);
}
return true;
}
void IC::UpdateMonomorphicIC(Handle<Object> handler, Handle<Name> name) {
DCHECK(IsHandler(*handler));
ConfigureVectorState(name, receiver_map(), handler);
}
void IC::CopyICToMegamorphicCache(Handle<Name> name) {
MapHandleList maps;
List<Handle<Object>> handlers;
TargetMaps(&maps);
if (!nexus()->FindHandlers(&handlers, maps.length())) return;
for (int i = 0; i < maps.length(); i++) {
UpdateMegamorphicCache(*maps.at(i), *name, *handlers.at(i));
}
}
bool IC::IsTransitionOfMonomorphicTarget(Map* source_map, Map* target_map) {
if (source_map == NULL) return true;
if (target_map == NULL) return false;
ElementsKind target_elements_kind = target_map->elements_kind();
bool more_general_transition = IsMoreGeneralElementsKindTransition(
source_map->elements_kind(), target_elements_kind);
Map* transitioned_map = nullptr;
if (more_general_transition) {
MapHandleList map_list;
map_list.Add(handle(target_map));
transitioned_map = source_map->FindElementsKindTransitionedMap(&map_list);
}
return transitioned_map == target_map;
}
void IC::PatchCache(Handle<Name> name, Handle<Object> handler) {
DCHECK(IsHandler(*handler));
// Currently only LoadIC and KeyedLoadIC support non-code handlers.
DCHECK_IMPLIES(!handler->IsCode(), kind() == Code::LOAD_IC ||
kind() == Code::KEYED_LOAD_IC ||
kind() == Code::STORE_IC ||
kind() == Code::KEYED_STORE_IC);
switch (state()) {
case UNINITIALIZED:
case PREMONOMORPHIC:
UpdateMonomorphicIC(handler, name);
break;
case RECOMPUTE_HANDLER:
case MONOMORPHIC:
if (kind() == Code::LOAD_GLOBAL_IC) {
UpdateMonomorphicIC(handler, name);
break;
}
// Fall through.
case POLYMORPHIC:
if (!is_keyed() || state() == RECOMPUTE_HANDLER) {
if (UpdatePolymorphicIC(name, handler)) break;
// For keyed stubs, we can't know whether old handlers were for the
// same key.
CopyICToMegamorphicCache(name);
}
DCHECK(UseVector());
ConfigureVectorState(MEGAMORPHIC, name);
// Fall through.
case MEGAMORPHIC:
UpdateMegamorphicCache(*receiver_map(), *name, *handler);
// Indicate that we've handled this case.
DCHECK(UseVector());
vector_set_ = true;
break;
case GENERIC:
UNREACHABLE();
break;
}
}
Handle<Code> KeyedStoreIC::ChooseMegamorphicStub(Isolate* isolate,
ExtraICState extra_state) {
DCHECK(!FLAG_tf_store_ic_stub);
LanguageMode mode = StoreICState::GetLanguageMode(extra_state);
return is_strict(mode)
? isolate->builtins()->KeyedStoreIC_Megamorphic_Strict()
: isolate->builtins()->KeyedStoreIC_Megamorphic();
}
Handle<Object> LoadIC::SimpleFieldLoad(FieldIndex index) {
if (FLAG_tf_load_ic_stub) {
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadFieldDH);
return LoadHandler::LoadField(isolate(), index);
}
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadFieldStub);
LoadFieldStub stub(isolate(), index);
return stub.GetCode();
}
namespace {
template <bool fill_array = true>
int InitPrototypeChecks(Isolate* isolate, Handle<Map> receiver_map,
Handle<JSObject> holder, Handle<FixedArray> array,
Handle<Name> name, int first_index) {
DCHECK(holder.is_null() || holder->HasFastProperties());
// The following kinds of receiver maps require custom handler compilation.
if (receiver_map->IsJSGlobalObjectMap()) {
return -1;
}
// We don't encode the requirement to check access rights because we already
// passed the access check for current native context and the access
// can't be revoked.
HandleScope scope(isolate);
int checks_count = 0;
if (receiver_map->IsPrimitiveMap() || receiver_map->IsJSGlobalProxyMap()) {
// The validity cell check for primitive and global proxy receivers does
// not guarantee that certain native context ever had access to other
// native context. However, a handler created for one native context could
// be used in other native context through the megamorphic stub cache.
// So we record the original native context to which this handler
// corresponds.
if (fill_array) {
Handle<Context> native_context = isolate->native_context();
array->set(LoadHandler::kFirstPrototypeIndex + checks_count,
native_context->self_weak_cell());
}
checks_count++;
}
// Create/count entries for each global or dictionary prototype appeared in
// the prototype chain contains from receiver till holder.
for (PrototypeIterator iter(receiver_map); !iter.IsAtEnd(); iter.Advance()) {
Handle<JSObject> current = PrototypeIterator::GetCurrent<JSObject>(iter);
if (holder.is_identical_to(current)) break;
Handle<Map> current_map(current->map(), isolate);
if (current_map->IsJSGlobalObjectMap()) {
if (fill_array) {
Handle<JSGlobalObject> global = Handle<JSGlobalObject>::cast(current);
Handle<PropertyCell> cell = JSGlobalObject::EnsureEmptyPropertyCell(
global, name, PropertyCellType::kInvalidated);
DCHECK(cell->value()->IsTheHole(isolate));
Handle<WeakCell> weak_cell = isolate->factory()->NewWeakCell(cell);
array->set(first_index + checks_count, *weak_cell);
}
checks_count++;
} else if (current_map->is_dictionary_map()) {
DCHECK(!current_map->IsJSGlobalProxyMap()); // Proxy maps are fast.
if (fill_array) {
DCHECK_EQ(NameDictionary::kNotFound,
current->property_dictionary()->FindEntry(name));
Handle<WeakCell> weak_cell =
Map::GetOrCreatePrototypeWeakCell(current, isolate);
array->set(first_index + checks_count, *weak_cell);
}
checks_count++;
}
}
return checks_count;
}
// Returns 0 if the validity cell check is enough to ensure that the
// prototype chain from |receiver_map| till |holder| did not change.
// If the |holder| is an empty handle then the full prototype chain is
// checked.
// Returns -1 if the handler has to be compiled or the number of prototype
// checks otherwise.
int GetPrototypeCheckCount(Isolate* isolate, Handle<Map> receiver_map,
Handle<JSObject> holder) {
return InitPrototypeChecks<false>(isolate, receiver_map, holder,
Handle<FixedArray>(), Handle<Name>(), 0);
}
} // namespace
Handle<Object> LoadIC::LoadFromPrototype(Handle<Map> receiver_map,
Handle<JSObject> holder,
Handle<Name> name,
Handle<Object> smi_handler) {
int checks_count = GetPrototypeCheckCount(isolate(), receiver_map, holder);
DCHECK_LE(0, checks_count);
DCHECK(!receiver_map->IsJSGlobalObjectMap());
if (receiver_map->IsPrimitiveMap() || receiver_map->IsJSGlobalProxyMap()) {
DCHECK(!receiver_map->is_dictionary_map());
DCHECK_LE(1, checks_count); // For native context.
smi_handler =
LoadHandler::EnableAccessCheckOnReceiver(isolate(), smi_handler);
} else if (receiver_map->is_dictionary_map()) {
smi_handler =
LoadHandler::EnableNegativeLookupOnReceiver(isolate(), smi_handler);
}
Handle<Cell> validity_cell =
Map::GetOrCreatePrototypeChainValidityCell(receiver_map, isolate());
DCHECK(!validity_cell.is_null());
Handle<WeakCell> holder_cell =
Map::GetOrCreatePrototypeWeakCell(holder, isolate());
if (checks_count == 0) {
return isolate()->factory()->NewTuple3(holder_cell, smi_handler,
validity_cell);
}
Handle<FixedArray> handler_array(isolate()->factory()->NewFixedArray(
LoadHandler::kFirstPrototypeIndex + checks_count, TENURED));
handler_array->set(LoadHandler::kSmiHandlerIndex, *smi_handler);
handler_array->set(LoadHandler::kValidityCellIndex, *validity_cell);
handler_array->set(LoadHandler::kHolderCellIndex, *holder_cell);
InitPrototypeChecks(isolate(), receiver_map, holder, handler_array, name,
LoadHandler::kFirstPrototypeIndex);
return handler_array;
}
Handle<Object> LoadIC::LoadNonExistent(Handle<Map> receiver_map,
Handle<Name> name) {
Handle<JSObject> holder; // null handle
int checks_count = GetPrototypeCheckCount(isolate(), receiver_map, holder);
DCHECK_LE(0, checks_count);
DCHECK(!receiver_map->IsJSGlobalObjectMap());
Handle<Object> smi_handler = LoadHandler::LoadNonExistent(
isolate(), receiver_map->is_dictionary_map());
if (receiver_map->IsPrimitiveMap() || receiver_map->IsJSGlobalProxyMap()) {
DCHECK(!receiver_map->is_dictionary_map());
DCHECK_LE(1, checks_count); // For native context.
smi_handler =
LoadHandler::EnableAccessCheckOnReceiver(isolate(), smi_handler);
}
Handle<Object> validity_cell =
Map::GetOrCreatePrototypeChainValidityCell(receiver_map, isolate());
if (validity_cell.is_null()) {
// This must be a case when receiver's prototype is null.
DCHECK_EQ(*isolate()->factory()->null_value(),
receiver_map->GetPrototypeChainRootMap(isolate())->prototype());
DCHECK_EQ(0, checks_count);
validity_cell = handle(Smi::FromInt(0), isolate());
}
Factory* factory = isolate()->factory();
if (checks_count == 0) {
return factory->NewTuple3(factory->null_value(), smi_handler,
validity_cell);
}
Handle<FixedArray> handler_array(factory->NewFixedArray(
LoadHandler::kFirstPrototypeIndex + checks_count, TENURED));
handler_array->set(LoadHandler::kSmiHandlerIndex, *smi_handler);
handler_array->set(LoadHandler::kValidityCellIndex, *validity_cell);
handler_array->set(LoadHandler::kHolderCellIndex, *factory->null_value());
InitPrototypeChecks(isolate(), receiver_map, holder, handler_array, name,
LoadHandler::kFirstPrototypeIndex);
return handler_array;
}
bool IsCompatibleReceiver(LookupIterator* lookup, Handle<Map> receiver_map) {
DCHECK(lookup->state() == LookupIterator::ACCESSOR);
Isolate* isolate = lookup->isolate();
Handle<Object> accessors = lookup->GetAccessors();
if (accessors->IsAccessorInfo()) {
Handle<AccessorInfo> info = Handle<AccessorInfo>::cast(accessors);
if (info->getter() != NULL &&
!AccessorInfo::IsCompatibleReceiverMap(isolate, info, receiver_map)) {
return false;
}
} else if (accessors->IsAccessorPair()) {
Handle<Object> getter(Handle<AccessorPair>::cast(accessors)->getter(),
isolate);
if (!getter->IsJSFunction() && !getter->IsFunctionTemplateInfo()) {
return false;
}
Handle<JSObject> holder = lookup->GetHolder<JSObject>();
Handle<Object> receiver = lookup->GetReceiver();
if (holder->HasFastProperties()) {
if (getter->IsJSFunction()) {
Handle<JSFunction> function = Handle<JSFunction>::cast(getter);
if (!receiver->IsJSObject() && function->shared()->IsUserJavaScript() &&
is_sloppy(function->shared()->language_mode())) {
// Calling sloppy non-builtins with a value as the receiver
// requires boxing.
return false;
}
}
CallOptimization call_optimization(getter);
if (call_optimization.is_simple_api_call() &&
!call_optimization.IsCompatibleReceiverMap(receiver_map, holder)) {
return false;
}
}
}
return true;
}
void LoadIC::UpdateCaches(LookupIterator* lookup) {
if (state() == UNINITIALIZED && kind() != Code::LOAD_GLOBAL_IC) {
// This is the first time we execute this inline cache. Set the target to
// the pre monomorphic stub to delay setting the monomorphic state.
TRACE_HANDLER_STATS(isolate(), LoadIC_Premonomorphic);
ConfigureVectorState(PREMONOMORPHIC, Handle<Object>());
TRACE_IC("LoadIC", lookup->name());
return;
}
Handle<Object> code;
if (lookup->state() == LookupIterator::JSPROXY ||
lookup->state() == LookupIterator::ACCESS_CHECK) {
code = slow_stub();
} else if (!lookup->IsFound()) {
if (kind() == Code::LOAD_IC) {
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadNonexistentDH);
code = LoadNonExistent(receiver_map(), lookup->name());
} else if (kind() == Code::LOAD_GLOBAL_IC) {
code = NamedLoadHandlerCompiler::ComputeLoadNonexistent(lookup->name(),
receiver_map());
// TODO(jkummerow/verwaest): Introduce a builtin that handles this case.
if (code.is_null()) code = slow_stub();
} else {
code = slow_stub();
}
} else {
if (kind() == Code::LOAD_GLOBAL_IC &&
lookup->state() == LookupIterator::DATA &&
lookup->GetHolder<Object>()->IsJSGlobalObject()) {
#if DEBUG
Handle<Object> holder = lookup->GetHolder<Object>();
Handle<Object> receiver = lookup->GetReceiver();
DCHECK_EQ(*receiver, *holder);
#endif
// Now update the cell in the feedback vector.
LoadGlobalICNexus* nexus = casted_nexus<LoadGlobalICNexus>();
nexus->ConfigurePropertyCellMode(lookup->GetPropertyCell());
TRACE_IC("LoadGlobalIC", lookup->name());
return;
} else if (lookup->state() == LookupIterator::ACCESSOR) {
if (!IsCompatibleReceiver(lookup, receiver_map())) {
TRACE_GENERIC_IC(isolate(), "LoadIC", "incompatible receiver type");
code = slow_stub();
}
} else if (lookup->state() == LookupIterator::INTERCEPTOR) {
// Perform a lookup behind the interceptor. Copy the LookupIterator
// since the original iterator will be used to fetch the value.
LookupIterator it = *lookup;
it.Next();
LookupForRead(&it);
if (it.state() == LookupIterator::ACCESSOR &&
!IsCompatibleReceiver(&it, receiver_map())) {
TRACE_GENERIC_IC(isolate(), "LoadIC", "incompatible receiver type");
code = slow_stub();
}
}
if (code.is_null()) code = ComputeHandler(lookup);
}
PatchCache(lookup->name(), code);
TRACE_IC("LoadIC", lookup->name());
}
StubCache* IC::stub_cache() {
switch (kind()) {
case Code::LOAD_IC:
case Code::KEYED_LOAD_IC:
return isolate()->load_stub_cache();
case Code::STORE_IC:
case Code::KEYED_STORE_IC:
return isolate()->store_stub_cache();
default:
break;
}
UNREACHABLE();
return nullptr;
}
void IC::UpdateMegamorphicCache(Map* map, Name* name, Object* handler) {
stub_cache()->Set(name, map, handler);
}
void IC::TraceHandlerCacheHitStats(LookupIterator* lookup) {
if (!FLAG_runtime_call_stats) return;
if (kind() == Code::LOAD_IC || kind() == Code::LOAD_GLOBAL_IC ||
kind() == Code::KEYED_LOAD_IC) {
switch (lookup->state()) {
case LookupIterator::ACCESS_CHECK:
TRACE_HANDLER_STATS(isolate(), LoadIC_HandlerCacheHit_AccessCheck);
break;
case LookupIterator::INTEGER_INDEXED_EXOTIC:
TRACE_HANDLER_STATS(isolate(), LoadIC_HandlerCacheHit_Exotic);
break;
case LookupIterator::INTERCEPTOR:
TRACE_HANDLER_STATS(isolate(), LoadIC_HandlerCacheHit_Interceptor);
break;
case LookupIterator::JSPROXY:
TRACE_HANDLER_STATS(isolate(), LoadIC_HandlerCacheHit_JSProxy);
break;
case LookupIterator::NOT_FOUND:
TRACE_HANDLER_STATS(isolate(), LoadIC_HandlerCacheHit_NonExistent);
break;
case LookupIterator::ACCESSOR:
TRACE_HANDLER_STATS(isolate(), LoadIC_HandlerCacheHit_Accessor);
break;
case LookupIterator::DATA:
TRACE_HANDLER_STATS(isolate(), LoadIC_HandlerCacheHit_Data);
break;
case LookupIterator::TRANSITION:
TRACE_HANDLER_STATS(isolate(), LoadIC_HandlerCacheHit_Transition);
break;
}
} else if (kind() == Code::STORE_IC || kind() == Code::KEYED_STORE_IC) {
switch (lookup->state()) {
case LookupIterator::ACCESS_CHECK:
TRACE_HANDLER_STATS(isolate(), StoreIC_HandlerCacheHit_AccessCheck);
break;
case LookupIterator::INTEGER_INDEXED_EXOTIC:
TRACE_HANDLER_STATS(isolate(), StoreIC_HandlerCacheHit_Exotic);
break;
case LookupIterator::INTERCEPTOR:
TRACE_HANDLER_STATS(isolate(), StoreIC_HandlerCacheHit_Interceptor);
break;
case LookupIterator::JSPROXY:
TRACE_HANDLER_STATS(isolate(), StoreIC_HandlerCacheHit_JSProxy);
break;
case LookupIterator::NOT_FOUND:
TRACE_HANDLER_STATS(isolate(), StoreIC_HandlerCacheHit_NonExistent);
break;
case LookupIterator::ACCESSOR:
TRACE_HANDLER_STATS(isolate(), StoreIC_HandlerCacheHit_Accessor);
break;
case LookupIterator::DATA:
TRACE_HANDLER_STATS(isolate(), StoreIC_HandlerCacheHit_Data);
break;
case LookupIterator::TRANSITION:
TRACE_HANDLER_STATS(isolate(), StoreIC_HandlerCacheHit_Transition);
break;
}
} else {
TRACE_HANDLER_STATS(isolate(), IC_HandlerCacheHit);
}
}
Handle<Object> IC::ComputeHandler(LookupIterator* lookup,
Handle<Object> value) {
// Try to find a globally shared handler stub.
Handle<Object> shared_handler = GetMapIndependentHandler(lookup);
if (!shared_handler.is_null()) {
DCHECK(IC::IsHandler(*shared_handler));
return shared_handler;
}
// Otherwise check the map's handler cache for a map-specific handler, and
// compile one if the cache comes up empty.
bool receiver_is_holder =
lookup->GetReceiver().is_identical_to(lookup->GetHolder<JSObject>());
CacheHolderFlag flag;
Handle<Map> stub_holder_map;
if (kind() == Code::LOAD_IC || kind() == Code::LOAD_GLOBAL_IC ||
kind() == Code::KEYED_LOAD_IC) {
stub_holder_map = IC::GetHandlerCacheHolder(
receiver_map(), receiver_is_holder, isolate(), &flag);
} else {
DCHECK(kind() == Code::STORE_IC || kind() == Code::KEYED_STORE_IC);
// Store handlers cannot be cached on prototypes.
flag = kCacheOnReceiver;
stub_holder_map = receiver_map();
}
Handle<Object> handler = PropertyHandlerCompiler::Find(
lookup->name(), stub_holder_map, kind(), flag);
// Use the cached value if it exists, and if it is different from the
// handler that just missed.
if (!handler.is_null()) {
Handle<Object> current_handler;
if (maybe_handler_.ToHandle(¤t_handler)) {
if (!current_handler.is_identical_to(handler)) {
TraceHandlerCacheHitStats(lookup);
return handler;
}
} else {
// maybe_handler_ is only populated for MONOMORPHIC and POLYMORPHIC ICs.
// In MEGAMORPHIC case, check if the handler in the megamorphic stub
// cache (which just missed) is different from the cached handler.
if (state() == MEGAMORPHIC && lookup->GetReceiver()->IsHeapObject()) {
Map* map = Handle<HeapObject>::cast(lookup->GetReceiver())->map();
Object* megamorphic_cached_handler =
stub_cache()->Get(*lookup->name(), map);
if (megamorphic_cached_handler != *handler) {
TraceHandlerCacheHitStats(lookup);
return handler;
}
} else {
TraceHandlerCacheHitStats(lookup);
return handler;
}
}
}
handler = CompileHandler(lookup, value, flag);
DCHECK(IC::IsHandler(*handler));
if (handler->IsCode()) {
Handle<Code> code = Handle<Code>::cast(handler);
DCHECK_EQ(Code::ExtractCacheHolderFromFlags(code->flags()), flag);
Map::UpdateCodeCache(stub_holder_map, lookup->name(), code);
}
return handler;
}
Handle<Object> LoadIC::GetMapIndependentHandler(LookupIterator* lookup) {
Handle<Object> receiver = lookup->GetReceiver();
if (receiver->IsString() &&
Name::Equals(isolate()->factory()->length_string(), lookup->name())) {
FieldIndex index = FieldIndex::ForInObjectOffset(String::kLengthOffset);
return SimpleFieldLoad(index);
}
if (receiver->IsStringWrapper() &&
Name::Equals(isolate()->factory()->length_string(), lookup->name())) {
TRACE_HANDLER_STATS(isolate(), LoadIC_StringLengthStub);
StringLengthStub string_length_stub(isolate());
return string_length_stub.GetCode();
}
// Use specialized code for getting prototype of functions.
if (receiver->IsJSFunction() &&
Name::Equals(isolate()->factory()->prototype_string(), lookup->name()) &&
receiver->IsConstructor() &&
!Handle<JSFunction>::cast(receiver)
->map()
->has_non_instance_prototype()) {
Handle<Code> stub;
TRACE_HANDLER_STATS(isolate(), LoadIC_FunctionPrototypeStub);
FunctionPrototypeStub function_prototype_stub(isolate());
return function_prototype_stub.GetCode();
}
Handle<Map> map = receiver_map();
Handle<JSObject> holder = lookup->GetHolder<JSObject>();
bool receiver_is_holder = receiver.is_identical_to(holder);
switch (lookup->state()) {
case LookupIterator::INTERCEPTOR:
break; // Custom-compiled handler.
case LookupIterator::ACCESSOR: {
// Use simple field loads for some well-known callback properties.
// The method will only return true for absolute truths based on the
// receiver maps.
int object_offset;
if (Accessors::IsJSObjectFieldAccessor(map, lookup->name(),
&object_offset)) {
FieldIndex index = FieldIndex::ForInObjectOffset(object_offset, *map);
return SimpleFieldLoad(index);
}
if (IsCompatibleReceiver(lookup, map)) {
Handle<Object> accessors = lookup->GetAccessors();
if (accessors->IsAccessorPair()) {
if (!holder->HasFastProperties()) {
TRACE_HANDLER_STATS(isolate(), LoadIC_SlowStub);
return slow_stub();
}
// When debugging we need to go the slow path to flood the accessor.
if (GetSharedFunctionInfo()->HasDebugInfo()) {
TRACE_HANDLER_STATS(isolate(), LoadIC_SlowStub);
return slow_stub();
}
break; // Custom-compiled handler.
} else if (accessors->IsAccessorInfo()) {
Handle<AccessorInfo> info = Handle<AccessorInfo>::cast(accessors);
if (v8::ToCData<Address>(info->getter()) == nullptr) {
TRACE_HANDLER_STATS(isolate(), LoadIC_SlowStub);
return slow_stub();
}
// Ruled out by IsCompatibleReceiver() above.
DCHECK(AccessorInfo::IsCompatibleReceiverMap(isolate(), info, map));
if (!holder->HasFastProperties() ||
(info->is_sloppy() && !receiver->IsJSReceiver())) {
DCHECK(!holder->HasFastProperties() || !receiver_is_holder);
TRACE_HANDLER_STATS(isolate(), LoadIC_SlowStub);
return slow_stub();
}
if (FLAG_tf_load_ic_stub) {
Handle<Object> smi_handler = LoadHandler::LoadApiGetter(
isolate(), lookup->GetAccessorIndex());
if (receiver_is_holder) {
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadApiGetterDH);
return smi_handler;
}
if (kind() != Code::LOAD_GLOBAL_IC) {
TRACE_HANDLER_STATS(isolate(),
LoadIC_LoadApiGetterFromPrototypeDH);
return LoadFromPrototype(map, holder, lookup->name(),
smi_handler);
}
} else {
if (receiver_is_holder) {
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadApiGetterStub);
int index = lookup->GetAccessorIndex();
LoadApiGetterStub stub(isolate(), true, index);
return stub.GetCode();
}
}
break; // Custom-compiled handler.
}
}
TRACE_HANDLER_STATS(isolate(), LoadIC_SlowStub);
return slow_stub();
}
case LookupIterator::DATA: {
if (lookup->is_dictionary_holder()) {
if (kind() != Code::LOAD_IC && kind() != Code::LOAD_GLOBAL_IC) {
TRACE_HANDLER_STATS(isolate(), LoadIC_SlowStub);
return slow_stub();
}
if (holder->IsJSGlobalObject()) {
break; // Custom-compiled handler.
}
// There is only one shared stub for loading normalized
// properties. It does not traverse the prototype chain, so the
// property must be found in the object for the stub to be
// applicable.
if (!receiver_is_holder) {
TRACE_HANDLER_STATS(isolate(), LoadIC_SlowStub);
return slow_stub();
}
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadNormal);
return isolate()->builtins()->LoadIC_Normal();
}
// -------------- Fields --------------
if (lookup->property_details().type() == DATA) {
FieldIndex field = lookup->GetFieldIndex();
Handle<Object> smi_handler = SimpleFieldLoad(field);
if (receiver_is_holder) {
return smi_handler;
}
if (FLAG_tf_load_ic_stub && kind() != Code::LOAD_GLOBAL_IC) {
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadFieldFromPrototypeDH);
return LoadFromPrototype(map, holder, lookup->name(), smi_handler);
}
break; // Custom-compiled handler.
}
// -------------- Constant properties --------------
DCHECK(lookup->property_details().type() == DATA_CONSTANT);
if (FLAG_tf_load_ic_stub) {
Handle<Object> smi_handler =
LoadHandler::LoadConstant(isolate(), lookup->GetConstantIndex());
if (receiver_is_holder) {
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadConstantDH);
return smi_handler;
}
if (kind() != Code::LOAD_GLOBAL_IC) {
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadConstantFromPrototypeDH);
return LoadFromPrototype(map, holder, lookup->name(), smi_handler);
}
} else {
if (receiver_is_holder) {
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadConstantStub);
LoadConstantStub stub(isolate(), lookup->GetConstantIndex());
return stub.GetCode();
}
}
break; // Custom-compiled handler.
}
case LookupIterator::INTEGER_INDEXED_EXOTIC:
TRACE_HANDLER_STATS(isolate(), LoadIC_SlowStub);
return slow_stub();
case LookupIterator::ACCESS_CHECK:
case LookupIterator::JSPROXY:
case LookupIterator::NOT_FOUND:
case LookupIterator::TRANSITION:
UNREACHABLE();
}
return Handle<Code>::null();
}
Handle<Object> LoadIC::CompileHandler(LookupIterator* lookup,
Handle<Object> unused,
CacheHolderFlag cache_holder) {
Handle<JSObject> holder = lookup->GetHolder<JSObject>();
#ifdef DEBUG
// Only used by DCHECKs below.
Handle<Object> receiver = lookup->GetReceiver();
bool receiver_is_holder = receiver.is_identical_to(holder);
#endif
// Non-map-specific handler stubs have already been selected.
DCHECK(!receiver->IsString() ||
!Name::Equals(isolate()->factory()->length_string(), lookup->name()));
DCHECK(!receiver->IsStringWrapper() ||
!Name::Equals(isolate()->factory()->length_string(), lookup->name()));
DCHECK(!(
receiver->IsJSFunction() &&
Name::Equals(isolate()->factory()->prototype_string(), lookup->name()) &&
receiver->IsConstructor() &&
!Handle<JSFunction>::cast(receiver)
->map()
->has_non_instance_prototype()));
Handle<Map> map = receiver_map();
switch (lookup->state()) {
case LookupIterator::INTERCEPTOR: {
DCHECK(!holder->GetNamedInterceptor()->getter()->IsUndefined(isolate()));
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadInterceptor);
NamedLoadHandlerCompiler compiler(isolate(), map, holder, cache_holder);
// Perform a lookup behind the interceptor. Copy the LookupIterator since
// the original iterator will be used to fetch the value.
LookupIterator it = *lookup;
it.Next();
LookupForRead(&it);
return compiler.CompileLoadInterceptor(&it);
}
case LookupIterator::ACCESSOR: {
#ifdef DEBUG
int object_offset;
DCHECK(!Accessors::IsJSObjectFieldAccessor(map, lookup->name(),
&object_offset));
#endif
DCHECK(IsCompatibleReceiver(lookup, map));
Handle<Object> accessors = lookup->GetAccessors();
if (accessors->IsAccessorPair()) {
if (lookup->TryLookupCachedProperty()) {
DCHECK_EQ(LookupIterator::DATA, lookup->state());
return ComputeHandler(lookup);
}
DCHECK(holder->HasFastProperties());
DCHECK(!GetSharedFunctionInfo()->HasDebugInfo());
Handle<Object> getter(Handle<AccessorPair>::cast(accessors)->getter(),
isolate());
CallOptimization call_optimization(getter);
NamedLoadHandlerCompiler compiler(isolate(), map, holder, cache_holder);
if (call_optimization.is_simple_api_call()) {
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadCallback);
int index = lookup->GetAccessorIndex();
Handle<Code> code = compiler.CompileLoadCallback(
lookup->name(), call_optimization, index, slow_stub());
return code;
}
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadViaGetter);
int expected_arguments = Handle<JSFunction>::cast(getter)
->shared()
->internal_formal_parameter_count();
return compiler.CompileLoadViaGetter(
lookup->name(), lookup->GetAccessorIndex(), expected_arguments);
} else {
DCHECK(accessors->IsAccessorInfo());
Handle<AccessorInfo> info = Handle<AccessorInfo>::cast(accessors);
DCHECK(v8::ToCData<Address>(info->getter()) != nullptr);
DCHECK(AccessorInfo::IsCompatibleReceiverMap(isolate(), info, map));
DCHECK(holder->HasFastProperties());
DCHECK(!receiver_is_holder);
DCHECK(!info->is_sloppy() || receiver->IsJSReceiver());
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadCallback);
NamedLoadHandlerCompiler compiler(isolate(), map, holder, cache_holder);
Handle<Code> code =
compiler.CompileLoadCallback(lookup->name(), info, slow_stub());
return code;
}
UNREACHABLE();
}
case LookupIterator::DATA: {
if (lookup->is_dictionary_holder()) {
DCHECK(kind() == Code::LOAD_IC || kind() == Code::LOAD_GLOBAL_IC);
DCHECK(holder->IsJSGlobalObject());
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadGlobal);
NamedLoadHandlerCompiler compiler(isolate(), map, holder, cache_holder);
Handle<PropertyCell> cell = lookup->GetPropertyCell();
Handle<Code> code = compiler.CompileLoadGlobal(
cell, lookup->name(), lookup->IsConfigurable());
return code;
}
// -------------- Fields --------------
if (lookup->property_details().type() == DATA) {
FieldIndex field = lookup->GetFieldIndex();
DCHECK(!receiver_is_holder);
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadField);
NamedLoadHandlerCompiler compiler(isolate(), map, holder, cache_holder);
return compiler.CompileLoadField(lookup->name(), field);
}
// -------------- Constant properties --------------
DCHECK(lookup->property_details().type() == DATA_CONSTANT);
DCHECK(!receiver_is_holder);
TRACE_HANDLER_STATS(isolate(), LoadIC_LoadConstant);
NamedLoadHandlerCompiler compiler(isolate(), map, holder, cache_holder);
return compiler.CompileLoadConstant(lookup->name(),
lookup->GetConstantIndex());
}
case LookupIterator::INTEGER_INDEXED_EXOTIC:
case LookupIterator::ACCESS_CHECK:
case LookupIterator::JSPROXY:
case LookupIterator::NOT_FOUND:
case LookupIterator::TRANSITION:
UNREACHABLE();
}
UNREACHABLE();
return slow_stub();
}
static Handle<Object> TryConvertKey(Handle<Object> key, Isolate* isolate) {
// This helper implements a few common fast cases for converting
// non-smi keys of keyed loads/stores to a smi or a string.
if (key->IsHeapNumber()) {
double value = Handle<HeapNumber>::cast(key)->value();
if (std::isnan(value)) {
key = isolate->factory()->nan_string();
} else {
int int_value = FastD2I(value);
if (value == int_value && Smi::IsValid(int_value)) {
key = handle(Smi::FromInt(int_value), isolate);
}
}
} else if (key->IsUndefined(isolate)) {
key = isolate->factory()->undefined_string();
}
return key;
}
void KeyedLoadIC::UpdateLoadElement(Handle<HeapObject> receiver) {
Handle<Map> receiver_map(receiver->map(), isolate());
DCHECK(receiver_map->instance_type() != JS_VALUE_TYPE &&
receiver_map->instance_type() != JS_PROXY_TYPE); // Checked by caller.
MapHandleList target_receiver_maps;
TargetMaps(&target_receiver_maps);
if (target_receiver_maps.length() == 0) {
Handle<Object> handler =
ElementHandlerCompiler::GetKeyedLoadHandler(receiver_map, isolate());
return ConfigureVectorState(Handle<Name>(), receiver_map, handler);
}
for (int i = 0; i < target_receiver_maps.length(); i++) {
Handle<Map> map = target_receiver_maps.at(i);
if (map.is_null()) continue;
if (map->instance_type() == JS_VALUE_TYPE) {
TRACE_GENERIC_IC(isolate(), "KeyedLoadIC", "JSValue");
return;
}
if (map->instance_type() == JS_PROXY_TYPE) {
TRACE_GENERIC_IC(isolate(), "KeyedLoadIC", "JSProxy");
return;
}
}
// The first time a receiver is seen that is a transitioned version of the
// previous monomorphic receiver type, assume the new ElementsKind is the
// monomorphic type. This benefits global arrays that only transition
// once, and all call sites accessing them are faster if they remain
// monomorphic. If this optimistic assumption is not true, the IC will
// miss again and it will become polymorphic and support both the
// untransitioned and transitioned maps.
if (state() == MONOMORPHIC && !receiver->IsString() &&
IsMoreGeneralElementsKindTransition(
target_receiver_maps.at(0)->elements_kind(),
Handle<JSObject>::cast(receiver)->GetElementsKind())) {
Handle<Object> handler =
ElementHandlerCompiler::GetKeyedLoadHandler(receiver_map, isolate());
return ConfigureVectorState(Handle<Name>(), receiver_map, handler);
}
DCHECK(state() != GENERIC);
// Determine the list of receiver maps that this call site has seen,
// adding the map that was just encountered.
if (!AddOneReceiverMapIfMissing(&target_receiver_maps, receiver_map)) {
// If the miss wasn't due to an unseen map, a polymorphic stub
// won't help, use the generic stub.
TRACE_GENERIC_IC(isolate(), "KeyedLoadIC", "same map added twice");
return;
}
// If the maximum number of receiver maps has been exceeded, use the generic
// version of the IC.
if (target_receiver_maps.length() > kMaxKeyedPolymorphism) {
TRACE_GENERIC_IC(isolate(), "KeyedLoadIC", "max polymorph exceeded");
return;
}
List<Handle<Object>> handlers(target_receiver_maps.length());
ElementHandlerCompiler compiler(isolate());
compiler.CompileElementHandlers(&target_receiver_maps, &handlers);
ConfigureVectorState(Handle<Name>(), &target_receiver_maps, &handlers);
}
MaybeHandle<Object> KeyedLoadIC::Load(Handle<Object> object,
Handle<Object> key) {
if (MigrateDeprecated(object)) {
Handle<Object> result;
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result, Runtime::GetObjectProperty(isolate(), object, key),
Object);
return result;
}
Handle<Object> load_handle;
// Check for non-string values that can be converted into an
// internalized string directly or is representable as a smi.
key = TryConvertKey(key, isolate());
uint32_t index;
if ((key->IsInternalizedString() &&
!String::cast(*key)->AsArrayIndex(&index)) ||
key->IsSymbol()) {
ASSIGN_RETURN_ON_EXCEPTION(isolate(), load_handle,
LoadIC::Load(object, Handle<Name>::cast(key)),
Object);
} else if (FLAG_use_ic && !object->IsAccessCheckNeeded() &&
!object->IsJSValue()) {
if ((object->IsJSObject() && key->IsSmi()) ||
(object->IsString() && key->IsNumber())) {
UpdateLoadElement(Handle<HeapObject>::cast(object));
if (is_vector_set()) {
TRACE_IC("LoadIC", key);
}
}
}
if (!is_vector_set()) {
ConfigureVectorState(MEGAMORPHIC, key);
TRACE_GENERIC_IC(isolate(), "KeyedLoadIC", "set generic");
TRACE_IC("LoadIC", key);
}
if (!load_handle.is_null()) return load_handle;
Handle<Object> result;
ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
Runtime::GetObjectProperty(isolate(), object, key),
Object);
return result;
}
bool StoreIC::LookupForWrite(LookupIterator* it, Handle<Object> value,
JSReceiver::StoreFromKeyed store_mode) {
// Disable ICs for non-JSObjects for now.
Handle<Object> object = it->GetReceiver();
if (!object->IsJSObject()) return false;
Handle<JSObject> receiver = Handle<JSObject>::cast(object);
DCHECK(!receiver->map()->is_deprecated());
for (; it->IsFound(); it->Next()) {
switch (it->state()) {
case LookupIterator::NOT_FOUND:
case LookupIterator::TRANSITION:
UNREACHABLE();
case LookupIterator::JSPROXY:
return false;
case LookupIterator::INTERCEPTOR: {
Handle<JSObject> holder = it->GetHolder<JSObject>();
InterceptorInfo* info = holder->GetNamedInterceptor();
if (it->HolderIsReceiverOrHiddenPrototype()) {
return !info->non_masking() && receiver.is_identical_to(holder) &&
!info->setter()->IsUndefined(it->isolate());
} else if (!info->getter()->IsUndefined(it->isolate()) ||
!info->query()->IsUndefined(it->isolate())) {
return false;
}
break;
}
case LookupIterator::ACCESS_CHECK:
if (it->GetHolder<JSObject>()->IsAccessCheckNeeded()) return false;
break;
case LookupIterator::ACCESSOR:
return !it->IsReadOnly();
case LookupIterator::INTEGER_INDEXED_EXOTIC:
return false;
case LookupIterator::DATA: {
if (it->IsReadOnly()) return false;
Handle<JSObject> holder = it->GetHolder<JSObject>();
if (receiver.is_identical_to(holder)) {
it->PrepareForDataProperty(value);
// The previous receiver map might just have been deprecated,
// so reload it.
update_receiver_map(receiver);
return true;
}
// Receiver != holder.
if (receiver->IsJSGlobalProxy()) {
PrototypeIterator iter(it->isolate(), receiver);
return it->GetHolder<Object>().is_identical_to(
PrototypeIterator::GetCurrent(iter));
}
if (it->HolderIsReceiverOrHiddenPrototype()) return false;
if (it->ExtendingNonExtensible(receiver)) return false;
it->PrepareTransitionToDataProperty(receiver, value, NONE, store_mode);
return it->IsCacheableTransition();
}
}
}
receiver = it->GetStoreTarget();
if (it->ExtendingNonExtensible(receiver)) return false;
it->PrepareTransitionToDataProperty(receiver, value, NONE, store_mode);
return it->IsCacheableTransition();
}
MaybeHandle<Object> StoreIC::Store(Handle<Object> object, Handle<Name> name,
Handle<Object> value,
JSReceiver::StoreFromKeyed store_mode) {
if (object->IsJSGlobalObject() && name->IsString()) {
// Look up in script context table.
Handle<String> str_name = Handle<String>::cast(name);
Handle<JSGlobalObject> global = Handle<JSGlobalObject>::cast(object);
Handle<ScriptContextTable> script_contexts(
global->native_context()->script_context_table());
ScriptContextTable::LookupResult lookup_result;
if (ScriptContextTable::Lookup(script_contexts, str_name, &lookup_result)) {
Handle<Context> script_context = ScriptContextTable::GetContext(
script_contexts, lookup_result.context_index);
if (lookup_result.mode == CONST) {
return TypeError(MessageTemplate::kConstAssign, object, name);
}
Handle<Object> previous_value =
FixedArray::get(*script_context, lookup_result.slot_index, isolate());
if (previous_value->IsTheHole(isolate())) {
// Do not install stubs and stay pre-monomorphic for
// uninitialized accesses.
return ReferenceError(name);
}
if (FLAG_use_ic &&
StoreScriptContextFieldStub::Accepted(&lookup_result)) {
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreScriptContextFieldStub);
StoreScriptContextFieldStub stub(isolate(), &lookup_result);
PatchCache(name, stub.GetCode());
}
script_context->set(lookup_result.slot_index, *value);
return value;
}
}
// TODO(verwaest): Let SetProperty do the migration, since storing a property
// might deprecate the current map again, if value does not fit.
if (MigrateDeprecated(object) || object->IsJSProxy()) {
Handle<Object> result;
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result,
Object::SetProperty(object, name, value, language_mode()), Object);
return result;
}
// If the object is undefined or null it's illegal to try to set any
// properties on it; throw a TypeError in that case.
if (object->IsUndefined(isolate()) || object->IsNull(isolate())) {
return TypeError(MessageTemplate::kNonObjectPropertyStore, object, name);
}
if (state() != UNINITIALIZED) {
JSObject::MakePrototypesFast(object, kStartAtPrototype, isolate());
}
LookupIterator it(object, name);
if (FLAG_use_ic) UpdateCaches(&it, value, store_mode);
MAYBE_RETURN_NULL(
Object::SetProperty(&it, value, language_mode(), store_mode));
return value;
}
void StoreIC::UpdateCaches(LookupIterator* lookup, Handle<Object> value,
JSReceiver::StoreFromKeyed store_mode) {
if (state() == UNINITIALIZED) {
// This is the first time we execute this inline cache. Set the target to
// the pre monomorphic stub to delay setting the monomorphic state.
TRACE_HANDLER_STATS(isolate(), StoreIC_Premonomorphic);
ConfigureVectorState(PREMONOMORPHIC, Handle<Object>());
TRACE_IC("StoreIC", lookup->name());
return;
}
bool use_ic = LookupForWrite(lookup, value, store_mode);
if (!use_ic) {
TRACE_GENERIC_IC(isolate(), "StoreIC", "LookupForWrite said 'false'");
}
Handle<Object> handler = use_ic ? ComputeHandler(lookup, value)
: Handle<Object>::cast(slow_stub());
PatchCache(lookup->name(), handler);
TRACE_IC("StoreIC", lookup->name());
}
Handle<Object> StoreIC::StoreTransition(Handle<Map> receiver_map,
Handle<JSObject> holder,
Handle<Map> transition,
Handle<Name> name) {
int descriptor = transition->LastAdded();
Handle<DescriptorArray> descriptors(transition->instance_descriptors());
PropertyDetails details = descriptors->GetDetails(descriptor);
Representation representation = details.representation();
DCHECK(!representation.IsNone());
// Declarative handlers don't support access checks.
DCHECK(!transition->is_access_check_needed());
Handle<Object> smi_handler;
if (details.type() == DATA_CONSTANT) {
smi_handler = StoreHandler::TransitionToConstant(isolate(), descriptor);
} else {
DCHECK_EQ(DATA, details.type());
bool extend_storage =
Map::cast(transition->GetBackPointer())->unused_property_fields() == 0;
FieldIndex index = FieldIndex::ForDescriptor(*transition, descriptor);
smi_handler = StoreHandler::TransitionToField(
isolate(), descriptor, index, representation, extend_storage);
}
int checks_count = GetPrototypeCheckCount(isolate(), receiver_map, holder);
DCHECK_LE(0, checks_count);
DCHECK(!receiver_map->IsJSGlobalObjectMap());
Handle<Object> validity_cell =
Map::GetOrCreatePrototypeChainValidityCell(receiver_map, isolate());
if (validity_cell.is_null()) {
// This must be a case when receiver's prototype is null.
DCHECK_EQ(*isolate()->factory()->null_value(),
receiver_map->GetPrototypeChainRootMap(isolate())->prototype());
DCHECK_EQ(0, checks_count);
validity_cell = handle(Smi::FromInt(0), isolate());
}
Handle<WeakCell> transition_cell = Map::WeakCellForMap(transition);
Factory* factory = isolate()->factory();
if (checks_count == 0) {
return factory->NewTuple3(transition_cell, smi_handler, validity_cell);
}
Handle<FixedArray> handler_array(factory->NewFixedArray(
StoreHandler::kFirstPrototypeIndex + checks_count, TENURED));
handler_array->set(StoreHandler::kSmiHandlerIndex, *smi_handler);
handler_array->set(StoreHandler::kValidityCellIndex, *validity_cell);
handler_array->set(StoreHandler::kTransitionCellIndex, *transition_cell);
InitPrototypeChecks(isolate(), receiver_map, holder, handler_array, name,
StoreHandler::kFirstPrototypeIndex);
return handler_array;
}
static Handle<Code> PropertyCellStoreHandler(
Isolate* isolate, Handle<JSObject> receiver, Handle<JSGlobalObject> holder,
Handle<Name> name, Handle<PropertyCell> cell, PropertyCellType type) {
auto constant_type = Nothing<PropertyCellConstantType>();
if (type == PropertyCellType::kConstantType) {
constant_type = Just(cell->GetConstantType());
}
StoreGlobalStub stub(isolate, type, constant_type,
receiver->IsJSGlobalProxy());
auto code = stub.GetCodeCopyFromTemplate(holder, cell);
// TODO(verwaest): Move caching of these NORMAL stubs outside as well.
HeapObject::UpdateMapCodeCache(receiver, name, code);
return code;
}
Handle<Object> StoreIC::GetMapIndependentHandler(LookupIterator* lookup) {
DCHECK_NE(LookupIterator::JSPROXY, lookup->state());
// This is currently guaranteed by checks in StoreIC::Store.
Handle<JSObject> receiver = Handle<JSObject>::cast(lookup->GetReceiver());
Handle<JSObject> holder = lookup->GetHolder<JSObject>();
DCHECK(!receiver->IsAccessCheckNeeded() || lookup->name()->IsPrivate());
switch (lookup->state()) {
case LookupIterator::TRANSITION: {
auto store_target = lookup->GetStoreTarget();
if (store_target->IsJSGlobalObject()) {
break; // Custom-compiled handler.
}
// Currently not handled by CompileStoreTransition.
if (!holder->HasFastProperties()) {
TRACE_GENERIC_IC(isolate(), "StoreIC", "transition from slow");
TRACE_HANDLER_STATS(isolate(), StoreIC_SlowStub);
return slow_stub();
}
DCHECK(lookup->IsCacheableTransition());
if (FLAG_tf_store_ic_stub) {
Handle<Map> transition = lookup->transition_map();
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreTransitionDH);
return StoreTransition(receiver_map(), holder, transition,
lookup->name());
}
break; // Custom-compiled handler.
}
case LookupIterator::INTERCEPTOR: {
DCHECK(!holder->GetNamedInterceptor()->setter()->IsUndefined(isolate()));
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreInterceptorStub);
StoreInterceptorStub stub(isolate());
return stub.GetCode();
}
case LookupIterator::ACCESSOR: {
if (!holder->HasFastProperties()) {
TRACE_GENERIC_IC(isolate(), "StoreIC", "accessor on slow map");
TRACE_HANDLER_STATS(isolate(), StoreIC_SlowStub);
return slow_stub();
}
Handle<Object> accessors = lookup->GetAccessors();
if (accessors->IsAccessorInfo()) {
Handle<AccessorInfo> info = Handle<AccessorInfo>::cast(accessors);
if (v8::ToCData<Address>(info->setter()) == nullptr) {
TRACE_GENERIC_IC(isolate(), "StoreIC", "setter == nullptr");
TRACE_HANDLER_STATS(isolate(), StoreIC_SlowStub);
return slow_stub();
}
if (AccessorInfo::cast(*accessors)->is_special_data_property() &&
!lookup->HolderIsReceiverOrHiddenPrototype()) {
TRACE_GENERIC_IC(isolate(), "StoreIC",
"special data property in prototype chain");
TRACE_HANDLER_STATS(isolate(), StoreIC_SlowStub);
return slow_stub();
}
if (!AccessorInfo::IsCompatibleReceiverMap(isolate(), info,
receiver_map())) {
TRACE_GENERIC_IC(isolate(), "StoreIC", "incompatible receiver type");
TRACE_HANDLER_STATS(isolate(), StoreIC_SlowStub);
return slow_stub();
}
if (info->is_sloppy() && !receiver->IsJSReceiver()) {
TRACE_HANDLER_STATS(isolate(), StoreIC_SlowStub);
return slow_stub();
}
break; // Custom-compiled handler.
} else if (accessors->IsAccessorPair()) {
Handle<Object> setter(Handle<AccessorPair>::cast(accessors)->setter(),
isolate());
if (!setter->IsJSFunction() && !setter->IsFunctionTemplateInfo()) {
TRACE_GENERIC_IC(isolate(), "StoreIC", "setter not a function");
TRACE_HANDLER_STATS(isolate(), StoreIC_SlowStub);
return slow_stub();
}
CallOptimization call_optimization(setter);
if (call_optimization.is_simple_api_call()) {
if (call_optimization.IsCompatibleReceiver(receiver, holder)) {
break; // Custom-compiled handler.
}
TRACE_GENERIC_IC(isolate(), "StoreIC", "incompatible receiver");
TRACE_HANDLER_STATS(isolate(), StoreIC_SlowStub);
return slow_stub();
}
break; // Custom-compiled handler.
}
TRACE_HANDLER_STATS(isolate(), StoreIC_SlowStub);
return slow_stub();
}
case LookupIterator::DATA: {
if (lookup->is_dictionary_holder()) {
if (holder->IsJSGlobalObject()) {
break; // Custom-compiled handler.
}
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreNormal);
DCHECK(holder.is_identical_to(receiver));
return isolate()->builtins()->StoreIC_Normal();
}
// -------------- Fields --------------
if (lookup->property_details().type() == DATA) {
if (FLAG_tf_store_ic_stub) {
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreFieldDH);
int descriptor = lookup->GetFieldDescriptorIndex();
FieldIndex index = lookup->GetFieldIndex();
return StoreHandler::StoreField(isolate(), descriptor, index,
lookup->representation());
} else {
bool use_stub = true;
if (lookup->representation().IsHeapObject()) {
// Only use a generic stub if no types need to be tracked.
Handle<FieldType> field_type = lookup->GetFieldType();
use_stub = !field_type->IsClass();
}
if (use_stub) {
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreFieldStub);
StoreFieldStub stub(isolate(), lookup->GetFieldIndex(),
lookup->representation());
return stub.GetCode();
}
}
break; // Custom-compiled handler.
}
// -------------- Constant properties --------------
DCHECK(lookup->property_details().type() == DATA_CONSTANT);
TRACE_GENERIC_IC(isolate(), "StoreIC", "constant property");
TRACE_HANDLER_STATS(isolate(), StoreIC_SlowStub);
return slow_stub();
}
case LookupIterator::INTEGER_INDEXED_EXOTIC:
case LookupIterator::ACCESS_CHECK:
case LookupIterator::JSPROXY:
case LookupIterator::NOT_FOUND:
UNREACHABLE();
}
return Handle<Code>::null();
}
Handle<Object> StoreIC::CompileHandler(LookupIterator* lookup,
Handle<Object> value,
CacheHolderFlag cache_holder) {
DCHECK_NE(LookupIterator::JSPROXY, lookup->state());
// This is currently guaranteed by checks in StoreIC::Store.
Handle<JSObject> receiver = Handle<JSObject>::cast(lookup->GetReceiver());
Handle<JSObject> holder = lookup->GetHolder<JSObject>();
DCHECK(!receiver->IsAccessCheckNeeded() || lookup->name()->IsPrivate());
switch (lookup->state()) {
case LookupIterator::TRANSITION: {
auto store_target = lookup->GetStoreTarget();
if (store_target->IsJSGlobalObject()) {
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreGlobalTransition);
Handle<PropertyCell> cell = lookup->transition_cell();
cell->set_value(*value);
Handle<Code> code = PropertyCellStoreHandler(
isolate(), store_target, Handle<JSGlobalObject>::cast(store_target),
lookup->name(), cell, PropertyCellType::kConstant);
cell->set_value(isolate()->heap()->the_hole_value());
return code;
}
DCHECK(!FLAG_tf_store_ic_stub);
Handle<Map> transition = lookup->transition_map();
// Currently not handled by CompileStoreTransition.
DCHECK(holder->HasFastProperties());
DCHECK(lookup->IsCacheableTransition());
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreTransition);
NamedStoreHandlerCompiler compiler(isolate(), receiver_map(), holder);
return compiler.CompileStoreTransition(transition, lookup->name());
}
case LookupIterator::INTERCEPTOR:
UNREACHABLE();
case LookupIterator::ACCESSOR: {
DCHECK(holder->HasFastProperties());
Handle<Object> accessors = lookup->GetAccessors();
if (accessors->IsAccessorInfo()) {
Handle<AccessorInfo> info = Handle<AccessorInfo>::cast(accessors);
DCHECK(v8::ToCData<Address>(info->setter()) != 0);
DCHECK(!AccessorInfo::cast(*accessors)->is_special_data_property() ||
lookup->HolderIsReceiverOrHiddenPrototype());
DCHECK(AccessorInfo::IsCompatibleReceiverMap(isolate(), info,
receiver_map()));
DCHECK(!info->is_sloppy() || receiver->IsJSReceiver());
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreCallback);
NamedStoreHandlerCompiler compiler(isolate(), receiver_map(), holder);
Handle<Code> code = compiler.CompileStoreCallback(
receiver, lookup->name(), info, language_mode());
return code;
} else {
DCHECK(accessors->IsAccessorPair());
Handle<Object> setter(Handle<AccessorPair>::cast(accessors)->setter(),
isolate());
DCHECK(setter->IsJSFunction() || setter->IsFunctionTemplateInfo());
CallOptimization call_optimization(setter);
NamedStoreHandlerCompiler compiler(isolate(), receiver_map(), holder);
if (call_optimization.is_simple_api_call()) {
DCHECK(call_optimization.IsCompatibleReceiver(receiver, holder));
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreCallback);
Handle<Code> code = compiler.CompileStoreCallback(
receiver, lookup->name(), call_optimization,
lookup->GetAccessorIndex(), slow_stub());
return code;
}
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreViaSetter);
int expected_arguments = JSFunction::cast(*setter)
->shared()
->internal_formal_parameter_count();
return compiler.CompileStoreViaSetter(receiver, lookup->name(),
lookup->GetAccessorIndex(),
expected_arguments);
}
}
case LookupIterator::DATA: {
if (lookup->is_dictionary_holder()) {
DCHECK(holder->IsJSGlobalObject());
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreGlobal);
DCHECK(holder.is_identical_to(receiver) ||
receiver->map()->prototype() == *holder);
auto cell = lookup->GetPropertyCell();
auto updated_type =
PropertyCell::UpdatedType(cell, value, lookup->property_details());
auto code = PropertyCellStoreHandler(
isolate(), receiver, Handle<JSGlobalObject>::cast(holder),
lookup->name(), cell, updated_type);
return code;
}
// -------------- Fields --------------
if (lookup->property_details().type() == DATA) {
DCHECK(!FLAG_tf_store_ic_stub);
#ifdef DEBUG
bool use_stub = true;
if (lookup->representation().IsHeapObject()) {
// Only use a generic stub if no types need to be tracked.
Handle<FieldType> field_type = lookup->GetFieldType();
use_stub = !field_type->IsClass();
}
DCHECK(!use_stub);
#endif
TRACE_HANDLER_STATS(isolate(), StoreIC_StoreField);
NamedStoreHandlerCompiler compiler(isolate(), receiver_map(), holder);
return compiler.CompileStoreField(lookup);
}
// -------------- Constant properties --------------
DCHECK(lookup->property_details().type() == DATA_CONSTANT);
UNREACHABLE();
}
case LookupIterator::INTEGER_INDEXED_EXOTIC:
case LookupIterator::ACCESS_CHECK:
case LookupIterator::JSPROXY:
case LookupIterator::NOT_FOUND:
UNREACHABLE();
}
UNREACHABLE();
return slow_stub();
}
void KeyedStoreIC::UpdateStoreElement(Handle<Map> receiver_map,
KeyedAccessStoreMode store_mode) {
MapHandleList target_receiver_maps;
TargetMaps(&target_receiver_maps);
if (target_receiver_maps.length() == 0) {
Handle<Map> monomorphic_map =
ComputeTransitionedMap(receiver_map, store_mode);
store_mode = GetNonTransitioningStoreMode(store_mode);
Handle<Code> handler =
PropertyICCompiler::ComputeKeyedStoreMonomorphicHandler(monomorphic_map,
store_mode);
return ConfigureVectorState(Handle<Name>(), monomorphic_map, handler);
}
for (int i = 0; i < target_receiver_maps.length(); i++) {
if (!target_receiver_maps.at(i).is_null() &&
target_receiver_maps.at(i)->instance_type() == JS_VALUE_TYPE) {
TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "JSValue");
return;
}
}
// There are several special cases where an IC that is MONOMORPHIC can still
// transition to a different GetNonTransitioningStoreMode IC that handles a
// superset of the original IC. Handle those here if the receiver map hasn't
// changed or it has transitioned to a more general kind.
KeyedAccessStoreMode old_store_mode = GetKeyedAccessStoreMode();
Handle<Map> previous_receiver_map = target_receiver_maps.at(0);
if (state() == MONOMORPHIC) {
Handle<Map> transitioned_receiver_map = receiver_map;
if (IsTransitionStoreMode(store_mode)) {
transitioned_receiver_map =
ComputeTransitionedMap(receiver_map, store_mode);
}
if ((receiver_map.is_identical_to(previous_receiver_map) &&
IsTransitionStoreMode(store_mode)) ||
IsTransitionOfMonomorphicTarget(*previous_receiver_map,
*transitioned_receiver_map)) {
// If the "old" and "new" maps are in the same elements map family, or
// if they at least come from the same origin for a transitioning store,
// stay MONOMORPHIC and use the map for the most generic ElementsKind.
store_mode = GetNonTransitioningStoreMode(store_mode);
Handle<Code> handler =
PropertyICCompiler::ComputeKeyedStoreMonomorphicHandler(
transitioned_receiver_map, store_mode);
ConfigureVectorState(Handle<Name>(), transitioned_receiver_map, handler);
return;
}
if (receiver_map.is_identical_to(previous_receiver_map) &&
old_store_mode == STANDARD_STORE &&
(store_mode == STORE_AND_GROW_NO_TRANSITION ||
store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS ||
store_mode == STORE_NO_TRANSITION_HANDLE_COW)) {
// A "normal" IC that handles stores can switch to a version that can
// grow at the end of the array, handle OOB accesses or copy COW arrays
// and still stay MONOMORPHIC.
Handle<Code> handler =
PropertyICCompiler::ComputeKeyedStoreMonomorphicHandler(receiver_map,
store_mode);
return ConfigureVectorState(Handle<Name>(), receiver_map, handler);
}
}
DCHECK(state() != GENERIC);
bool map_added =
AddOneReceiverMapIfMissing(&target_receiver_maps, receiver_map);
if (IsTransitionStoreMode(store_mode)) {
Handle<Map> transitioned_receiver_map =
ComputeTransitionedMap(receiver_map, store_mode);
map_added |= AddOneReceiverMapIfMissing(&target_receiver_maps,
transitioned_receiver_map);
}
if (!map_added) {
// If the miss wasn't due to an unseen map, a polymorphic stub
// won't help, use the megamorphic stub which can handle everything.
TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "same map added twice");
return;
}
// If the maximum number of receiver maps has been exceeded, use the
// megamorphic version of the IC.
if (target_receiver_maps.length() > kMaxKeyedPolymorphism) return;
// Make sure all polymorphic handlers have the same store mode, otherwise the
// megamorphic stub must be used.
store_mode = GetNonTransitioningStoreMode(store_mode);
if (old_store_mode != STANDARD_STORE) {
if (store_mode == STANDARD_STORE) {
store_mode = old_store_mode;
} else if (store_mode != old_store_mode) {
TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "store mode mismatch");
return;
}
}
// If the store mode isn't the standard mode, make sure that all polymorphic
// receivers are either external arrays, or all "normal" arrays. Otherwise,
// use the megamorphic stub.
if (store_mode != STANDARD_STORE) {
int external_arrays = 0;
for (int i = 0; i < target_receiver_maps.length(); ++i) {
if (target_receiver_maps[i]->has_fixed_typed_array_elements()) {
external_arrays++;
}
}
if (external_arrays != 0 &&
external_arrays != target_receiver_maps.length()) {
TRACE_GENERIC_IC(isolate(), "KeyedStoreIC",
"unsupported combination of external and normal arrays");
return;
}
}
MapHandleList transitioned_maps(target_receiver_maps.length());
CodeHandleList handlers(target_receiver_maps.length());
PropertyICCompiler::ComputeKeyedStorePolymorphicHandlers(
&target_receiver_maps, &transitioned_maps, &handlers, store_mode);
ConfigureVectorState(&target_receiver_maps, &transitioned_maps, &handlers);
}
Handle<Map> KeyedStoreIC::ComputeTransitionedMap(
Handle<Map> map, KeyedAccessStoreMode store_mode) {
switch (store_mode) {
case STORE_TRANSITION_TO_OBJECT:
case STORE_AND_GROW_TRANSITION_TO_OBJECT: {
ElementsKind kind = IsFastHoleyElementsKind(map->elements_kind())
? FAST_HOLEY_ELEMENTS
: FAST_ELEMENTS;
return Map::TransitionElementsTo(map, kind);
}
case STORE_TRANSITION_TO_DOUBLE:
case STORE_AND_GROW_TRANSITION_TO_DOUBLE: {
ElementsKind kind = IsFastHoleyElementsKind(map->elements_kind())
? FAST_HOLEY_DOUBLE_ELEMENTS
: FAST_DOUBLE_ELEMENTS;
return Map::TransitionElementsTo(map, kind);
}
case STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS:
DCHECK(map->has_fixed_typed_array_elements());
// Fall through
case STORE_NO_TRANSITION_HANDLE_COW:
case STANDARD_STORE:
case STORE_AND_GROW_NO_TRANSITION:
return map;
}
UNREACHABLE();
return MaybeHandle<Map>().ToHandleChecked();
}
bool IsOutOfBoundsAccess(Handle<JSObject> receiver, uint32_t index) {
uint32_t length = 0;
if (receiver->IsJSArray()) {
JSArray::cast(*receiver)->length()->ToArrayLength(&length);
} else {
length = static_cast<uint32_t>(receiver->elements()->length());
}
return index >= length;
}
static KeyedAccessStoreMode GetStoreMode(Handle<JSObject> receiver,
uint32_t index, Handle<Object> value) {
bool oob_access = IsOutOfBoundsAccess(receiver, index);
// Don't consider this a growing store if the store would send the receiver to
// dictionary mode.
bool allow_growth = receiver->IsJSArray() && oob_access &&
!receiver->WouldConvertToSlowElements(index);
if (allow_growth) {
// Handle growing array in stub if necessary.
if (receiver->HasFastSmiElements()) {
if (value->IsHeapNumber()) {
return STORE_AND_GROW_TRANSITION_TO_DOUBLE;
}
if (value->IsHeapObject()) {
return STORE_AND_GROW_TRANSITION_TO_OBJECT;
}
} else if (receiver->HasFastDoubleElements()) {
if (!value->IsSmi() && !value->IsHeapNumber()) {
return STORE_AND_GROW_TRANSITION_TO_OBJECT;
}
}
return STORE_AND_GROW_NO_TRANSITION;
} else {
// Handle only in-bounds elements accesses.
if (receiver->HasFastSmiElements()) {
if (value->IsHeapNumber()) {
return STORE_TRANSITION_TO_DOUBLE;
} else if (value->IsHeapObject()) {
return STORE_TRANSITION_TO_OBJECT;
}
} else if (receiver->HasFastDoubleElements()) {
if (!value->IsSmi() && !value->IsHeapNumber()) {
return STORE_TRANSITION_TO_OBJECT;
}
}
if (!FLAG_trace_external_array_abuse &&
receiver->map()->has_fixed_typed_array_elements() && oob_access) {
return STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS;
}
Heap* heap = receiver->GetHeap();
if (receiver->elements()->map() == heap->fixed_cow_array_map()) {
return STORE_NO_TRANSITION_HANDLE_COW;
} else {
return STANDARD_STORE;
}
}
}
MaybeHandle<Object> KeyedStoreIC::Store(Handle<Object> object,
Handle<Object> key,
Handle<Object> value) {
// TODO(verwaest): Let SetProperty do the migration, since storing a property
// might deprecate the current map again, if value does not fit.
if (MigrateDeprecated(object)) {
Handle<Object> result;
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result, Runtime::SetObjectProperty(isolate(), object, key,
value, language_mode()),
Object);
return result;
}
// Check for non-string values that can be converted into an
// internalized string directly or is representable as a smi.
key = TryConvertKey(key, isolate());
Handle<Object> store_handle;
uint32_t index;
if ((key->IsInternalizedString() &&
!String::cast(*key)->AsArrayIndex(&index)) ||
key->IsSymbol()) {
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), store_handle,
StoreIC::Store(object, Handle<Name>::cast(key), value,
JSReceiver::MAY_BE_STORE_FROM_KEYED),
Object);
if (!is_vector_set()) {
ConfigureVectorState(MEGAMORPHIC, key);
TRACE_GENERIC_IC(isolate(), "KeyedStoreIC",
"unhandled internalized string key");
TRACE_IC("StoreIC", key);
}
return store_handle;
}
bool use_ic = FLAG_use_ic && !object->IsStringWrapper() &&
!object->IsAccessCheckNeeded() && !object->IsJSGlobalProxy();
if (use_ic && !object->IsSmi()) {
// Don't use ICs for maps of the objects in Array's prototype chain. We
// expect to be able to trap element sets to objects with those maps in
// the runtime to enable optimization of element hole access.
Handle<HeapObject> heap_object = Handle<HeapObject>::cast(object);
if (heap_object->map()->IsMapInArrayPrototypeChain()) {
TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "map in array prototype");
use_ic = false;
}
}
Handle<Map> old_receiver_map;
bool sloppy_arguments_elements = false;
bool key_is_valid_index = false;
KeyedAccessStoreMode store_mode = STANDARD_STORE;
if (use_ic && object->IsJSObject()) {
Handle<JSObject> receiver = Handle<JSObject>::cast(object);
old_receiver_map = handle(receiver->map(), isolate());
sloppy_arguments_elements =
!is_sloppy(language_mode()) &&
receiver->elements()->map() ==
isolate()->heap()->sloppy_arguments_elements_map();
if (!sloppy_arguments_elements) {
key_is_valid_index = key->IsSmi() && Smi::cast(*key)->value() >= 0;
if (key_is_valid_index) {
uint32_t index = static_cast<uint32_t>(Smi::cast(*key)->value());
store_mode = GetStoreMode(receiver, index, value);
}
}
}
DCHECK(store_handle.is_null());
ASSIGN_RETURN_ON_EXCEPTION(isolate(), store_handle,
Runtime::SetObjectProperty(isolate(), object, key,
value, language_mode()),
Object);
if (use_ic) {
if (!old_receiver_map.is_null()) {
if (sloppy_arguments_elements) {
TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "arguments receiver");
} else if (key_is_valid_index) {
// We should go generic if receiver isn't a dictionary, but our
// prototype chain does have dictionary elements. This ensures that
// other non-dictionary receivers in the polymorphic case benefit
// from fast path keyed stores.
if (!old_receiver_map->DictionaryElementsInPrototypeChainOnly()) {
UpdateStoreElement(old_receiver_map, store_mode);
} else {
TRACE_GENERIC_IC(isolate(), "KeyedStoreIC",
"dictionary or proxy prototype");
}
} else {
TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "non-smi-like key");
}
} else {
TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "non-JSObject receiver");
}
}
if (!is_vector_set()) {
ConfigureVectorState(MEGAMORPHIC, key);
TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "set generic");
}
TRACE_IC("StoreIC", key);
return store_handle;
}
void CallIC::HandleMiss(Handle<Object> function) {
Handle<Object> name = isolate()->factory()->empty_string();
CallICNexus* nexus = casted_nexus<CallICNexus>();
Object* feedback = nexus->GetFeedback();
// Hand-coded MISS handling is easier if CallIC slots don't contain smis.
DCHECK(!feedback->IsSmi());
if (feedback->IsWeakCell() || !function->IsJSFunction() ||
feedback->IsAllocationSite()) {
// We are going generic.
nexus->ConfigureMegamorphic();
} else {
DCHECK(feedback == *TypeFeedbackVector::UninitializedSentinel(isolate()));
Handle<JSFunction> js_function = Handle<JSFunction>::cast(function);
Handle<JSFunction> array_function =
Handle<JSFunction>(isolate()->native_context()->array_function());
if (array_function.is_identical_to(js_function)) {
// Alter the slot.
nexus->ConfigureMonomorphicArray();
} else if (js_function->context()->native_context() !=
*isolate()->native_context()) {
// Don't collect cross-native context feedback for the CallIC.
// TODO(bmeurer): We should collect the SharedFunctionInfo as
// feedback in this case instead.
nexus->ConfigureMegamorphic();
} else {
nexus->ConfigureMonomorphic(js_function);
}
}
if (function->IsJSFunction()) {
Handle<JSFunction> js_function = Handle<JSFunction>::cast(function);
name = handle(js_function->shared()->name(), isolate());
}
OnTypeFeedbackChanged(isolate(), get_host());
TRACE_IC("CallIC", name);
}
#undef TRACE_IC
// ----------------------------------------------------------------------------
// Static IC stub generators.
//
// Used from ic-<arch>.cc.
RUNTIME_FUNCTION(Runtime_CallIC_Miss) {
HandleScope scope(isolate);
DCHECK_EQ(3, args.length());
// Runtime functions don't follow the IC's calling convention.
Handle<Object> function = args.at<Object>(0);
Handle<TypeFeedbackVector> vector = args.at<TypeFeedbackVector>(1);
Handle<Smi> slot = args.at<Smi>(2);
FeedbackVectorSlot vector_slot = vector->ToSlot(slot->value());
CallICNexus nexus(vector, vector_slot);
CallIC ic(isolate, &nexus);
ic.HandleMiss(function);
return *function;
}
// Used from ic-<arch>.cc.
RUNTIME_FUNCTION(Runtime_LoadIC_Miss) {
HandleScope scope(isolate);
DCHECK_EQ(4, args.length());
// Runtime functions don't follow the IC's calling convention.
Handle<Object> receiver = args.at<Object>(0);
Handle<Smi> slot = args.at<Smi>(2);
Handle<TypeFeedbackVector> vector = args.at<TypeFeedbackVector>(3);
FeedbackVectorSlot vector_slot = vector->ToSlot(slot->value());
// A monomorphic or polymorphic KeyedLoadIC with a string key can call the
// LoadIC miss handler if the handler misses. Since the vector Nexus is
// set up outside the IC, handle that here.
FeedbackVectorSlotKind kind = vector->GetKind(vector_slot);
if (kind == FeedbackVectorSlotKind::LOAD_IC) {
Handle<Name> key = args.at<Name>(1);
LoadICNexus nexus(vector, vector_slot);
LoadIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
ic.UpdateState(receiver, key);
RETURN_RESULT_OR_FAILURE(isolate, ic.Load(receiver, key));
} else if (kind == FeedbackVectorSlotKind::LOAD_GLOBAL_IC) {
Handle<Name> key(vector->GetName(vector_slot), isolate);
DCHECK_NE(*key, isolate->heap()->empty_string());
DCHECK_EQ(*isolate->global_object(), *receiver);
LoadGlobalICNexus nexus(vector, vector_slot);
LoadGlobalIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
ic.UpdateState(receiver, key);
RETURN_RESULT_OR_FAILURE(isolate, ic.Load(key));
} else {
Handle<Name> key = args.at<Name>(1);
DCHECK_EQ(FeedbackVectorSlotKind::KEYED_LOAD_IC, kind);
KeyedLoadICNexus nexus(vector, vector_slot);
KeyedLoadIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
ic.UpdateState(receiver, key);
RETURN_RESULT_OR_FAILURE(isolate, ic.Load(receiver, key));
}
}
// Used from ic-<arch>.cc.
RUNTIME_FUNCTION(Runtime_LoadGlobalIC_Miss) {
HandleScope scope(isolate);
DCHECK_EQ(2, args.length());
// Runtime functions don't follow the IC's calling convention.
Handle<JSGlobalObject> global = isolate->global_object();
Handle<Smi> slot = args.at<Smi>(0);
Handle<TypeFeedbackVector> vector = args.at<TypeFeedbackVector>(1);
FeedbackVectorSlot vector_slot = vector->ToSlot(slot->value());
DCHECK_EQ(FeedbackVectorSlotKind::LOAD_GLOBAL_IC,
vector->GetKind(vector_slot));
Handle<String> name(vector->GetName(vector_slot), isolate);
DCHECK_NE(*name, isolate->heap()->empty_string());
LoadGlobalICNexus nexus(vector, vector_slot);
LoadGlobalIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
ic.UpdateState(global, name);
Handle<Object> result;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, ic.Load(name));
return *result;
}
RUNTIME_FUNCTION(Runtime_LoadGlobalIC_Slow) {
HandleScope scope(isolate);
DCHECK_EQ(2, args.length());
CONVERT_SMI_ARG_CHECKED(slot, 0);
CONVERT_ARG_HANDLE_CHECKED(TypeFeedbackVector, vector, 1);
FeedbackVectorSlot vector_slot = vector->ToSlot(slot);
DCHECK_EQ(FeedbackVectorSlotKind::LOAD_GLOBAL_IC,
vector->GetKind(vector_slot));
Handle<String> name(vector->GetName(vector_slot), isolate);
DCHECK_NE(*name, isolate->heap()->empty_string());
Handle<JSGlobalObject> global = isolate->global_object();
Handle<ScriptContextTable> script_contexts(
global->native_context()->script_context_table());
ScriptContextTable::LookupResult lookup_result;
if (ScriptContextTable::Lookup(script_contexts, name, &lookup_result)) {
Handle<Context> script_context = ScriptContextTable::GetContext(
script_contexts, lookup_result.context_index);
Handle<Object> result =
FixedArray::get(*script_context, lookup_result.slot_index, isolate);
if (*result == isolate->heap()->the_hole_value()) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewReferenceError(MessageTemplate::kNotDefined, name));
}
return *result;
}
Handle<Object> result;
bool is_found = false;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, result,
Runtime::GetObjectProperty(isolate, global, name, &is_found));
if (!is_found) {
LoadICNexus nexus(isolate);
LoadIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
// It is actually a LoadGlobalICs here but the predicate handles this case
// properly.
if (ic.ShouldThrowReferenceError()) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewReferenceError(MessageTemplate::kNotDefined, name));
}
}
return *result;
}
// Used from ic-<arch>.cc
RUNTIME_FUNCTION(Runtime_KeyedLoadIC_Miss) {
HandleScope scope(isolate);
DCHECK_EQ(4, args.length());
// Runtime functions don't follow the IC's calling convention.
Handle<Object> receiver = args.at<Object>(0);
Handle<Object> key = args.at<Object>(1);
Handle<Smi> slot = args.at<Smi>(2);
Handle<TypeFeedbackVector> vector = args.at<TypeFeedbackVector>(3);
FeedbackVectorSlot vector_slot = vector->ToSlot(slot->value());
KeyedLoadICNexus nexus(vector, vector_slot);
KeyedLoadIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
ic.UpdateState(receiver, key);
RETURN_RESULT_OR_FAILURE(isolate, ic.Load(receiver, key));
}
RUNTIME_FUNCTION(Runtime_KeyedLoadIC_MissFromStubFailure) {
HandleScope scope(isolate);
typedef LoadWithVectorDescriptor Descriptor;
DCHECK_EQ(Descriptor::kParameterCount, args.length());
Handle<Object> receiver = args.at<Object>(Descriptor::kReceiver);
Handle<Object> key = args.at<Object>(Descriptor::kName);
Handle<Smi> slot = args.at<Smi>(Descriptor::kSlot);
Handle<TypeFeedbackVector> vector =
args.at<TypeFeedbackVector>(Descriptor::kVector);
FeedbackVectorSlot vector_slot = vector->ToSlot(slot->value());
KeyedLoadICNexus nexus(vector, vector_slot);
KeyedLoadIC ic(IC::EXTRA_CALL_FRAME, isolate, &nexus);
ic.UpdateState(receiver, key);
RETURN_RESULT_OR_FAILURE(isolate, ic.Load(receiver, key));
}
// Used from ic-<arch>.cc.
RUNTIME_FUNCTION(Runtime_StoreIC_Miss) {
HandleScope scope(isolate);
DCHECK_EQ(5, args.length());
// Runtime functions don't follow the IC's calling convention.
Handle<Object> value = args.at<Object>(0);
Handle<Smi> slot = args.at<Smi>(1);
Handle<TypeFeedbackVector> vector = args.at<TypeFeedbackVector>(2);
Handle<Object> receiver = args.at<Object>(3);
Handle<Name> key = args.at<Name>(4);
FeedbackVectorSlot vector_slot = vector->ToSlot(slot->value());
if (vector->GetKind(vector_slot) == FeedbackVectorSlotKind::STORE_IC) {
StoreICNexus nexus(vector, vector_slot);
StoreIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
ic.UpdateState(receiver, key);
RETURN_RESULT_OR_FAILURE(isolate, ic.Store(receiver, key, value));
} else {
DCHECK_EQ(FeedbackVectorSlotKind::KEYED_STORE_IC,
vector->GetKind(vector_slot));
KeyedStoreICNexus nexus(vector, vector_slot);
KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
ic.UpdateState(receiver, key);
RETURN_RESULT_OR_FAILURE(isolate, ic.Store(receiver, key, value));
}
}
// Used from ic-<arch>.cc.
RUNTIME_FUNCTION(Runtime_KeyedStoreIC_Miss) {
HandleScope scope(isolate);
DCHECK_EQ(5, args.length());
// Runtime functions don't follow the IC's calling convention.
Handle<Object> value = args.at<Object>(0);
Handle<Smi> slot = args.at<Smi>(1);
Handle<TypeFeedbackVector> vector = args.at<TypeFeedbackVector>(2);
Handle<Object> receiver = args.at<Object>(3);
Handle<Object> key = args.at<Object>(4);
FeedbackVectorSlot vector_slot = vector->ToSlot(slot->value());
KeyedStoreICNexus nexus(vector, vector_slot);
KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
ic.UpdateState(receiver, key);
RETURN_RESULT_OR_FAILURE(isolate, ic.Store(receiver, key, value));
}
RUNTIME_FUNCTION(Runtime_KeyedStoreIC_Slow) {
HandleScope scope(isolate);
DCHECK_EQ(5, args.length());
// Runtime functions don't follow the IC's calling convention.
Handle<Object> value = args.at<Object>(0);
// slot and vector parameters are not used.
Handle<Object> object = args.at<Object>(3);
Handle<Object> key = args.at<Object>(4);
LanguageMode language_mode;
KeyedStoreICNexus nexus(isolate);
KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
language_mode = ic.language_mode();
RETURN_RESULT_OR_FAILURE(
isolate,
Runtime::SetObjectProperty(isolate, object, key, value, language_mode));
}
RUNTIME_FUNCTION(Runtime_ElementsTransitionAndStoreIC_Miss) {
HandleScope scope(isolate);
// Runtime functions don't follow the IC's calling convention.
Handle<Object> object = args.at<Object>(0);
Handle<Object> key = args.at<Object>(1);
Handle<Object> value = args.at<Object>(2);
Handle<Map> map = args.at<Map>(3);
LanguageMode language_mode;
KeyedStoreICNexus nexus(isolate);
KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
language_mode = ic.language_mode();
if (object->IsJSObject()) {
JSObject::TransitionElementsKind(Handle<JSObject>::cast(object),
map->elements_kind());
}
RETURN_RESULT_OR_FAILURE(
isolate,
Runtime::SetObjectProperty(isolate, object, key, value, language_mode));
}
MaybeHandle<Object> BinaryOpIC::Transition(
Handle<AllocationSite> allocation_site, Handle<Object> left,
Handle<Object> right) {
BinaryOpICState state(isolate(), extra_ic_state());
// Compute the actual result using the builtin for the binary operation.
Handle<Object> result;
switch (state.op()) {
default:
UNREACHABLE();
case Token::ADD:
ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
Object::Add(isolate(), left, right), Object);
break;
case Token::SUB:
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result, Object::Subtract(isolate(), left, right), Object);
break;
case Token::MUL:
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result, Object::Multiply(isolate(), left, right), Object);
break;
case Token::DIV:
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result, Object::Divide(isolate(), left, right), Object);
break;
case Token::MOD:
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result, Object::Modulus(isolate(), left, right), Object);
break;
case Token::BIT_OR:
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result, Object::BitwiseOr(isolate(), left, right), Object);
break;
case Token::BIT_AND:
ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
Object::BitwiseAnd(isolate(), left, right),
Object);
break;
case Token::BIT_XOR:
ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
Object::BitwiseXor(isolate(), left, right),
Object);
break;
case Token::SAR:
ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
Object::ShiftRight(isolate(), left, right),
Object);
break;
case Token::SHR:
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result, Object::ShiftRightLogical(isolate(), left, right),
Object);
break;
case Token::SHL:
ASSIGN_RETURN_ON_EXCEPTION(
isolate(), result, Object::ShiftLeft(isolate(), left, right), Object);
break;
}
// Do not try to update the target if the code was marked for lazy
// deoptimization. (Since we do not relocate addresses in these
// code objects, an attempt to access the target could fail.)
if (AddressIsDeoptimizedCode()) {
return result;
}
// Compute the new state.
BinaryOpICState old_state(isolate(), target()->extra_ic_state());
state.Update(left, right, result);
// Check if we have a string operation here.
Handle<Code> new_target;
if (!allocation_site.is_null() || state.ShouldCreateAllocationMementos()) {
// Setup the allocation site on-demand.
if (allocation_site.is_null()) {
allocation_site = isolate()->factory()->NewAllocationSite();
}
// Install the stub with an allocation site.
BinaryOpICWithAllocationSiteStub stub(isolate(), state);
new_target = stub.GetCodeCopyFromTemplate(allocation_site);
// Sanity check the trampoline stub.
DCHECK_EQ(*allocation_site, new_target->FindFirstAllocationSite());
} else {
// Install the generic stub.
BinaryOpICStub stub(isolate(), state);
new_target = stub.GetCode();
// Sanity check the generic stub.
DCHECK_NULL(new_target->FindFirstAllocationSite());
}
set_target(*new_target);
if (FLAG_trace_ic) {
OFStream os(stdout);
os << "[BinaryOpIC" << old_state << " => " << state << " @ "
<< static_cast<void*>(*new_target) << " <- ";
JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
if (!allocation_site.is_null()) {
os << " using allocation site " << static_cast<void*>(*allocation_site);
}
os << "]" << std::endl;
}
// Patch the inlined smi code as necessary.
if (!old_state.UseInlinedSmiCode() && state.UseInlinedSmiCode()) {
PatchInlinedSmiCode(isolate(), address(), ENABLE_INLINED_SMI_CHECK);
} else if (old_state.UseInlinedSmiCode() && !state.UseInlinedSmiCode()) {
PatchInlinedSmiCode(isolate(), address(), DISABLE_INLINED_SMI_CHECK);
}
return result;
}
RUNTIME_FUNCTION(Runtime_BinaryOpIC_Miss) {
HandleScope scope(isolate);
DCHECK_EQ(2, args.length());
typedef BinaryOpDescriptor Descriptor;
Handle<Object> left = args.at<Object>(Descriptor::kLeft);
Handle<Object> right = args.at<Object>(Descriptor::kRight);
BinaryOpIC ic(isolate);
RETURN_RESULT_OR_FAILURE(
isolate, ic.Transition(Handle<AllocationSite>::null(), left, right));
}
RUNTIME_FUNCTION(Runtime_BinaryOpIC_MissWithAllocationSite) {
HandleScope scope(isolate);
DCHECK_EQ(3, args.length());
typedef BinaryOpWithAllocationSiteDescriptor Descriptor;
Handle<AllocationSite> allocation_site =
args.at<AllocationSite>(Descriptor::kAllocationSite);
Handle<Object> left = args.at<Object>(Descriptor::kLeft);
Handle<Object> right = args.at<Object>(Descriptor::kRight);
BinaryOpIC ic(isolate);
RETURN_RESULT_OR_FAILURE(isolate,
ic.Transition(allocation_site, left, right));
}
Code* CompareIC::GetRawUninitialized(Isolate* isolate, Token::Value op) {
CompareICStub stub(isolate, op, CompareICState::UNINITIALIZED,
CompareICState::UNINITIALIZED,
CompareICState::UNINITIALIZED);
Code* code = NULL;
CHECK(stub.FindCodeInCache(&code));
return code;
}
Code* CompareIC::UpdateCaches(Handle<Object> x, Handle<Object> y) {
HandleScope scope(isolate());
CompareICStub old_stub(target()->stub_key(), isolate());
CompareICState::State new_left =
CompareICState::NewInputState(old_stub.left(), x);
CompareICState::State new_right =
CompareICState::NewInputState(old_stub.right(), y);
CompareICState::State state = CompareICState::TargetState(
isolate(), old_stub.state(), old_stub.left(), old_stub.right(), op_,
HasInlinedSmiCode(address()), x, y);
CompareICStub stub(isolate(), op_, new_left, new_right, state);
if (state == CompareICState::KNOWN_RECEIVER) {
stub.set_known_map(
Handle<Map>(Handle<JSReceiver>::cast(x)->map(), isolate()));
}
Handle<Code> new_target = stub.GetCode();
set_target(*new_target);
if (FLAG_trace_ic) {
PrintF("[CompareIC in ");
JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
PrintF(" ((%s+%s=%s)->(%s+%s=%s))#%s @ %p]\n",
CompareICState::GetStateName(old_stub.left()),
CompareICState::GetStateName(old_stub.right()),
CompareICState::GetStateName(old_stub.state()),
CompareICState::GetStateName(new_left),
CompareICState::GetStateName(new_right),
CompareICState::GetStateName(state), Token::Name(op_),
static_cast<void*>(*stub.GetCode()));
}
// Activate inlined smi code.
if (old_stub.state() == CompareICState::UNINITIALIZED) {
PatchInlinedSmiCode(isolate(), address(), ENABLE_INLINED_SMI_CHECK);
}
return *new_target;
}
// Used from CompareICStub::GenerateMiss in code-stubs-<arch>.cc.
RUNTIME_FUNCTION(Runtime_CompareIC_Miss) {
HandleScope scope(isolate);
DCHECK(args.length() == 3);
CompareIC ic(isolate, static_cast<Token::Value>(args.smi_at(2)));
return ic.UpdateCaches(args.at<Object>(0), args.at<Object>(1));
}
RUNTIME_FUNCTION(Runtime_Unreachable) {
UNREACHABLE();
CHECK(false);
return isolate->heap()->undefined_value();
}
Handle<Object> ToBooleanIC::ToBoolean(Handle<Object> object) {
ToBooleanICStub stub(isolate(), extra_ic_state());
bool to_boolean_value = stub.UpdateStatus(object);
Handle<Code> code = stub.GetCode();
set_target(*code);
return isolate()->factory()->ToBoolean(to_boolean_value);
}
RUNTIME_FUNCTION(Runtime_ToBooleanIC_Miss) {
DCHECK(args.length() == 1);
HandleScope scope(isolate);
Handle<Object> object = args.at<Object>(0);
ToBooleanIC ic(isolate);
return *ic.ToBoolean(object);
}
RUNTIME_FUNCTION(Runtime_StoreCallbackProperty) {
Handle<JSObject> receiver = args.at<JSObject>(0);
Handle<JSObject> holder = args.at<JSObject>(1);
Handle<HeapObject> callback_or_cell = args.at<HeapObject>(2);
Handle<Name> name = args.at<Name>(3);
Handle<Object> value = args.at<Object>(4);
CONVERT_LANGUAGE_MODE_ARG_CHECKED(language_mode, 5);
HandleScope scope(isolate);
if (V8_UNLIKELY(FLAG_runtime_stats)) {
RETURN_RESULT_OR_FAILURE(
isolate, Runtime::SetObjectProperty(isolate, receiver, name, value,
language_mode));
}
Handle<AccessorInfo> callback(
callback_or_cell->IsWeakCell()
? AccessorInfo::cast(WeakCell::cast(*callback_or_cell)->value())
: AccessorInfo::cast(*callback_or_cell));
DCHECK(callback->IsCompatibleReceiver(*receiver));
Address setter_address = v8::ToCData<Address>(callback->setter());
v8::AccessorNameSetterCallback fun =
FUNCTION_CAST<v8::AccessorNameSetterCallback>(setter_address);
DCHECK(fun != NULL);
Object::ShouldThrow should_throw =
is_sloppy(language_mode) ? Object::DONT_THROW : Object::THROW_ON_ERROR;
PropertyCallbackArguments custom_args(isolate, callback->data(), *receiver,
*holder, should_throw);
custom_args.Call(fun, name, value);
RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
return *value;
}
/**
* Attempts to load a property with an interceptor (which must be present),
* but doesn't search the prototype chain.
*
* Returns |Heap::no_interceptor_result_sentinel()| if interceptor doesn't
* provide any value for the given name.
*/
RUNTIME_FUNCTION(Runtime_LoadPropertyWithInterceptorOnly) {
DCHECK(args.length() == NamedLoadHandlerCompiler::kInterceptorArgsLength);
Handle<Name> name =
args.at<Name>(NamedLoadHandlerCompiler::kInterceptorArgsNameIndex);
Handle<Object> receiver =
args.at<Object>(NamedLoadHandlerCompiler::kInterceptorArgsThisIndex);
Handle<JSObject> holder =
args.at<JSObject>(NamedLoadHandlerCompiler::kInterceptorArgsHolderIndex);
HandleScope scope(isolate);
if (!receiver->IsJSReceiver()) {
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, receiver, Object::ConvertReceiver(isolate, receiver));
}
InterceptorInfo* interceptor = holder->GetNamedInterceptor();
PropertyCallbackArguments arguments(isolate, interceptor->data(), *receiver,
*holder, Object::DONT_THROW);
v8::GenericNamedPropertyGetterCallback getter =
v8::ToCData<v8::GenericNamedPropertyGetterCallback>(
interceptor->getter());
Handle<Object> result = arguments.Call(getter, name);
RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
if (!result.is_null()) return *result;
return isolate->heap()->no_interceptor_result_sentinel();
}
/**
* Loads a property with an interceptor performing post interceptor
* lookup if interceptor failed.
*/
RUNTIME_FUNCTION(Runtime_LoadPropertyWithInterceptor) {
HandleScope scope(isolate);
DCHECK(args.length() == NamedLoadHandlerCompiler::kInterceptorArgsLength);
Handle<Name> name =
args.at<Name>(NamedLoadHandlerCompiler::kInterceptorArgsNameIndex);
Handle<Object> receiver =
args.at<Object>(NamedLoadHandlerCompiler::kInterceptorArgsThisIndex);
Handle<JSObject> holder =
args.at<JSObject>(NamedLoadHandlerCompiler::kInterceptorArgsHolderIndex);
if (!receiver->IsJSReceiver()) {
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, receiver, Object::ConvertReceiver(isolate, receiver));
}
InterceptorInfo* interceptor = holder->GetNamedInterceptor();
PropertyCallbackArguments arguments(isolate, interceptor->data(), *receiver,
*holder, Object::DONT_THROW);
v8::GenericNamedPropertyGetterCallback getter =
v8::ToCData<v8::GenericNamedPropertyGetterCallback>(
interceptor->getter());
Handle<Object> result = arguments.Call(getter, name);
RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
if (!result.is_null()) return *result;
LookupIterator it(receiver, name, holder);
// Skip any lookup work until we hit the (possibly non-masking) interceptor.
while (it.state() != LookupIterator::INTERCEPTOR ||
!it.GetHolder<JSObject>().is_identical_to(holder)) {
DCHECK(it.state() != LookupIterator::ACCESS_CHECK || it.HasAccess());
it.Next();
}
// Skip past the interceptor.
it.Next();
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, Object::GetProperty(&it));
if (it.IsFound()) return *result;
LoadICNexus nexus(isolate);
LoadIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
// It could actually be any kind of LoadICs here but the predicate handles
// all the cases properly.
if (!ic.ShouldThrowReferenceError()) {
return isolate->heap()->undefined_value();
}
// Throw a reference error.
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewReferenceError(MessageTemplate::kNotDefined, it.name()));
}
RUNTIME_FUNCTION(Runtime_StorePropertyWithInterceptor) {
HandleScope scope(isolate);
DCHECK(args.length() == 3);
StoreICNexus nexus(isolate);
StoreIC ic(IC::NO_EXTRA_FRAME, isolate, &nexus);
Handle<JSObject> receiver = args.at<JSObject>(0);
Handle<Name> name = args.at<Name>(1);
Handle<Object> value = args.at<Object>(2);
DCHECK(receiver->HasNamedInterceptor());
InterceptorInfo* interceptor = receiver->GetNamedInterceptor();
DCHECK(!interceptor->non_masking());
PropertyCallbackArguments arguments(isolate, interceptor->data(), *receiver,
*receiver, Object::DONT_THROW);
v8::GenericNamedPropertySetterCallback setter =
v8::ToCData<v8::GenericNamedPropertySetterCallback>(
interceptor->setter());
Handle<Object> result = arguments.Call(setter, name, value);
RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
if (!result.is_null()) return *value;
LookupIterator it(receiver, name, receiver);
// Skip past any access check on the receiver.
if (it.state() == LookupIterator::ACCESS_CHECK) {
DCHECK(it.HasAccess());
it.Next();
}
// Skip past the interceptor on the receiver.
DCHECK_EQ(LookupIterator::INTERCEPTOR, it.state());
it.Next();
MAYBE_RETURN(Object::SetProperty(&it, value, ic.language_mode(),
JSReceiver::CERTAINLY_NOT_STORE_FROM_KEYED),
isolate->heap()->exception());
return *value;
}
RUNTIME_FUNCTION(Runtime_LoadElementWithInterceptor) {
// TODO(verwaest): This should probably get the holder and receiver as input.
HandleScope scope(isolate);
Handle<JSObject> receiver = args.at<JSObject>(0);
DCHECK(args.smi_at(1) >= 0);
uint32_t index = args.smi_at(1);
InterceptorInfo* interceptor = receiver->GetIndexedInterceptor();
PropertyCallbackArguments arguments(isolate, interceptor->data(), *receiver,
*receiver, Object::DONT_THROW);
v8::IndexedPropertyGetterCallback getter =
v8::ToCData<v8::IndexedPropertyGetterCallback>(interceptor->getter());
Handle<Object> result = arguments.Call(getter, index);
RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
if (result.is_null()) {
LookupIterator it(isolate, receiver, index, receiver);
DCHECK_EQ(LookupIterator::INTERCEPTOR, it.state());
it.Next();
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result,
Object::GetProperty(&it));
}
return *result;
}
} // namespace internal
} // namespace v8
| [
"sdoa5335717@163.com"
] | sdoa5335717@163.com |
0a875a4661d4d4f6cf2bb5138c4472c6aa58e31c | 55dfa9c807fc4e6a716b0fbe861a7736e2217cff | /include/cusparse/gthrz.h | 0d9e8738343e4ecd1dd5de1e3d1e859e1a0ad499 | [] | no_license | sonwell/ib.cu | a2451e2ffc3daf633f3bbd6134fd38c79908b452 | 3217b443aa568930208d258d577dddd05a0fbf18 | refs/heads/master | 2023-04-12T10:01:47.485122 | 2021-07-16T18:21:07 | 2021-07-16T18:21:07 | 272,534,593 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 488 | h | #pragma once
#include "types.h"
#include "handle.h"
#include "index_base.h"
namespace cusparse {
inline void
gthrz(handle& h, int nnz, float* y, float* values, const int* indices,
index_base_adaptor base)
{
throw_if_error(cusparseSgthrz(h, nnz, y, values, indices, base));
}
inline void
gthrz(handle& h, int nnz, double* y, double* values, const int* indices,
index_base_adaptor base)
{
throw_if_error(cusparseDgthrz(h, nnz, y, values, indices, base));
}
} // namespace cusparse | [
"atkassen@gmail.com"
] | atkassen@gmail.com |
2b20dd1ae7449023e787664e1e772e02324d0c4a | 2d17040d5f8e7eac41e9d1ef90b5cbab22e52bbf | /include/exceptions/itemnotfound.hpp | 138b6792c2e4f836893a5beaa97103def840e7a8 | [] | no_license | ne0ndrag0n/Concordia | 5818a09af5919288b3ebbca21f7f2fcef1a4f52a | 98a0444509f9b0110a3e57cc9f4d535fd4585037 | refs/heads/master | 2021-06-17T17:20:22.976001 | 2019-07-27T20:41:47 | 2019-07-27T20:41:47 | 34,757,048 | 8 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 305 | hpp | #ifndef ITEMNOTFOUNDEXCEPTION
#define ITEMNOTFOUNDEXCEPTION
#include <exception>
namespace BlueBear {
namespace Exceptions {
struct ItemNotFoundException : public std::exception {
const char* what() const throw() {
return "Required item not found!";
}
};
}
}
#endif
| [
"ne0ndrag0n@users.noreply.github.com"
] | ne0ndrag0n@users.noreply.github.com |
eccd3544175faaaf6ab094656c550e7c35e85823 | 0c0f13cee78d79e75f4befaf1e3648e99d806cc6 | /General - Arduino/Project_5/Project_5.ino | 480e2118666277e9d095a6ad0e95918933942fbb | [] | no_license | AndersAskeland/Programming | 4fbdf1c945043d10da49c972b0e0cd4ac3d17405 | 26fe5253a77a9e6c69ccd6388f6fc54ecb2d534d | refs/heads/master | 2021-12-12T23:11:26.468519 | 2021-12-10T09:03:59 | 2021-12-10T09:03:59 | 235,389,552 | 1 | 0 | null | 2021-10-01T09:33:20 | 2020-01-21T16:35:02 | Java | UTF-8 | C++ | false | false | 687 | ino | // Include servo library
#include <Servo.h>
// Create servo object
Servo myServo;
// Constants
int const potPin = A0; // Potentiomiter
// Variables
int potVal;
int angle;
void setup() {
// ATtach servo to digital output
myServo.attach(9);
// Begin analog stuff
Serial.begin(9600);
}
void loop() {
// Read and print potentiomiter position
potVal = analogRead(potPin);
Serial.print("potVal: ");
Serial.print(potVal);
// Change analog input (0 - 1023) to angle on servo (0 - 179) using the map function.
angle = map(potVal, 0, 1023, 0, 179);
Serial.print(", angle: ");
Serial.println(angle);
// Rotate servo
myServo.write(angle);
delay(15);
}
| [
"anders_askeland@hotmail.com"
] | anders_askeland@hotmail.com |
e8cd2b2c4ae988a8d15ab26b40a4700137e12e35 | 0ae6350c59130a6116a9afb66bb08195f7f5f1a0 | /JetContext.h | f5f237989983976423587e853327391f18edb784 | [
"MIT"
] | permissive | glcolor/Jx | 6d35f8288de7d84a9753492f3646082c814d8aa8 | 454507a1a9250a1eee2fa84bb3cb8ee00efb4cf9 | refs/heads/master | 2021-05-13T15:09:27.947497 | 2018-01-09T08:01:44 | 2018-01-09T08:01:44 | 116,758,544 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,357 | h | #ifndef _LANG_CONTEXT_HEADER
#define _LANG_CONTEXT_HEADER
#include <functional>
#include <string>
#include <map>
#include <algorithm>
#include "Value.h"
#include "VMStack.h"
#include "Parser.h"
#include "JetInstructions.h"
#include "JetExceptions.h"
#include "GarbageCollector.h"
#ifdef _WIN32
#include <Windows.h>
//#define JET_TIME_EXECUTION
#endif
//GC触发阈值
#define GC_INTERVAL 200
//第0代内存垃圾与第1代内存垃圾的转换阈值(第0代在经历多少次收集后若仍然存活,则转为第1代垃圾)
#define GC_STEPS 4
#define JET_STACK_SIZE 1024
#define JET_MAX_CALLDEPTH 1024
namespace Jet
{
typedef std::function<void(Jet::JetContext*,Jet::Value*,int)> JetFunction;
#define JetBind(context, fun) auto temp__bind_##fun = [](Jet::JetContext* context,Jet::Value* args, int numargs) { return Value(fun(args[0]));};context[#fun] = Jet::Value(temp__bind_##fun);
#define JetBind2(context, fun) auto temp__bind_##fun = [](Jet::JetContext* context,Jet::Value* args, int numargs) { return Value(fun(args[0],args[1]));};context[#fun] = Jet::Value(temp__bind_##fun);
#define JetBind3(context, fun, type) auto temp__bind_##fun = [](Jet::JetContext* context,Jet::Value* args, int numargs) { return Value(fun((type)args[0],(type)args[1]));};context[#fun] = Jet::Value(temp__bind_##fun);
//内置函数
Value gc(JetContext* context,Value* args, int numargs);
Value print(JetContext* context,Value* args, int numargs);
Value tostring(JetContext* context, Value* args, int numargs);
Value toint(JetContext* context, Value* args, int numargs);
Value toreal(JetContext* context, Value* args, int numargs);
//信息输出函数的定义
typedef int (__cdecl *OutputFunction) (const char* format, ...);
/// <summary>
/// 脚本执行上下文(虚拟机)
/// </summary>
class JetContext
{
friend struct Generator;
friend struct Value;
friend class JetObject;
friend class GarbageCollector;
public:
//构造函数
JetContext();
//析构函数
~JetContext();
/// <summary>
/// 创建新对象
/// </summary>
/// <returns>创建的对象</returns>
Value CreateNewObject();
/// <summary>
/// 创建新数组
/// </summary>
/// <returns>创建的数组</returns>
Value CreateNewArray();
/// <summary>
/// 创建新自定义数据
/// </summary>
/// <param name="data">自定义数据的指针</param>
/// <param name="proto">自定义数据的原型</param>
/// <returns>创建的自定义数据</returns>
Value CreateNewUserData(void* data, const Value& proto);
/// <summary>
/// 创建新字符串
/// </summary>
/// <param name="string">字符串(以0结尾)</param>
/// <param name="copy">是否复制数据,如果不复制,则直接使用参数提供的字符串</param>
/// <returns>创建的字符串</returns>
Value CreateNewString(const char* string, bool copy = true);
/// <summary>
/// 添加一个自定义数据原型
/// </summary>
/// <param name="Typename">原型的名字</param>
/// <returns>原型对象</returns>
Value AddPrototype(const char* Typename);
/// <summary>
/// 添加一个函数库
/// </summary>
/// <param name="name">名字</param>
/// <param name="library">包含所有可执行代码的对象(Assemble方法的返回值)</param>
void AddLibrary(const std::string& name, Value& library)
{
library.AddRef();
this->m_Libraries[name] = library;
}
//访问全局变量的接口
Value& operator[](const std::string& id);
Value Get(const std::string& name);
void Set(const std::string& name, const Value& value);
//直接执行指定的代码
std::string Script(const std::string& code, const std::string& filename = "file");
Value Script(const char* code, const char* filename = "file");
//将指定代码编译为汇编指令
std::vector<IntermediateInstruction> Compile(const char* code, const char* filename = "file");
//将汇编指令编译为可执行函数
Value Assemble(const std::vector<IntermediateInstruction>& code);
//调用指定的函数
Value Call(const char* m_FunctionPrototype, Value* args = 0, unsigned int numargs = 0);
Value Call(const Value* m_FunctionPrototype, Value* args = 0, unsigned int numargs = 0);
//执行一次内存垃圾回收
void RunGC();
//获取和设置信息输出函数
OutputFunction GetOutputFunction() const { return m_OutputFunction; }
void SetOutputFunction(OutputFunction val);
private:
//开始执行 iptr 处的指令
Value Execute(int iptr, Closure* frame);
//VM内部使用的函数调用
unsigned int Call(const Value* m_FunctionPrototype, unsigned int iptr, unsigned int args);
//调试用的函数
void GetCode(int ptr, Closure* closure, std::string& ret, unsigned int& line);
//追踪堆栈
void StackTrace(int curiptr, Closure* cframe);
//打印调用栈
static Value Callstack(JetContext* context, Value* v, int ar);
private:
//数据栈
VMStack<Value> m_Stack;
//调用栈
VMStack<std::pair<unsigned int, Closure*> > m_CallStack;
//函数
std::unordered_map<std::string, Function*> m_Functions;
//入口点
std::vector<Function*> m_EntryPoints;
//变量
std::vector<Value> m_Variables;
//变量的名称索引表
std::unordered_map<std::string, unsigned int> m_VariableIndex;
//编译器上下文
CompilerContext m_Compiler;
// 基础类型的原型
JetObject* m_StringPrototype;
JetObject* m_ArrayPrototype;
JetObject* m_ObjectPrototype;
JetObject* m_ArrayIterPrototype;
JetObject* m_ObjectIterPrototype;
JetObject* m_FunctionPrototype;
//require指令的缓冲区
std::map<std::string, Value> m_RequireCache;
//导入的库
std::map<std::string, Value> m_Libraries;
//内存管理器
GarbageCollector m_GC;
//注册到虚拟机的原型
std::vector<JetObject*> m_Prototypes;
//最近添加的闭包
Closure* m_LastAdded;
struct OpenCapture
{
Capture* capture;
#ifdef _DEBUG
Closure* creator;
#endif
};
std::deque<OpenCapture> m_OpenCaptures;
//当前闭包
Closure* m_CurFrame;
//局部变量栈指针stack pointer
Value* m_SP;
//局部变量栈,用于保存局部变量?
Value m_LocalStack[JET_STACK_SIZE];
//输出函数指针
OutputFunction m_OutputFunction = printf;
};
}
#endif | [
"glcolor@163.com"
] | glcolor@163.com |
002b54ec26e481bda6969d0cf54a8c6bfa467c1a | a4f3147444dc20651af683ec3be995aba835d646 | /examples/simple.cpp | f9394e2851b6e5a5238042459e7bc543b5857596 | [
"0BSD"
] | permissive | orazdow/PortAudio-Wrapper | 0b8340e59743f9db53c0cb02ab7450624dc62c11 | accfe6c16ea372eabbbb35a304c3434ce22c4870 | refs/heads/master | 2023-06-23T06:15:35.090422 | 2022-12-23T21:21:22 | 2022-12-23T21:21:22 | 96,049,861 | 13 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 425 | cpp | #include "pa.h"
#include "math.h"
#define TWO_PI 6.2831853
double phase = 0, step = TWO_PI*440/44100.0;
void paFunc(const float* in, float* out, long frames, void* data){
for(int i = 0; i < frames; i++ ){
phase += step;
*out++ = sin(phase)*0.5;
}
}
int main() {
Pa a(paFunc, NULL);
a.start(Pa::waitForKey);
return 0;
} | [
"ollierazdow@hotmail.com"
] | ollierazdow@hotmail.com |
6c53cfc18ceb8ff3d5cae85c8aa8b88adddfb31c | a9bf6bfab87702cdcae9aec23dc6070e36f42d2d | /include/twec/id_holder.hpp | 15ae895e0c5484eceb0db7725eb5d27a1dd75be9 | [
"MIT"
] | permissive | Malekblubb/tw_econ_gui | 036ec72b7dfc0bf55be51036777c1d0378fc9a93 | 1c231112e87a0c75e8e7e6c5b5558a4dff3aa72e | refs/heads/master | 2021-01-23T18:21:41.614799 | 2019-01-12T21:12:02 | 2019-01-12T21:12:02 | 16,891,343 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 491 | hpp | //
// Copyright (c) 2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef TWEC_ID_HOLDER_HPP
#define TWEC_ID_HOLDER_HPP
#include <QWidget>
namespace twec
{
class id_holder : public QWidget
{
int m_id;
public:
id_holder(int id) :
QWidget{nullptr},
m_id{id}
{ }
int get_id() const noexcept
{return m_id;}
};
template<typename Ptr_Type>
id_holder* to_id_holder(Ptr_Type* ptr)
{return static_cast<id_holder*>(ptr);}
}
#endif // TWEC_ID_HOLDER_HPP
| [
"malekchristoph@gmail.com"
] | malekchristoph@gmail.com |
4702939b4ad2da2e6db1b8eae54a5f87feaaa62f | 73539efb2e2ed4c11aa28ca23ac9b34f3759c63a | /src/Sequence.h | ed843cb5718d8852a3d9e1130fdebada8fd7cdf1 | [] | no_license | pnrobinson/rnx | f6b87ee12e7b9cc6d09d19ae690484e9ccd936e3 | 3cf303ecee88a9d775bc3e2ec134994b7617a26f | refs/heads/master | 2021-01-10T06:15:25.707961 | 2016-01-23T19:27:27 | 2016-01-23T19:27:27 | 45,527,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,258 | h | #ifndef SEQUENCE_H
#define SEQUENCE_H
/**
* Sequence.h
* A set of classes designed to input and store DNA and RNA sequence data and
* to provide a well defined interface to the RNA folding sections of the code.
* @author Peter Robinson
* @version 0.0.2 (22 November 2015)
*/
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
/**
* \class Record
*
* \ingroup PackageName
* (Note, this needs exactly one \defgroup somewhere)
*
* \brief Class for representing a single sequence from a file
*
* Right now, FASTA
*
* \note Attempts at zen rarely work.
*
* \author (last to touch it) $Author: bv $
*
* \version $Revision: 0.0.1 $
*
* \date $Date: 2005/04/14 14:16:20 $
*
* Contact: peter.robinson@charite.de
*
* Created on: Wed Apr 13 18:39:37 2005
*
* $Id: doxygen-howto.html,v 1.5 2005/04/14 14:16:20 bv Exp $
*
*/
class Record {
private:
/** The name */
std::string header_;
/** The DNA or RNA sequence */
std::string sequence_;
/** The NCBI gi number of the sequence */
unsigned int gi_;
/** The accession number plus version suffix */
std::string accession_;
/** The name of the locus */
std::string locus_;
/** Start position (one based) of coding sequence. */
unsigned int CDS_startpos_;
/** End position (one based) of coding sequence. */
unsigned int CDS_endpos_;
public:
Record(std::string h);
void appendSequenceLine(std::string line);
unsigned int get_size();
std::string substr(unsigned int start_pos, unsigned int length);
std::string get_rna() const;
int get_gi() const;
std::string get_accession_number() const;
std::string get_locus() const;
unsigned int get_CDS_startpos() const;
unsigned int get_CDS_endpos() const;
unsigned int get_CDS_length() const;
std::string get_5utr() const;
//
void set_locus(std::string loc);
void set_accession(std::string acc);
void set_gi(int);
void set_CDS_startpos(int startpos);
void set_CDS_endpos(int endpos);
// some implementation details
void appendSequenceFromGeneBankLines(std::vector<std::string> seqlines);
};
bool parseFASTA(std::string path, std::vector<Record> & records);
bool parseGenBank(std::string path, std::vector<Record> & records);
#endif
/* eof */
| [
"peter.robinson@charite.de"
] | peter.robinson@charite.de |
d1ae35b3e823faff234046c585479d829508d4d0 | ce0b796b4197697c331f7381cc649a1e297869d8 | /NimServer/server.cpp | 1c15f66f173f52987ecea989f7b0b028b4b71343 | [] | no_license | jgreenlee24/NIM | cf90b1ff971e5e644d08fd48b37f31a053fc5ea8 | 50ca66875510f120adaa1ecddf908fadd3328808 | refs/heads/master | 2021-01-19T04:56:13.696923 | 2015-05-01T16:49:31 | 2015-05-01T16:49:31 | 34,473,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,353 | cpp | #include <iostream>
#include <string>
#include <WinSock2.h>
#include "server.h"
#include "AI.h"
using std::string;
using std::cout;
using std::endl;
using std::cin;
using std::getline;
using std::to_string;
using std::stoi;
#pragma comment (lib, "ws2_32.lib")
void playGame(SOCKET connectSocket)
{
string board = "";
int temp;
const string leadZero = "0";
cout << "How many rock pile? (3-9 piles) ";
cin >> temp;
cout << endl;
while (temp < 3 || temp > 9)
{
cout << "Wrong value. Please input a number between 3 and 9: ";
cin >> temp;
cout << endl;
}
board = to_string(temp);
int x = 0;
for (int i = 1; i <= temp; i++)
{
cout << "How many rocks in pile " << i << "? (1-20): ";
cin >> x;
while (x < 1 || x > 20)
{
cout << "Wrong value. Please input a number between 1 and 20: ";
cin >> x;
cout << endl;
}
if (x < 10)
{
board += leadZero;
board += to_string(x);
}
else
{
board += to_string(x);
}
}
send(connectSocket, (char*)board.c_str(), board.length() + 1, 0);
play();
}
void server_main(int argc, char *argv[], string playerName)
{
SOCKET s;
char buf[MAX_RECV_BUF];
string host;
string port;
char response_str[MAX_SEND_BUF];
sockaddr_in clientSocketInfo;
SOCKET listenSocket;
SOCKET connectSocket;
int clen = sizeof(clientSocketInfo);
char ip_addr[MAXIPBUF];
char buffer[MAXBUF];
int len;
char choice;
const string Refuse = "NO";
const string Accept = "YES";
cout << "Please enter your name: ";
getline(cin, playerName);
WORD wVersion = 0x0202;
WSADATA wsaData;
int error = WSAStartup(wVersion, &wsaData);
if (error)
{
cout << "Unable to initialize Windows Socket library." << endl;
return;
}
s = passivesock(UDPPORT_NIM, "udp");
cout << endl << "Waiting for a challenge..." << endl;
len = UDP_recv(s, buf, MAX_RECV_BUF, (char*)host.c_str(), (char*)port.c_str());
bool flag = false;
while (!flag)
{
if (strcmp(buf, Nim_QUERY) == 0)
{
UDP_send(s, (char*)playerName.c_str(), playerName.length() + 1,
(char*)host.c_str(), (char*)port.c_str());
len = UDP_recv(s, buf, MAX_RECV_BUF, (char*)host.c_str(), (char*)port.c_str());
if (strncmp(buf, Nim_CHALLENGE, strlen(Nim_CHALLENGE)) == 0)
{
char *startOfName = strstr(buf, Nim_CHALLENGE);
if (startOfName != NULL)
{
cout << endl << "You have been challenged by " << startOfName + strlen(Nim_CHALLENGE) << endl;
}
cout << "Accept challenge? Y/N: ";
cin >> choice;
if (choice == 'N' || choice == 'n')
{
UDP_send(s, (char*)Refuse.c_str(), Refuse.length() + 1,
(char*)host.c_str(), (char*)port.c_str());
}
else if (choice == 'Y' || choice == 'y')
{
listenSocket = passivesock(TCPPORT_NIM, "TCP");
UDP_send(s, (char*)Accept.c_str(), Accept.length() + 1,
(char*)host.c_str(), (char*)port.c_str());
if (wait(s, 5, 0))
{
int len = UDP_recv(s, buf, MAX_RECV_BUF, (char*)host.c_str(), (char*)port.c_str());
if (strcmp(buf, Nim_ACK) == 0)
{
closesocket(s);
connectSocket = accept(listenSocket, (LPSOCKADDR)&clientSocketInfo, &clen);
strcpy_s(ip_addr, MAXIPBUF, inet_ntoa(clientSocketInfo.sin_addr));
cout << "Connected!!" << endl;
playGame(connectSocket);
}
else
{
closesocket(listenSocket);
}
}
}
}
}
}
} | [
"awebb@harding.edu"
] | awebb@harding.edu |
93e287e150539aa6cc141ca1a0d33e246a915067 | 2e45720a8747bbcd06213a3dfc2b3a5c668052d6 | /org.glite.wms.ice/src/iceDb/GetRegisteredStats.cpp | 25c69ac3f81f461404a8b3d691982871141351ae | [
"Apache-2.0"
] | permissive | italiangrid/org.glite.wms | df0616a06b034b875b3c93e16995fc022a206685 | 0fc86edb5b0395c5400023a4cfb29b5273eba729 | refs/heads/master | 2021-01-10T20:25:56.444145 | 2015-01-23T15:09:44 | 2015-01-23T15:09:44 | 5,776,443 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,100 | cpp | /* LICENSE:
Copyright (c) Members of the EGEE Collaboration. 2010.
See http://www.eu-egee.org/partners/ for details on the copyright
holders.
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.
END LICENSE */
#include "GetRegisteredStats.h"
#include "iceUtils/IceUtils.h"
#include <vector>
#include <cstdlib>
#include <boost/lexical_cast.hpp>
using namespace glite::wms::ice;
using namespace std;
namespace { // begin local namespace
// Local helper function: callback for sqlite
static int fetch_fields_callback(void *param, int argc, char **argv, char **azColName) {
//vector< pair<time_t, int> >* result = (vector< pair<time_t, int> >*) param;
vector<boost::tuple<time_t, std::string, std::string, std::string> >* result =
(vector<boost::tuple<time_t, std::string, std::string, std::string> >*)param;
if ( argv && argv[0] && argv[1] && argv[2] ) {
result->push_back( boost::make_tuple( (time_t)atoi(argv[0]), argv[1], argv[2], argv[3] ) ) ;
}
return 0;
}
} // end local namespace
void db::GetRegisteredStats::execute( sqlite3* db ) throw ( DbOperationException& )
{
string sqlcmd("SELECT timestamp,ceurl,grid_jobid,cream_jobid FROM registered_jobs WHERE timestamp >= ");
sqlcmd += util::IceUtils::withSQLDelimiters( boost::lexical_cast<std::string>( (unsigned long long int)m_datefrom ) );
sqlcmd += " AND timestamp <= ";
sqlcmd += util::IceUtils::withSQLDelimiters( boost::lexical_cast<std::string>( (unsigned long long int)m_dateto ) );
sqlcmd += ";";
do_query( db, sqlcmd, fetch_fields_callback, m_target );
}
| [
"dorigoa@sl6-devel.novalocal"
] | dorigoa@sl6-devel.novalocal |
deec8e0e2d6e694ae3c6ec260cbb3ffdaab5e042 | ccc5ce51d172bed2f42a4c16971052068232b9e9 | /groupboxwindow_Qt4.8/main.cpp | a28163ad3c4360dea834e1aaebc4899bd481cf57 | [
"MIT"
] | permissive | stephaneAG/Qt_tests_Mac | 6ce6c07493e482e715e2e8dcf4be2edd5458c4dd | 06eca49531521ac6a75e5f828b6fd97c8ef452c5 | refs/heads/master | 2020-05-30T02:53:18.528395 | 2015-06-14T06:40:59 | 2015-06-14T06:40:59 | 37,402,102 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,290 | cpp | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Digia Plc and its Subsidiary(-ies) 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."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QApplication>
#include "window.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Window window;
#if defined(Q_OS_SYMBIAN)
window.showMaximized();
#else
window.show();
#endif
return app.exec();
} | [
"seedsodesign@gmail.com"
] | seedsodesign@gmail.com |
6fcf1d3dd06f9725ea3dd16f2ea4659f4ad7c6f2 | 20a9059a7f7dfff397a93b80632168f46d43fcad | /src/processPointClouds.cpp | 5874884d0a702ef63e1bb8b79a39c7e6174cebc5 | [] | no_license | TypHo22/SFND_LIDAR_Obstacle | 02044774ce7afa1642444c250acc58e8e4d4452d | a118e5e50726fbc4a28bb43a2146e014731161a3 | refs/heads/main | 2023-04-22T19:03:25.627174 | 2021-05-15T14:51:34 | 2021-05-15T14:51:34 | 367,656,581 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,078 | cpp | // PCL lib Functions for processing point clouds
#include "processPointClouds.h"
#include <memory.h>
//constructor:
template<typename PointT>
ProcessPointClouds<PointT>::ProcessPointClouds() {}
//de-constructor:
template<typename PointT>
ProcessPointClouds<PointT>::~ProcessPointClouds() {}
template<typename PointT>
void ProcessPointClouds<PointT>::numPoints(typename pcl::PointCloud<PointT>::Ptr cloud)
{
std::cout << cloud->points.size() << std::endl;
}
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr ProcessPointClouds<PointT>::FilterCloud(typename pcl::PointCloud<PointT>::Ptr cloud, float filterRes, Eigen::Vector4f minPoint, Eigen::Vector4f maxPoint)
{
// Time segmentation process
auto startTime = std::chrono::steady_clock::now();
// TODO:: Fill in the function to do voxel grid point reduction and region based filtering
pcl::VoxelGrid<PointT> vg;
typename pcl::PointCloud<PointT>::Ptr cloudFiltered (new pcl::PointCloud<PointT>);
vg.setInputCloud(cloud);
vg.setLeafSize(filterRes, filterRes, filterRes);
vg.filter(*cloudFiltered);
typename pcl::PointCloud<PointT>::Ptr cloudRegion (new pcl::PointCloud<PointT>);
pcl::CropBox<PointT> region(true);
region.setMin(minPoint);
region.setMax(maxPoint);
region.setInputCloud(cloudFiltered);
region.filter(*cloudRegion);
std::vector<int> indices;
pcl::CropBox<PointT> roof(true);
roof.setMin(Eigen::Vector4f(-1.5, -1.7, -1, 1));
roof.setMax(Eigen::Vector4f(2.6, 1.7, -0.4, 1));
roof.setInputCloud(cloudRegion);
roof.filter(indices);
pcl::PointIndices::Ptr inliers{new pcl::PointIndices};
for (int point : indices) {
inliers->indices.push_back(point);
}
pcl::ExtractIndices<PointT> extract;
extract.setInputCloud(cloudRegion);
extract.setIndices(inliers);
extract.setNegative(true);
extract.filter(*cloudRegion);
auto endTime = std::chrono::steady_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
std::cout << "filtering took " << elapsedTime.count() << " milliseconds" << std::endl;
return cloudRegion;
}
template<typename PointT>
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> ProcessPointClouds<PointT>::SeparateClouds(
pcl::PointIndices::Ptr inliers, typename pcl::PointCloud<PointT>::Ptr cloud)
{
// TODO: Create two new point clouds, one cloud with obstacles and other with segmented plane
typename pcl::PointCloud<PointT>::Ptr obstCloud (new pcl::PointCloud<PointT>());
typename pcl::PointCloud<PointT>::Ptr planeCloud (new pcl::PointCloud<PointT> ());
for(int index : inliers.get()->indices)
planeCloud->points.push_back(cloud->points[index]);
pcl::ExtractIndices<PointT> extract;
extract.setInputCloud(cloud);
extract.setIndices(inliers);
extract.setNegative(true);
extract.filter(*obstCloud);
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> segResult(obstCloud, planeCloud);
//std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> segResult(cloud, cloud);
return segResult;
}
template<typename PointT>
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> ProcessPointClouds<PointT>::SegmentPlane(
typename pcl::PointCloud<PointT>::Ptr cloud,
int maxIterations,
float distanceThreshold)
{
// Time segmentation process
auto startTime = std::chrono::steady_clock::now();
// TODO:: Fill in this function to find inliers for the cloud.
pcl::SACSegmentation<PointT> seg;
pcl::PointIndices::Ptr inliers {new pcl::PointIndices};
pcl::ModelCoefficients::Ptr coefficients {new pcl::ModelCoefficients};
seg.setOptimizeCoefficients(true);
seg.setModelType(pcl::SACMODEL_PLANE);
seg.setMethodType(pcl::SAC_RANSAC);
seg.setMaxIterations(maxIterations);
seg.setDistanceThreshold(distanceThreshold);
seg.setInputCloud(cloud);
seg.segment(*inliers,*coefficients);
if(inliers.get()->indices.size() == 0)
std::cout<< "Could not estimate a planar model for the given dataset."<<std::endl;
std::pair<typename pcl::PointCloud<PointT>::Ptr, typename pcl::PointCloud<PointT>::Ptr> segResult = SeparateClouds(inliers,cloud);
auto endTime = std::chrono::steady_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
std::cout << "plane segmentation took " << elapsedTime.count() << " milliseconds" << std::endl;
return segResult;
}
template<typename PointT>
std::vector<typename pcl::PointCloud<PointT>::Ptr> ProcessPointClouds<PointT>::Clustering(typename pcl::PointCloud<PointT>::Ptr cloud, float clusterTolerance, int minSize, int maxSize)
{
// Time clustering process
auto startTime = std::chrono::steady_clock::now();
std::vector<typename pcl::PointCloud<PointT>::Ptr> clusters;
// TODO:: Fill in the function to perform euclidean clustering to group detected obstacles
typename pcl::search::KdTree<PointT>::Ptr tree(new pcl::search::KdTree<PointT>);
// Input obstacle point cloud to create KD-tree
tree->setInputCloud(cloud);
std::vector<pcl::PointIndices> cluster_indices; // this is point cloud indice type
pcl::EuclideanClusterExtraction<PointT> ec; // clustering object
ec.setClusterTolerance(clusterTolerance);
ec.setMinClusterSize(minSize);
ec.setMaxClusterSize(maxSize);
ec.setSearchMethod(tree);
ec.setInputCloud(cloud); // feed point cloud
ec.extract(cluster_indices); // get all clusters Indice
for(pcl::PointIndices getIndices : cluster_indices)
{
typename pcl::PointCloud<PointT>::Ptr cloudCluster (new pcl::PointCloud<PointT>);
for(int index : getIndices.indices)
cloudCluster->points.push_back(cloud.get()->points[index]);
cloudCluster->width = cloudCluster->points.size();
cloudCluster->height = 1;
cloudCluster->is_dense = true;
clusters.push_back(cloudCluster);
}
auto endTime = std::chrono::steady_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
std::cout << "clustering took " << elapsedTime.count() << " milliseconds and found " << clusters.size() << " clusters" << std::endl;
return clusters;
}
template<typename PointT>
Box ProcessPointClouds<PointT>::BoundingBox(typename pcl::PointCloud<PointT>::Ptr cluster)
{
// Find bounding box for one of the clusters
PointT minPoint, maxPoint;
pcl::getMinMax3D(*cluster, minPoint, maxPoint);
Box box;
box.x_min = minPoint.x;
box.y_min = minPoint.y;
box.z_min = minPoint.z;
box.x_max = maxPoint.x;
box.y_max = maxPoint.y;
box.z_max = maxPoint.z;
return box;
}
template<typename PointT>
void ProcessPointClouds<PointT>::savePcd(typename pcl::PointCloud<PointT>::Ptr cloud, std::string file)
{
pcl::io::savePCDFileASCII (file, *cloud);
std::cerr << "Saved " << cloud->points.size () << " data points to "+file << std::endl;
}
template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr ProcessPointClouds<PointT>::loadPcd(std::string file)
{
typename pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>);
if (pcl::io::loadPCDFile<PointT> (file, *cloud) == -1) //* load the file
{
PCL_ERROR ("Couldn't read file \n");
}
std::cerr << "Loaded " << cloud->points.size () << " data points from "+file << std::endl;
return cloud;
}
template<typename PointT>
std::vector<boost::filesystem::path> ProcessPointClouds<PointT>::streamPcd(std::string dataPath)
{
std::vector<boost::filesystem::path> paths(boost::filesystem::directory_iterator{dataPath}, boost::filesystem::directory_iterator{});
// sort files in accending order so playback is chronological
sort(paths.begin(), paths.end());
return paths;
}
| [
"42981587+TypHo22@users.noreply.github.com"
] | 42981587+TypHo22@users.noreply.github.com |
1c13da63e91fc186dd2f48ef77e49022a5748f94 | 1284efd6d722ba290df712e17dd0f57fd23fab3d | /CAPI/CAPI/CAPI/include/linux/tclap/UnlabeledMultiArg.h | b98c18ad96b3996f5600e7690064dfa9da2543dc | [
"MIT"
] | permissive | godfather991/THUAI4 | f93cc30cf7b29d3fd20f6281467e082add5a032b | 2921a64c7ac768c5f45de06d34a21a7a24360128 | refs/heads/dev | 2023-04-29T05:15:06.088447 | 2021-05-14T12:05:28 | 2021-05-14T12:05:28 | 352,122,831 | 0 | 0 | MIT | 2021-04-22T08:51:29 | 2021-03-27T16:35:00 | C++ | UTF-8 | C++ | false | false | 9,895 | h | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
/******************************************************************************
*
* file: UnlabeledMultiArg.h
*
* Copyright (c) 2003, Michael E. Smoot.
* Copyright (c) 2017, Google LLC
* All rights reserved.
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_UNLABELED_MULTI_ARG_H
#define TCLAP_UNLABELED_MULTI_ARG_H
#include <tclap/MultiArg.h>
#include <tclap/OptionalUnlabeledTracker.h>
#include <list>
#include <string>
#include <vector>
namespace TCLAP {
/**
* Just like a MultiArg, except that the arguments are unlabeled. Basically,
* this Arg will slurp up everything that hasn't been matched to another
* Arg.
*/
template <class T>
class UnlabeledMultiArg : public MultiArg<T> {
// If compiler has two stage name lookup (as gcc >= 3.4 does)
// this is required to prevent undef. symbols
using MultiArg<T>::_ignoreable;
using MultiArg<T>::_hasBlanks;
using MultiArg<T>::_extractValue;
using MultiArg<T>::_typeDesc;
using MultiArg<T>::_name;
using MultiArg<T>::_description;
using MultiArg<T>::_alreadySet;
using MultiArg<T>::_setBy;
using MultiArg<T>::toString;
public:
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg(const std::string &name, const std::string &desc,
bool req, const std::string &typeDesc,
bool ignoreable = false, Visitor *v = NULL);
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg(const std::string &name, const std::string &desc,
bool req, const std::string &typeDesc,
ArgContainer &parser, bool ignoreable = false,
Visitor *v = NULL);
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg(const std::string &name, const std::string &desc,
bool req, Constraint<T> *constraint,
bool ignoreable = false, Visitor *v = NULL);
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg(const std::string &name, const std::string &desc,
bool req, Constraint<T> *constraint, ArgContainer &parser,
bool ignoreable = false, Visitor *v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference
* between labeled and unlabeled.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed from main().
*/
virtual bool processArg(int *i, std::vector<std::string> &args);
/**
* Returns the a short id string. Used in the usage.
*/
virtual std::string shortID(const std::string &) const {
return Arg::getName() + " ...";
}
/**
* Returns the a long id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string longID(const std::string &) const {
return Arg::getName() + " (accepted multiple times) <" + _typeDesc +
">";
}
/**
* Operator ==.
* \param a - The Arg to be compared to this.
*/
virtual bool operator==(const Arg &a) const;
/**
* Pushes this to back of list rather than front.
* \param argList - The list this should be added to.
*/
virtual void addToList(std::list<Arg *> &argList) const;
virtual bool hasLabel() const { return false; }
};
template <class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name,
const std::string &desc, bool req,
const std::string &typeDesc,
bool ignoreable, Visitor *v)
: MultiArg<T>("", name, desc, req, typeDesc, v) {
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
}
template <class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name,
const std::string &desc, bool req,
const std::string &typeDesc,
ArgContainer &parser, bool ignoreable,
Visitor *v)
: MultiArg<T>("", name, desc, req, typeDesc, v) {
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
parser.add(this);
}
template <class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name,
const std::string &desc, bool req,
Constraint<T> *constraint,
bool ignoreable, Visitor *v)
: MultiArg<T>("", name, desc, req, constraint, v) {
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
}
template <class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name,
const std::string &desc, bool req,
Constraint<T> *constraint,
ArgContainer &parser, bool ignoreable,
Visitor *v)
: MultiArg<T>("", name, desc, req, constraint, v) {
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
parser.add(this);
}
template <class T>
bool UnlabeledMultiArg<T>::processArg(int *i, std::vector<std::string> &args) {
if (_hasBlanks(args[*i])) return false;
// never ignore an unlabeled multi arg
// always take the first value, regardless of the start string
_extractValue(args[(*i)]);
/*
// continue taking args until we hit the end or a start string
while ( (unsigned int)(*i)+1 < args.size() &&
args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 )
_extractValue( args[++(*i)] );
*/
_alreadySet = true;
_setBy = args[*i];
return true;
}
template <class T>
bool UnlabeledMultiArg<T>::operator==(const Arg &a) const {
if (_name == a.getName() || _description == a.getDescription())
return true;
else
return false;
}
template <class T>
void UnlabeledMultiArg<T>::addToList(std::list<Arg *> &argList) const {
argList.push_back(const_cast<Arg *>(static_cast<const Arg *const>(this)));
}
} // namespace TCLAP
#endif // TCLAP_UNLABELED_MULTI_ARG_H
| [
"hesicheng2001@163.com"
] | hesicheng2001@163.com |
b6ddced83fdf46bb77fbd710fc3edb9db7ab6e70 | ada03eb58d8ad648bd7b1e831da2553f96b61aa6 | /src/mean_std.h | 0f7f03b028649789a2f744acb12c9707df369862 | [] | no_license | rising-turtle/error_comp | ebdaf12ef8015e2cf4b441238a8f7c57120b0f25 | 751bf5d538cec0075780e6703ec8e28ae797a1ad | refs/heads/master | 2020-07-07T18:56:43.029193 | 2020-05-03T18:23:12 | 2020-05-03T18:23:12 | 203,445,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 564 | h |
/*
* Sep. 23, 2015, David Z
*
* compute the mean and sigma of an array of data
*
* */
#ifndef MEAN_SIGMA_H
#define MEAN_SIGMA_H
#include <cmath>
template<typename T>
bool compute_mu_sigma(T* in, int N, T& mu, T& sigma)
{
if(N<=0)
{
mu = 0;
sigma = 0;
return false;
}
// compute mu
T total = 0;
for(int i=0; i<N; i++)
{
total += in[i];
}
mu = total/(T)(N);
// compute sigma
total = 0;
for(int i=0; i<N; i++)
{
total += (in[i]-mu)*(in[i]-mu);
}
sigma = sqrt(total/(T)N);
return true;
}
#endif
| [
"hzhang8@vcu.edu"
] | hzhang8@vcu.edu |
7b0c46c4b96284227876b72e50b8d68647a526f5 | 88c0e520e2389e676fea559f944109e1ee7e157b | /include/Windows.ApplicationModel.Background.2_4bc8ceb3.h | 09cfc2e46082a6f8007de5a7cc76bc08fd67a861 | [] | no_license | jchoi2022/NtFuzz-HeaderData | fb4ecbd5399f4fac6a4982a0fb516dd7f9368118 | 6adc3d339e6cac072cde6cfef07eccafbc6b204c | refs/heads/main | 2023-08-03T02:26:10.666986 | 2021-09-17T13:35:26 | 2021-09-17T13:35:26 | 407,547,359 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,137 | h |
#include "winrt/impl/Windows.ApplicationModel.Activation.1.h"
#include "winrt/impl/Windows.ApplicationModel.Calls.Background.1.h"
#include "winrt/impl/Windows.Devices.Bluetooth.1.h"
#include "winrt/impl/Windows.Devices.Bluetooth.Advertisement.1.h"
#include "winrt/impl/Windows.Devices.Bluetooth.Background.1.h"
#include "winrt/impl/Windows.Devices.Bluetooth.GenericAttributeProfile.1.h"
#include "winrt/impl/Windows.Devices.Geolocation.1.h"
#include "winrt/impl/Windows.Devices.Sensors.1.h"
#include "winrt/impl/Windows.Devices.SmartCards.1.h"
#include "winrt/impl/Windows.Devices.Sms.1.h"
#include "winrt/impl/Windows.Foundation.Collections.1.h"
#include "winrt/impl/Windows.Networking.1.h"
#include "winrt/impl/Windows.Networking.Sockets.1.h"
#include "winrt/impl/Windows.Storage.1.h"
#include "winrt/impl/Windows.Storage.Provider.1.h"
#include "winrt/impl/Windows.System.1.h"
#include "winrt/impl/Windows.UI.Notifications.1.h"
#include "winrt/impl/Windows.ApplicationModel.Background.1.h"
WINRT_EXPORT namespace winrt::Windows::ApplicationModel::Background {
struct BackgroundTaskCanceledEventHandler : Windows::Foundation::IUnknown
{
BackgroundTaskCanceledEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> BackgroundTaskCanceledEventHandler(L lambda);
template <typename F> BackgroundTaskCanceledEventHandler(F* function);
template <typename O, typename M> BackgroundTaskCanceledEventHandler(O* object, M method);
template <typename O, typename M> BackgroundTaskCanceledEventHandler(com_ptr<O>&& object, M method);
template <typename O, typename M> BackgroundTaskCanceledEventHandler(weak_ref<O>&& object, M method);
void operator()(Windows::ApplicationModel::Background::IBackgroundTaskInstance const& sender, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason const& reason) const;
};
struct BackgroundTaskCompletedEventHandler : Windows::Foundation::IUnknown
{
BackgroundTaskCompletedEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> BackgroundTaskCompletedEventHandler(L lambda);
template <typename F> BackgroundTaskCompletedEventHandler(F* function);
template <typename O, typename M> BackgroundTaskCompletedEventHandler(O* object, M method);
template <typename O, typename M> BackgroundTaskCompletedEventHandler(com_ptr<O>&& object, M method);
template <typename O, typename M> BackgroundTaskCompletedEventHandler(weak_ref<O>&& object, M method);
void operator()(Windows::ApplicationModel::Background::BackgroundTaskRegistration const& sender, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs const& args) const;
};
struct BackgroundTaskProgressEventHandler : Windows::Foundation::IUnknown
{
BackgroundTaskProgressEventHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> BackgroundTaskProgressEventHandler(L lambda);
template <typename F> BackgroundTaskProgressEventHandler(F* function);
template <typename O, typename M> BackgroundTaskProgressEventHandler(O* object, M method);
template <typename O, typename M> BackgroundTaskProgressEventHandler(com_ptr<O>&& object, M method);
template <typename O, typename M> BackgroundTaskProgressEventHandler(weak_ref<O>&& object, M method);
void operator()(Windows::ApplicationModel::Background::BackgroundTaskRegistration const& sender, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs const& args) const;
};
}
namespace winrt::impl {
}
WINRT_EXPORT namespace winrt::Windows::ApplicationModel::Background {
struct WINRT_EBO ActivitySensorTrigger :
Windows::ApplicationModel::Background::IActivitySensorTrigger
{
ActivitySensorTrigger(std::nullptr_t) noexcept {}
ActivitySensorTrigger(uint32_t reportIntervalInMilliseconds);
};
struct AlarmApplicationManager
{
AlarmApplicationManager() = delete;
static Windows::Foundation::IAsyncOperation<Windows::ApplicationModel::Background::AlarmAccessStatus> RequestAccessAsync();
static Windows::ApplicationModel::Background::AlarmAccessStatus GetAccessStatus();
};
struct WINRT_EBO AppBroadcastTrigger :
Windows::ApplicationModel::Background::IAppBroadcastTrigger
{
AppBroadcastTrigger(std::nullptr_t) noexcept {}
AppBroadcastTrigger(param::hstring const& providerKey);
};
struct WINRT_EBO AppBroadcastTriggerProviderInfo :
Windows::ApplicationModel::Background::IAppBroadcastTriggerProviderInfo
{
AppBroadcastTriggerProviderInfo(std::nullptr_t) noexcept {}
};
struct WINRT_EBO ApplicationTrigger :
Windows::ApplicationModel::Background::IApplicationTrigger
{
ApplicationTrigger(std::nullptr_t) noexcept {}
ApplicationTrigger();
};
struct WINRT_EBO ApplicationTriggerDetails :
Windows::ApplicationModel::Background::IApplicationTriggerDetails
{
ApplicationTriggerDetails(std::nullptr_t) noexcept {}
};
struct WINRT_EBO AppointmentStoreNotificationTrigger :
Windows::ApplicationModel::Background::IAppointmentStoreNotificationTrigger
{
AppointmentStoreNotificationTrigger(std::nullptr_t) noexcept {}
AppointmentStoreNotificationTrigger();
};
struct BackgroundExecutionManager
{
BackgroundExecutionManager() = delete;
static Windows::Foundation::IAsyncOperation<Windows::ApplicationModel::Background::BackgroundAccessStatus> RequestAccessAsync();
static Windows::Foundation::IAsyncOperation<Windows::ApplicationModel::Background::BackgroundAccessStatus> RequestAccessAsync(param::hstring const& applicationId);
static void RemoveAccess();
static void RemoveAccess(param::hstring const& applicationId);
static Windows::ApplicationModel::Background::BackgroundAccessStatus GetAccessStatus();
static Windows::ApplicationModel::Background::BackgroundAccessStatus GetAccessStatus(param::hstring const& applicationId);
static Windows::Foundation::IAsyncOperation<bool> RequestAccessKindAsync(Windows::ApplicationModel::Background::BackgroundAccessRequestKind const& requestedAccess, param::hstring const& reason);
};
struct WINRT_EBO BackgroundTaskBuilder :
Windows::ApplicationModel::Background::IBackgroundTaskBuilder,
impl::require<BackgroundTaskBuilder, Windows::ApplicationModel::Background::IBackgroundTaskBuilder2, Windows::ApplicationModel::Background::IBackgroundTaskBuilder3, Windows::ApplicationModel::Background::IBackgroundTaskBuilder4>
{
BackgroundTaskBuilder(std::nullptr_t) noexcept {}
BackgroundTaskBuilder();
};
struct WINRT_EBO BackgroundTaskCompletedEventArgs :
Windows::ApplicationModel::Background::IBackgroundTaskCompletedEventArgs
{
BackgroundTaskCompletedEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO BackgroundTaskDeferral :
Windows::ApplicationModel::Background::IBackgroundTaskDeferral
{
BackgroundTaskDeferral(std::nullptr_t) noexcept {}
};
struct WINRT_EBO BackgroundTaskProgressEventArgs :
Windows::ApplicationModel::Background::IBackgroundTaskProgressEventArgs
{
BackgroundTaskProgressEventArgs(std::nullptr_t) noexcept {}
};
struct WINRT_EBO BackgroundTaskRegistration :
Windows::ApplicationModel::Background::IBackgroundTaskRegistration,
impl::require<BackgroundTaskRegistration, Windows::ApplicationModel::Background::IBackgroundTaskRegistration2, Windows::ApplicationModel::Background::IBackgroundTaskRegistration3>
{
BackgroundTaskRegistration(std::nullptr_t) noexcept {}
static Windows::Foundation::Collections::IMapView<winrt::guid, Windows::ApplicationModel::Background::IBackgroundTaskRegistration> AllTasks();
static Windows::Foundation::Collections::IMapView<hstring, Windows::ApplicationModel::Background::BackgroundTaskRegistrationGroup> AllTaskGroups();
static Windows::ApplicationModel::Background::BackgroundTaskRegistrationGroup GetTaskGroup(param::hstring const& groupId);
};
struct WINRT_EBO BackgroundTaskRegistrationGroup :
Windows::ApplicationModel::Background::IBackgroundTaskRegistrationGroup
{
BackgroundTaskRegistrationGroup(std::nullptr_t) noexcept {}
BackgroundTaskRegistrationGroup(param::hstring const& id);
BackgroundTaskRegistrationGroup(param::hstring const& id, param::hstring const& name);
};
struct BackgroundWorkCost
{
BackgroundWorkCost() = delete;
static Windows::ApplicationModel::Background::BackgroundWorkCostValue CurrentBackgroundWorkCost();
};
struct WINRT_EBO BluetoothLEAdvertisementPublisherTrigger :
Windows::ApplicationModel::Background::IBluetoothLEAdvertisementPublisherTrigger
{
BluetoothLEAdvertisementPublisherTrigger(std::nullptr_t) noexcept {}
BluetoothLEAdvertisementPublisherTrigger();
};
struct WINRT_EBO BluetoothLEAdvertisementWatcherTrigger :
Windows::ApplicationModel::Background::IBluetoothLEAdvertisementWatcherTrigger
{
BluetoothLEAdvertisementWatcherTrigger(std::nullptr_t) noexcept {}
BluetoothLEAdvertisementWatcherTrigger();
};
struct WINRT_EBO CachedFileUpdaterTrigger :
Windows::ApplicationModel::Background::ICachedFileUpdaterTrigger
{
CachedFileUpdaterTrigger(std::nullptr_t) noexcept {}
CachedFileUpdaterTrigger();
};
struct WINRT_EBO CachedFileUpdaterTriggerDetails :
Windows::ApplicationModel::Background::ICachedFileUpdaterTriggerDetails
{
CachedFileUpdaterTriggerDetails(std::nullptr_t) noexcept {}
};
struct WINRT_EBO ChatMessageNotificationTrigger :
Windows::ApplicationModel::Background::IChatMessageNotificationTrigger
{
ChatMessageNotificationTrigger(std::nullptr_t) noexcept {}
ChatMessageNotificationTrigger();
};
struct WINRT_EBO ChatMessageReceivedNotificationTrigger :
Windows::ApplicationModel::Background::IChatMessageReceivedNotificationTrigger
{
ChatMessageReceivedNotificationTrigger(std::nullptr_t) noexcept {}
ChatMessageReceivedNotificationTrigger();
};
struct WINRT_EBO CommunicationBlockingAppSetAsActiveTrigger :
Windows::ApplicationModel::Background::ICommunicationBlockingAppSetAsActiveTrigger
{
CommunicationBlockingAppSetAsActiveTrigger(std::nullptr_t) noexcept {}
CommunicationBlockingAppSetAsActiveTrigger();
};
struct WINRT_EBO ContactStoreNotificationTrigger :
Windows::ApplicationModel::Background::IContactStoreNotificationTrigger
{
ContactStoreNotificationTrigger(std::nullptr_t) noexcept {}
ContactStoreNotificationTrigger();
};
struct WINRT_EBO ContentPrefetchTrigger :
Windows::ApplicationModel::Background::IContentPrefetchTrigger
{
ContentPrefetchTrigger(std::nullptr_t) noexcept {}
ContentPrefetchTrigger();
ContentPrefetchTrigger(Windows::Foundation::TimeSpan const& waitInterval);
};
struct WINRT_EBO ConversationalAgentTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
ConversationalAgentTrigger(std::nullptr_t) noexcept {}
ConversationalAgentTrigger();
};
struct WINRT_EBO CustomSystemEventTrigger :
Windows::ApplicationModel::Background::ICustomSystemEventTrigger,
impl::require<CustomSystemEventTrigger, Windows::ApplicationModel::Background::IBackgroundTrigger>
{
CustomSystemEventTrigger(std::nullptr_t) noexcept {}
CustomSystemEventTrigger(param::hstring const& triggerId, Windows::ApplicationModel::Background::CustomSystemEventTriggerRecurrence const& recurrence);
};
struct WINRT_EBO DeviceConnectionChangeTrigger :
Windows::ApplicationModel::Background::IDeviceConnectionChangeTrigger
{
DeviceConnectionChangeTrigger(std::nullptr_t) noexcept {}
static Windows::Foundation::IAsyncOperation<Windows::ApplicationModel::Background::DeviceConnectionChangeTrigger> FromIdAsync(param::hstring const& deviceId);
};
struct WINRT_EBO DeviceManufacturerNotificationTrigger :
Windows::ApplicationModel::Background::IDeviceManufacturerNotificationTrigger
{
DeviceManufacturerNotificationTrigger(std::nullptr_t) noexcept {}
DeviceManufacturerNotificationTrigger(param::hstring const& triggerQualifier, bool oneShot);
};
struct WINRT_EBO DeviceServicingTrigger :
Windows::ApplicationModel::Background::IDeviceServicingTrigger
{
DeviceServicingTrigger(std::nullptr_t) noexcept {}
DeviceServicingTrigger();
};
struct WINRT_EBO DeviceUseTrigger :
Windows::ApplicationModel::Background::IDeviceUseTrigger
{
DeviceUseTrigger(std::nullptr_t) noexcept {}
DeviceUseTrigger();
};
struct WINRT_EBO DeviceWatcherTrigger :
Windows::ApplicationModel::Background::IDeviceWatcherTrigger
{
DeviceWatcherTrigger(std::nullptr_t) noexcept {}
};
struct WINRT_EBO EmailStoreNotificationTrigger :
Windows::ApplicationModel::Background::IEmailStoreNotificationTrigger
{
EmailStoreNotificationTrigger(std::nullptr_t) noexcept {}
EmailStoreNotificationTrigger();
};
struct WINRT_EBO GattCharacteristicNotificationTrigger :
Windows::ApplicationModel::Background::IGattCharacteristicNotificationTrigger,
impl::require<GattCharacteristicNotificationTrigger, Windows::ApplicationModel::Background::IGattCharacteristicNotificationTrigger2>
{
GattCharacteristicNotificationTrigger(std::nullptr_t) noexcept {}
GattCharacteristicNotificationTrigger(Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic const& characteristic);
GattCharacteristicNotificationTrigger(Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic const& characteristic, Windows::Devices::Bluetooth::Background::BluetoothEventTriggeringMode const& eventTriggeringMode);
};
struct WINRT_EBO GattServiceProviderTrigger :
Windows::ApplicationModel::Background::IGattServiceProviderTrigger,
impl::require<GattServiceProviderTrigger, Windows::ApplicationModel::Background::IBackgroundTrigger>
{
GattServiceProviderTrigger(std::nullptr_t) noexcept {}
static Windows::Foundation::IAsyncOperation<Windows::ApplicationModel::Background::GattServiceProviderTriggerResult> CreateAsync(param::hstring const& triggerId, winrt::guid const& serviceUuid);
};
struct WINRT_EBO GattServiceProviderTriggerResult :
Windows::ApplicationModel::Background::IGattServiceProviderTriggerResult
{
GattServiceProviderTriggerResult(std::nullptr_t) noexcept {}
};
struct WINRT_EBO GeovisitTrigger :
Windows::ApplicationModel::Background::IGeovisitTrigger
{
GeovisitTrigger(std::nullptr_t) noexcept {}
GeovisitTrigger();
};
struct WINRT_EBO LocationTrigger :
Windows::ApplicationModel::Background::ILocationTrigger
{
LocationTrigger(std::nullptr_t) noexcept {}
LocationTrigger(Windows::ApplicationModel::Background::LocationTriggerType const& triggerType);
};
struct WINRT_EBO MaintenanceTrigger :
Windows::ApplicationModel::Background::IMaintenanceTrigger
{
MaintenanceTrigger(std::nullptr_t) noexcept {}
MaintenanceTrigger(uint32_t freshnessTime, bool oneShot);
};
struct WINRT_EBO MediaProcessingTrigger :
Windows::ApplicationModel::Background::IMediaProcessingTrigger
{
MediaProcessingTrigger(std::nullptr_t) noexcept {}
MediaProcessingTrigger();
};
struct WINRT_EBO MobileBroadbandDeviceServiceNotificationTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
MobileBroadbandDeviceServiceNotificationTrigger(std::nullptr_t) noexcept {}
MobileBroadbandDeviceServiceNotificationTrigger();
};
struct WINRT_EBO MobileBroadbandPcoDataChangeTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
MobileBroadbandPcoDataChangeTrigger(std::nullptr_t) noexcept {}
MobileBroadbandPcoDataChangeTrigger();
};
struct WINRT_EBO MobileBroadbandPinLockStateChangeTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
MobileBroadbandPinLockStateChangeTrigger(std::nullptr_t) noexcept {}
MobileBroadbandPinLockStateChangeTrigger();
};
struct WINRT_EBO MobileBroadbandRadioStateChangeTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
MobileBroadbandRadioStateChangeTrigger(std::nullptr_t) noexcept {}
MobileBroadbandRadioStateChangeTrigger();
};
struct WINRT_EBO MobileBroadbandRegistrationStateChangeTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
MobileBroadbandRegistrationStateChangeTrigger(std::nullptr_t) noexcept {}
MobileBroadbandRegistrationStateChangeTrigger();
};
struct WINRT_EBO NetworkOperatorDataUsageTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
NetworkOperatorDataUsageTrigger(std::nullptr_t) noexcept {}
NetworkOperatorDataUsageTrigger();
};
struct WINRT_EBO NetworkOperatorHotspotAuthenticationTrigger :
Windows::ApplicationModel::Background::INetworkOperatorHotspotAuthenticationTrigger
{
NetworkOperatorHotspotAuthenticationTrigger(std::nullptr_t) noexcept {}
NetworkOperatorHotspotAuthenticationTrigger();
};
struct WINRT_EBO NetworkOperatorNotificationTrigger :
Windows::ApplicationModel::Background::INetworkOperatorNotificationTrigger
{
NetworkOperatorNotificationTrigger(std::nullptr_t) noexcept {}
NetworkOperatorNotificationTrigger(param::hstring const& networkAccountId);
};
struct WINRT_EBO PaymentAppCanMakePaymentTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
PaymentAppCanMakePaymentTrigger(std::nullptr_t) noexcept {}
PaymentAppCanMakePaymentTrigger();
};
struct WINRT_EBO PhoneTrigger :
Windows::ApplicationModel::Background::IPhoneTrigger
{
PhoneTrigger(std::nullptr_t) noexcept {}
PhoneTrigger(Windows::ApplicationModel::Calls::Background::PhoneTriggerType const& type, bool oneShot);
};
struct WINRT_EBO PushNotificationTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
PushNotificationTrigger(std::nullptr_t) noexcept {}
PushNotificationTrigger();
PushNotificationTrigger(param::hstring const& applicationId);
};
struct WINRT_EBO RcsEndUserMessageAvailableTrigger :
Windows::ApplicationModel::Background::IRcsEndUserMessageAvailableTrigger
{
RcsEndUserMessageAvailableTrigger(std::nullptr_t) noexcept {}
RcsEndUserMessageAvailableTrigger();
};
struct WINRT_EBO RfcommConnectionTrigger :
Windows::ApplicationModel::Background::IRfcommConnectionTrigger
{
RfcommConnectionTrigger(std::nullptr_t) noexcept {}
RfcommConnectionTrigger();
};
struct WINRT_EBO SecondaryAuthenticationFactorAuthenticationTrigger :
Windows::ApplicationModel::Background::ISecondaryAuthenticationFactorAuthenticationTrigger
{
SecondaryAuthenticationFactorAuthenticationTrigger(std::nullptr_t) noexcept {}
SecondaryAuthenticationFactorAuthenticationTrigger();
};
struct WINRT_EBO SensorDataThresholdTrigger :
Windows::ApplicationModel::Background::ISensorDataThresholdTrigger
{
SensorDataThresholdTrigger(std::nullptr_t) noexcept {}
SensorDataThresholdTrigger(Windows::Devices::Sensors::ISensorDataThreshold const& threshold);
};
struct WINRT_EBO SmartCardTrigger :
Windows::ApplicationModel::Background::ISmartCardTrigger
{
SmartCardTrigger(std::nullptr_t) noexcept {}
SmartCardTrigger(Windows::Devices::SmartCards::SmartCardTriggerType const& triggerType);
};
struct WINRT_EBO SmsMessageReceivedTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
SmsMessageReceivedTrigger(std::nullptr_t) noexcept {}
SmsMessageReceivedTrigger(Windows::Devices::Sms::SmsFilterRules const& filterRules);
};
struct WINRT_EBO SocketActivityTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger,
impl::require<SocketActivityTrigger, Windows::ApplicationModel::Background::ISocketActivityTrigger>
{
SocketActivityTrigger(std::nullptr_t) noexcept {}
SocketActivityTrigger();
};
struct WINRT_EBO StorageLibraryChangeTrackerTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
StorageLibraryChangeTrackerTrigger(std::nullptr_t) noexcept {}
StorageLibraryChangeTrackerTrigger(Windows::Storage::StorageLibraryChangeTracker const& tracker);
};
struct WINRT_EBO StorageLibraryContentChangedTrigger :
Windows::ApplicationModel::Background::IStorageLibraryContentChangedTrigger
{
StorageLibraryContentChangedTrigger(std::nullptr_t) noexcept {}
static Windows::ApplicationModel::Background::StorageLibraryContentChangedTrigger Create(Windows::Storage::StorageLibrary const& storageLibrary);
static Windows::ApplicationModel::Background::StorageLibraryContentChangedTrigger CreateFromLibraries(param::iterable<Windows::Storage::StorageLibrary> const& storageLibraries);
};
struct WINRT_EBO SystemCondition :
Windows::ApplicationModel::Background::ISystemCondition
{
SystemCondition(std::nullptr_t) noexcept {}
SystemCondition(Windows::ApplicationModel::Background::SystemConditionType const& conditionType);
};
struct WINRT_EBO SystemTrigger :
Windows::ApplicationModel::Background::ISystemTrigger
{
SystemTrigger(std::nullptr_t) noexcept {}
SystemTrigger(Windows::ApplicationModel::Background::SystemTriggerType const& triggerType, bool oneShot);
};
struct WINRT_EBO TetheringEntitlementCheckTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
TetheringEntitlementCheckTrigger(std::nullptr_t) noexcept {}
TetheringEntitlementCheckTrigger();
};
struct WINRT_EBO TimeTrigger :
Windows::ApplicationModel::Background::ITimeTrigger
{
TimeTrigger(std::nullptr_t) noexcept {}
TimeTrigger(uint32_t freshnessTime, bool oneShot);
};
struct WINRT_EBO ToastNotificationActionTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
ToastNotificationActionTrigger(std::nullptr_t) noexcept {}
ToastNotificationActionTrigger();
ToastNotificationActionTrigger(param::hstring const& applicationId);
};
struct WINRT_EBO ToastNotificationHistoryChangedTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
ToastNotificationHistoryChangedTrigger(std::nullptr_t) noexcept {}
ToastNotificationHistoryChangedTrigger();
ToastNotificationHistoryChangedTrigger(param::hstring const& applicationId);
};
struct WINRT_EBO UserNotificationChangedTrigger :
Windows::ApplicationModel::Background::IBackgroundTrigger
{
UserNotificationChangedTrigger(std::nullptr_t) noexcept {}
UserNotificationChangedTrigger(Windows::UI::Notifications::NotificationKinds const& notificationKinds);
};
}
| [
"jschoi.2022@gmail.com"
] | jschoi.2022@gmail.com |
fe954882594c9bb27b420640b3fc123f79b6ca0f | 8ff8f38ad0c071362f1f4cf93482a9fbfe27719d | /KuStudio/src/kummon/kuPlayerSend.h | dfc8cd1f0e127259cc1db7ec33abb2fe09730207 | [] | no_license | kuflex/KuStudio | 43d6e7e539f01137d45b280a84c61d89167d5f79 | 88aeb210138b1cc990bd22b25de60f9eb09df014 | refs/heads/master | 2021-01-20T18:07:28.387420 | 2020-07-30T13:46:30 | 2020-07-30T13:46:30 | 61,441,101 | 46 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 542 | h | #pragma once
//Посылатель OSC в kuPlayer
#include "ofMain.h"
#include "kuOscSend.h"
class kuPlayerSend : public kuOscSend
{
public:
//kuPlayerSend();
//~kuPlayerSend();
//void setup( string host, int port );
//void setupFromString( const string &s );
//void setupFromDialog( const string &title );
//string toString();
//void start();
//void stop();
//void sendFloat( const string &address, float value );
void sendStop();
void sendTime( float time );
private:
};
| [
"perevalovds@gmail.com"
] | perevalovds@gmail.com |
218d8bc0b2687a694509cf42dbfe5bbdbe8dddd3 | 1d18bbc37229f905e105a65e295f627f8417823b | /BaconBox/Display/Window/NullMainWindow.h | ae2d312556a45126df258e33897769338d80ef97 | [] | no_license | anhero/BaconBox | 57b82a889fe12f5524267a9bb5035973d054706d | afa4b97d86be876f8375f3898667aabb3610c52c | refs/heads/develop | 2021-01-17T09:35:05.986399 | 2017-04-07T04:36:43 | 2017-04-07T04:36:43 | 22,391,368 | 1 | 0 | null | 2015-03-12T19:21:30 | 2014-07-29T18:49:08 | C++ | UTF-8 | C++ | false | false | 2,300 | h | /**
* @file
* @ingroup WindowDisplay
*/
#ifndef BB_NULL_MAIN_WINDOW_H
#define BB_NULL_MAIN_WINDOW_H
#include "BaconBox/Display/Window/MainWindow.h"
namespace BaconBox {
class NullMainWindow : public MainWindow {
friend class BaseEngine;
public:
void onBaconBoxInit(unsigned int resolutionWidth,
unsigned int resolutionHeight,
float contextWidth,
float contextHeight,
WindowOrientation::type orientation);
void setUpdatesPerSecond(double setFrameInterval);
/**
* Activates and opens the window.
*/
void show();
/**
* Changes the caption of the window. This is usually
* the title in the titlebar.
* @param caption The text used to replace the title.
*/
void setCaption(const std::string &caption);
/**
* Checks if the main window is full screen.
* @return True if the main window is in full screen, false if not.
*/
bool isFullScreen() const;
/**
* Makes the main window full screen or not.
* @param newFullScreen If true, sets the main window to full screen.
* If false, makes sure it's not full screen.
*/
void setFullScreen(bool newFullScreen);
/**
* Checks if the main window grabs the input. When the input is
* grabbed, the cursor is invisible.
* @return True if the main window grabbed the input, false if not.
*/
bool isInputGrabbed() const;
/**
* Sets if the main window grabbed the input or not.
* @param newInputGrabbed
*/
void setInputGrabbed(bool newInputGrabbed);
/**
* Set the resolution of the window.
*/
void setResolution(unsigned int resolutionWidth, unsigned int resolutionHeight);
/**
* Hide the pointer. The pointer still work, but it won't be visible.
*/
void hideCursor();
/**
* Show the pointer. If you called hideCursor(), this will reactivate it.
*/
void showCursor();
/**
* Sets the context size. If you want to work in pixels, set them to 0 and they
* will automagically match the current resolution width and height
*/
void setContextSize(float newContextWidth,
float newContextHeight);
private:
NullMainWindow();
~NullMainWindow();
};
}
#endif
| [
"joe.dupuis@anhero.net"
] | joe.dupuis@anhero.net |
fcc905466121f707b6512aa5b3a3847b990a239b | 61eeece81800c3e71d1dd717569524ce92d9ef8a | /Arduino/16_led_control_Arduino/16_led_control_Arduino.ino | 3d78b6445ade476c5bc5732a700e82ad2037250b | [
"MIT"
] | permissive | j1fvandenbosch/IOT-WorkArea-Storage | db775e187512f40165866e529fec80c3d4fadbfb | 3232f1e9afc3d8d05828de11fc85c226ef46a716 | refs/heads/main | 2023-06-02T10:52:00.175772 | 2021-06-20T22:54:03 | 2021-06-20T22:54:03 | 378,742,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,077 | ino | int latchPin = 7;
int clockPin = 12;
int dataPin = 11;
int numOfRegisters = 2;
byte* registerState;
long effectId = 0;
long prevEffect = 0;
long effectRepeat = 0;
long effectSpeed = 30;
void setup() {
//Initialize array
registerState = new byte[numOfRegisters];
for (size_t i = 0; i < numOfRegisters; i++) {
registerState[i] = 0;
}
//set pins to output so you can control the shift register
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void loop() {
do{
effectId = random(6);
} while (effectId == prevEffect);
prevEffect = effectId;
switch (effectId)
{
case 0:
effectRepeat = random(1, 2);
break;
case 1:
effectRepeat = random(1, 2);
break;
case 3:
effectRepeat = random(1, 5);
break;
case 4:
effectRepeat = random(1, 2);
break;
case 5:
effectRepeat = random(1, 2);
break;
}
for (int i = 0; i < effectRepeat; i++) {
effectSpeed = random(10, 90);
switch (effectId)
{
case 0:
effectA(effectSpeed);
break;
case 1:
effectB(effectSpeed);
break;
case 3:
effectC(effectSpeed);
break;
case 4:
effectD(effectSpeed);
break;
case 6:
effectE(effectSpeed);
break;
}
}
}
void effectA(int speed){
for (int i = 0; i < 16; i++){
for (int k = i; k < 16; k++){
regWrite(k, HIGH);
delay(speed);
regWrite(k, LOW);
}
regWrite(i, HIGH);
}
}
void effectB(int speed){
for (int i = 15; i >= 0; i--){
for (int k = 0; k < i; k++){
regWrite(k, HIGH);
delay(speed);
regWrite(k, LOW);
}
regWrite(i, HIGH);
}
}
void effectC(int speed){
int prevI = 0;
for (int i = 0; i < 16; i++){
regWrite(prevI, LOW);
regWrite(i, HIGH);
prevI = i;
delay(speed);
}
for (int i = 15; i >= 0; i--){
regWrite(prevI, LOW);
regWrite(i, HIGH);
prevI = i;
delay(speed);
}
}
void effectD(int speed){
for (int i = 0; i < 8; i++){
for (int k = i; k < 8; k++)
{
regWrite(k, HIGH);
regWrite(15 - k, HIGH);
delay(speed);
regWrite(k, LOW);
regWrite(15 - k, LOW);
}
regWrite(i, HIGH);
regWrite(15 - i, HIGH);
}
}
void effectE(int speed){
for (int i = 7; i >= 0; i--){
for (int k = 0; k <= i; k++)
{
regWrite(k, HIGH);
regWrite(15 - k, HIGH);
delay(speed);
regWrite(k, LOW);
regWrite(15 - k, LOW);
}
regWrite(i, HIGH);
regWrite(15 - i, HIGH);
}
}
void regWrite(int pin, bool state){
//Determines register
int reg = pin / 8;
//Determines pin for actual register
int actualPin = pin - (8 * reg);
//Begin session
digitalWrite(latchPin, LOW);
for (int i = 0; i < numOfRegisters; i++){
//Get actual states for register
byte* states = ®isterState[i];
//Update state
if (i == reg){
bitWrite(*states, actualPin, state);
}
//Write
shiftOut(dataPin, clockPin, MSBFIRST, *states);
}
//End session
digitalWrite(latchPin, HIGH);
}
| [
"75092070+j1fvandenbosch@users.noreply.github.com"
] | 75092070+j1fvandenbosch@users.noreply.github.com |
3cf07fe470fd6628e10891391751a7f2b13e1b84 | 688d5a8227bfd8e7e503a06b256d83f707cdb162 | /pet/PetWorldG4.cc | 8560390aa3509e94894761cfb57dadc713030059 | [] | no_license | pavel1murat/murat | ea65ee1baf5b3335d080585b04e18d0304963097 | d76111a73a18c150e6b5218fc411a2fd05e91e10 | refs/heads/main | 2023-06-11T07:22:18.986114 | 2023-05-24T16:35:22 | 2023-05-24T16:35:22 | 118,154,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,856 | cc | // G4 specific geometry info. Not available in non-geant jobs.
//
// Rob Kutschke, 2011
#include "murat/pet/PetWorldG4.hh"
#include <limits>
#include <algorithm>
#include <iterator>
#include "cetlib/exception.h"
using namespace std;
namespace mu2e {
//-----------------------------------------------------------------------------
PetWorldG4::PetWorldG4() {
}
//-----------------------------------------------------------------------------
// The argument is a point in Mu2e coordinates. Return true if this point
// is inside the G4 world, false otherwise.
//-----------------------------------------------------------------------------
bool PetWorldG4::inWorld( CLHEP::Hep3Vector const& x0InMu2e ) const{
CLHEP::Hep3Vector x0InG4 = x0InMu2e + _mu2eOriginInWorld;
if ( std::abs(x0InG4.x()) > _halfLengths[0] ) return false;
if ( std::abs(x0InG4.y()) > _halfLengths[1] ) return false;
if ( std::abs(x0InG4.z()) > _halfLengths[2] ) return false;
return true;
}
// The arugment is a point in Mu2e coordinates. Throw an exception if this point
// is outside the G4 world.
void PetWorldG4::inWorldOrThrow( CLHEP::Hep3Vector const& x0 ) const{
if ( ! inWorld(x0) ){
throw cet::exception("GEOM")
<< "Point is outside of the G4 world: " << x0 << "\n";
}
return;
}
std::ostream& operator<<(std::ostream& os, const PetWorldG4& w) {
os<<"WordG4(halfLengths = {";
std::copy(w.halfLengths().begin(), w.halfLengths().end(), std::ostream_iterator<double>(os, ", "));
os<<"}, hallFormalHalfSize = {";
std::copy(w.hallFormalHalfSize().begin(), w.hallFormalHalfSize().end(), std::ostream_iterator<double>(os, ", "));
os<<"}, hallFormalCenterInWorld = "<<w.hallFormalCenterInWorld()
<<", mu2eOriginInWorld = "<<w.mu2eOriginInWorld()
<<")";
return os;
}
}
| [
"murat@fnal.gov"
] | murat@fnal.gov |
4671e65368152f8fce2161e14bed0ab24d5c26ec | a7f02ead4809d7555e5d64c862c8dc8f0b045781 | /BaseFAMC/MathTools.cpp | 87561badfd808df9bae8505cad3bcfa1215fe618 | [
"Zlib"
] | permissive | isabella232/openFAMC | fac300a457d16e92f0e94bb9c5d73c2cbb6d6ec6 | e36ec4d846fca577a838008570346e148b05a150 | refs/heads/master | 2022-05-07T13:12:36.760995 | 2015-01-13T16:29:15 | 2015-01-13T16:29:15 | 487,459,496 | 0 | 0 | NOASSERTION | 2022-05-02T20:31:14 | 2022-05-01T06:06:43 | null | UTF-8 | C++ | false | false | 3,251 | cpp | /*!
************************************************************************
* \file
* MathTools.cpp
* \brief
* MathTools class.
* \author
* Copyright (C) 2007 ARTEMIS Department INT/GET, Paris, France.
*
* Khaled MAMOU <khaled.mamou@int-evry.fr>
*
* Institut National des Telecommunications tel.: +33 (0)1 60 76 40 94
* 9, Rue Charles Fourier, fax.: +33 (0)1 60 76 43 81
* 91011 Evry Cedex France
*
************************************************************************
*/
#include "MathTools.h"
#include <math.h>
#define EPS 0.00000001
#define PI 3.141592653589
MathTools::MathTools(void)
{
}
MathTools::~MathTools(void)
{
}
void MathTools::vecteur(float *pt1, float *pt2, float *vect, int n) {
for(int i = 0; i < n; i++) {
vect[i] = pt2[i] - pt1[i];
}
}
void MathTools::vectoriel(float vect1[3], float vect2[3], float vect[3]) {
vect[0] = vect1[1] * vect2[2] - vect1[2] * vect2[1];
vect[1] = vect1[2] * vect2[0] - vect1[0] * vect2[2];
vect[2] = vect1[0] * vect2[1] - vect1[1] * vect2[0];
}
float MathTools::vectorNorm(float vect[3]) {
return (float) pow( (double) vect[0]*vect[0] + vect[1]*vect[1] + vect[2]*vect[2] ,0.5);
}
void MathTools::vectorUnitary(float vect[3]) {
float normVect = vectorNorm(vect);
if ( normVect > EPS) {
for( int k = 0; k < 3; k++) {
vect[k] /= normVect;
}
}
}
float MathTools::vectorDot(float vect1[3], float vect2[3]) {
return vect1[0] * vect2[0] + vect1[1] * vect2[1] + vect1[2] * vect2[2];
}
void MathTools::vectorBasis(float vect1[3], float vect2[3], float vect3[3]) {
vectorUnitary(vect1);
float b[3][3] = {{1.0f,0.0f,0.0f}, {0.0f,1.0f,0.0f}, {0.0f,0.0f,1.0f}};
int k = 0;
double d0 = fabs(vectorDot(vect1, b[0]));
for (int p = 1; p < 3; p++) {
double d = fabs(vectorDot(vect1, b[p]));
if ( d > d0 ) {
k = p;
d0 = d;
}
}
int k1 = (k+1)%3;
float d = vectorDot(vect1, b[k1]);
for (int p = 0; p < 3; p++) {
vect2[p] = b[k1][p] - d * vect1[p];
}
vectorUnitary(vect2);
vectoriel(vect1, vect2, vect3);
}
void MathTools::cartesian2Spherical(float coord[3], float& r, float& tetha, float& phi) {
double x = coord[0];
double y = coord[1];
double z = coord[2];
r = (float) pow(x*x+y*y+z*z, 0.5);
phi = 0.0f;
tetha = 0.0f;
if ( (x == 0.0) && (y == 0.0) ) {
tetha = 0.0f;
phi = 0.0f;
} else {
if (x == 0.0) {
tetha = (float) PI/2;
}
else {
tetha = (float) atan(fabs(y/x));
}
}
if ((x<=0.0) && (y<=0.0)) {
tetha = (float) (PI + tetha);
}
else if ((x<=0.0) && (y>=0.0)) {
tetha = (float) PI - tetha;
}
else if ((x>=0.0) && (y<=0.0)) tetha = (float) (2*PI - tetha);
if (r > EPS) {
phi = (float) acos(z/r);
}
}
void MathTools::spherical2Cartesian(float r, float tetha, float phi, float coord[3]) {
coord[0] = (float) r* cos(tetha)*sin(phi);
coord[1] = (float) r* sin(tetha)*sin(phi);
coord[2] = (float) r* cos(phi);
}
float MathTools::Signe(float x) {
if ( x > 0.0) return 1.0f;
return -1.0f;
}
int MathTools::nBinaryBits(unsigned int m){
int n=0;
while (m!=0) {
m = (m>>1);
n++;
}
return n;
}
| [
"rufael84@ce3af695-dfca-4357-9c92-0dcba94ce5f8"
] | rufael84@ce3af695-dfca-4357-9c92-0dcba94ce5f8 |
72c473eb89fe0e04db70a02c27b7e9c850266ff9 | 8b03df3c9427cab311e96a94474ae99b4a6b6332 | /hw3/10082WERTYU/main.cpp | ea32f9df7ea11a800c8a2d31f5ad9d86ba4a88b3 | [] | no_license | 026rus/csce4123 | 5d9c0f00b9f3ac319d91a6d4e8bcc06fb300b6a7 | b458375fbe1998216827d3bb167a19b1b4ce42a0 | refs/heads/master | 2021-01-11T02:37:50.235447 | 2016-12-09T14:28:20 | 2016-12-09T14:28:20 | 70,951,071 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,950 | cpp | /*
* =====================================================================================
*
* Filename: main.cpp
*
* Description: Shift the rey
*
* Version: 1.0
* Created: 09/10/2016 05:37:02 PM
* Revision: none
* Compiler: gcc
*
* Author: Vitaly Borodin, vvborodi@email.uare.edu
*
* =====================================================================================
*/
#include <iostream>
#include <time.h>
#include <cstdlib>
#include<stdio.h>
using namespace std;
/*
*
*/
void wertyu();
char translate(char);
int main(int argc, char** argv)
{
// Get start time
// clock_t time1=clock();
wertyu ();
// clock_t time2=clock();
// double run_time = (time2-time1)/(double)CLOCKS_PER_SEC;
// cout << "Run time: " << run_time << " seconds" << endl;
return 0;
}
void wertyu ()
{
string line;
while(getline(cin, line))
{
for(unsigned int i=0; i < line.length(); i++)
cout << translate(line[i]);
cout << endl;
}
}
char translate( char x)
{
char retval = x;
switch(x)
{
case 'W': retval = 'Q'; break;
case 'E': retval = 'W'; break;
case 'R': retval = 'E'; break;
case 'T': retval = 'R'; break;
case 'Y': retval = 'T'; break;
case 'U': retval = 'Y'; break;
case 'I': retval = 'U'; break;
case 'O': retval = 'I'; break;
case 'P': retval = 'O'; break;
case 'S': retval = 'A'; break;
case 'D': retval = 'S'; break;
case 'F': retval = 'D'; break;
case 'G': retval = 'F'; break;
case 'H': retval = 'G'; break;
case 'J': retval = 'H'; break;
case 'K': retval = 'J'; break;
case 'L': retval = 'K'; break;
case 'X': retval = 'Z'; break;
case 'C': retval = 'X'; break;
case 'V': retval = 'C'; break;
case 'B': retval = 'V'; break;
case 'N': retval = 'B'; break;
case 'M': retval = 'N'; break;
case '2': retval = '1'; break;
case '3': retval = '2'; break;
case '4': retval = '3'; break;
case '5': retval = '4'; break;
case '6': retval = '5'; break;
case '7': retval = '6'; break;
case '8': retval = '7'; break;
case '9': retval = '8'; break;
case '0': retval = '9'; break;
case '-': retval = '0'; break;
case '=': retval = '-'; break;
case '[': retval = 'P'; break;
case ']': retval = '['; break;
case '\\': retval = ']'; break;
case ';': retval = 'L'; break;
case '1': retval = '`'; break;
case ',': retval = 'M'; break;
case '.': retval = ','; break;
case '/': retval = '.'; break;
case '\'': retval = ';'; break;
}
return retval;
}
| [
"026rus@gmail.com"
] | 026rus@gmail.com |
e64d94ed4bd3e664d335914b0424d2ccfe10dc30 | 7a17d90d655482898c6777c101d3ab6578ccc6ba | /SDK/PUBG_GamepadHelpInterface_functions.cpp | f6cf19ff6dde5dffb3df21091b1522939f9abe49 | [] | no_license | Chordp/PUBG-SDK | 7625f4a419d5b028f7ff5afa5db49e18fcee5de6 | 1b23c750ec97cb842bf5bc2b827da557e4ff828f | refs/heads/master | 2022-08-25T10:07:15.641579 | 2022-08-14T14:12:48 | 2022-08-14T14:12:48 | 245,409,493 | 17 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 355 | cpp | // PUBG (9.1.5.3) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_GamepadHelpInterface_parameters.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"1263178881@qq.com"
] | 1263178881@qq.com |
d7c617c9bcbde8ff1f740608862e87b30a73f7be | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/Calorimeter/CaloRec/src/CaloCellMaker.cxx | 1acc3829f799168973db082909e0e88c1da302dc | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,317 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
/********************************************************************
NAME: CaloCellMaker.h
PACKAGE: offline/Calorimeter/CaloRec
AUTHORS: David Rousseau
CREATED: May 11, 2004
PURPOSE: Create a CaloCellContainer by calling a set of tools
sharing interface CaloUtils/ICaloCellMakerTool.h
FIXME : should see how Chronostat and MemStat report could still be obtained
********************************************************************/
// Gaudi includes
#include "GaudiKernel/IChronoStatSvc.h"
// Athena includes
#include "AthenaKernel/errorcheck.h"
#include "NavFourMom/INavigable4MomentumCollection.h"
// Calo includes
#include "CaloRec/CaloCellMaker.h"
#include "CaloInterface/ICaloCellMakerTool.h"
#include "CaloEvent/CaloCell.h"
#include "CaloEvent/CaloCellContainer.h"
#include "CLHEP/Units/SystemOfUnits.h"
using CLHEP::microsecond;
using CLHEP::second;
/////////////////////////////////////////////////////////////////////
// CONSTRUCTOR:
/////////////////////////////////////////////////////////////////////
CaloCellMaker::CaloCellMaker(const std::string& name, ISvcLocator* pSvcLocator)
: AthAlgorithm(name, pSvcLocator)
, m_chrono("ChronoStatSvc", name)
, m_ownPolicy(static_cast<int>(SG::VIEW_ELEMENTS))
, m_caloCellsOutputName("")
, m_caloCellHack(false)
, m_caloCellMakerTools()
, m_evCounter(0)
{
declareProperty("OwnPolicy", m_ownPolicy);
declareProperty("CaloCellMakerToolNames", m_caloCellMakerTools);
declareProperty("CaloCellsOutputName", m_caloCellsOutputName);
declareProperty("CaloCellHack", m_caloCellHack);
}
/////////////////////////////////////////////////////////////////////
// DESTRUCTOR:
/////////////////////////////////////////////////////////////////////
CaloCellMaker::~CaloCellMaker() {
}
/////////////////////////////////////////////////////////////////////
// INITIALIZE:
// The initialize method will create all the required algorithm objects
/////////////////////////////////////////////////////////////////////
StatusCode CaloCellMaker::initialize() {
CHECK( m_chrono.retrieve() );
// Add ":PUBLIC" to the tool names to force ToolSvc into creating
// public tools.
std::vector< std::string > typesAndNames;
for( const std::string& typeName : m_caloCellMakerTools.typesAndNames() ) {
typesAndNames.push_back( typeName + ":PUBLIC" );
}
m_caloCellMakerTools.setTypesAndNames( typesAndNames );
// access tools and store them
CHECK( m_caloCellMakerTools.retrieve() );
ATH_MSG_DEBUG( "Successfully retrieve CaloCellMakerTools: " << m_caloCellMakerTools );
ATH_MSG_INFO( " Output CaloCellContainer Name " << m_caloCellsOutputName );
if (m_ownPolicy == SG::OWN_ELEMENTS) {
ATH_MSG_INFO( "...will OWN its cells." );
} else {
ATH_MSG_INFO( "...will VIEW its cells." );
}
if (m_caloCellHack) {
ATH_MSG_WARNING( " CaloCellContainer: " << m_caloCellsOutputName
<< "will be read in and modified !. To be used with care. " );
}
return StatusCode::SUCCESS;
}
StatusCode CaloCellMaker::execute() {
// create and record the empty container
CaloCellContainer * theContainer;
if (!m_caloCellHack) {
theContainer = new CaloCellContainer(static_cast<SG::OwnershipPolicy>(m_ownPolicy));
if (evtStore()->record(theContainer, m_caloCellsOutputName).isFailure()) {
ATH_MSG_WARNING( "execute() : cannot record CaloCellContainer " << m_caloCellsOutputName );
return StatusCode::SUCCESS;
}
// also symLink as INavigable4MomentumCollection!
INavigable4MomentumCollection* theNav4Coll = 0;
if (evtStore()->symLink(theContainer, theNav4Coll).isFailure()) {
ATH_MSG_WARNING( "Error symlinking CaloCellContainer to INavigable4MomentumCollection " );
return StatusCode::SUCCESS;
}
} else {
// take CaloCellContainer from input and cast away constness
const CaloCellContainer * theConstContainer;
if (evtStore()->retrieve(theConstContainer, m_caloCellsOutputName).isFailure()
|| theConstContainer == 0) {
ATH_MSG_WARNING( "Could not retrieve CaloCellContainer " << m_caloCellsOutputName );
return StatusCode::SUCCESS;
}
theContainer = const_cast<CaloCellContainer *>(theConstContainer);
}
ToolHandleArray<ICaloCellMakerTool>::iterator itrTool = m_caloCellMakerTools.begin();
ToolHandleArray<ICaloCellMakerTool>::iterator endTool = m_caloCellMakerTools.end();
//The following piece of code would be even more efficient but unfortunately the
//ToolHandleArray doesn't allow to remove elements.
// // For performance reasons want to remove the cell-checker tool from the list
// // of tools at the fifth event.
// if ((++m_evCounter)==5) {
// //Search for cell-checker tool in list of tools
// for (;itrTool!=endTool && itrTool->typeAndName()!="CaloCellContainerCheckerTool/CaloCellContainerCheckerTool";++itrTool);
// if (itrTool!=endTool) { //Found cell-checker tool
// m_caloCellMakerTools.erase(itrTool); //Remove cell-checker tool
// //Re-initialize the iterators
// itrTool=m_caloCellMakerTools.begin();
// endTool=m_caloCellMakerTools.end();
// ATH_MSG_INFO( "Remove CellChecking tool from list of tools" );
// ATH_MSG_DEBUG( "Tools left: " << m_caloCellMakerTools );
// }
// }
// loop on tools
// note that finalization and checks are also done with tools
++m_evCounter;
for (; itrTool != endTool; ++itrTool) {
if (m_evCounter > 5) {
if (itrTool->typeAndName() == "CaloCellContainerCheckerTool/CaloCellContainerCheckerTool")
continue;
}
ATH_MSG_DEBUG( "Calling tool " << itrTool->name() );
std::string chronoName = this->name() + "_" + itrTool->name();
m_chrono->chronoStart(chronoName);
StatusCode sc = (*itrTool)->process(theContainer);
m_chrono->chronoStop(chronoName);
ATH_MSG_DEBUG( "Chrono stop : delta "
<< m_chrono->chronoDelta(chronoName, IChronoStatSvc::USER) * (microsecond / second)
<< " second " );
if (sc.isFailure()) {
ATH_MSG_ERROR( "Error executing tool " << itrTool->name() );
}
}
return StatusCode::SUCCESS;
}
StatusCode CaloCellMaker::finalize() {
return StatusCode::SUCCESS;
}
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
2bee88cf451e8f82076f39c02b67875d4c23a4db | 28d9f1413f52d9cedc7775f59c8dbd6bffa7d8c0 | /tests/test_integer.cpp | ee67112bea97e0f4a81afd6a5075ae435adc88e9 | [
"MIT"
] | permissive | ToruNiina/wad | e5ce63492b0d7feebd11cc5fe0b290a202995b1a | f5f0445f7f0a53efd31988ce7d381bccb463b951 | refs/heads/master | 2022-12-14T15:07:15.128072 | 2020-09-01T14:43:06 | 2020-09-01T14:43:06 | 241,058,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,517 | cpp | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "wad/integer.hpp"
#include "utility.hpp"
TEST_CASE( "uint8_t save/load", "[u8]" ) {
REQUIRE(wad::save_load(std::uint8_t(42)) == 42u);
REQUIRE(wad::save_load(std::uint8_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::uint8_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::uint8_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::uint8_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::uint8_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::uint8_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::uint8_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::int8_t>(std::uint8_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::uint8_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::uint8_t(142)) == 142);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint8_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint8_t(142)) == 142);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint8_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint8_t(142)) == 142);
}
TEST_CASE( "uint16_t save/load", "[u16]" ) {
REQUIRE(wad::save_load(std::uint16_t( 42)) == 42u);
REQUIRE(wad::save_load(std::uint16_t( 142)) == 142u);
REQUIRE(wad::save_load(std::uint16_t(0xBEEF)) == 0xBEEFu);
REQUIRE(wad::save_load_convert<std::uint8_t >(std::uint16_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint8_t >(std::uint16_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::uint16_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::uint16_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::uint16_t(0xBEEF)) == 0xBEEFu);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::uint16_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::uint16_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::uint16_t(0xBEEF)) == 0xBEEFu);
REQUIRE(wad::save_load_convert<std::int8_t >(std::uint8_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::uint16_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::uint16_t(142)) == 142);
REQUIRE(wad::save_load_convert<std::int16_t>(std::uint16_t(0x0123)) == 0x0123);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint16_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint16_t(142)) == 142);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint16_t(0xBEEF)) == 0xBEEF);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint16_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint16_t(142)) == 142);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint16_t(0xBEEF)) == 0xBEEF);
}
TEST_CASE( "uint32_t save/load", "[u32]" ) {
REQUIRE(wad::save_load(std::uint32_t( 42)) == 42u);
REQUIRE(wad::save_load(std::uint32_t( 142)) == 142u);
REQUIRE(wad::save_load(std::uint32_t(0xBEEF)) == 0xBEEFu);
REQUIRE(wad::save_load(std::uint32_t(0xDEADBEEF)) == 0xDEADBEEFu);
REQUIRE(wad::save_load_convert<std::uint8_t >(std::uint32_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint8_t >(std::uint32_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::uint32_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::uint32_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::uint32_t(0xBEEF)) == 0xBEEFu);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::uint32_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::uint32_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::uint32_t(0xBEEF)) == 0xBEEFu);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::uint32_t(0xDEADBEEF)) == 0xDEADBEEFu);
REQUIRE(wad::save_load_convert<std::int8_t >(std::uint32_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::uint32_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::uint32_t(142)) == 142);
REQUIRE(wad::save_load_convert<std::int16_t>(std::uint32_t(0x0123)) == 0x0123);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint32_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint32_t(142)) == 142);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint32_t(0xBEEF)) == 0xBEEF);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint32_t(0x00C0FFEE)) == 0x00C0FFEE);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint32_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint32_t(142)) == 142);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint32_t(0xBEEF)) == 0xBEEF);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint32_t(0x00C0FFEE)) == 0x00C0FFEE);
}
TEST_CASE( "uint64_t save/load", "[u64]" ) {
REQUIRE(wad::save_load(std::uint64_t( 42)) == 42u);
REQUIRE(wad::save_load(std::uint64_t( 142)) == 142u);
REQUIRE(wad::save_load(std::uint64_t(0xBEEF)) == 0xBEEFu);
REQUIRE(wad::save_load(std::uint64_t(0xDEADBEEF)) == 0xDEADBEEFu);
REQUIRE(wad::save_load(std::uint64_t(0xDEADBEEF00C0FFEE)) == 0xDEADBEEF00C0FFEEu);
REQUIRE(wad::save_load_convert<std::uint8_t >(std::uint64_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint8_t >(std::uint64_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::uint64_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::uint64_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::uint64_t(0xBEEF)) == 0xBEEFu);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::uint64_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::uint64_t(142)) == 142u);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::uint64_t(0xBEEF)) == 0xBEEFu);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::uint64_t(0xDEADBEEF)) == 0xDEADBEEFu);
REQUIRE(wad::save_load_convert<std::int8_t >(std::uint64_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::uint64_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::uint64_t(142)) == 142);
REQUIRE(wad::save_load_convert<std::int16_t>(std::uint64_t(0x0123)) == 0x0123);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint64_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint64_t(142)) == 142);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint64_t(0xBEEF)) == 0xBEEF);
REQUIRE(wad::save_load_convert<std::int32_t>(std::uint64_t(0x00C0FFEE)) == 0x00C0FFEE);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint64_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint64_t(142)) == 142);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint64_t(0xBEEF)) == 0xBEEF);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint64_t(0xDEADBEEF)) == 0xDEADBEEF);
REQUIRE(wad::save_load_convert<std::int64_t>(std::uint64_t(0x00C0FFEEDEADBEEF)) == 0x00C0FFEEDEADBEEF);
}
TEST_CASE( "int8_t save/load", "[i8]" ) {
REQUIRE(wad::save_load(std::int8_t(42)) == 42);
REQUIRE(wad::save_load(std::int8_t(-42)) == -42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::int8_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::int8_t(-42)) == -42);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int8_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int8_t(-42)) == -42);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int8_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int8_t(-42)) == -42);
REQUIRE(wad::save_load_convert<std::uint8_t>(std::int8_t(42)) == 42);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::int8_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::int8_t(42)) == 42u);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::int8_t(42)) == 42u);
}
TEST_CASE( "int16_t save/load", "[i16]" ) {
REQUIRE(wad::save_load(std::int16_t(42)) == 42);
REQUIRE(wad::save_load(std::int16_t(-42)) == -42);
REQUIRE(wad::save_load(std::int16_t(1024)) == 1024);
REQUIRE(wad::save_load(std::int16_t(-1024)) == -1024);
REQUIRE(wad::save_load_convert<std::int8_t >(std::int16_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::int8_t >(std::int16_t( -42)) == -42);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int16_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int16_t( -42)) == -42);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int16_t( 1024)) == 1024);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int16_t(-1024)) == -1024);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int16_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int16_t( -42)) == -42);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int16_t( 1024)) == 1024);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int16_t(-1024)) == -1024);
REQUIRE(wad::save_load_convert<std::uint8_t >(std::int16_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::int16_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::int16_t(1024)) == 1024);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::int16_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::int16_t(1024)) == 1024);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::int16_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::int16_t(1024)) == 1024);
}
TEST_CASE( "int32_t save/load", "[i32]" ) {
REQUIRE(wad::save_load(std::int32_t( 42)) == 42);
REQUIRE(wad::save_load(std::int32_t( -42)) == -42);
REQUIRE(wad::save_load(std::int32_t( 1024)) == 1024);
REQUIRE(wad::save_load(std::int32_t( -1024)) == -1024);
REQUIRE(wad::save_load(std::int32_t( 111111)) == 111111);
REQUIRE(wad::save_load(std::int32_t(-111111)) == -111111);
REQUIRE(wad::save_load_convert<std::int8_t >(std::int32_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::int8_t >(std::int32_t( -42)) == -42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::int32_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::int32_t( -42)) == -42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::int32_t( 1024)) == 1024);
REQUIRE(wad::save_load_convert<std::int16_t>(std::int32_t(-1024)) == -1024);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int32_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int32_t( -42)) == -42);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int32_t( 1024)) == 1024);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int32_t( -1024)) == -1024);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int32_t( 111111)) == 111111);
REQUIRE(wad::save_load_convert<std::int64_t>(std::int32_t(-111111)) == -111111);
REQUIRE(wad::save_load_convert<std::uint8_t >(std::int32_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::int32_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::int32_t( 1024)) == 1024);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::int32_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::int32_t( 1024)) == 1024);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::int32_t(111111)) == 111111);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::int32_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::int32_t(1024)) == 1024);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::int32_t(111111)) == 111111);
}
TEST_CASE( "int64_t save/load", "[i64]" ) {
REQUIRE(wad::save_load(std::int64_t( 42)) == 42);
REQUIRE(wad::save_load(std::int64_t( -42)) == -42);
REQUIRE(wad::save_load(std::int64_t( 1024)) == 1024);
REQUIRE(wad::save_load(std::int64_t( -1024)) == -1024);
REQUIRE(wad::save_load(std::int64_t( 111111)) == 111111);
REQUIRE(wad::save_load(std::int64_t(-111111)) == -111111);
REQUIRE(wad::save_load(std::int64_t( 123456789012)) == 123456789012);
REQUIRE(wad::save_load(std::int64_t(-123456789012)) == -123456789012);
REQUIRE(wad::save_load_convert<std::int8_t >(std::int64_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::int8_t >(std::int64_t( -42)) == -42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::int64_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::int64_t( -42)) == -42);
REQUIRE(wad::save_load_convert<std::int16_t>(std::int64_t( 1024)) == 1024);
REQUIRE(wad::save_load_convert<std::int16_t>(std::int64_t(-1024)) == -1024);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int64_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int64_t( -42)) == -42);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int64_t( 1024)) == 1024);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int64_t( -1024)) == -1024);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int64_t( 111111)) == 111111);
REQUIRE(wad::save_load_convert<std::int32_t>(std::int64_t(-111111)) == -111111);
REQUIRE(wad::save_load_convert<std::uint8_t >(std::int64_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::int64_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint16_t>(std::int64_t( 1024)) == 1024);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::int64_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::int64_t( 1024)) == 1024);
REQUIRE(wad::save_load_convert<std::uint32_t>(std::int64_t(111111)) == 111111);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::int64_t( 42)) == 42);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::int64_t(1024)) == 1024);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::int64_t(111111)) == 111111);
REQUIRE(wad::save_load_convert<std::uint64_t>(std::int64_t(123456789012)) == 123456789012);
}
| [
"niina.toru.68u@gmail.com"
] | niina.toru.68u@gmail.com |
20febf6a0ee36bd7db72318a1e8839838d885595 | b01cf4f1eff5b8b9d0ad00e61cad353b0fe02cf4 | /main.cpp | 74eaeb4900b1b97a6cb8bdaf10f31acbe178f2ec | [] | no_license | JonasLopezMesa/cpp_SSI_cifrado_vingenere | 48a9854f508d2000d547e98e4e96fa291e42a004 | c8f531f355a57afe5bba87adf89867efafbc00c5 | refs/heads/master | 2020-04-19T10:40:59.431626 | 2014-02-13T14:54:11 | 2014-02-13T14:54:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,423 | cpp | //
// main.cpp
// Cifrado_Vingenere
//
// Created by jonas on 18/02/13.
// Copyright (c) 2013 jonas. All rights reserved.
//
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
char alfabeto[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char clave[100], texto_original[100], texto_cifrado[100], texto_descifrado[100];
cout << "introduce la clave: " << endl;
gets(clave);
cout << "introduce el texto original" << endl;
gets(texto_original);
for(int j = 0; texto_original[j]; j++){
texto_original[j] = tolower(texto_original[j]); //<--convierte a minusculas la cadena
}
for(int j = 0; clave[j]; j++){
clave[j] = tolower(clave[j]); //<--convierte a minusculas la cadena
}
cout << "CIFRADO: " << endl; //Cifrado de Vingenere////////////////////////////
int a = 0;
for (int i = 0; i < strlen(texto_original); i++) { //recorre todos los caracteres del texto original
if (texto_original[i] == ' ') { //si el caracter es espacio, inserta espacio
texto_cifrado[i] = ' ';
} else {
int temp, temp1, temp2;
for (int j = 0; j <= 26; j++) { //si no es espacio, recorre todo el alfabeto y busca coincidencias entre
if (alfabeto[j] == texto_original[i]) { //el caracter del texto original
temp1 = j;
}
if (alfabeto[j] == clave[a%strlen(clave)]) { //y el caracter de la clave
temp2 = j;
} //y almacena las posiciones en temp1 y temp2
}
temp = (temp1 + temp2)%26; //suma las posiciones y hace el módulo de 26 y
texto_cifrado[i] = alfabeto[temp]; //pone en el texto cifrado la letra del alfabeto que corresponda
a++;
}
}
///////////////////////////////////////////////////////////////////////////////
for (int a = 0; a < strlen(texto_cifrado); a++) { //Muestra resultado
cout << texto_cifrado[a];
}
cout << endl << "DESCIFRADO: " << endl; //Descifrado de Vingenere//////////////
int b = 0;
for (int i = 0; i < strlen(texto_original); i++) { //recorre todas las letras del texto cifrado
if (texto_original[i] == ' ') { //si es espacio, inserta un espacio en el texto descifrado
texto_descifrado[i] = ' ';
} else {
int temp, temp1, temp2, ext;
for (int j = 0; j <= 26; j++) { //busca coincidencias entre la letra que corresponda del texto cifrado
if (alfabeto[j] == texto_cifrado[i]) {
temp1 = j;
}
if (alfabeto[j] == clave[b%strlen(clave)]) { // y la clave
temp2 = j;
} //con el alfabeto y lo almacena en temp1 y temp2
}
temp = (temp1 - temp2); //resta las posiciones
if (temp < 0) { // si esa resta da menos de 0
ext = (26-abs(temp))%26; //
temp = ext;
}
texto_descifrado[i] = alfabeto[temp];
b++;
}
}
///////////////////////////////////////////////////////////////////////////////
for (int a = 0; a < strlen(texto_descifrado); a++) { //Muestra resultado
cout << texto_descifrado[a];
}
}
| [
"77jonas77@gmail.com"
] | 77jonas77@gmail.com |
70a29034c9bd434814f8b68ab7914db018fd1003 | 5bc9f98921bc395116d20b0fdbf485cbc987e82d | /app/components/hotkeyselectorlineedit.h | e95838ecb43d06cd11ed66bca395cdab369d39fd | [] | no_license | nickdonnelly/horus | 0082c6d3750952eafeb6e265b02ab70ff2efca13 | 6c2cc9d47da3cf0f09d014f44116a78c1910b43b | refs/heads/master | 2021-04-27T00:17:49.216025 | 2018-06-30T14:09:44 | 2018-06-30T14:09:44 | 123,788,239 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | h | #ifndef HOTKEYSELECTORLINEEDIT_H
#define HOTKEYSELECTORLINEEDIT_H
#include <QObject>
#include <QLineEdit>
#include <QFocusEvent>
class HotkeySelectorLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit HotkeySelectorLineEdit(QWidget *parent = 0);
signals:
void focusIn();
void focusOut();
protected:
void focusInEvent(QFocusEvent *);
void focusOutEvent(QFocusEvent *);
};
#endif // HOTKEYSELECTORLINEEDIT_H
| [
"nick@donnelly.cc"
] | nick@donnelly.cc |
1626639e22130869bb194e1fe4d52dcb4e2a608b | 85c1bc724e59cea08b6c178f8c3eabd554cb99ee | /script_array_object.cpp | eb20ea8faaedd669cf54c61b6298bc3b2ae7133d | [] | no_license | vtsaplin/jlsl | 92068f6880a366c1de49efd658409b696884346a | 019e3c3ce7638df633ec2a1787074343bc827145 | refs/heads/master | 2021-01-19T11:03:04.234409 | 2012-12-19T20:26:02 | 2012-12-19T20:26:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,098 | cpp | #include "script_array_object.h"
script_array_object::script_array_object () {
_iter = _vector.begin ();
}
script_array_object::script_array_object (unsigned long size) {
_vector.resize (size);
_iter = _vector.begin ();
}
script_array_object::~script_array_object () {
}
void script_array_object::array_subscript (script_container& r, const script_container& v) {
unsigned long i = v.to_unsigned_integer ();
if (i >= 0 && i < _vector.size ()) {
r.set_reference (_vector [v.to_integer ()]);
} else {
throw script_exception ("array object: ouf of range.");
}
}
void script_array_object::assignment (script_container& r) {
r.set_object (this);
}
void script_array_object::begin () {
_iter = _vector.begin ();
}
void script_array_object::end () {
_iter = _vector.end ();
}
void script_array_object::backward () {
_iter--;
}
void script_array_object::forward () {
_iter++;
}
void script_array_object::current (script_container& r) {
(* _iter).assignment (r);
}
void script_array_object::remove () {
_iter = _vector.erase (_iter);
}
bool script_array_object::is_end () {
if (_iter == _vector.end ()) return true;
return false;
}
unsigned long script_array_object::count () {
return (unsigned long)_vector.size ();
}
string script_array_object::to_string () const {
return "";
}
unsigned long script_array_object::get_descriptor () const {
return __script_array_object_descriptor;
}
const char * script_array_object::get_descriptor_as_string () const {
return __script_array_object_descriptor_as_string;
}
void script_array_object::collect (unsigned long wave)
{
if (!is_locked (wave)) {
script_object::collect (wave);
vector<script_container>::iterator iter;
for (iter=_vector.begin (); iter!=_vector.end (); iter++) {
(* iter).collect (wave);
}
}
}
// function: CreateArray
script_container collection_CreateArray (vector<script_container>& args) {
script_container c;
c.set_object (new script_array_object (args [0].to_integer ()));
return c;
}
script_predefined_function collection_CreateArray_def ("createarray", collection_CreateArray, 1);
| [
"vitaly@tsaplin.com"
] | vitaly@tsaplin.com |
161a512c70f68826d44c9fdc30e8fb05a1be8e2b | bfad0c504fff3c17d1d4681ac82216f804af2f87 | /libraries/MPU9250_LIB/inv_mpu.cpp | 44653b93cb465ee4610cee62da4317d1eba4dc74 | [] | no_license | kenne839/Senior_Design_source | 36592a8a03b1f4683e15c9ca295f5144f5850971 | 8b3d1f4774d3f61bc7ea1edc48363d9fbb95f425 | refs/heads/master | 2021-01-23T02:23:30.107174 | 2017-04-06T21:02:31 | 2017-04-06T21:02:31 | 85,989,922 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 81,458 | cpp | /*
$License:
Copyright (C) 2011-2012 InvenSense Corporation, All Rights Reserved.
See included License.txt for License information.
$
*/
/**
* @addtogroup DRIVERS Sensor Driver Layer
* @brief Hardware drivers to communicate with sensors via I2C.
*
* @{
* @file inv_mpu.c
* @brief An I2C-based driver for Invensense gyroscopes.
* @details This driver currently works for the following devices:
* MPU6050
* MPU6500
* MPU9150 (or MPU6050 w/ AK8975 on the auxiliary bus)
* MPU9250 (or MPU6500 w/ AK8963 on the auxiliary bus)
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "inv_mpu.h"
#define MPU9250
/* The following functions must be defined for this platform:
* i2c_write(unsigned char slave_addr, unsigned char reg_addr,
* unsigned char length, unsigned char const *data)
* i2c_read(unsigned char slave_addr, unsigned char reg_addr,
* unsigned char length, unsigned char *data)
* delay_ms(unsigned long num_ms)
* get_ms(unsigned long *count)
* reg_int_cb(void (*cb)(void), unsigned char port, unsigned char pin)
* labs(long x)
* fabsf(float x)
* min(int a, int b)
*/
#define i2c_write !I2Cdev::writeBytes
#define i2c_read !I2Cdev::readBytes
#define delay_ms delay
static inline int reg_int_cb(struct int_param_s *int_param)
{
}
#define min(a,b) ((a<b)?a:b)
#if !defined MPU6050 && !defined MPU9150 && !defined MPU6500 && !defined MPU9250
#error Which gyro are you using? Define MPUxxxx in your compiler options.
#endif
/* Time for some messy macro work. =]
* #define MPU9150
* is equivalent to..
* #define MPU6050
* #define AK8975_SECONDARY
*
* #define MPU9250
* is equivalent to..
* #define MPU6500
* #define AK8963_SECONDARY
*/
#if defined MPU9150
#ifndef MPU6050
#define MPU6050
#endif /* #ifndef MPU6050 */
#if defined AK8963_SECONDARY
#error "MPU9150 and AK8963_SECONDARY cannot both be defined."
#elif !defined AK8975_SECONDARY /* #if defined AK8963_SECONDARY */
#define AK8975_SECONDARY
#endif /* #if defined AK8963_SECONDARY */
#elif defined MPU9250 /* #if defined MPU9150 */
#ifndef MPU6500
#define MPU6500
#endif /* #ifndef MPU6500 */
#if defined AK8975_SECONDARY
#error "MPU9250 and AK8975_SECONDARY cannot both be defined."
#elif !defined AK8963_SECONDARY /* #if defined AK8975_SECONDARY */
#define AK8963_SECONDARY
#endif /* #if defined AK8975_SECONDARY */
#endif /* #if defined MPU9150 */
#if defined AK8975_SECONDARY || defined AK8963_SECONDARY
#define AK89xx_SECONDARY
#else
/* #warning "No compass = less profit for Invensense. Lame." */
#endif
static int set_int_enable(unsigned char enable);
/* Hardware registers needed by driver. */
struct gyro_reg_s {
unsigned char who_am_i;
unsigned char rate_div;
unsigned char lpf;
unsigned char prod_id;
unsigned char user_ctrl;
unsigned char fifo_en;
unsigned char gyro_cfg;
unsigned char accel_cfg;
unsigned char accel_cfg2;
unsigned char lp_accel_odr;
unsigned char motion_thr;
unsigned char motion_dur;
unsigned char fifo_count_h;
unsigned char fifo_r_w;
unsigned char raw_gyro;
unsigned char raw_accel;
unsigned char temp;
unsigned char int_enable;
unsigned char dmp_int_status;
unsigned char int_status;
unsigned char accel_intel;
unsigned char pwr_mgmt_1;
unsigned char pwr_mgmt_2;
unsigned char int_pin_cfg;
unsigned char mem_r_w;
unsigned char accel_offs;
unsigned char i2c_mst;
unsigned char bank_sel;
unsigned char mem_start_addr;
unsigned char prgm_start_h;
#if defined AK89xx_SECONDARY
unsigned char s0_addr;
unsigned char s0_reg;
unsigned char s0_ctrl;
unsigned char s1_addr;
unsigned char s1_reg;
unsigned char s1_ctrl;
unsigned char s4_ctrl;
unsigned char s0_do;
unsigned char s1_do;
unsigned char i2c_delay_ctrl;
unsigned char raw_compass;
/* The I2C_MST_VDDIO bit is in this register. */
unsigned char yg_offs_tc;
#endif
};
/* Information specific to a particular device. */
struct hw_s {
unsigned char addr;
unsigned short max_fifo;
unsigned char num_reg;
unsigned short temp_sens;
short temp_offset;
unsigned short bank_size;
#if defined AK89xx_SECONDARY
unsigned short compass_fsr;
#endif
};
/* When entering motion interrupt mode, the driver keeps track of the
* previous state so that it can be restored at a later time.
* TODO: This is tacky. Fix it.
*/
struct motion_int_cache_s {
unsigned short gyro_fsr;
unsigned char accel_fsr;
unsigned short lpf;
unsigned short sample_rate;
unsigned char sensors_on;
unsigned char fifo_sensors;
unsigned char dmp_on;
};
/* Cached chip configuration data.
* TODO: A lot of these can be handled with a bitmask.
*/
struct chip_cfg_s {
/* Matches gyro_cfg >> 3 & 0x03 */
unsigned char gyro_fsr;
/* Matches accel_cfg >> 3 & 0x03 */
unsigned char accel_fsr;
/* Enabled sensors. Uses same masks as fifo_en, NOT pwr_mgmt_2. */
unsigned char sensors;
/* Matches config register. */
unsigned char lpf;
unsigned char clk_src;
/* Sample rate, NOT rate divider. */
unsigned short sample_rate;
/* Matches fifo_en register. */
unsigned char fifo_enable;
/* Matches int enable register. */
unsigned char int_enable;
/* 1 if devices on auxiliary I2C bus appear on the primary. */
unsigned char bypass_mode;
/* 1 if half-sensitivity.
* NOTE: This doesn't belong here, but everything else in hw_s is const,
* and this allows us to save some precious RAM.
*/
unsigned char accel_half;
/* 1 if device in low-power accel-only mode. */
unsigned char lp_accel_mode;
/* 1 if interrupts are only triggered on motion events. */
unsigned char int_motion_only;
struct motion_int_cache_s cache;
/* 1 for active low interrupts. */
unsigned char active_low_int;
/* 1 for latched interrupts. */
unsigned char latched_int;
/* 1 if DMP is enabled. */
unsigned char dmp_on;
/* Ensures that DMP will only be loaded once. */
unsigned char dmp_loaded;
/* Sampling rate used when DMP is enabled. */
unsigned short dmp_sample_rate;
#ifdef AK89xx_SECONDARY
/* Compass sample rate. */
unsigned short compass_sample_rate;
unsigned char compass_addr;
short mag_sens_adj[3];
#endif
};
/* Information for self-test-> */
struct test_s {
unsigned long gyro_sens;
unsigned long accel_sens;
unsigned char reg_rate_div;
unsigned char reg_lpf;
unsigned char reg_gyro_fsr;
unsigned char reg_accel_fsr;
unsigned short wait_ms;
unsigned char packet_thresh;
float min_dps;
float max_dps;
float max_gyro_var;
float min_g;
float max_g;
float max_accel_var;
};
/* Gyro driver state variables. */
struct gyro_state_s {
const struct gyro_reg_s *reg;
const struct hw_s *hw;
struct chip_cfg_s chip_cfg;
const struct test_s *test;
};
/* Filter configurations. */
enum lpf_e {
INV_FILTER_256HZ_NOLPF2 = 0,
INV_FILTER_188HZ,
INV_FILTER_98HZ,
INV_FILTER_42HZ,
INV_FILTER_20HZ,
INV_FILTER_10HZ,
INV_FILTER_5HZ,
INV_FILTER_2100HZ_NOLPF,
NUM_FILTER
};
/* Full scale ranges. */
enum gyro_fsr_e {
INV_FSR_250DPS = 0,
INV_FSR_500DPS,
INV_FSR_1000DPS,
INV_FSR_2000DPS,
NUM_GYRO_FSR
};
/* Full scale ranges. */
enum accel_fsr_e {
INV_FSR_2G = 0,
INV_FSR_4G,
INV_FSR_8G,
INV_FSR_16G,
NUM_ACCEL_FSR
};
/* Clock sources. */
enum clock_sel_e {
INV_CLK_INTERNAL = 0,
INV_CLK_PLL,
NUM_CLK
};
/* Low-power accel wakeup rates. */
enum lp_accel_rate_e {
#if defined MPU6050
INV_LPA_1_25HZ,
INV_LPA_5HZ,
INV_LPA_20HZ,
INV_LPA_40HZ
#elif defined MPU6500
INV_LPA_0_3125HZ,
INV_LPA_0_625HZ,
INV_LPA_1_25HZ,
INV_LPA_2_5HZ,
INV_LPA_5HZ,
INV_LPA_10HZ,
INV_LPA_20HZ,
INV_LPA_40HZ,
INV_LPA_80HZ,
INV_LPA_160HZ,
INV_LPA_320HZ,
INV_LPA_640HZ
#endif
};
#define BIT_I2C_MST_VDDIO (0x80)
#define BIT_FIFO_EN (0x40)
#define BIT_DMP_EN (0x80)
#define BIT_FIFO_RST (0x04)
#define BIT_DMP_RST (0x08)
#define BIT_FIFO_OVERFLOW (0x10)
#define BIT_DATA_RDY_EN (0x01)
#define BIT_DMP_INT_EN (0x02)
#define BIT_MOT_INT_EN (0x40)
#define BITS_FSR (0x18)
#define BITS_LPF (0x07)
#define BITS_HPF (0x07)
#define BITS_CLK (0x07)
#define BIT_FIFO_SIZE_1024 (0x40)
#define BIT_FIFO_SIZE_2048 (0x80)
#define BIT_FIFO_SIZE_4096 (0xC0)
#define BIT_RESET (0x80)
#define BIT_SLEEP (0x40)
#define BIT_S0_DELAY_EN (0x01)
#define BIT_S2_DELAY_EN (0x04)
#define BITS_SLAVE_LENGTH (0x0F)
#define BIT_SLAVE_BYTE_SW (0x40)
#define BIT_SLAVE_GROUP (0x10)
#define BIT_SLAVE_EN (0x80)
#define BIT_I2C_READ (0x80)
#define BITS_I2C_MASTER_DLY (0x1F)
#define BIT_AUX_IF_EN (0x20)
#define BIT_ACTL (0x80)
#define BIT_LATCH_EN (0x20)
#define BIT_ANY_RD_CLR (0x10)
#define BIT_BYPASS_EN (0x02)
#define BITS_WOM_EN (0xC0)
#define BIT_LPA_CYCLE (0x20)
#define BIT_STBY_XA (0x20)
#define BIT_STBY_YA (0x10)
#define BIT_STBY_ZA (0x08)
#define BIT_STBY_XG (0x04)
#define BIT_STBY_YG (0x02)
#define BIT_STBY_ZG (0x01)
#define BIT_STBY_XYZA (BIT_STBY_XA | BIT_STBY_YA | BIT_STBY_ZA)
#define BIT_STBY_XYZG (BIT_STBY_XG | BIT_STBY_YG | BIT_STBY_ZG)
#if defined AK8975_SECONDARY
#define SUPPORTS_AK89xx_HIGH_SENS (0x00)
#define AK89xx_FSR (9830)
#elif defined AK8963_SECONDARY
#define SUPPORTS_AK89xx_HIGH_SENS (0x10)
#define AK89xx_FSR (4915)
#endif
#ifdef AK89xx_SECONDARY
#define AKM_REG_WHOAMI (0x00)
#define AKM_REG_ST1 (0x02)
#define AKM_REG_HXL (0x03)
#define AKM_REG_ST2 (0x09)
#define AKM_REG_CNTL (0x0A)
#define AKM_REG_ASTC (0x0C)
#define AKM_REG_ASAX (0x10)
#define AKM_REG_ASAY (0x11)
#define AKM_REG_ASAZ (0x12)
#define AKM_DATA_READY (0x01)
#define AKM_DATA_OVERRUN (0x02)
#define AKM_OVERFLOW (0x80)
#define AKM_DATA_ERROR (0x40)
#define AKM_BIT_SELF_TEST (0x40)
#define AKM_POWER_DOWN (0x00 | SUPPORTS_AK89xx_HIGH_SENS)
#define AKM_SINGLE_MEASUREMENT (0x01 | SUPPORTS_AK89xx_HIGH_SENS)
#define AKM_FUSE_ROM_ACCESS (0x0F | SUPPORTS_AK89xx_HIGH_SENS)
#define AKM_MODE_SELF_TEST (0x08 | SUPPORTS_AK89xx_HIGH_SENS)
#define AKM_WHOAMI (0x48)
#endif
struct gyro_reg_s regArray[MPU_MAX_DEVICES];
struct hw_s hwArray[MPU_MAX_DEVICES];
struct test_s testArray[MPU_MAX_DEVICES];
struct gyro_state_s gyroArray[MPU_MAX_DEVICES];
// These variables are set by the mpu_delect_device function
struct gyro_reg_s *reg;
struct hw_s *hw;
struct test_s *test;
struct gyro_state_s *st;
static int deviceIndex = 0;
int mpu_select_device(int device)
{
if ((device < 0) || (device >= MPU_MAX_DEVICES))
return -1;
deviceIndex = device;
reg = regArray + device;
hw = hwArray + device;
test = testArray + device;
st = gyroArray + device;
return 0;
}
#if defined MPU6050
void mpu_init_structures()
{
reg->who_am_i = 0x75;
reg->rate_div = 0x19;
reg->lpf = 0x1A;
reg->prod_id = 0x0C;
reg->user_ctrl = 0x6A;
reg->fifo_en = 0x23;
reg->gyro_cfg = 0x1B;
reg->accel_cfg = 0x1C;
reg->motion_thr = 0x1F;
reg->motion_dur = 0x20;
reg->fifo_count_h = 0x72;
reg->fifo_r_w = 0x74;
reg->raw_gyro = 0x43;
reg->raw_accel = 0x3B;
reg->temp = 0x41;
reg->int_enable = 0x38;
reg->dmp_int_status = 0x39;
reg->int_status = 0x3A;
reg->pwr_mgmt_1 = 0x6B;
reg->pwr_mgmt_2 = 0x6C;
reg->int_pin_cfg = 0x37;
reg->mem_r_w = 0x6F;
reg->accel_offs = 0x06;
reg->i2c_mst = 0x24;
reg->bank_sel = 0x6D;
reg->mem_start_addr = 0x6E;
reg->prgm_start_h = 0x70;
#ifdef AK89xx_SECONDARY
reg->raw_compass = 0x49;
reg->yg_offs_tc = 0x01;
reg->s0_addr = 0x25;
reg->s0_reg = 0x26;
reg->s0_ctrl = 0x27;
reg->s1_addr = 0x28;
reg->s1_reg = 0x29;
reg->s1_ctrl = 0x2A;
reg->s4_ctrl = 0x34;
reg->s0_do = 0x63;
reg->s1_do = 0x64;
reg->i2c_delay_ctrl = 0x67;
#endif
switch (deviceIndex) {
case 0:
hw->addr = 0x68;
break;
case 1:
hw->addr = 0x69;
break;
}
hw->max_fifo = 1024;
hw->num_reg = 118;
hw->temp_sens = 340;
hw->temp_offset = -521;
hw->bank_size = 256;
#if defined AK89xx_SECONDARY
hw->compass_fsr = AK89xx_FSR;
#endif
test->gyro_sens = 32768/250;
test->accel_sens = 32768/16;
test->reg_rate_div = 0; /* 1kHz. */
test->reg_lpf = 1; /* 188Hz. */
test->reg_gyro_fsr = 0; /* 250dps. */
test->reg_accel_fsr = 0x18; /* 16g. */
test->wait_ms = 50;
test->packet_thresh = 5; /* 5% */
test->min_dps = 10.f;
test->max_dps = 105.f;
test->max_gyro_var = 0.14f;
test->min_g = 0.3f;
test->max_g = 0.95f;
test->max_accel_var = 0.14f;
st->reg = reg;
st->hw = hw;
st->test = test;
};
#elif defined MPU6500
void mpu_init_structures()
{
reg->who_am_i = 0x75;
reg->rate_div = 0x19;
reg->lpf = 0x1A;
reg->prod_id = 0x0C;
reg->user_ctrl = 0x6A;
reg->fifo_en = 0x23;
reg->gyro_cfg = 0x1B;
reg->accel_cfg = 0x1C;
reg->accel_cfg2 = 0x1D;
reg->lp_accel_odr = 0x1E;
reg->motion_thr = 0x1F;
reg->motion_dur = 0x20;
reg->fifo_count_h = 0x72;
reg->fifo_r_w = 0x74;
reg->raw_gyro = 0x43;
reg->raw_accel = 0x3B;
reg->temp = 0x41;
reg->int_enable = 0x38;
reg->dmp_int_status = 0x39;
reg->int_status = 0x3A;
reg->accel_intel = 0x69;
reg->pwr_mgmt_1 = 0x6B;
reg->pwr_mgmt_2 = 0x6C;
reg->int_pin_cfg = 0x37;
reg->mem_r_w = 0x6F;
reg->accel_offs = 0x77;
reg->i2c_mst = 0x24;
reg->bank_sel = 0x6D;
reg->mem_start_addr = 0x6E;
reg->prgm_start_h = 0x70;
#ifdef AK89xx_SECONDARY
reg->raw_compass = 0x49;
reg->yg_offs_tc = 0x01;
reg->s0_addr = 0x25;
reg->s0_reg = 0x26;
reg->s0_ctrl = 0x27;
reg->s1_addr = 0x28;
reg->s1_reg = 0x29;
reg->s1_ctrl = 0x2A;
reg->s4_ctrl = 0x34;
reg->s0_do = 0x63;
reg->s1_do = 0x64;
reg->i2c_delay_ctrl = 0x67;
#endif
switch (deviceIndex) {
case 0:
hw->addr = 0x68;
break;
case 1:
hw->addr = 0x69;
break;
}
hw->max_fifo = 1024;
hw->num_reg = 128;
hw->temp_sens = 321;
hw->temp_offset = 0;
hw->bank_size = 256;
#if defined AK89xx_SECONDARY
hw->compass_fsr = AK89xx_FSR;
#endif
test->gyro_sens = 32768/250;
test->accel_sens = 32768/16;
test->reg_rate_div = 0; /* 1kHz. */
test->reg_lpf = 1; /* 188Hz. */
test->reg_gyro_fsr = 0; /* 250dps. */
test->reg_accel_fsr = 0x18; /* 16g. */
test->wait_ms = 50;
test->packet_thresh = 5; /* 5% */
test->min_dps = 10.f;
test->max_dps = 105.f;
test->max_gyro_var = 0.14f;
test->min_g = 0.3f;
test->max_g = 0.95f;
test->max_accel_var = 0.14f;
st->reg = reg;
st->hw = hw;
st->test = test;
};
#endif
#define MAX_PACKET_LENGTH (12)
#ifdef AK89xx_SECONDARY
static int setup_compass(void);
#define MAX_COMPASS_SAMPLE_RATE (100)
#endif
/**
* @brief Enable/disable data ready interrupt.
* If the DMP is on, the DMP interrupt is enabled. Otherwise, the data ready
* interrupt is used.
* @param[in] enable 1 to enable interrupt.
* @return 0 if successful.
*/
static int set_int_enable(unsigned char enable)
{
unsigned char tmp;
if (st->chip_cfg.dmp_on) {
if (enable)
tmp = BIT_DMP_INT_EN;
else
tmp = 0x00;
if (i2c_write(st->hw->addr, st->reg->int_enable, 1, &tmp))
return -1;
st->chip_cfg.int_enable = tmp;
} else {
if (!st->chip_cfg.sensors)
return -1;
if (enable && st->chip_cfg.int_enable)
return 0;
if (enable)
tmp = BIT_DATA_RDY_EN;
else
tmp = 0x00;
if (i2c_write(st->hw->addr, st->reg->int_enable, 1, &tmp))
return -1;
st->chip_cfg.int_enable = tmp;
}
return 0;
}
/**
* @brief Register dump for testing.
* @return 0 if successful.
*/
int mpu_reg_dump(void)
{
unsigned char ii;
unsigned char data;
for (ii = 0; ii < st->hw->num_reg; ii++) {
if (ii == st->reg->fifo_r_w || ii == st->reg->mem_r_w)
continue;
if (i2c_read(st->hw->addr, ii, 1, &data))
return -1;
// log_i("%#5x: %#5x\r\n", ii, data);
}
return 0;
}
/**
* @brief Read from a single register.
* NOTE: The memory and FIFO read/write registers cannot be accessed.
* @param[in] reg Register address.
* @param[out] data Register data.
* @return 0 if successful.
*/
int mpu_read_reg(unsigned char reg, unsigned char *data)
{
if (reg == st->reg->fifo_r_w || reg == st->reg->mem_r_w)
return -1;
if (reg >= st->hw->num_reg)
return -1;
return i2c_read(st->hw->addr, reg, 1, data);
}
/**
* @brief Initialize hardware.
* Initial configuration:\n
* Gyro FSR: +/- 2000DPS\n
* Accel FSR +/- 2G\n
* DLPF: 42Hz\n
* FIFO rate: 50Hz\n
* Clock source: Gyro PLL\n
* FIFO: Disabled.\n
* Data ready interrupt: Disabled, active low, unlatched.
* @param[in] int_param Platform-specific parameters to interrupt API.
* @return 0 if successful.
*/
int mpu_init(struct int_param_s *int_param)
{
unsigned char data[6], rev;
int errCode;
/* Reset device. */
data[0] = BIT_RESET;
if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, data))
return -1;
delay_ms(100);
/* Wake up chip. */
data[0] = 0x00;
if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, data))
return -2;
#if defined MPU6050
/* Check product revision. */
if (i2c_read(st->hw->addr, st->reg->accel_offs, 6, data))
return -3;
rev = ((data[5] & 0x01) << 2) | ((data[3] & 0x01) << 1) |
(data[1] & 0x01);
if (rev) {
/* Congrats, these parts are better. */
if (rev == 1)
st->chip_cfg.accel_half = 1;
else if (rev == 2)
st->chip_cfg.accel_half = 0;
else {
#ifdef MPU_DEBUG
Serial.print("Unsupported software product rev: "); Serial.println(rev);
#endif
return -4;
}
} else {
if (i2c_read(st->hw->addr, st->reg->prod_id, 1, data))
return -5;
rev = data[0] & 0x0F;
if (!rev) {
#ifdef MPU_DEBUG
Serial.println("Product ID read as 0 indicates device is either incompatible or an MPU3050");
#endif
return -6;
} else if (rev == 4) {
#ifdef MPU_DEBUG
Serial.println("Half sensitivity part found.");
#endif
st->chip_cfg.accel_half = 1;
} else
st->chip_cfg.accel_half = 0;
}
#elif defined MPU6500
#define MPU6500_MEM_REV_ADDR (0x17)
if (mpu_read_mem(MPU6500_MEM_REV_ADDR, 1, &rev))
return -7;
if (rev == 0x1)
st->chip_cfg.accel_half = 0;
else {
#ifdef MPU_DEBUG
Serial.print("Unsupported software product rev: "); Serial.println(rev);
#endif
return -8;
}
/* MPU6500 shares 4kB of memory between the DMP and the FIFO. Since the
* first 3kB are needed by the DMP, we'll use the last 1kB for the FIFO.
*/
data[0] = BIT_FIFO_SIZE_1024 | 0x8;
if (i2c_write(st->hw->addr, st->reg->accel_cfg2, 1, data))
return -9;
#endif
/* Set to invalid values to ensure no I2C writes are skipped. */
st->chip_cfg.sensors = 0xFF;
st->chip_cfg.gyro_fsr = 0xFF;
st->chip_cfg.accel_fsr = 0xFF;
st->chip_cfg.lpf = 0xFF;
st->chip_cfg.sample_rate = 0xFFFF;
st->chip_cfg.fifo_enable = 0xFF;
st->chip_cfg.bypass_mode = 0xFF;
#ifdef AK89xx_SECONDARY
st->chip_cfg.compass_sample_rate = 0xFFFF;
#endif
/* mpu_set_sensors always preserves this setting. */
st->chip_cfg.clk_src = INV_CLK_PLL;
/* Handled in next call to mpu_set_bypass. */
st->chip_cfg.active_low_int = 1;
st->chip_cfg.latched_int = 0;
st->chip_cfg.int_motion_only = 0;
st->chip_cfg.lp_accel_mode = 0;
memset(&st->chip_cfg.cache, 0, sizeof(st->chip_cfg.cache));
st->chip_cfg.dmp_on = 0;
st->chip_cfg.dmp_loaded = 0;
st->chip_cfg.dmp_sample_rate = 0;
if (mpu_set_gyro_fsr(2000))
return -10;
if (mpu_set_accel_fsr(2))
return -11;
if (mpu_set_lpf(42))
return -12;
if (mpu_set_sample_rate(50))
return -13;
if (mpu_configure_fifo(0))
return -14;
if (int_param)
reg_int_cb(int_param);
#ifdef AK89xx_SECONDARY
#ifdef MPU_DEBUG
Serial.println("Setting up compass");
#endif
errCode = setup_compass();
if (errCode != 0) {
#ifdef MPU_DEBUG
Serial.print("Setup compass failed: "); Serial.println(errCode);
#endif
}
if (mpu_set_compass_sample_rate(10))
return -15;
#else
/* Already disabled by setup_compass. */
if (mpu_set_bypass(0))
return -16;
#endif
mpu_set_sensors(0);
return 0;
}
/**
* @brief Enter low-power accel-only mode.
* In low-power accel mode, the chip goes to sleep and only wakes up to sample
* the accelerometer at one of the following frequencies:
* \n MPU6050: 1.25Hz, 5Hz, 20Hz, 40Hz
* \n MPU6500: 1.25Hz, 2.5Hz, 5Hz, 10Hz, 20Hz, 40Hz, 80Hz, 160Hz, 320Hz, 640Hz
* \n If the requested rate is not one listed above, the device will be set to
* the next highest rate. Requesting a rate above the maximum supported
* frequency will result in an error.
* \n To select a fractional wake-up frequency, round down the value passed to
* @e rate.
* @param[in] rate Minimum sampling rate, or zero to disable LP
* accel mode.
* @return 0 if successful.
*/
int mpu_lp_accel_mode(unsigned char rate)
{
unsigned char tmp[2];
if (rate > 40)
return -1;
if (!rate) {
mpu_set_int_latched(0);
tmp[0] = 0;
tmp[1] = BIT_STBY_XYZG;
if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 2, tmp))
return -1;
st->chip_cfg.lp_accel_mode = 0;
return 0;
}
/* For LP accel, we automatically configure the hardware to produce latched
* interrupts. In LP accel mode, the hardware cycles into sleep mode before
* it gets a chance to deassert the interrupt pin; therefore, we shift this
* responsibility over to the MCU.
*
* Any register read will clear the interrupt.
*/
mpu_set_int_latched(1);
#if defined MPU6050
tmp[0] = BIT_LPA_CYCLE;
if (rate == 1) {
tmp[1] = INV_LPA_1_25HZ;
mpu_set_lpf(5);
} else if (rate <= 5) {
tmp[1] = INV_LPA_5HZ;
mpu_set_lpf(5);
} else if (rate <= 20) {
tmp[1] = INV_LPA_20HZ;
mpu_set_lpf(10);
} else {
tmp[1] = INV_LPA_40HZ;
mpu_set_lpf(20);
}
tmp[1] = (tmp[1] << 6) | BIT_STBY_XYZG;
if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 2, tmp))
return -1;
#elif defined MPU6500
/* Set wake frequency. */
if (rate == 1)
tmp[0] = INV_LPA_1_25HZ;
else if (rate == 2)
tmp[0] = INV_LPA_2_5HZ;
else if (rate <= 5)
tmp[0] = INV_LPA_5HZ;
else if (rate <= 10)
tmp[0] = INV_LPA_10HZ;
else if (rate <= 20)
tmp[0] = INV_LPA_20HZ;
else if (rate <= 40)
tmp[0] = INV_LPA_40HZ;
else if (rate <= 80)
tmp[0] = INV_LPA_80HZ;
else if (rate <= 160)
tmp[0] = INV_LPA_160HZ;
else if (rate <= 320)
tmp[0] = INV_LPA_320HZ;
else
tmp[0] = INV_LPA_640HZ;
if (i2c_write(st->hw->addr, st->reg->lp_accel_odr, 1, tmp))
return -1;
tmp[0] = BIT_LPA_CYCLE;
if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, tmp))
return -1;
#endif
st->chip_cfg.sensors = INV_XYZ_ACCEL;
st->chip_cfg.clk_src = 0;
st->chip_cfg.lp_accel_mode = 1;
mpu_configure_fifo(0);
return 0;
}
/**
* @brief Read raw gyro data directly from the registers.
* @param[out] data Raw data in hardware units.
* @param[out] timestamp Timestamp in milliseconds. Null if not needed.
* @return 0 if successful.
*/
int mpu_get_gyro_reg(short *data, unsigned long *timestamp)
{
unsigned char tmp[6];
if (!(st->chip_cfg.sensors & INV_XYZ_GYRO))
return -1;
if (i2c_read(st->hw->addr, st->reg->raw_gyro, 6, tmp))
return -1;
data[0] = (tmp[0] << 8) | tmp[1];
data[1] = (tmp[2] << 8) | tmp[3];
data[2] = (tmp[4] << 8) | tmp[5];
if (timestamp)
get_ms(timestamp);
return 0;
}
/**
* @brief Read raw accel data directly from the registers.
* @param[out] data Raw data in hardware units.
* @param[out] timestamp Timestamp in milliseconds. Null if not needed.
* @return 0 if successful.
*/
int mpu_get_accel_reg(short *data, unsigned long *timestamp)
{
unsigned char tmp[6];
if (!(st->chip_cfg.sensors & INV_XYZ_ACCEL))
return -1;
if (i2c_read(st->hw->addr, st->reg->raw_accel, 6, tmp))
return -1;
data[0] = (tmp[0] << 8) | tmp[1];
data[1] = (tmp[2] << 8) | tmp[3];
data[2] = (tmp[4] << 8) | tmp[5];
if (timestamp)
get_ms(timestamp);
return 0;
}
/**
* @brief Read temperature data directly from the registers.
* @param[out] data Data in q16 format.
* @param[out] timestamp Timestamp in milliseconds. Null if not needed.
* @return 0 if successful.
*/
int mpu_get_temperature(long *data, unsigned long *timestamp)
{
unsigned char tmp[2];
short raw;
if (!(st->chip_cfg.sensors))
return -1;
if (i2c_read(st->hw->addr, st->reg->temp, 2, tmp))
return -1;
raw = (tmp[0] << 8) | tmp[1];
if (timestamp)
get_ms(timestamp);
data[0] = (long)((35 + ((raw - (float)st->hw->temp_offset) / st->hw->temp_sens)) * 65536L);
return 0;
}
/**
* @brief Push biases to the accel bias registers.
* This function expects biases relative to the current sensor output, and
* these biases will be added to the factory-supplied values.
* @param[in] accel_bias New biases.
* @return 0 if successful.
*/
int mpu_set_accel_bias(const long *accel_bias)
{
unsigned char data[6];
short accel_hw[3];
short got_accel[3];
short fg[3];
if (!accel_bias)
return -1;
if (!accel_bias[0] && !accel_bias[1] && !accel_bias[2])
return 0;
if (i2c_read(st->hw->addr, 3, 3, data))
return -1;
fg[0] = ((data[0] >> 4) + 8) & 0xf;
fg[1] = ((data[1] >> 4) + 8) & 0xf;
fg[2] = ((data[2] >> 4) + 8) & 0xf;
accel_hw[0] = (short)(accel_bias[0] * 2 / (64 + fg[0]));
accel_hw[1] = (short)(accel_bias[1] * 2 / (64 + fg[1]));
accel_hw[2] = (short)(accel_bias[2] * 2 / (64 + fg[2]));
if (i2c_read(st->hw->addr, 0x06, 6, data))
return -1;
got_accel[0] = ((short)data[0] << 8) | data[1];
got_accel[1] = ((short)data[2] << 8) | data[3];
got_accel[2] = ((short)data[4] << 8) | data[5];
accel_hw[0] += got_accel[0];
accel_hw[1] += got_accel[1];
accel_hw[2] += got_accel[2];
data[0] = (accel_hw[0] >> 8) & 0xff;
data[1] = (accel_hw[0]) & 0xff;
data[2] = (accel_hw[1] >> 8) & 0xff;
data[3] = (accel_hw[1]) & 0xff;
data[4] = (accel_hw[2] >> 8) & 0xff;
data[5] = (accel_hw[2]) & 0xff;
if (i2c_write(st->hw->addr, 0x06, 6, data))
return -1;
return 0;
}
/**
* @brief Reset FIFO read/write pointers.
* @return 0 if successful.
*/
int mpu_reset_fifo(void)
{
unsigned char data;
if (!(st->chip_cfg.sensors))
return -1;
data = 0;
if (i2c_write(st->hw->addr, st->reg->int_enable, 1, &data))
return -1;
if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, &data))
return -1;
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &data))
return -1;
if (st->chip_cfg.dmp_on) {
data = BIT_FIFO_RST | BIT_DMP_RST;
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &data))
return -1;
delay_ms(50);
data = BIT_DMP_EN | BIT_FIFO_EN;
if (st->chip_cfg.sensors & INV_XYZ_COMPASS)
data |= BIT_AUX_IF_EN;
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &data))
return -1;
if (st->chip_cfg.int_enable)
data = BIT_DMP_INT_EN;
else
data = 0;
if (i2c_write(st->hw->addr, st->reg->int_enable, 1, &data))
return -1;
data = 0;
if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, &data))
return -1;
} else {
data = BIT_FIFO_RST;
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &data))
return -1;
if (st->chip_cfg.bypass_mode || !(st->chip_cfg.sensors & INV_XYZ_COMPASS))
data = BIT_FIFO_EN;
else
data = BIT_FIFO_EN | BIT_AUX_IF_EN;
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &data))
return -1;
delay_ms(50);
if (st->chip_cfg.int_enable)
data = BIT_DATA_RDY_EN;
else
data = 0;
if (i2c_write(st->hw->addr, st->reg->int_enable, 1, &data))
return -1;
if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, &st->chip_cfg.fifo_enable))
return -1;
}
return 0;
}
/**
* @brief Get the gyro full-scale range.
* @param[out] fsr Current full-scale range.
* @return 0 if successful.
*/
int mpu_get_gyro_fsr(unsigned short *fsr)
{
switch (st->chip_cfg.gyro_fsr) {
case INV_FSR_250DPS:
fsr[0] = 250;
break;
case INV_FSR_500DPS:
fsr[0] = 500;
break;
case INV_FSR_1000DPS:
fsr[0] = 1000;
break;
case INV_FSR_2000DPS:
fsr[0] = 2000;
break;
default:
fsr[0] = 0;
break;
}
return 0;
}
/**
* @brief Set the gyro full-scale range.
* @param[in] fsr Desired full-scale range.
* @return 0 if successful.
*/
int mpu_set_gyro_fsr(unsigned short fsr)
{
unsigned char data;
if (!(st->chip_cfg.sensors))
return -1;
switch (fsr) {
case 250:
data = INV_FSR_250DPS << 3;
break;
case 500:
data = INV_FSR_500DPS << 3;
break;
case 1000:
data = INV_FSR_1000DPS << 3;
break;
case 2000:
data = INV_FSR_2000DPS << 3;
break;
default:
return -1;
}
if (st->chip_cfg.gyro_fsr == (data >> 3))
return 0;
if (i2c_write(st->hw->addr, st->reg->gyro_cfg, 1, &data))
return -1;
st->chip_cfg.gyro_fsr = data >> 3;
return 0;
}
/**
* @brief Get the accel full-scale range.
* @param[out] fsr Current full-scale range.
* @return 0 if successful.
*/
int mpu_get_accel_fsr(unsigned char *fsr)
{
switch (st->chip_cfg.accel_fsr) {
case INV_FSR_2G:
fsr[0] = 2;
break;
case INV_FSR_4G:
fsr[0] = 4;
break;
case INV_FSR_8G:
fsr[0] = 8;
break;
case INV_FSR_16G:
fsr[0] = 16;
break;
default:
return -1;
}
if (st->chip_cfg.accel_half)
fsr[0] <<= 1;
return 0;
}
/**
* @brief Set the accel full-scale range.
* @param[in] fsr Desired full-scale range.
* @return 0 if successful.
*/
int mpu_set_accel_fsr(unsigned char fsr)
{
unsigned char data;
if (!(st->chip_cfg.sensors))
return -1;
switch (fsr) {
case 2:
data = INV_FSR_2G << 3;
break;
case 4:
data = INV_FSR_4G << 3;
break;
case 8:
data = INV_FSR_8G << 3;
break;
case 16:
data = INV_FSR_16G << 3;
break;
default:
return -1;
}
if (st->chip_cfg.accel_fsr == (data >> 3))
return 0;
if (i2c_write(st->hw->addr, st->reg->accel_cfg, 1, &data))
return -1;
st->chip_cfg.accel_fsr = data >> 3;
return 0;
}
/**
* @brief Get the current DLPF setting.
* @param[out] lpf Current LPF setting.
* 0 if successful.
*/
int mpu_get_lpf(unsigned short *lpf)
{
switch (st->chip_cfg.lpf) {
case INV_FILTER_188HZ:
lpf[0] = 188;
break;
case INV_FILTER_98HZ:
lpf[0] = 98;
break;
case INV_FILTER_42HZ:
lpf[0] = 42;
break;
case INV_FILTER_20HZ:
lpf[0] = 20;
break;
case INV_FILTER_10HZ:
lpf[0] = 10;
break;
case INV_FILTER_5HZ:
lpf[0] = 5;
break;
case INV_FILTER_256HZ_NOLPF2:
case INV_FILTER_2100HZ_NOLPF:
default:
lpf[0] = 0;
break;
}
return 0;
}
/**
* @brief Set digital low pass filter.
* The following LPF settings are supported: 188, 98, 42, 20, 10, 5.
* @param[in] lpf Desired LPF setting.
* @return 0 if successful.
*/
int mpu_set_lpf(unsigned short lpf)
{
unsigned char data;
if (!(st->chip_cfg.sensors))
return -1;
if (lpf >= 188)
data = INV_FILTER_188HZ;
else if (lpf >= 98)
data = INV_FILTER_98HZ;
else if (lpf >= 42)
data = INV_FILTER_42HZ;
else if (lpf >= 20)
data = INV_FILTER_20HZ;
else if (lpf >= 10)
data = INV_FILTER_10HZ;
else
data = INV_FILTER_5HZ;
if (st->chip_cfg.lpf == data)
return 0;
if (i2c_write(st->hw->addr, st->reg->lpf, 1, &data))
return -1;
st->chip_cfg.lpf = data;
return 0;
}
/**
* @brief Get sampling rate.
* @param[out] rate Current sampling rate (Hz).
* @return 0 if successful.
*/
int mpu_get_sample_rate(unsigned short *rate)
{
if (st->chip_cfg.dmp_on)
return -1;
else
rate[0] = st->chip_cfg.sample_rate;
return 0;
}
/**
* @brief Set sampling rate.
* Sampling rate must be between 4Hz and 1kHz.
* @param[in] rate Desired sampling rate (Hz).
* @return 0 if successful.
*/
int mpu_set_sample_rate(unsigned short rate)
{
unsigned char data;
if (!(st->chip_cfg.sensors))
return -1;
if (st->chip_cfg.dmp_on)
return -1;
else {
if (st->chip_cfg.lp_accel_mode) {
if (rate && (rate <= 40)) {
/* Just stay in low-power accel mode. */
mpu_lp_accel_mode(rate);
return 0;
}
/* Requested rate exceeds the allowed frequencies in LP accel mode,
* switch back to full-power mode.
*/
mpu_lp_accel_mode(0);
}
if (rate < 4)
rate = 4;
else if (rate > 1000)
rate = 1000;
data = 1000 / rate - 1;
if (i2c_write(st->hw->addr, st->reg->rate_div, 1, &data))
return -1;
st->chip_cfg.sample_rate = 1000 / (1 + data);
#ifdef AK89xx_SECONDARY
mpu_set_compass_sample_rate(min(st->chip_cfg.compass_sample_rate, MAX_COMPASS_SAMPLE_RATE));
#endif
/* Automatically set LPF to 1/2 sampling rate. */
mpu_set_lpf(st->chip_cfg.sample_rate >> 1);
return 0;
}
}
/**
* @brief Get compass sampling rate.
* @param[out] rate Current compass sampling rate (Hz).
* @return 0 if successful.
*/
int mpu_get_compass_sample_rate(unsigned short *rate)
{
#ifdef AK89xx_SECONDARY
rate[0] = st->chip_cfg.compass_sample_rate;
return 0;
#else
rate[0] = 0;
return -1;
#endif
}
/**
* @brief Set compass sampling rate.
* The compass on the auxiliary I2C bus is read by the MPU hardware at a
* maximum of 100Hz. The actual rate can be set to a fraction of the gyro
* sampling rate.
*
* \n WARNING: The new rate may be different than what was requested. Call
* mpu_get_compass_sample_rate to check the actual setting.
* @param[in] rate Desired compass sampling rate (Hz).
* @return 0 if successful.
*/
int mpu_set_compass_sample_rate(unsigned short rate)
{
#ifdef AK89xx_SECONDARY
unsigned char div;
if (!rate || rate > st->chip_cfg.sample_rate || rate > MAX_COMPASS_SAMPLE_RATE)
return -1;
div = st->chip_cfg.sample_rate / rate - 1;
if (i2c_write(st->hw->addr, st->reg->s4_ctrl, 1, &div))
return -1;
st->chip_cfg.compass_sample_rate = st->chip_cfg.sample_rate / (div + 1);
return 0;
#else
return -1;
#endif
}
/**
* @brief Get gyro sensitivity scale factor.
* @param[out] sens Conversion from hardware units to dps.
* @return 0 if successful.
*/
int mpu_get_gyro_sens(float *sens)
{
switch (st->chip_cfg.gyro_fsr) {
case INV_FSR_250DPS:
sens[0] = 131.f;
break;
case INV_FSR_500DPS:
sens[0] = 65.5f;
break;
case INV_FSR_1000DPS:
sens[0] = 32.8f;
break;
case INV_FSR_2000DPS:
sens[0] = 16.4f;
break;
default:
return -1;
}
return 0;
}
/**
* @brief Get accel sensitivity scale factor.
* @param[out] sens Conversion from hardware units to g's.
* @return 0 if successful.
*/
int mpu_get_accel_sens(unsigned short *sens)
{
switch (st->chip_cfg.accel_fsr) {
case INV_FSR_2G:
sens[0] = 16384;
break;
case INV_FSR_4G:
sens[0] = 8092;
break;
case INV_FSR_8G:
sens[0] = 4096;
break;
case INV_FSR_16G:
sens[0] = 2048;
break;
default:
return -1;
}
if (st->chip_cfg.accel_half)
sens[0] >>= 1;
return 0;
}
/**
* @brief Get current FIFO configuration.
* @e sensors can contain a combination of the following flags:
* \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO
* \n INV_XYZ_GYRO
* \n INV_XYZ_ACCEL
* @param[out] sensors Mask of sensors in FIFO.
* @return 0 if successful.
*/
int mpu_get_fifo_config(unsigned char *sensors)
{
sensors[0] = st->chip_cfg.fifo_enable;
return 0;
}
/**
* @brief Select which sensors are pushed to FIFO.
* @e sensors can contain a combination of the following flags:
* \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO
* \n INV_XYZ_GYRO
* \n INV_XYZ_ACCEL
* @param[in] sensors Mask of sensors to push to FIFO.
* @return 0 if successful.
*/
int mpu_configure_fifo(unsigned char sensors)
{
unsigned char prev;
int result = 0;
/* Compass data isn't going into the FIFO. Stop trying. */
sensors &= ~INV_XYZ_COMPASS;
if (st->chip_cfg.dmp_on)
return 0;
else {
if (!(st->chip_cfg.sensors))
return -1;
prev = st->chip_cfg.fifo_enable;
st->chip_cfg.fifo_enable = sensors & st->chip_cfg.sensors;
if (st->chip_cfg.fifo_enable != sensors)
/* You're not getting what you asked for. Some sensors are
* asleep.
*/
result = -1;
else
result = 0;
if (sensors || st->chip_cfg.lp_accel_mode)
set_int_enable(1);
else
set_int_enable(0);
if (sensors) {
if (mpu_reset_fifo()) {
st->chip_cfg.fifo_enable = prev;
return -1;
}
}
}
return result;
}
/**
* @brief Get current power state.
* @param[in] power_on 1 if turned on, 0 if suspended.
* @return 0 if successful.
*/
int mpu_get_power_state(unsigned char *power_on)
{
if (st->chip_cfg.sensors)
power_on[0] = 1;
else
power_on[0] = 0;
return 0;
}
/**
* @brief Turn specific sensors on/off.
* @e sensors can contain a combination of the following flags:
* \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO
* \n INV_XYZ_GYRO
* \n INV_XYZ_ACCEL
* \n INV_XYZ_COMPASS
* @param[in] sensors Mask of sensors to wake.
* @return 0 if successful.
*/
int mpu_set_sensors(unsigned char sensors)
{
unsigned char data;
#ifdef AK89xx_SECONDARY
unsigned char user_ctrl;
#endif
if (sensors & INV_XYZ_GYRO)
data = INV_CLK_PLL;
else if (sensors)
data = 0;
else
data = BIT_SLEEP;
if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, &data)) {
st->chip_cfg.sensors = 0;
return -1;
}
st->chip_cfg.clk_src = data & ~BIT_SLEEP;
data = 0;
if (!(sensors & INV_X_GYRO))
data |= BIT_STBY_XG;
if (!(sensors & INV_Y_GYRO))
data |= BIT_STBY_YG;
if (!(sensors & INV_Z_GYRO))
data |= BIT_STBY_ZG;
if (!(sensors & INV_XYZ_ACCEL))
data |= BIT_STBY_XYZA;
if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_2, 1, &data)) {
st->chip_cfg.sensors = 0;
return -1;
}
if (sensors && (sensors != INV_XYZ_ACCEL))
/* Latched interrupts only used in LP accel mode. */
mpu_set_int_latched(0);
#ifdef AK89xx_SECONDARY
#ifdef AK89xx_BYPASS
if (sensors & INV_XYZ_COMPASS)
mpu_set_bypass(1);
else
mpu_set_bypass(0);
#else
if (i2c_read(st->hw->addr, st->reg->user_ctrl, 1, &user_ctrl))
return -1;
/* Handle AKM power management. */
if (sensors & INV_XYZ_COMPASS) {
data = AKM_SINGLE_MEASUREMENT;
user_ctrl |= BIT_AUX_IF_EN;
} else {
data = AKM_POWER_DOWN;
user_ctrl &= ~BIT_AUX_IF_EN;
}
if (st->chip_cfg.dmp_on)
user_ctrl |= BIT_DMP_EN;
else
user_ctrl &= ~BIT_DMP_EN;
if (i2c_write(st->hw->addr, st->reg->s1_do, 1, &data))
return -1;
/* Enable/disable I2C master mode. */
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &user_ctrl))
return -1;
#endif
#endif
st->chip_cfg.sensors = sensors;
st->chip_cfg.lp_accel_mode = 0;
delay_ms(50);
return 0;
}
/**
* @brief Read the MPU interrupt status registers.
* @param[out] status Mask of interrupt bits.
* @return 0 if successful.
*/
int mpu_get_int_status(short *status)
{
unsigned char tmp[2];
if (!st->chip_cfg.sensors)
return -1;
if (i2c_read(st->hw->addr, st->reg->dmp_int_status, 2, tmp))
return -1;
status[0] = (tmp[0] << 8) | tmp[1];
return 0;
}
/**
* @brief Get one packet from the FIFO.
* If @e sensors does not contain a particular sensor, disregard the data
* returned to that pointer.
* \n @e sensors can contain a combination of the following flags:
* \n INV_X_GYRO, INV_Y_GYRO, INV_Z_GYRO
* \n INV_XYZ_GYRO
* \n INV_XYZ_ACCEL
* \n If the FIFO has no new data, @e sensors will be zero.
* \n If the FIFO is disabled, @e sensors will be zero and this function will
* return a non-zero error code.
* @param[out] gyro Gyro data in hardware units.
* @param[out] accel Accel data in hardware units.
* @param[out] timestamp Timestamp in milliseconds.
* @param[out] sensors Mask of sensors read from FIFO.
* @param[out] more Number of remaining packets.
* @return 0 if successful.
*/
int mpu_read_fifo(short *gyro, short *accel, unsigned long *timestamp,
unsigned char *sensors, unsigned char *more)
{
/* Assumes maximum packet size is gyro (6) + accel (6). */
unsigned char data[MAX_PACKET_LENGTH];
unsigned char packet_size = 0;
unsigned short fifo_count, index = 0;
if (st->chip_cfg.dmp_on)
return -1;
sensors[0] = 0;
if (!st->chip_cfg.sensors)
return -2;
if (!st->chip_cfg.fifo_enable)
return -3;
if (st->chip_cfg.fifo_enable & INV_X_GYRO)
packet_size += 2;
if (st->chip_cfg.fifo_enable & INV_Y_GYRO)
packet_size += 2;
if (st->chip_cfg.fifo_enable & INV_Z_GYRO)
packet_size += 2;
if (st->chip_cfg.fifo_enable & INV_XYZ_ACCEL)
packet_size += 6;
if (i2c_read(st->hw->addr, st->reg->fifo_count_h, 2, data))
return -4;
if (fifo_count < packet_size)
return 1;
// log_i("FIFO count: %hd\n", fifo_count);
if (fifo_count > (st->hw->max_fifo >> 1)) {
/* FIFO is 50% full, better check overflow bit. */
if (i2c_read(st->hw->addr, st->reg->int_status, 1, data))
return -5;
if (data[0] & BIT_FIFO_OVERFLOW) {
mpu_reset_fifo();
return 2;
}
}
if (timestamp)
get_ms((unsigned long*)timestamp);
if (i2c_read(st->hw->addr, st->reg->fifo_r_w, packet_size, data))
return -7;
more[0] = fifo_count / packet_size - 1;
sensors[0] = 0;
if ((index != packet_size) && st->chip_cfg.fifo_enable & INV_XYZ_ACCEL) {
accel[0] = (data[index+0] << 8) | data[index+1];
accel[1] = (data[index+2] << 8) | data[index+3];
accel[2] = (data[index+4] << 8) | data[index+5];
sensors[0] |= INV_XYZ_ACCEL;
index += 6;
}
if ((index != packet_size) && st->chip_cfg.fifo_enable & INV_X_GYRO) {
gyro[0] = (data[index+0] << 8) | data[index+1];
sensors[0] |= INV_X_GYRO;
index += 2;
}
if ((index != packet_size) && st->chip_cfg.fifo_enable & INV_Y_GYRO) {
gyro[1] = (data[index+0] << 8) | data[index+1];
sensors[0] |= INV_Y_GYRO;
index += 2;
}
if ((index != packet_size) && st->chip_cfg.fifo_enable & INV_Z_GYRO) {
gyro[2] = (data[index+0] << 8) | data[index+1];
sensors[0] |= INV_Z_GYRO;
index += 2;
}
return 0;
}
/**
* @brief Get one unparsed packet from the FIFO.
* This function should be used if the packet is to be parsed elsewhere.
* @param[in] length Length of one FIFO packet.
* @param[in] data FIFO packet.
* @param[in] more Number of remaining packets.
*/
int mpu_read_fifo_stream(unsigned short length, unsigned char *data,
unsigned char *more)
{
unsigned char tmp[2];
unsigned short fifo_count;
if (!st->chip_cfg.dmp_on)
return -1;
if (!st->chip_cfg.sensors)
return -2;
if (i2c_read(st->hw->addr, st->reg->fifo_count_h, 2, tmp))
return -3;
fifo_count = (tmp[0] << 8) | tmp[1];
if (fifo_count < length) {
more[0] = 0;
return 1;
}
if (fifo_count > (st->hw->max_fifo >> 1)) {
/* FIFO is 50% full, better check overflow bit. */
if (i2c_read(st->hw->addr, st->reg->int_status, 1, tmp))
return -5;
if (tmp[0] & BIT_FIFO_OVERFLOW) {
mpu_reset_fifo();
return 2;
}
}
if (i2c_read(st->hw->addr, st->reg->fifo_r_w, length, data))
return -7;
more[0] = fifo_count / length - 1;
return 0;
}
/**
* @brief Set device to bypass mode.
* @param[in] bypass_on 1 to enable bypass mode.
* @return 0 if successful.
*/
int mpu_set_bypass(unsigned char bypass_on)
{
unsigned char tmp;
if (st->chip_cfg.bypass_mode == bypass_on)
return 0;
if (bypass_on) {
if (i2c_read(st->hw->addr, st->reg->user_ctrl, 1, &tmp))
return -1;
tmp &= ~BIT_AUX_IF_EN;
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &tmp))
return -1;
delay_ms(3);
tmp = BIT_BYPASS_EN;
if (st->chip_cfg.active_low_int)
tmp |= BIT_ACTL;
if (st->chip_cfg.latched_int)
tmp |= BIT_LATCH_EN | BIT_ANY_RD_CLR;
if (i2c_write(st->hw->addr, st->reg->int_pin_cfg, 1, &tmp))
return -1;
} else {
/* Enable I2C master mode if compass is being used. */
if (i2c_read(st->hw->addr, st->reg->user_ctrl, 1, &tmp))
return -1;
if (st->chip_cfg.sensors & INV_XYZ_COMPASS)
tmp |= BIT_AUX_IF_EN;
else
tmp &= ~BIT_AUX_IF_EN;
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, &tmp))
return -1;
delay_ms(3);
if (st->chip_cfg.active_low_int)
tmp = BIT_ACTL;
else
tmp = 0;
if (st->chip_cfg.latched_int)
tmp |= BIT_LATCH_EN | BIT_ANY_RD_CLR;
if (i2c_write(st->hw->addr, st->reg->int_pin_cfg, 1, &tmp))
return -1;
}
st->chip_cfg.bypass_mode = bypass_on;
return 0;
}
/**
* @brief Set interrupt level.
* @param[in] active_low 1 for active low, 0 for active high.
* @return 0 if successful.
*/
int mpu_set_int_level(unsigned char active_low)
{
st->chip_cfg.active_low_int = active_low;
return 0;
}
/**
* @brief Enable latched interrupts.
* Any MPU register will clear the interrupt.
* @param[in] enable 1 to enable, 0 to disable.
* @return 0 if successful.
*/
int mpu_set_int_latched(unsigned char enable)
{
unsigned char tmp;
if (st->chip_cfg.latched_int == enable)
return 0;
if (enable)
tmp = BIT_LATCH_EN | BIT_ANY_RD_CLR;
else
tmp = 0;
if (st->chip_cfg.bypass_mode)
tmp |= BIT_BYPASS_EN;
if (st->chip_cfg.active_low_int)
tmp |= BIT_ACTL;
if (i2c_write(st->hw->addr, st->reg->int_pin_cfg, 1, &tmp))
return -1;
st->chip_cfg.latched_int = enable;
return 0;
}
#ifdef MPU_MAXIMAL
#ifdef MPU6050
static int get_accel_prod_shift(float *st_shift)
{
unsigned char tmp[4], shift_code[3], ii;
if (i2c_read(st->hw->addr, 0x0D, 4, tmp))
return 0x07;
shift_code[0] = ((tmp[0] & 0xE0) >> 3) | ((tmp[3] & 0x30) >> 4);
shift_code[1] = ((tmp[1] & 0xE0) >> 3) | ((tmp[3] & 0x0C) >> 2);
shift_code[2] = ((tmp[2] & 0xE0) >> 3) | (tmp[3] & 0x03);
for (ii = 0; ii < 3; ii++) {
if (!shift_code[ii]) {
st_shift[ii] = 0.f;
continue;
}
/* Equivalent to..
* st_shift[ii] = 0.34f * powf(0.92f/0.34f, (shift_code[ii]-1) / 30.f)
*/
st_shift[ii] = 0.34f;
while (--shift_code[ii])
st_shift[ii] *= 1.034f;
}
return 0;
}
static int accel_self_test(long *bias_regular, long *bias_st)
{
int jj, result = 0;
float st_shift[3], st_shift_cust, st_shift_var;
get_accel_prod_shift(st_shift);
for(jj = 0; jj < 3; jj++) {
st_shift_cust = labs(bias_regular[jj] - bias_st[jj]) / 65536.f;
if (st_shift[jj]) {
st_shift_var = st_shift_cust / st_shift[jj] - 1.f;
if (fabs(st_shift_var) > test->max_accel_var)
result |= 1 << jj;
} else if ((st_shift_cust < test->min_g) ||
(st_shift_cust > test->max_g))
result |= 1 << jj;
}
return result;
}
static int gyro_self_test(long *bias_regular, long *bias_st)
{
int jj, result = 0;
unsigned char tmp[3];
float st_shift, st_shift_cust, st_shift_var;
if (i2c_read(st->hw->addr, 0x0D, 3, tmp))
return 0x07;
tmp[0] &= 0x1F;
tmp[1] &= 0x1F;
tmp[2] &= 0x1F;
for (jj = 0; jj < 3; jj++) {
st_shift_cust = labs(bias_regular[jj] - bias_st[jj]) / 65536.f;
if (tmp[jj]) {
st_shift = 3275.f / test->gyro_sens;
while (--tmp[jj])
st_shift *= 1.046f;
st_shift_var = st_shift_cust / st_shift - 1.f;
if (fabs(st_shift_var) > test->max_gyro_var)
result |= 1 << jj;
} else if ((st_shift_cust < test->min_dps) ||
(st_shift_cust > test->max_dps))
result |= 1 << jj;
}
return result;
}
#ifdef AK89xx_SECONDARY
static int compass_self_test(void)
{
unsigned char tmp[6];
unsigned char tries = 10;
int result = 0x07;
short data;
mpu_set_bypass(1);
tmp[0] = AKM_POWER_DOWN;
if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp))
return 0x07;
tmp[0] = AKM_BIT_SELF_TEST;
if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_ASTC, 1, tmp))
goto AKM_restore;
tmp[0] = AKM_MODE_SELF_TEST;
if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp))
goto AKM_restore;
do {
delay_ms(10);
if (i2c_read(st->chip_cfg.compass_addr, AKM_REG_ST1, 1, tmp))
goto AKM_restore;
if (tmp[0] & AKM_DATA_READY)
break;
} while (tries--);
if (!(tmp[0] & AKM_DATA_READY))
goto AKM_restore;
if (i2c_read(st->chip_cfg.compass_addr, AKM_REG_HXL, 6, tmp))
goto AKM_restore;
result = 0;
data = (short)(tmp[1] << 8) | tmp[0];
if ((data > 100) || (data < -100))
result |= 0x01;
data = (short)(tmp[3] << 8) | tmp[2];
if ((data > 100) || (data < -100))
result |= 0x02;
data = (short)(tmp[5] << 8) | tmp[4];
if ((data > -300) || (data < -1000))
result |= 0x04;
AKM_restore:
tmp[0] = 0 | SUPPORTS_AK89xx_HIGH_SENS;
i2c_write(st->chip_cfg.compass_addr, AKM_REG_ASTC, 1, tmp);
tmp[0] = SUPPORTS_AK89xx_HIGH_SENS;
i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp);
mpu_set_bypass(0);
return result;
}
#endif
#endif
static int get_st_biases(long *gyro, long *accel, unsigned char hw_test)
{
unsigned char data[MAX_PACKET_LENGTH];
unsigned char packet_count, ii;
unsigned short fifo_count;
data[0] = 0x01;
data[1] = 0;
if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 2, data))
return -1;
delay_ms(200);
data[0] = 0;
if (i2c_write(st->hw->addr, st->reg->int_enable, 1, data))
return -1;
if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, data))
return -1;
if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, data))
return -1;
if (i2c_write(st->hw->addr, st->reg->i2c_mst, 1, data))
return -1;
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, data))
return -1;
data[0] = BIT_FIFO_RST | BIT_DMP_RST;
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, data))
return -1;
delay_ms(15);
data[0] = st->test->reg_lpf;
if (i2c_write(st->hw->addr, st->reg->lpf, 1, data))
return -1;
data[0] = st->test->reg_rate_div;
if (i2c_write(st->hw->addr, st->reg->rate_div, 1, data))
return -1;
if (hw_test)
data[0] = st->test->reg_gyro_fsr | 0xE0;
else
data[0] = st->test->reg_gyro_fsr;
if (i2c_write(st->hw->addr, st->reg->gyro_cfg, 1, data))
return -1;
if (hw_test)
data[0] = st->test->reg_accel_fsr | 0xE0;
else
data[0] = test->reg_accel_fsr;
if (i2c_write(st->hw->addr, st->reg->accel_cfg, 1, data))
return -1;
if (hw_test)
delay_ms(200);
/* Fill FIFO for test->wait_ms milliseconds. */
data[0] = BIT_FIFO_EN;
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 1, data))
return -1;
data[0] = INV_XYZ_GYRO | INV_XYZ_ACCEL;
if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, data))
return -1;
delay_ms(test->wait_ms);
data[0] = 0;
if (i2c_write(st->hw->addr, st->reg->fifo_en, 1, data))
return -1;
if (i2c_read(st->hw->addr, st->reg->fifo_count_h, 2, data))
return -1;
fifo_count = (data[0] << 8) | data[1];
packet_count = fifo_count / MAX_PACKET_LENGTH;
gyro[0] = gyro[1] = gyro[2] = 0;
accel[0] = accel[1] = accel[2] = 0;
for (ii = 0; ii < packet_count; ii++) {
short accel_cur[3], gyro_cur[3];
if (i2c_read(st->hw->addr, st->reg->fifo_r_w, MAX_PACKET_LENGTH, data))
return -1;
accel_cur[0] = ((short)data[0] << 8) | data[1];
accel_cur[1] = ((short)data[2] << 8) | data[3];
accel_cur[2] = ((short)data[4] << 8) | data[5];
accel[0] += (long)accel_cur[0];
accel[1] += (long)accel_cur[1];
accel[2] += (long)accel_cur[2];
gyro_cur[0] = (((short)data[6] << 8) | data[7]);
gyro_cur[1] = (((short)data[8] << 8) | data[9]);
gyro_cur[2] = (((short)data[10] << 8) | data[11]);
gyro[0] += (long)gyro_cur[0];
gyro[1] += (long)gyro_cur[1];
gyro[2] += (long)gyro_cur[2];
}
#ifdef EMPL_NO_64BIT
gyro[0] = (long)(((float)gyro[0]*65536.f) / test->gyro_sens / packet_count);
gyro[1] = (long)(((float)gyro[1]*65536.f) / test->gyro_sens / packet_count);
gyro[2] = (long)(((float)gyro[2]*65536.f) / test->gyro_sens / packet_count);
if (has_accel) {
accel[0] = (long)(((float)accel[0]*65536.f) / test->accel_sens /
packet_count);
accel[1] = (long)(((float)accel[1]*65536.f) / test->accel_sens /
packet_count);
accel[2] = (long)(((float)accel[2]*65536.f) / test->accel_sens /
packet_count);
/* Don't remove gravity! */
accel[2] -= 65536L;
}
#else
gyro[0] = (long)(((long long)gyro[0]<<16) / test->gyro_sens / packet_count);
gyro[1] = (long)(((long long)gyro[1]<<16) / test->gyro_sens / packet_count);
gyro[2] = (long)(((long long)gyro[2]<<16) / test->gyro_sens / packet_count);
accel[0] = (long)(((long long)accel[0]<<16) / test->accel_sens /
packet_count);
accel[1] = (long)(((long long)accel[1]<<16) / test->accel_sens /
packet_count);
accel[2] = (long)(((long long)accel[2]<<16) / test->accel_sens /
packet_count);
/* Don't remove gravity! */
if (accel[2] > 0L)
accel[2] -= 65536L;
else
accel[2] += 65536L;
#endif
return 0;
}
/**
* @brief Trigger gyro/accel/compass self-test->
* On success/error, the self-test returns a mask representing the sensor(s)
* that failed. For each bit, a one (1) represents a "pass" case; conversely,
* a zero (0) indicates a failure.
*
* \n The mask is defined as follows:
* \n Bit 0: Gyro.
* \n Bit 1: Accel.
* \n Bit 2: Compass.
*
* \n Currently, the hardware self-test is unsupported for MPU6500. However,
* this function can still be used to obtain the accel and gyro biases.
*
* \n This function must be called with the device either face-up or face-down
* (z-axis is parallel to gravity).
* @param[out] gyro Gyro biases in q16 format.
* @param[out] accel Accel biases (if applicable) in q16 format.
* @return Result mask (see above).
*/
int mpu_run_self_test(long *gyro, long *accel)
{
#ifdef MPU6050
const unsigned char tries = 2;
long gyro_st[3], accel_st[3];
unsigned char accel_result, gyro_result;
#ifdef AK89xx_SECONDARY
unsigned char compass_result;
#endif
int ii;
#endif
int result;
unsigned char accel_fsr, fifo_sensors, sensors_on;
unsigned short gyro_fsr, sample_rate, lpf;
unsigned char dmp_was_on;
if (st->chip_cfg.dmp_on) {
mpu_set_dmp_state(0);
dmp_was_on = 1;
} else
dmp_was_on = 0;
/* Get initial settings. */
mpu_get_gyro_fsr(&gyro_fsr);
mpu_get_accel_fsr(&accel_fsr);
mpu_get_lpf(&lpf);
mpu_get_sample_rate(&sample_rate);
sensors_on = st->chip_cfg.sensors;
mpu_get_fifo_config(&fifo_sensors);
/* For older chips, the self-test will be different. */
#if defined MPU6050
for (ii = 0; ii < tries; ii++)
if (!get_st_biases(gyro, accel, 0))
break;
if (ii == tries) {
/* If we reach this point, we most likely encountered an I2C error.
* We'll just report an error for all three sensors.
*/
result = 0;
goto restore;
}
for (ii = 0; ii < tries; ii++)
if (!get_st_biases(gyro_st, accel_st, 1))
break;
if (ii == tries) {
/* Again, probably an I2C error. */
result = 0;
goto restore;
}
accel_result = accel_self_test(accel, accel_st);
gyro_result = gyro_self_test(gyro, gyro_st);
result = 0;
if (!gyro_result)
result |= 0x01;
if (!accel_result)
result |= 0x02;
#ifdef AK89xx_SECONDARY
compass_result = compass_self_test();
if (!compass_result)
result |= 0x04;
#endif
restore:
#elif defined MPU6500
/* For now, this function will return a "pass" result for all three sensors
* for compatibility with current test applications.
*/
get_st_biases(gyro, accel, 0);
result = 0x7;
#endif
/* Set to invalid values to ensure no I2C writes are skipped. */
st->chip_cfg.gyro_fsr = 0xFF;
st->chip_cfg.accel_fsr = 0xFF;
st->chip_cfg.lpf = 0xFF;
st->chip_cfg.sample_rate = 0xFFFF;
st->chip_cfg.sensors = 0xFF;
st->chip_cfg.fifo_enable = 0xFF;
st->chip_cfg.clk_src = INV_CLK_PLL;
mpu_set_gyro_fsr(gyro_fsr);
mpu_set_accel_fsr(accel_fsr);
mpu_set_lpf(lpf);
mpu_set_sample_rate(sample_rate);
mpu_set_sensors(sensors_on);
mpu_configure_fifo(fifo_sensors);
if (dmp_was_on)
mpu_set_dmp_state(1);
return result;
}
#endif // MPU_MAXIMAL
/**
* @brief Write to the DMP memory.
* This function prevents I2C writes past the bank boundaries. The DMP memory
* is only accessible when the chip is awake.
* @param[in] mem_addr Memory location (bank << 8 | start address)
* @param[in] length Number of bytes to write.
* @param[in] data Bytes to write to memory.
* @return 0 if successful.
*/
int mpu_write_mem(unsigned short mem_addr, unsigned short length,
unsigned char *data)
{
unsigned char tmp[2];
if (!data)
return -1;
if (!st->chip_cfg.sensors)
return -2;
tmp[0] = (unsigned char)(mem_addr >> 8);
tmp[1] = (unsigned char)(mem_addr & 0xFF);
/* Check bank boundaries. */
if (tmp[1] + length > st->hw->bank_size)
return -3;
if (i2c_write(st->hw->addr, st->reg->bank_sel, 2, tmp))
return -4;
if (i2c_write(st->hw->addr, st->reg->mem_r_w, length, data))
return -5;
return 0;
}
/**
* @brief Read from the DMP memory.
* This function prevents I2C reads past the bank boundaries. The DMP memory
* is only accessible when the chip is awake.
* @param[in] mem_addr Memory location (bank << 8 | start address)
* @param[in] length Number of bytes to read.
* @param[out] data Bytes read from memory.
* @return 0 if successful.
*/
int mpu_read_mem(unsigned short mem_addr, unsigned short length,
unsigned char *data)
{
unsigned char tmp[2];
if (!data)
return -1;
if (!st->chip_cfg.sensors)
return -1;
tmp[0] = (unsigned char)(mem_addr >> 8);
tmp[1] = (unsigned char)(mem_addr & 0xFF);
/* Check bank boundaries. */
if (tmp[1] + length > st->hw->bank_size)
return -1;
if (i2c_write(st->hw->addr, st->reg->bank_sel, 2, tmp))
return -1;
if (i2c_read(st->hw->addr, st->reg->mem_r_w, length, data))
return -1;
return 0;
}
/**
* @brief Load and verify DMP image.
* @param[in] length Length of DMP image.
* @param[in] firmware DMP code.
* @param[in] start_addr Starting address of DMP code memory.
* @param[in] sample_rate Fixed sampling rate used when DMP is enabled.
* @return 0 if successful.
*/
int mpu_load_firmware(unsigned short length, const unsigned char *firmware,
unsigned short start_addr, unsigned short sample_rate)
{
unsigned short ii;
unsigned short this_write;
int errCode;
uint8_t *progBuffer;
/* Must divide evenly into st->hw->bank_size to avoid bank crossings. */
#define LOAD_CHUNK (16)
unsigned char cur[LOAD_CHUNK], tmp[2];
if (st->chip_cfg.dmp_loaded)
/* DMP should only be loaded once. */
return -1;
if (!firmware)
return -2;
progBuffer = (uint8_t *)malloc(LOAD_CHUNK);
for (ii = 0; ii < length; ii += this_write) {
this_write = min(LOAD_CHUNK, length - ii);
for (int progIndex = 0; progIndex < this_write; progIndex++)
#ifdef __SAM3X8E__
progBuffer[progIndex] = firmware[ii + progIndex];
#else
progBuffer[progIndex] = pgm_read_byte(firmware + ii + progIndex);
#endif
if ((errCode = mpu_write_mem(ii, this_write, progBuffer))) {
#ifdef MPU_DEBUG
Serial.print("fimrware write failed: ");
Serial.println(errCode);
#endif
return -3;
}
if (mpu_read_mem(ii, this_write, cur))
return -4;
if (memcmp(progBuffer, cur, this_write)) {
#ifdef MPU_DEBUG
Serial.print("Firmware compare failed addr "); Serial.println(ii);
for (int i = 0; i < 10; i++) {
Serial.print(progBuffer[i]);
Serial.print(" ");
}
Serial.println();
for (int i = 0; i < 10; i++) {
Serial.print(cur[i]);
Serial.print(" ");
}
Serial.println();
#endif
return -5;
}
}
/* Set program start address. */
tmp[0] = start_addr >> 8;
tmp[1] = start_addr & 0xFF;
if (i2c_write(st->hw->addr, st->reg->prgm_start_h, 2, tmp))
return -6;
st->chip_cfg.dmp_loaded = 1;
st->chip_cfg.dmp_sample_rate = sample_rate;
#ifdef MPU_DEBUG
Serial.println("Firmware loaded");
#endif
return 0;
}
/**
* @brief Enable/disable DMP support.
* @param[in] enable 1 to turn on the DMP.
* @return 0 if successful.
*/
int mpu_set_dmp_state(unsigned char enable)
{
unsigned char tmp;
if (st->chip_cfg.dmp_on == enable)
return 0;
if (enable) {
if (!st->chip_cfg.dmp_loaded)
return -1;
/* Disable data ready interrupt. */
set_int_enable(0);
/* Disable bypass mode. */
mpu_set_bypass(0);
/* Keep constant sample rate, FIFO rate controlled by DMP. */
mpu_set_sample_rate(st->chip_cfg.dmp_sample_rate);
/* Remove FIFO elements. */
tmp = 0;
i2c_write(st->hw->addr, 0x23, 1, &tmp);
st->chip_cfg.dmp_on = 1;
/* Enable DMP interrupt. */
set_int_enable(1);
mpu_reset_fifo();
} else {
/* Disable DMP interrupt. */
set_int_enable(0);
/* Restore FIFO settings. */
tmp = st->chip_cfg.fifo_enable;
i2c_write(st->hw->addr, 0x23, 1, &tmp);
st->chip_cfg.dmp_on = 0;
mpu_reset_fifo();
}
return 0;
}
/**
* @brief Get DMP state.
* @param[out] enabled 1 if enabled.
* @return 0 if successful.
*/
int mpu_get_dmp_state(unsigned char *enabled)
{
enabled[0] = st->chip_cfg.dmp_on;
return 0;
}
/* This initialization is similar to the one in ak8975.c. */
static int setup_compass(void)
{
#ifdef AK89xx_SECONDARY
unsigned char data[4], akm_addr;
mpu_set_bypass(1);
/* Find compass. Possible addresses range from 0x0C to 0x0F. */
for (akm_addr = 0x0C; akm_addr <= 0x0F; akm_addr++) {
int result;
result = i2c_read(akm_addr, AKM_REG_WHOAMI, 1, data);
if (!result && (data[0] == AKM_WHOAMI))
break;
}
if (akm_addr > 0x0F) {
/* TODO: Handle this case in all compass-related functions. */
#ifdef MPU_DEBUG
Serial.println("Compass not found.");
#endif
return -1;
}
st->chip_cfg.compass_addr = akm_addr;
data[0] = AKM_POWER_DOWN;
if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, data))
return -2;
delay_ms(1);
data[0] = AKM_FUSE_ROM_ACCESS;
if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, data))
return -3;
delay_ms(1);
/* Get sensitivity adjustment data from fuse ROM. */
if (i2c_read(st->chip_cfg.compass_addr, AKM_REG_ASAX, 3, data))
return -4;
st->chip_cfg.mag_sens_adj[0] = (long)data[0] + 128;
st->chip_cfg.mag_sens_adj[1] = (long)data[1] + 128;
st->chip_cfg.mag_sens_adj[2] = (long)data[2] + 128;
#ifdef MPU_DEBUG
Serial.print("Compass sens: "); Serial.print(st->chip_cfg.mag_sens_adj[0]); Serial.print(" ");
Serial.print(st->chip_cfg.mag_sens_adj[1]); Serial.print(" ");
Serial.print(st->chip_cfg.mag_sens_adj[2]); Serial.println();
#endif
data[0] = AKM_POWER_DOWN;
if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, data))
return -5;
delay_ms(1);
mpu_set_bypass(0);
/* Set up master mode, master clock, and ES bit. */
data[0] = 0x40;
if (i2c_write(st->hw->addr, st->reg->i2c_mst, 1, data))
return -6;
/* Slave 0 reads from AKM data registers. */
data[0] = BIT_I2C_READ | st->chip_cfg.compass_addr;
if (i2c_write(st->hw->addr, st->reg->s0_addr, 1, data))
return -7;
/* Compass reads start at this register. */
data[0] = AKM_REG_ST1;
if (i2c_write(st->hw->addr, st->reg->s0_reg, 1, data))
return -8;
/* Enable slave 0, 8-byte reads. */
data[0] = BIT_SLAVE_EN | 8;
if (i2c_write(st->hw->addr, st->reg->s0_ctrl, 1, data))
return -9;
/* Slave 1 changes AKM measurement mode. */
data[0] = st->chip_cfg.compass_addr;
if (i2c_write(st->hw->addr, st->reg->s1_addr, 1, data))
return -10;
/* AKM measurement mode register. */
data[0] = AKM_REG_CNTL;
if (i2c_write(st->hw->addr, st->reg->s1_reg, 1, data))
return -11;
/* Enable slave 1, 1-byte writes. */
data[0] = BIT_SLAVE_EN | 1;
if (i2c_write(st->hw->addr, st->reg->s1_ctrl, 1, data))
return -12;
/* Set slave 1 data. */
data[0] = AKM_SINGLE_MEASUREMENT;
if (i2c_write(st->hw->addr, st->reg->s1_do, 1, data))
return -13;
/* Trigger slave 0 and slave 1 actions at each sample. */
data[0] = 0x03;
if (i2c_write(st->hw->addr, st->reg->i2c_delay_ctrl, 1, data))
return -14;
#ifdef MPU9150
/* For the MPU9150, the auxiliary I2C bus needs to be set to VDD. */
data[0] = BIT_I2C_MST_VDDIO;
if (i2c_write(st->hw->addr, st->reg->yg_offs_tc, 1, data))
return -15;
#endif
return 0;
#else
return -16;
#endif
}
/**
* @brief Read raw compass data.
* @param[out] data Raw data in hardware units.
* @param[out] timestamp Timestamp in milliseconds. Null if not needed.
* @return 0 if successful.
*/
int mpu_get_compass_reg(short *data, unsigned long *timestamp)
{
#ifdef AK89xx_SECONDARY
unsigned char tmp[9];
if (!(st->chip_cfg.sensors & INV_XYZ_COMPASS))
return -1;
#ifdef AK89xx_BYPASS
if (i2c_read(st->chip_cfg.compass_addr, AKM_REG_ST1, 8, tmp))
return -2;
tmp[8] = AKM_SINGLE_MEASUREMENT;
if (i2c_write(st->chip_cfg.compass_addr, AKM_REG_CNTL, 1, tmp+8))
return -3;
#else
if (i2c_read(st->hw->addr, st->reg->raw_compass, 8, tmp))
return -4;
#endif
#if defined AK8975_SECONDARY
/* AK8975 doesn't have the overrun error bit. */
if (!(tmp[0] & AKM_DATA_READY))
return -5;
if ((tmp[7] & AKM_OVERFLOW) || (tmp[7] & AKM_DATA_ERROR))
return -6;
#elif defined AK8963_SECONDARY
/* AK8963 doesn't have the data read error bit. */
if (!(tmp[0] & AKM_DATA_READY) || (tmp[0] & AKM_DATA_OVERRUN))
return -7;
if (tmp[7] & AKM_OVERFLOW)
return -8;
#endif
data[0] = ((unsigned short)tmp[2] << 8) | (unsigned short)tmp[1];
data[1] = ((unsigned short)tmp[4] << 8) | (unsigned short)tmp[3];
data[2] = ((unsigned short)tmp[6] << 8) | (unsigned short)tmp[5];
data[0] = ((long)data[0] * st->chip_cfg.mag_sens_adj[0]) >> 8;
data[1] = ((long)data[1] * st->chip_cfg.mag_sens_adj[1]) >> 8;
data[2] = ((long)data[2] * st->chip_cfg.mag_sens_adj[2]) >> 8;
if (timestamp)
get_ms(timestamp);
return 0;
#else
return -9;
#endif
}
/**
* @brief Get the compass full-scale range.
* @param[out] fsr Current full-scale range.
* @return 0 if successful.
*/
int mpu_get_compass_fsr(unsigned short *fsr)
{
#ifdef AK89xx_SECONDARY
fsr[0] = st->hw->compass_fsr;
return 0;
#else
return -1;
#endif
}
/**
* @brief Enters LP accel motion interrupt mode.
* The behavior of this feature is very different between the MPU6050 and the
* MPU6500. Each chip's version of this feature is explained below.
*
* \n MPU6050:
* \n When this mode is first enabled, the hardware captures a single accel
* sample, and subsequent samples are compared with this one to determine if
* the device is in motion. Therefore, whenever this "locked" sample needs to
* be changed, this function must be called again.
*
* \n The hardware motion threshold can be between 32mg and 8160mg in 32mg
* increments.
*
* \n Low-power accel mode supports the following frequencies:
* \n 1.25Hz, 5Hz, 20Hz, 40Hz
*
* \n MPU6500:
* \n Unlike the MPU6050 version, the hardware does not "lock in" a reference
* sample. The hardware monitors the accel data and detects any large change
* over a short period of time.
*
* \n The hardware motion threshold can be between 4mg and 1020mg in 4mg
* increments.
*
* \n MPU6500 Low-power accel mode supports the following frequencies:
* \n 1.25Hz, 2.5Hz, 5Hz, 10Hz, 20Hz, 40Hz, 80Hz, 160Hz, 320Hz, 640Hz
*
* \n\n NOTES:
* \n The driver will round down @e thresh to the nearest supported value if
* an unsupported threshold is selected.
* \n To select a fractional wake-up frequency, round down the value passed to
* @e lpa_freq.
* \n The MPU6500 does not support a delay parameter. If this function is used
* for the MPU6500, the value passed to @e time will be ignored.
* \n To disable this mode, set @e lpa_freq to zero. The driver will restore
* the previous configuration.
*
* @param[in] thresh Motion threshold in mg.
* @param[in] time Duration in milliseconds that the accel data must
* exceed @e thresh before motion is reported.
* @param[in] lpa_freq Minimum sampling rate, or zero to disable.
* @return 0 if successful.
*/
int mpu_lp_motion_interrupt(unsigned short thresh, unsigned char time,
unsigned char lpa_freq)
{
unsigned char data[3];
if (lpa_freq) {
unsigned char thresh_hw;
#if defined MPU6050
/* TODO: Make these const/#defines. */
/* 1LSb = 32mg. */
if (thresh > 8160)
thresh_hw = 255;
else if (thresh < 32)
thresh_hw = 1;
else
thresh_hw = thresh >> 5;
#elif defined MPU6500
/* 1LSb = 4mg. */
if (thresh > 1020)
thresh_hw = 255;
else if (thresh < 4)
thresh_hw = 1;
else
thresh_hw = thresh >> 2;
#endif
if (!time)
/* Minimum duration must be 1ms. */
time = 1;
#if defined MPU6050
if (lpa_freq > 40)
#elif defined MPU6500
if (lpa_freq > 640)
#endif
/* At this point, the chip has not been re-configured, so the
* function can safely exit.
*/
return -1;
if (!st->chip_cfg.int_motion_only) {
/* Store current settings for later. */
if (st->chip_cfg.dmp_on) {
mpu_set_dmp_state(0);
st->chip_cfg.cache.dmp_on = 1;
} else
st->chip_cfg.cache.dmp_on = 0;
mpu_get_gyro_fsr(&st->chip_cfg.cache.gyro_fsr);
mpu_get_accel_fsr(&st->chip_cfg.cache.accel_fsr);
mpu_get_lpf(&st->chip_cfg.cache.lpf);
mpu_get_sample_rate(&st->chip_cfg.cache.sample_rate);
st->chip_cfg.cache.sensors_on = st->chip_cfg.sensors;
mpu_get_fifo_config(&st->chip_cfg.cache.fifo_sensors);
}
#ifdef MPU6050
/* Disable hardware interrupts for now. */
set_int_enable(0);
/* Enter full-power accel-only mode. */
mpu_lp_accel_mode(0);
/* Override current LPF (and HPF) settings to obtain a valid accel
* reading.
*/
data[0] = INV_FILTER_256HZ_NOLPF2;
if (i2c_write(st->hw->addr, st->reg->lpf, 1, data))
return -1;
/* NOTE: Digital high pass filter should be configured here. Since this
* driver doesn't modify those bits anywhere, they should already be
* cleared by default.
*/
/* Configure the device to send motion interrupts. */
/* Enable motion interrupt. */
data[0] = BIT_MOT_INT_EN;
if (i2c_write(st->hw->addr, st->reg->int_enable, 1, data))
goto lp_int_restore;
/* Set motion interrupt parameters. */
data[0] = thresh_hw;
data[1] = time;
if (i2c_write(st->hw->addr, st->reg->motion_thr, 2, data))
goto lp_int_restore;
/* Force hardware to "lock" current accel sample. */
delay_ms(5);
data[0] = (st->chip_cfg.accel_fsr << 3) | BITS_HPF;
if (i2c_write(st->hw->addr, st->reg->accel_cfg, 1, data))
goto lp_int_restore;
/* Set up LP accel mode. */
data[0] = BIT_LPA_CYCLE;
if (lpa_freq == 1)
data[1] = INV_LPA_1_25HZ;
else if (lpa_freq <= 5)
data[1] = INV_LPA_5HZ;
else if (lpa_freq <= 20)
data[1] = INV_LPA_20HZ;
else
data[1] = INV_LPA_40HZ;
data[1] = (data[1] << 6) | BIT_STBY_XYZG;
if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 2, data))
goto lp_int_restore;
st->chip_cfg.int_motion_only = 1;
return 0;
#elif defined MPU6500
/* Disable hardware interrupts. */
set_int_enable(0);
/* Enter full-power accel-only mode, no FIFO/DMP. */
data[0] = 0;
data[1] = 0;
data[2] = BIT_STBY_XYZG;
if (i2c_write(st->hw->addr, st->reg->user_ctrl, 3, data))
goto lp_int_restore;
/* Set motion threshold. */
data[0] = thresh_hw;
if (i2c_write(st->hw->addr, st->reg->motion_thr, 1, data))
goto lp_int_restore;
/* Set wake frequency. */
if (lpa_freq == 1)
data[0] = INV_LPA_1_25HZ;
else if (lpa_freq == 2)
data[0] = INV_LPA_2_5HZ;
else if (lpa_freq <= 5)
data[0] = INV_LPA_5HZ;
else if (lpa_freq <= 10)
data[0] = INV_LPA_10HZ;
else if (lpa_freq <= 20)
data[0] = INV_LPA_20HZ;
else if (lpa_freq <= 40)
data[0] = INV_LPA_40HZ;
else if (lpa_freq <= 80)
data[0] = INV_LPA_80HZ;
else if (lpa_freq <= 160)
data[0] = INV_LPA_160HZ;
else if (lpa_freq <= 320)
data[0] = INV_LPA_320HZ;
else
data[0] = INV_LPA_640HZ;
if (i2c_write(st->hw->addr, st->reg->lp_accel_odr, 1, data))
goto lp_int_restore;
/* Enable motion interrupt (MPU6500 version). */
data[0] = BITS_WOM_EN;
if (i2c_write(st->hw->addr, st->reg->accel_intel, 1, data))
goto lp_int_restore;
/* Enable cycle mode. */
data[0] = BIT_LPA_CYCLE;
if (i2c_write(st->hw->addr, st->reg->pwr_mgmt_1, 1, data))
goto lp_int_restore;
/* Enable interrupt. */
data[0] = BIT_MOT_INT_EN;
if (i2c_write(st->hw->addr, st->reg->int_enable, 1, data))
goto lp_int_restore;
st->chip_cfg.int_motion_only = 1;
return 0;
#endif
} else {
/* Don't "restore" the previous state if no state has been saved. */
int ii;
char *cache_ptr = (char*)&st->chip_cfg.cache;
for (ii = 0; ii < sizeof(st->chip_cfg.cache); ii++) {
if (cache_ptr[ii] != 0)
goto lp_int_restore;
}
/* If we reach this point, motion interrupt mode hasn't been used yet. */
return -1;
}
lp_int_restore:
/* Set to invalid values to ensure no I2C writes are skipped. */
st->chip_cfg.gyro_fsr = 0xFF;
st->chip_cfg.accel_fsr = 0xFF;
st->chip_cfg.lpf = 0xFF;
st->chip_cfg.sample_rate = 0xFFFF;
st->chip_cfg.sensors = 0xFF;
st->chip_cfg.fifo_enable = 0xFF;
st->chip_cfg.clk_src = INV_CLK_PLL;
mpu_set_sensors(st->chip_cfg.cache.sensors_on);
mpu_set_gyro_fsr(st->chip_cfg.cache.gyro_fsr);
mpu_set_accel_fsr(st->chip_cfg.cache.accel_fsr);
mpu_set_lpf(st->chip_cfg.cache.lpf);
mpu_set_sample_rate(st->chip_cfg.cache.sample_rate);
mpu_configure_fifo(st->chip_cfg.cache.fifo_sensors);
if (st->chip_cfg.cache.dmp_on)
mpu_set_dmp_state(1);
#ifdef MPU6500
/* Disable motion interrupt (MPU6500 version). */
data[0] = 0;
if (i2c_write(st->hw->addr, st->reg->accel_intel, 1, data))
goto lp_int_restore;
#endif
st->chip_cfg.int_motion_only = 0;
return 0;
}
/**
* @}
*/
| [
"kenne839@umn.edu"
] | kenne839@umn.edu |
bfa26ce57fa97ccb7d3ceaca5058455b37c94433 | 884d8fd8d4e2bc5a71852de7131a7a6476bf9c48 | /grid-test/export/macos/obj/src/flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.cpp | fcc12a851dc6087f8c0124063209ed9dc1b49699 | [
"Apache-2.0"
] | permissive | VehpuS/learning-haxe-and-haxeflixel | 69655276f504748347decfea66b91a117a722f6c | cb18c074720656797beed7333eeaced2cf323337 | refs/heads/main | 2023-02-16T07:45:59.795832 | 2021-01-07T03:01:46 | 2021-01-07T03:01:46 | 324,458,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 26,665 | cpp | // Generated by Haxe 4.1.4
#include <hxcpp.h>
#ifndef INCLUDED_flixel_input_gamepad_FlxGamepadAnalogStick
#include <flixel/input/gamepad/FlxGamepadAnalogStick.h>
#endif
#ifndef INCLUDED_flixel_input_gamepad_FlxGamepadAttachment
#include <flixel/input/gamepad/FlxGamepadAttachment.h>
#endif
#ifndef INCLUDED_flixel_input_gamepad_id_MayflashWiiRemoteID
#include <flixel/input/gamepad/id/MayflashWiiRemoteID.h>
#endif
#ifndef INCLUDED_flixel_input_gamepad_mappings_FlxGamepadMapping
#include <flixel/input/gamepad/mappings/FlxGamepadMapping.h>
#endif
#ifndef INCLUDED_flixel_input_gamepad_mappings_MayflashWiiRemoteMapping
#include <flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.h>
#endif
#ifndef INCLUDED_flixel_input_gamepad_mappings_WiiRemoteMapping
#include <flixel/input/gamepad/mappings/WiiRemoteMapping.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_b96995a19667a299_7_new,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","new",0x14c5ed14,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.new","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",7,0xb7763ebe)
HX_LOCAL_STACK_FRAME(_hx_pos_b96995a19667a299_22_initValues,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","initValues",0x4dbe00de,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.initValues","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",22,0xb7763ebe)
HX_LOCAL_STACK_FRAME(_hx_pos_b96995a19667a299_27_getID,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","getID",0x3c1a43a5,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.getID","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",27,0xb7763ebe)
HX_LOCAL_STACK_FRAME(_hx_pos_b96995a19667a299_37_getIDClassicController,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","getIDClassicController",0xdc580be9,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.getIDClassicController","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",37,0xb7763ebe)
HX_LOCAL_STACK_FRAME(_hx_pos_b96995a19667a299_68_getIDNunchuk,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","getIDNunchuk",0xf7a650dd,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.getIDNunchuk","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",68,0xb7763ebe)
HX_LOCAL_STACK_FRAME(_hx_pos_b96995a19667a299_94_getIDDefault,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","getIDDefault",0x559cab9c,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.getIDDefault","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",94,0xb7763ebe)
HX_LOCAL_STACK_FRAME(_hx_pos_b96995a19667a299_113_getRawID,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","getRawID",0xc8a2c619,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.getRawID","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",113,0xb7763ebe)
HX_LOCAL_STACK_FRAME(_hx_pos_b96995a19667a299_123_getRawClassicController,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","getRawClassicController",0x0492e8b0,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.getRawClassicController","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",123,0xb7763ebe)
HX_LOCAL_STACK_FRAME(_hx_pos_b96995a19667a299_156_getRawNunchuk,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","getRawNunchuk",0x53b6bee4,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.getRawNunchuk","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",156,0xb7763ebe)
HX_LOCAL_STACK_FRAME(_hx_pos_b96995a19667a299_183_getRawDefault,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","getRawDefault",0xb1ad19a3,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.getRawDefault","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",183,0xb7763ebe)
HX_LOCAL_STACK_FRAME(_hx_pos_b96995a19667a299_245_set_attachment,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","set_attachment",0xdaecf06c,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.set_attachment","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",245,0xb7763ebe)
HX_LOCAL_STACK_FRAME(_hx_pos_b96995a19667a299_262_getInputLabel,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping","getInputLabel",0x116cb774,"flixel.input.gamepad.mappings.MayflashWiiRemoteMapping.getInputLabel","flixel/input/gamepad/mappings/MayflashWiiRemoteMapping.hx",262,0xb7763ebe)
namespace flixel{
namespace input{
namespace gamepad{
namespace mappings{
void MayflashWiiRemoteMapping_obj::__construct( ::flixel::input::gamepad::FlxGamepadAttachment attachment){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_7_new)
HXDLIN( 7) super::__construct(attachment);
}
Dynamic MayflashWiiRemoteMapping_obj::__CreateEmpty() { return new MayflashWiiRemoteMapping_obj; }
void *MayflashWiiRemoteMapping_obj::_hx_vtable = 0;
Dynamic MayflashWiiRemoteMapping_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< MayflashWiiRemoteMapping_obj > _hx_result = new MayflashWiiRemoteMapping_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool MayflashWiiRemoteMapping_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x21e2b607) {
return inClassId==(int)0x00000001 || inClassId==(int)0x21e2b607;
} else {
return inClassId==(int)0x5c688ddc;
}
}
void MayflashWiiRemoteMapping_obj::initValues(){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_22_initValues)
HXDLIN( 22) this->supportsPointer = true;
}
int MayflashWiiRemoteMapping_obj::getID(int rawID){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_27_getID)
HXDLIN( 27) switch((int)(this->attachment->_hx_getIndex())){
case (int)0: {
HXLINE( 30) return this->getIDNunchuk(rawID);
}
break;
case (int)1: {
HXLINE( 29) return this->getIDClassicController(rawID);
}
break;
case (int)2: {
HXLINE( 31) return this->getIDDefault(rawID);
}
break;
}
HXLINE( 27) return null();
}
int MayflashWiiRemoteMapping_obj::getIDClassicController(int rawID){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_37_getIDClassicController)
HXDLIN( 37) switch((int)(rawID)){
case (int)4: {
HXLINE( 50) return 11;
}
break;
case (int)5: {
HXLINE( 51) return 12;
}
break;
case (int)6: {
HXLINE( 52) return 13;
}
break;
case (int)7: {
HXLINE( 53) return 14;
}
break;
case (int)8: {
HXLINE( 42) return 2;
}
break;
case (int)9: {
HXLINE( 41) return 3;
}
break;
case (int)10: {
HXLINE( 40) return 0;
}
break;
case (int)11: {
HXLINE( 39) return 1;
}
break;
case (int)12: {
HXLINE( 46) return 17;
}
break;
case (int)13: {
HXLINE( 47) return 18;
}
break;
case (int)14: {
HXLINE( 48) return 4;
}
break;
case (int)15: {
HXLINE( 49) return 5;
}
break;
case (int)16: {
HXLINE( 43) return 6;
}
break;
case (int)17: {
HXLINE( 45) return 7;
}
break;
case (int)19: {
HXLINE( 44) return 10;
}
break;
default:{
HXLINE( 54) int id = rawID;
HXDLIN( 54) if ((id == this->leftStick->rawUp)) {
HXLINE( 54) return 34;
}
else {
HXLINE( 55) int id = rawID;
HXDLIN( 55) if ((id == this->leftStick->rawDown)) {
HXLINE( 55) return 36;
}
else {
HXLINE( 56) int id = rawID;
HXDLIN( 56) if ((id == this->leftStick->rawLeft)) {
HXLINE( 56) return 37;
}
else {
HXLINE( 57) int id = rawID;
HXDLIN( 57) if ((id == this->leftStick->rawRight)) {
HXLINE( 57) return 35;
}
else {
HXLINE( 58) int id = rawID;
HXDLIN( 58) if ((id == this->rightStick->rawUp)) {
HXLINE( 58) return 38;
}
else {
HXLINE( 59) int id = rawID;
HXDLIN( 59) if ((id == this->rightStick->rawDown)) {
HXLINE( 59) return 40;
}
else {
HXLINE( 60) int id = rawID;
HXDLIN( 60) if ((id == this->rightStick->rawLeft)) {
HXLINE( 60) return 41;
}
else {
HXLINE( 61) int id = rawID;
HXDLIN( 61) if ((id == this->rightStick->rawRight)) {
HXLINE( 61) return 39;
}
else {
HXLINE( 62) return -1;
}
}
}
}
}
}
}
}
}
}
HXLINE( 37) return null();
}
HX_DEFINE_DYNAMIC_FUNC1(MayflashWiiRemoteMapping_obj,getIDClassicController,return )
int MayflashWiiRemoteMapping_obj::getIDNunchuk(int rawID){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_68_getIDNunchuk)
HXDLIN( 68) switch((int)(rawID)){
case (int)4: {
HXLINE( 79) return 11;
}
break;
case (int)5: {
HXLINE( 80) return 12;
}
break;
case (int)6: {
HXLINE( 81) return 13;
}
break;
case (int)7: {
HXLINE( 82) return 14;
}
break;
case (int)8: {
HXLINE( 72) return 2;
}
break;
case (int)9: {
HXLINE( 73) return 3;
}
break;
case (int)10: {
HXLINE( 70) return 0;
}
break;
case (int)11: {
HXLINE( 71) return 1;
}
break;
case (int)12: {
HXLINE( 74) return 6;
}
break;
case (int)13: {
HXLINE( 75) return 7;
}
break;
case (int)14: {
HXLINE( 78) return 17;
}
break;
case (int)15: {
HXLINE( 77) return 4;
}
break;
case (int)19: {
HXLINE( 76) return 10;
}
break;
default:{
HXLINE( 84) bool _hx_tmp = (rawID == ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawUp);
HXLINE( 85) bool _hx_tmp1 = (rawID == ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawDown);
HXLINE( 86) bool _hx_tmp2 = (rawID == ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawLeft);
HXLINE( 87) bool _hx_tmp3 = (rawID == ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawRight);
HXLINE( 88) return -1;
}
}
HXLINE( 68) return null();
}
HX_DEFINE_DYNAMIC_FUNC1(MayflashWiiRemoteMapping_obj,getIDNunchuk,return )
int MayflashWiiRemoteMapping_obj::getIDDefault(int rawID){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_94_getIDDefault)
HXDLIN( 94) switch((int)(rawID)){
case (int)8: {
HXLINE( 98) return 2;
}
break;
case (int)9: {
HXLINE( 99) return 3;
}
break;
case (int)10: {
HXLINE( 96) return 0;
}
break;
case (int)11: {
HXLINE( 97) return 1;
}
break;
case (int)12: {
HXLINE( 100) return 6;
}
break;
case (int)13: {
HXLINE( 102) return 7;
}
break;
case (int)19: {
HXLINE( 101) return 10;
}
break;
case (int)22: {
HXLINE( 103) return 11;
}
break;
case (int)23: {
HXLINE( 104) return 12;
}
break;
case (int)24: {
HXLINE( 105) return 13;
}
break;
case (int)25: {
HXLINE( 106) return 14;
}
break;
default:{
HXLINE( 107) return -1;
}
}
HXLINE( 94) return null();
}
HX_DEFINE_DYNAMIC_FUNC1(MayflashWiiRemoteMapping_obj,getIDDefault,return )
int MayflashWiiRemoteMapping_obj::getRawID(int ID){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_113_getRawID)
HXDLIN( 113) switch((int)(this->attachment->_hx_getIndex())){
case (int)0: {
HXLINE( 116) return this->getRawNunchuk(ID);
}
break;
case (int)1: {
HXLINE( 115) return this->getRawClassicController(ID);
}
break;
case (int)2: {
HXLINE( 117) return this->getRawDefault(ID);
}
break;
}
HXLINE( 113) return 0;
}
int MayflashWiiRemoteMapping_obj::getRawClassicController(int ID){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_123_getRawClassicController)
HXDLIN( 123) switch((int)(ID)){
case (int)0: {
HXLINE( 125) return 10;
}
break;
case (int)1: {
HXLINE( 126) return 11;
}
break;
case (int)2: {
HXLINE( 127) return 8;
}
break;
case (int)3: {
HXLINE( 128) return 9;
}
break;
case (int)4: {
HXLINE( 136) return 14;
}
break;
case (int)5: {
HXLINE( 137) return 15;
}
break;
case (int)6: {
HXLINE( 133) return 16;
}
break;
case (int)7: {
HXLINE( 135) return 17;
}
break;
case (int)10: {
HXLINE( 134) return 19;
}
break;
case (int)11: {
HXLINE( 129) return 4;
}
break;
case (int)12: {
HXLINE( 130) return 5;
}
break;
case (int)13: {
HXLINE( 131) return 6;
}
break;
case (int)14: {
HXLINE( 132) return 7;
}
break;
case (int)17: {
HXLINE( 138) return 12;
}
break;
case (int)18: {
HXLINE( 139) return 13;
}
break;
case (int)30: {
HXLINE( 140) return -1;
}
break;
case (int)31: {
HXLINE( 141) return -1;
}
break;
case (int)34: {
HXLINE( 142) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawUp;
}
break;
case (int)35: {
HXLINE( 145) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawRight;
}
break;
case (int)36: {
HXLINE( 143) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawDown;
}
break;
case (int)37: {
HXLINE( 144) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawLeft;
}
break;
case (int)38: {
HXLINE( 146) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::RIGHT_ANALOG_STICK->rawUp;
}
break;
case (int)39: {
HXLINE( 149) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::RIGHT_ANALOG_STICK->rawRight;
}
break;
case (int)40: {
HXLINE( 147) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::RIGHT_ANALOG_STICK->rawDown;
}
break;
case (int)41: {
HXLINE( 148) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::RIGHT_ANALOG_STICK->rawLeft;
}
break;
default:{
HXLINE( 150) return this->getRawDefault(ID);
}
}
HXLINE( 123) return 0;
}
HX_DEFINE_DYNAMIC_FUNC1(MayflashWiiRemoteMapping_obj,getRawClassicController,return )
int MayflashWiiRemoteMapping_obj::getRawNunchuk(int ID){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_156_getRawNunchuk)
HXDLIN( 156) switch((int)(ID)){
case (int)0: {
HXLINE( 158) return 10;
}
break;
case (int)1: {
HXLINE( 159) return 11;
}
break;
case (int)2: {
HXLINE( 160) return 8;
}
break;
case (int)3: {
HXLINE( 161) return 9;
}
break;
case (int)4: {
HXLINE( 165) return 15;
}
break;
case (int)6: {
HXLINE( 162) return 12;
}
break;
case (int)7: {
HXLINE( 163) return 13;
}
break;
case (int)10: {
HXLINE( 164) return 19;
}
break;
case (int)11: {
HXLINE( 167) return 4;
}
break;
case (int)12: {
HXLINE( 168) return 5;
}
break;
case (int)13: {
HXLINE( 169) return 6;
}
break;
case (int)14: {
HXLINE( 170) return 7;
}
break;
case (int)17: {
HXLINE( 166) return 14;
}
break;
case (int)28: {
HXLINE( 171) return 2;
}
break;
case (int)29: {
HXLINE( 172) return 3;
}
break;
case (int)34: {
HXLINE( 173) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawUp;
}
break;
case (int)35: {
HXLINE( 176) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawRight;
}
break;
case (int)36: {
HXLINE( 174) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawDown;
}
break;
case (int)37: {
HXLINE( 175) return ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK->rawLeft;
}
break;
default:{
HXLINE( 177) return -1;
}
}
HXLINE( 156) return 0;
}
HX_DEFINE_DYNAMIC_FUNC1(MayflashWiiRemoteMapping_obj,getRawNunchuk,return )
int MayflashWiiRemoteMapping_obj::getRawDefault(int ID){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_183_getRawDefault)
HXDLIN( 183) switch((int)(ID)){
case (int)0: {
HXLINE( 185) return 10;
}
break;
case (int)1: {
HXLINE( 186) return 11;
}
break;
case (int)2: {
HXLINE( 187) return 8;
}
break;
case (int)3: {
HXLINE( 188) return 9;
}
break;
case (int)6: {
HXLINE( 193) return 12;
}
break;
case (int)7: {
HXLINE( 195) return 13;
}
break;
case (int)10: {
HXLINE( 194) return 19;
}
break;
case (int)11: {
HXLINE( 189) return 22;
}
break;
case (int)12: {
HXLINE( 190) return 23;
}
break;
case (int)13: {
HXLINE( 191) return 24;
}
break;
case (int)14: {
HXLINE( 192) return 25;
}
break;
default:{
HXLINE( 196) return -1;
}
}
HXLINE( 183) return 0;
}
HX_DEFINE_DYNAMIC_FUNC1(MayflashWiiRemoteMapping_obj,getRawDefault,return )
::flixel::input::gamepad::FlxGamepadAttachment MayflashWiiRemoteMapping_obj::set_attachment( ::flixel::input::gamepad::FlxGamepadAttachment attachment){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_245_set_attachment)
HXLINE( 246) ::flixel::input::gamepad::FlxGamepadAnalogStick _hx_tmp;
HXDLIN( 246) switch((int)(attachment->_hx_getIndex())){
case (int)0: case (int)1: {
HXLINE( 246) _hx_tmp = ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::LEFT_ANALOG_STICK;
}
break;
case (int)2: {
HXLINE( 246) _hx_tmp = ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::REMOTE_DPAD;
}
break;
}
HXDLIN( 246) this->leftStick = _hx_tmp;
HXLINE( 252) ::flixel::input::gamepad::FlxGamepadAnalogStick _hx_tmp1;
HXDLIN( 252) if ((attachment->_hx_getIndex() == 1)) {
HXLINE( 252) _hx_tmp1 = ::flixel::input::gamepad::id::MayflashWiiRemoteID_obj::RIGHT_ANALOG_STICK;
}
else {
HXLINE( 252) _hx_tmp1 = null();
}
HXDLIN( 252) this->rightStick = _hx_tmp1;
HXLINE( 258) return this->super::set_attachment(attachment);
}
::String MayflashWiiRemoteMapping_obj::getInputLabel(int id){
HX_STACKFRAME(&_hx_pos_b96995a19667a299_262_getInputLabel)
HXLINE( 263) ::String label = ::flixel::input::gamepad::mappings::WiiRemoteMapping_obj::getWiiInputLabel(id,this->attachment);
HXLINE( 264) if (::hx::IsNull( label )) {
HXLINE( 265) return this->super::getInputLabel(id);
}
HXLINE( 267) return label;
}
::hx::ObjectPtr< MayflashWiiRemoteMapping_obj > MayflashWiiRemoteMapping_obj::__new( ::flixel::input::gamepad::FlxGamepadAttachment attachment) {
::hx::ObjectPtr< MayflashWiiRemoteMapping_obj > __this = new MayflashWiiRemoteMapping_obj();
__this->__construct(attachment);
return __this;
}
::hx::ObjectPtr< MayflashWiiRemoteMapping_obj > MayflashWiiRemoteMapping_obj::__alloc(::hx::Ctx *_hx_ctx, ::flixel::input::gamepad::FlxGamepadAttachment attachment) {
MayflashWiiRemoteMapping_obj *__this = (MayflashWiiRemoteMapping_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(MayflashWiiRemoteMapping_obj), true, "flixel.input.gamepad.mappings.MayflashWiiRemoteMapping"));
*(void **)__this = MayflashWiiRemoteMapping_obj::_hx_vtable;
__this->__construct(attachment);
return __this;
}
MayflashWiiRemoteMapping_obj::MayflashWiiRemoteMapping_obj()
{
}
::hx::Val MayflashWiiRemoteMapping_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"getID") ) { return ::hx::Val( getID_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"getRawID") ) { return ::hx::Val( getRawID_dyn() ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"initValues") ) { return ::hx::Val( initValues_dyn() ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"getIDNunchuk") ) { return ::hx::Val( getIDNunchuk_dyn() ); }
if (HX_FIELD_EQ(inName,"getIDDefault") ) { return ::hx::Val( getIDDefault_dyn() ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"getRawNunchuk") ) { return ::hx::Val( getRawNunchuk_dyn() ); }
if (HX_FIELD_EQ(inName,"getRawDefault") ) { return ::hx::Val( getRawDefault_dyn() ); }
if (HX_FIELD_EQ(inName,"getInputLabel") ) { return ::hx::Val( getInputLabel_dyn() ); }
break;
case 14:
if (HX_FIELD_EQ(inName,"set_attachment") ) { return ::hx::Val( set_attachment_dyn() ); }
break;
case 22:
if (HX_FIELD_EQ(inName,"getIDClassicController") ) { return ::hx::Val( getIDClassicController_dyn() ); }
break;
case 23:
if (HX_FIELD_EQ(inName,"getRawClassicController") ) { return ::hx::Val( getRawClassicController_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *MayflashWiiRemoteMapping_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo *MayflashWiiRemoteMapping_obj_sStaticStorageInfo = 0;
#endif
static ::String MayflashWiiRemoteMapping_obj_sMemberFields[] = {
HX_("initValues",12,5f,fc,53),
HX_("getID",f1,91,60,91),
HX_("getIDClassicController",1d,e8,c4,20),
HX_("getIDNunchuk",11,a4,df,d0),
HX_("getIDDefault",d0,fe,d5,2e),
HX_("getRawID",4d,6f,fd,43),
HX_("getRawClassicController",fc,b9,66,9f),
HX_("getRawNunchuk",30,39,a6,8c),
HX_("getRawDefault",ef,93,9c,ea),
HX_("set_attachment",a0,78,88,73),
HX_("getInputLabel",c0,31,5c,4a),
::String(null()) };
::hx::Class MayflashWiiRemoteMapping_obj::__mClass;
void MayflashWiiRemoteMapping_obj::__register()
{
MayflashWiiRemoteMapping_obj _hx_dummy;
MayflashWiiRemoteMapping_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("flixel.input.gamepad.mappings.MayflashWiiRemoteMapping",22,13,e5,ee);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(MayflashWiiRemoteMapping_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< MayflashWiiRemoteMapping_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = MayflashWiiRemoteMapping_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = MayflashWiiRemoteMapping_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace flixel
} // end namespace input
} // end namespace gamepad
} // end namespace mappings
| [
"vehpus@gmail.com"
] | vehpus@gmail.com |
26bbe7cfe7cab231f82d5c3708429a046d13d413 | 1109273a550e1f1a31c9decc286b31caae317ec2 | /1.C++初识/Qt_2/Teacher.h | 256ce8b0503ea67c8872d52cd7d93e7b0604b9b1 | [] | no_license | guangyongxing/The-C-PLus-PLus-Language | b4dfafd122f504b336db176f202e19df6e6813e1 | 202bd914ca3488474cdcf717fd03d1103ce6c023 | refs/heads/master | 2023-07-16T06:18:34.414282 | 2021-08-27T14:11:47 | 2021-08-27T14:11:47 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 391 | h | #pragma once
#include <qobject.h>
#include<qobject.h>
class Teacher :
public QObject
{
Q_OBJECT;
public:
// explicit Teacher(QObject* parent=0);
signals:
//自定义信号,需要写到槽函数signals下、
//返回类型必须是void
//只需要声明,不需要实现
//信号可以有参数
//可以发生重载
void hungary();
public slots:
};
| [
"1627961573@qq.com"
] | 1627961573@qq.com |
31150d5bf6b1dd9a724a42b7501c58431ad24cd8 | ed6f1382dad7fd39102cef3895eacb7a467f43a0 | /genetik/GeneticAlgorithm.hpp | 110c467db0a99221b859f27512c27287346805d3 | [
"MIT"
] | permissive | karlphillip/Genetik | c1e80132dbba6f03698542ef29c22b6474376a1c | b8059f08ececa9bda6b2c19f35a925c070052f56 | refs/heads/main | 2023-07-03T22:04:41.811092 | 2021-08-13T01:09:12 | 2021-08-13T01:09:12 | 336,808,629 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,478 | hpp | #pragma once
#include "GeneticAlgorithm_i.hpp"
#include <iostream>
#include <vector>
template <typename P, typename C>
class GeneticAlgorithm : public GeneticAlgorithm_i<P, C>
{
public:
/*
* Parameterized constructor initializes member variables.
*
* @param crossoverRate a value that indicates the rate of crossover (0.0 to 1.0)
* @param mutationRate a value that indicates the rate of mutation (0.0 to 1.0)
* @return nothing
*/
GeneticAlgorithm(const float& crossoverRate, const float& mutationRate)
: GeneticAlgorithm_i<P, C>(crossoverRate, mutationRate)
{
}
/*
*
*/
void evolve(P& population)
{
//std::cout << "GeneticAlgorithm::evolve crossoverRate=" << this->_crossoverRate << " mutationRate=" << this->_mutationRate << std::endl;
std::vector<C> newPopulation;
// make sure rounding won't cause "invalid index" problems later when the old population gets replaced
unsigned int halfSize = static_cast<unsigned int>(((float)population.creatures()->size()/2.f) + 0.5f);
//std::cout << "GeneticAlgorithm::evolve halfSize=" << halfSize << std::endl;
// perform crossover/mutation on half of the population
for (unsigned int i = 0; i < halfSize; ++i)
{
//std::cout << "GeneticAlgorithm::evolve selection pop #" << i << std::endl;
/*
* perform selection: use the roulette to randomly select parents for crossover.
* a creature that occupies a bigger slice of pie has a bigger probability of being selected.
*/
C father = roulette(population);
C mother = roulette(population);
//std::cout << "GeneticAlgorithm::evolve father:" << father.stats() << std::endl;
//std::cout << "GeneticAlgorithm::evolve mother:" << mother.stats() << std::endl;
/*
* perform crossver
*/
C childA, childB;
crossover(father, mother, childA, childB);
//std::cout << "GeneticAlgorithm::evolve childA:" << childA.stats() << std::endl;
//std::cout << "GeneticAlgorithm::evolve childB:" << childB.stats() << std::endl;
/*
* perform mutation
*/
childA = mutation(childA);
//std::cout << "GeneticAlgorithm::evolve mutated childA:" << childA.stats() << std::endl;
childB = mutation(childB);
//std::cout << "GeneticAlgorithm::evolve mutated childB:" << childB.stats() << std::endl;
// save children as part of the new population
newPopulation.push_back(childA);
newPopulation.push_back(childB);
}
// replace old population members with new individuals
for (unsigned int i = 0; i < population.creatures()->size(); ++i)
{
//std::cout << "[GA] GeneticAlgorithm::run setCreature() #" << i << std::endl;
population.setCreature(i, newPopulation[i]);
}
//std::cout << "[GA] GeneticAlgorithm::run() recalculating fitness levels..." << std::endl;
// recalculate fitness levels of the entire population
population.updateValues();
this->_evolutions++;
}
/*
*
*/
unsigned int evolutions()
{
return this->_evolutions;
}
void crossover(const C& father, const C& mother, C& childA, C& childB)
{
// not the best way to retrieve the size of a chromosome
static unsigned int chromosomeSize = 0;
if (chromosomeSize == 0)
{
C creature;
chromosomeSize = creature.chromosome().size();
}
std::uniform_int_distribution<unsigned int> dist_i(0, chromosomeSize-1);
unsigned int cutPoint = dist_i(this->_rng);
// copy ALL father's chromosomes to child A, and mother's to child B
childA = father;
childB = mother;
// check if this creature falls within crossover rate and overwrite part of the genes
std::uniform_real_distribution<float> dist_f(0.0f, 1.0f);
float random = dist_f(this->_rng);
if (random < this->_crossoverRate)
{
// use cut point to copy the characteristics from the other parent
for (unsigned int i = cutPoint; i < chromosomeSize; ++i)
{
childA.setGene(i, mother.gene(i)); // first half is from the father
childB.setGene(i, father.gene(i)); // first half is from the mother
}
}
//std::cout << "[GA] crossover: cutPoint=" << cutPoint << " random=" << random << " crossoverRate=" << _crossoverRate << std::endl;
}
C mutation(const C& creature)
{
std::uniform_real_distribution<float> distUnit(0.0f, 1.0f);
float random = distUnit(this->_rng);
//std::cout << "GeneticAlgorithm::mutation random=" << random << " _mutationRate=" << this->_mutationRate << std::endl;
// if random falls outside the mutation rate, the creature is not mutated
C mutatedCreature = creature;
if (random >= this->_mutationRate)
return mutatedCreature;
/*
* on the other hand, when random falls within the mutation rate, 1 gene to 1% of its genes can be mutated
* the question is, how many genes is 1%?
*/
unsigned int onePercent = (unsigned int) mutatedCreature.chromosome().size() * 0.01f;
if (onePercent == 0)
onePercent = 1;
//std::cout << "GeneticAlgorithm::mutation onePercent=" << onePercent << std::endl;
// how many genes should be mutated?
std::uniform_int_distribution<unsigned int> distMutation(1, onePercent);
unsigned int numMutations = distMutation(this->_rng);
//std::cout << "GeneticAlgorithm::mutation numMutations=" << numMutations << std::endl;
std::uniform_int_distribution<unsigned int> distGenePos(0, mutatedCreature.chromosome().size()-1);
for (unsigned int m = 0; m < numMutations; ++m)
{
unsigned int genePos = distGenePos(this->_rng);
//std::cout << "GeneticAlgorithm::mutation genePos=" << genePos << std::endl;
mutatedCreature.mutateGene(genePos);
}
return mutatedCreature;
}
C roulette(const P& population)
{
// configurable: specify the range of the population that is used to select random creatures from
std::uniform_int_distribution<unsigned int> dist(50, 100); // 50, 100 represent the 50% of the fittest individuals
// generate a random number for the pizza slice that will be used to retrieve a single creature
unsigned int randomSlice = dist(this->_rng);
std::shared_ptr<std::vector<C>> creatures = population.creatures();
for (unsigned int i = 0; i < creatures->size(); ++i)
{
float start = 0, end = 0;
creatures->at(i).rouletteRange(start, end);
if (randomSlice >= start && randomSlice <= end)
return creatures->at(i);
}
std::cout << "GeneticAlgorithm::roulette !!! zero population (probably)" << std::endl;
C tmp;
return tmp;
}
};
| [
"karlphillip@gmail.com"
] | karlphillip@gmail.com |
b5b63e6fa90746f905cbc37162891af2d8eb4d50 | 3dccc67970f0dc181cee0b2939e1f726b254526e | /imebra/include/imebra/drawBitmap.h | 3732e8db60ed7ab23765616eaaa7b659a289d9dd | [
"MIT"
] | permissive | miyako/4d-plugin-imebra-v3 | 7c8424d5cdf768069c3d59fccaf8bec45a74de15 | a5feaa5d888a3b51bdd047b6996fda59d99a9029 | refs/heads/master | 2022-05-02T14:57:23.159083 | 2022-03-28T13:25:00 | 2022-03-28T13:25:00 | 189,965,106 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,514 | h | /*
Copyright 2005 - 2017 by Paolo Brandoli/Binarno s.p.
Imebra is available for free under the GNU General Public License.
The full text of the license is available in the file license.rst
in the project root folder.
If you do not want to be bound by the GPL terms (such as the requirement
that your application must also be GPL), you may purchase a commercial
license for Imebra from the Imebra’s website (http://imebra.com).
*/
/*! \file drawBitmap.h
\brief Declaration of the class DrawBitmap.
*/
#if !defined(imebraDrawBitmap__INCLUDED_)
#define imebraDrawBitmap__INCLUDED_
#include <memory>
#include "definitions.h"
#include "readWriteMemory.h"
#ifndef SWIG
namespace imebra
{
namespace implementation
{
class drawBitmap;
}
}
#endif
namespace imebra
{
class Transform;
class Image;
///
/// \brief DrawBitmap takes care of converting an Image object into an array
/// of bytes that can be displayed by the operating system facilities.
///
/// DrawBitmap can apply several transformations to the Image before generating
/// the bitmap.
///
/// DrawBitmap applies automatically the necessary color transform and high
/// bit shift in order to obtain a 8 bits per channel RGB image.
///
///////////////////////////////////////////////////////////////////////////////
class IMEBRA_API DrawBitmap
{
DrawBitmap(const DrawBitmap&) = delete;
DrawBitmap& operator=(const DrawBitmap&) = delete;
public:
/// \brief Construct a DrawBitmap with no transforms.
///
/// The getBitmap() method will not apply any Transform to the Image before
/// generating the bitmap.
///
///////////////////////////////////////////////////////////////////////////////
DrawBitmap();
/// \brief Construct a DrawBitmap object that always apply the transforms in
/// the specified TransformsChain before calculating the bitmap of the
/// Image in the getBitmap() method.
///
/// \param transformsChain the transforms to apply to the Image in the
/// getBitmap() method
///
///////////////////////////////////////////////////////////////////////////////
explicit DrawBitmap(const Transform& transformsChain);
/// \brief Destructor
///
///////////////////////////////////////////////////////////////////////////////
virtual ~DrawBitmap();
/// \brief Apply the transforms defined in the constructor (if any) to the
/// input image, then calculate an array of bytes containing a bitmap
/// that can be rendered by the operating system.
///
/// \param image the image for which the bitmap must be calculated
/// \param drawBitmapType the type of bitmap to generate
/// \param rowAlignBytes the number of bytes on which the bitmap rows are
/// aligned
/// \param destination a pointer to the pre-allocated buffer where
/// getBitmap() will store the generated bitmap
/// \param destinationSize the size of the allocated buffer
/// \return the number of bytes occupied by the bitmap in the pre-allocated
/// buffer. If the number of occupied bytes is bigger than the value
/// of the parameter bufferSize then the method doesn't generate
/// the bitmap
///
///////////////////////////////////////////////////////////////////////////////
size_t getBitmap(const Image& image, drawBitmapType_t drawBitmapType, std::uint32_t rowAlignBytes, char* destination, size_t destinationSize);
/// \brief Apply the transforms defined in the constructor (if any) to the
/// input image, then calculate an array of bytes containing a bitmap
/// that can be rendered by the operating system.
///
/// \param image the image for which the bitmap must be calculated
/// \param drawBitmapType the type of bitmap to generate
/// \param rowAlignBytes the number of bytes on which the bitmap rows are
/// aligned
/// \return a ReadWriteMemory object referencing the buffer containing the
/// generated bitmap
///
///////////////////////////////////////////////////////////////////////////////
ReadWriteMemory* getBitmap(const Image& image, drawBitmapType_t drawBitmapType, std::uint32_t rowAlignBytes);
#ifndef SWIG
protected:
std::shared_ptr<implementation::drawBitmap> m_pDrawBitmap;
#endif
};
}
#endif // !defined(imebraDrawBitmap__INCLUDED_)
| [
"keisuke.miyako@4d.com"
] | keisuke.miyako@4d.com |
f631fd018bfdae9b91236fad5e5fc6dc9b5cb892 | a1a8b69b2a24fd86e4d260c8c5d4a039b7c06286 | /build/iOS/Debug/include/Fuse.Effects.EffectType.h | d562b6c99c0c01fdefb5395e14ca008f20fa15d9 | [] | no_license | epireve/hikr-tute | df0af11d1cfbdf6e874372b019d30ab0541c09b7 | 545501fba7044b4cc927baea2edec0674769e22c | refs/heads/master | 2021-09-02T13:54:05.359975 | 2018-01-03T01:21:31 | 2018-01-03T01:21:31 | 115,536,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | h | // This file was generated based on /usr/local/share/uno/Packages/Fuse.Elements/1.4.2/Effects/Effect.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Int.h
namespace g{
namespace Fuse{
namespace Effects{
// public enum EffectType :8
uEnumType* EffectType_typeof();
}}} // ::g::Fuse::Effects
| [
"i@firdaus.my"
] | i@firdaus.my |
2487b7fcfa72e2fdda6a53a4846b49fa753f06c7 | 10b3f8b1bb2d43a053558e2974b1190ec5af9ab3 | /src/qt/forms/ui_assetcontroldialog.h | 7649a9e177686ef40bef978a504c283cbabdda8e | [
"MIT"
] | permissive | Satoex/Sato | ff4683226c2cedb14203a86af68ae168e3c45400 | fda51ccc241ca426e838e1ba833c7eea26f1aedd | refs/heads/master | 2022-07-27T23:30:32.734477 | 2022-01-29T17:44:00 | 2022-01-29T17:44:00 | 346,001,467 | 6 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 18,044 | h | /********************************************************************************
** Form generated from reading UI file 'assetcontroldialog.ui'
**
** Created by: Qt User Interface Compiler version 5.7.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_ASSETCONTROLDIALOG_H
#define UI_ASSETCONTROLDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QFrame>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QRadioButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QVBoxLayout>
#include <assetcontroltreewidget.h>
QT_BEGIN_NAMESPACE
class Ui_AssetControlDialog
{
public:
QVBoxLayout *verticalLayout;
QHBoxLayout *horizontalLayoutTop;
QFormLayout *formLayoutAssetControl1;
QLabel *labelAssetControlQuantityText;
QLabel *labelAssetControlQuantity;
QLabel *labelAssetControlBytesText;
QLabel *labelAssetControlBytes;
QFormLayout *formLayoutAssetControl2;
QLabel *labelAssetControlAmountText;
QLabel *labelAssetControlAmount;
QLabel *labelAssetControlLowOutputText;
QLabel *labelAssetControlLowOutput;
QFormLayout *formLayoutAssetControl3;
QLabel *labelAssetControlFeeText;
QLabel *labelAssetControlFee;
QFormLayout *formLayoutAssetControl4;
QLabel *labelAssetControlAfterFeeText;
QLabel *labelAssetControlAfterFee;
QLabel *labelAssetControlChangeText;
QLabel *labelAssetControlChange;
QFrame *frame;
QHBoxLayout *horizontalLayout;
QHBoxLayout *horizontalLayoutPanel;
QPushButton *pushButtonSelectAll;
QRadioButton *radioTreeMode;
QRadioButton *radioListMode;
QLabel *labelLocked;
QComboBox *assetList;
QCheckBox *viewAdministrator;
QSpacerItem *horizontalSpacer;
AssetControlTreeWidget *treeWidget;
QDialogButtonBox *buttonBox;
void setupUi(QDialog *AssetControlDialog)
{
if (AssetControlDialog->objectName().isEmpty())
AssetControlDialog->setObjectName(QStringLiteral("AssetControlDialog"));
AssetControlDialog->resize(1000, 500);
verticalLayout = new QVBoxLayout(AssetControlDialog);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
horizontalLayoutTop = new QHBoxLayout();
horizontalLayoutTop->setObjectName(QStringLiteral("horizontalLayoutTop"));
horizontalLayoutTop->setContentsMargins(-1, 0, -1, 10);
formLayoutAssetControl1 = new QFormLayout();
formLayoutAssetControl1->setObjectName(QStringLiteral("formLayoutAssetControl1"));
formLayoutAssetControl1->setHorizontalSpacing(10);
formLayoutAssetControl1->setVerticalSpacing(10);
formLayoutAssetControl1->setContentsMargins(6, -1, 6, -1);
labelAssetControlQuantityText = new QLabel(AssetControlDialog);
labelAssetControlQuantityText->setObjectName(QStringLiteral("labelAssetControlQuantityText"));
QFont font;
font.setBold(true);
font.setWeight(75);
labelAssetControlQuantityText->setFont(font);
formLayoutAssetControl1->setWidget(0, QFormLayout::LabelRole, labelAssetControlQuantityText);
labelAssetControlQuantity = new QLabel(AssetControlDialog);
labelAssetControlQuantity->setObjectName(QStringLiteral("labelAssetControlQuantity"));
labelAssetControlQuantity->setCursor(QCursor(Qt::IBeamCursor));
labelAssetControlQuantity->setContextMenuPolicy(Qt::ActionsContextMenu);
labelAssetControlQuantity->setText(QStringLiteral("0"));
labelAssetControlQuantity->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
formLayoutAssetControl1->setWidget(0, QFormLayout::FieldRole, labelAssetControlQuantity);
labelAssetControlBytesText = new QLabel(AssetControlDialog);
labelAssetControlBytesText->setObjectName(QStringLiteral("labelAssetControlBytesText"));
labelAssetControlBytesText->setFont(font);
formLayoutAssetControl1->setWidget(1, QFormLayout::LabelRole, labelAssetControlBytesText);
labelAssetControlBytes = new QLabel(AssetControlDialog);
labelAssetControlBytes->setObjectName(QStringLiteral("labelAssetControlBytes"));
labelAssetControlBytes->setCursor(QCursor(Qt::IBeamCursor));
labelAssetControlBytes->setContextMenuPolicy(Qt::ActionsContextMenu);
labelAssetControlBytes->setText(QStringLiteral("0"));
labelAssetControlBytes->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
formLayoutAssetControl1->setWidget(1, QFormLayout::FieldRole, labelAssetControlBytes);
horizontalLayoutTop->addLayout(formLayoutAssetControl1);
formLayoutAssetControl2 = new QFormLayout();
formLayoutAssetControl2->setObjectName(QStringLiteral("formLayoutAssetControl2"));
formLayoutAssetControl2->setHorizontalSpacing(10);
formLayoutAssetControl2->setVerticalSpacing(10);
formLayoutAssetControl2->setContentsMargins(6, -1, 6, -1);
labelAssetControlAmountText = new QLabel(AssetControlDialog);
labelAssetControlAmountText->setObjectName(QStringLiteral("labelAssetControlAmountText"));
labelAssetControlAmountText->setFont(font);
formLayoutAssetControl2->setWidget(0, QFormLayout::LabelRole, labelAssetControlAmountText);
labelAssetControlAmount = new QLabel(AssetControlDialog);
labelAssetControlAmount->setObjectName(QStringLiteral("labelAssetControlAmount"));
labelAssetControlAmount->setCursor(QCursor(Qt::IBeamCursor));
labelAssetControlAmount->setContextMenuPolicy(Qt::ActionsContextMenu);
labelAssetControlAmount->setText(QStringLiteral("0.00 SATO"));
labelAssetControlAmount->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
formLayoutAssetControl2->setWidget(0, QFormLayout::FieldRole, labelAssetControlAmount);
labelAssetControlLowOutputText = new QLabel(AssetControlDialog);
labelAssetControlLowOutputText->setObjectName(QStringLiteral("labelAssetControlLowOutputText"));
labelAssetControlLowOutputText->setEnabled(false);
labelAssetControlLowOutputText->setFont(font);
formLayoutAssetControl2->setWidget(1, QFormLayout::LabelRole, labelAssetControlLowOutputText);
labelAssetControlLowOutput = new QLabel(AssetControlDialog);
labelAssetControlLowOutput->setObjectName(QStringLiteral("labelAssetControlLowOutput"));
labelAssetControlLowOutput->setEnabled(false);
labelAssetControlLowOutput->setCursor(QCursor(Qt::IBeamCursor));
labelAssetControlLowOutput->setContextMenuPolicy(Qt::ActionsContextMenu);
labelAssetControlLowOutput->setText(QStringLiteral("no"));
labelAssetControlLowOutput->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
formLayoutAssetControl2->setWidget(1, QFormLayout::FieldRole, labelAssetControlLowOutput);
horizontalLayoutTop->addLayout(formLayoutAssetControl2);
formLayoutAssetControl3 = new QFormLayout();
formLayoutAssetControl3->setObjectName(QStringLiteral("formLayoutAssetControl3"));
formLayoutAssetControl3->setHorizontalSpacing(10);
formLayoutAssetControl3->setVerticalSpacing(10);
formLayoutAssetControl3->setContentsMargins(6, -1, 6, -1);
labelAssetControlFeeText = new QLabel(AssetControlDialog);
labelAssetControlFeeText->setObjectName(QStringLiteral("labelAssetControlFeeText"));
labelAssetControlFeeText->setFont(font);
formLayoutAssetControl3->setWidget(0, QFormLayout::LabelRole, labelAssetControlFeeText);
labelAssetControlFee = new QLabel(AssetControlDialog);
labelAssetControlFee->setObjectName(QStringLiteral("labelAssetControlFee"));
labelAssetControlFee->setCursor(QCursor(Qt::IBeamCursor));
labelAssetControlFee->setContextMenuPolicy(Qt::ActionsContextMenu);
labelAssetControlFee->setText(QStringLiteral("0.00 SATO"));
labelAssetControlFee->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
formLayoutAssetControl3->setWidget(0, QFormLayout::FieldRole, labelAssetControlFee);
horizontalLayoutTop->addLayout(formLayoutAssetControl3);
formLayoutAssetControl4 = new QFormLayout();
formLayoutAssetControl4->setObjectName(QStringLiteral("formLayoutAssetControl4"));
formLayoutAssetControl4->setHorizontalSpacing(10);
formLayoutAssetControl4->setVerticalSpacing(10);
formLayoutAssetControl4->setContentsMargins(6, -1, 6, -1);
labelAssetControlAfterFeeText = new QLabel(AssetControlDialog);
labelAssetControlAfterFeeText->setObjectName(QStringLiteral("labelAssetControlAfterFeeText"));
labelAssetControlAfterFeeText->setFont(font);
formLayoutAssetControl4->setWidget(0, QFormLayout::LabelRole, labelAssetControlAfterFeeText);
labelAssetControlAfterFee = new QLabel(AssetControlDialog);
labelAssetControlAfterFee->setObjectName(QStringLiteral("labelAssetControlAfterFee"));
labelAssetControlAfterFee->setCursor(QCursor(Qt::IBeamCursor));
labelAssetControlAfterFee->setContextMenuPolicy(Qt::ActionsContextMenu);
labelAssetControlAfterFee->setText(QStringLiteral("0.00 SATO"));
labelAssetControlAfterFee->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
formLayoutAssetControl4->setWidget(0, QFormLayout::FieldRole, labelAssetControlAfterFee);
labelAssetControlChangeText = new QLabel(AssetControlDialog);
labelAssetControlChangeText->setObjectName(QStringLiteral("labelAssetControlChangeText"));
labelAssetControlChangeText->setEnabled(false);
labelAssetControlChangeText->setFont(font);
formLayoutAssetControl4->setWidget(1, QFormLayout::LabelRole, labelAssetControlChangeText);
labelAssetControlChange = new QLabel(AssetControlDialog);
labelAssetControlChange->setObjectName(QStringLiteral("labelAssetControlChange"));
labelAssetControlChange->setEnabled(false);
labelAssetControlChange->setCursor(QCursor(Qt::IBeamCursor));
labelAssetControlChange->setContextMenuPolicy(Qt::ActionsContextMenu);
labelAssetControlChange->setText(QStringLiteral("0.00 SATO"));
labelAssetControlChange->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
formLayoutAssetControl4->setWidget(1, QFormLayout::FieldRole, labelAssetControlChange);
horizontalLayoutTop->addLayout(formLayoutAssetControl4);
verticalLayout->addLayout(horizontalLayoutTop);
frame = new QFrame(AssetControlDialog);
frame->setObjectName(QStringLiteral("frame"));
frame->setMinimumSize(QSize(0, 40));
frame->setFrameShape(QFrame::StyledPanel);
frame->setFrameShadow(QFrame::Sunken);
horizontalLayout = new QHBoxLayout(frame);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
horizontalLayoutPanel = new QHBoxLayout();
horizontalLayoutPanel->setSpacing(14);
horizontalLayoutPanel->setObjectName(QStringLiteral("horizontalLayoutPanel"));
pushButtonSelectAll = new QPushButton(frame);
pushButtonSelectAll->setObjectName(QStringLiteral("pushButtonSelectAll"));
QSizePolicy sizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(pushButtonSelectAll->sizePolicy().hasHeightForWidth());
pushButtonSelectAll->setSizePolicy(sizePolicy);
pushButtonSelectAll->setAutoDefault(false);
horizontalLayoutPanel->addWidget(pushButtonSelectAll);
radioTreeMode = new QRadioButton(frame);
radioTreeMode->setObjectName(QStringLiteral("radioTreeMode"));
sizePolicy.setHeightForWidth(radioTreeMode->sizePolicy().hasHeightForWidth());
radioTreeMode->setSizePolicy(sizePolicy);
horizontalLayoutPanel->addWidget(radioTreeMode);
radioListMode = new QRadioButton(frame);
radioListMode->setObjectName(QStringLiteral("radioListMode"));
sizePolicy.setHeightForWidth(radioListMode->sizePolicy().hasHeightForWidth());
radioListMode->setSizePolicy(sizePolicy);
radioListMode->setChecked(true);
horizontalLayoutPanel->addWidget(radioListMode);
labelLocked = new QLabel(frame);
labelLocked->setObjectName(QStringLiteral("labelLocked"));
labelLocked->setText(QStringLiteral("(1 locked)"));
horizontalLayoutPanel->addWidget(labelLocked);
assetList = new QComboBox(frame);
assetList->setObjectName(QStringLiteral("assetList"));
assetList->setMinimumContentsLength(30);
horizontalLayoutPanel->addWidget(assetList);
viewAdministrator = new QCheckBox(frame);
viewAdministrator->setObjectName(QStringLiteral("viewAdministrator"));
horizontalLayoutPanel->addWidget(viewAdministrator);
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayoutPanel->addItem(horizontalSpacer);
horizontalLayout->addLayout(horizontalLayoutPanel);
verticalLayout->addWidget(frame);
treeWidget = new AssetControlTreeWidget(AssetControlDialog);
treeWidget->headerItem()->setText(0, QString());
treeWidget->headerItem()->setText(7, QString());
treeWidget->headerItem()->setText(8, QString());
treeWidget->headerItem()->setText(9, QString());
treeWidget->headerItem()->setText(10, QString());
treeWidget->setObjectName(QStringLiteral("treeWidget"));
treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
treeWidget->setSortingEnabled(false);
treeWidget->setColumnCount(11);
treeWidget->header()->setProperty("showSortIndicator", QVariant(true));
treeWidget->header()->setStretchLastSection(false);
verticalLayout->addWidget(treeWidget);
buttonBox = new QDialogButtonBox(AssetControlDialog);
buttonBox->setObjectName(QStringLiteral("buttonBox"));
sizePolicy.setHeightForWidth(buttonBox->sizePolicy().hasHeightForWidth());
buttonBox->setSizePolicy(sizePolicy);
buttonBox->setOrientation(Qt::Horizontal);
buttonBox->setStandardButtons(QDialogButtonBox::Ok);
verticalLayout->addWidget(buttonBox);
retranslateUi(AssetControlDialog);
QMetaObject::connectSlotsByName(AssetControlDialog);
} // setupUi
void retranslateUi(QDialog *AssetControlDialog)
{
AssetControlDialog->setWindowTitle(QApplication::translate("AssetControlDialog", "Asset Selection", Q_NULLPTR));
labelAssetControlQuantityText->setText(QApplication::translate("AssetControlDialog", "Quantity:", Q_NULLPTR));
labelAssetControlBytesText->setText(QApplication::translate("AssetControlDialog", "Bytes:", Q_NULLPTR));
labelAssetControlAmountText->setText(QApplication::translate("AssetControlDialog", "Amount:", Q_NULLPTR));
labelAssetControlLowOutputText->setText(QApplication::translate("AssetControlDialog", "Dust:", Q_NULLPTR));
labelAssetControlFeeText->setText(QApplication::translate("AssetControlDialog", "Fee:", Q_NULLPTR));
labelAssetControlAfterFeeText->setText(QApplication::translate("AssetControlDialog", "After Fee:", Q_NULLPTR));
labelAssetControlChangeText->setText(QApplication::translate("AssetControlDialog", "Change:", Q_NULLPTR));
pushButtonSelectAll->setText(QApplication::translate("AssetControlDialog", "(un)select all", Q_NULLPTR));
radioTreeMode->setText(QApplication::translate("AssetControlDialog", "Tree mode", Q_NULLPTR));
radioListMode->setText(QApplication::translate("AssetControlDialog", "List mode", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
viewAdministrator->setToolTip(QApplication::translate("AssetControlDialog", "View assets that you have the ownership asset for", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
viewAdministrator->setText(QApplication::translate("AssetControlDialog", "View Administrator Assets", Q_NULLPTR));
QTreeWidgetItem *___qtreewidgetitem = treeWidget->headerItem();
___qtreewidgetitem->setText(6, QApplication::translate("AssetControlDialog", "Confirmations", Q_NULLPTR));
___qtreewidgetitem->setText(5, QApplication::translate("AssetControlDialog", "Date", Q_NULLPTR));
___qtreewidgetitem->setText(4, QApplication::translate("AssetControlDialog", "Received with address", Q_NULLPTR));
___qtreewidgetitem->setText(3, QApplication::translate("AssetControlDialog", "Received with label", Q_NULLPTR));
___qtreewidgetitem->setText(2, QApplication::translate("AssetControlDialog", "Amount", Q_NULLPTR));
___qtreewidgetitem->setText(1, QApplication::translate("AssetControlDialog", "Asset", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
___qtreewidgetitem->setToolTip(6, QApplication::translate("AssetControlDialog", "Confirmed", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
} // retranslateUi
};
namespace Ui {
class AssetControlDialog: public Ui_AssetControlDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_ASSETCONTROLDIALOG_H
| [
"78755872+Satoex@users.noreply.github.com"
] | 78755872+Satoex@users.noreply.github.com |
d7a975dfd2a9c8874c452c33da7e792cd14cd40f | 83fe0b04025d725f9aaef558f9c5fc8aafcff81b | /Game/Menu/ImGui/imgui_internal.h | 16462e31c11761f726b2e7f575e4289cfddf32aa | [] | no_license | Archie-osu/Underhacks | f3614496f174b2a0984e02da170f0b88e9067969 | 6c1b84b600ebf1576d562b41ad6f1f59727180a5 | refs/heads/master | 2022-08-29T15:39:21.150732 | 2020-05-24T18:06:13 | 2020-05-24T18:06:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 132,326 | h | // dear imgui, v1.77 WIP
// (internal structures/api)
// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility!
// Set:
// #define IMGUI_DEFINE_MATH_OPERATORS
// To implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators)
/*
Index of this file:
// Header mess
// Forward declarations
// STB libraries includes
// Context pointer
// Generic helpers
// Misc data structures
// Main imgui context
// Tab bar, tab item
// Internal API
*/
#pragma once
#ifndef IMGUI_DISABLE
//-----------------------------------------------------------------------------
// Header mess
//-----------------------------------------------------------------------------
#ifndef IMGUI_VERSION
#error Must include imgui.h before imgui_internal.h
#endif
#include <stdio.h> // FILE*, sscanf
#include <stdlib.h> // NULL, malloc, free, qsort, atoi, atof
#include <math.h> // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf
#include <limits.h> // INT_MIN, INT_MAX
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport)
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h
#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h
#pragma clang diagnostic ignored "-Wold-style-cast"
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#if __has_warning("-Wdouble-promotion")
#pragma clang diagnostic ignored "-Wdouble-promotion"
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
// Legacy defines
#ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Renamed in 1.74
#error Use IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
#endif
#ifdef IMGUI_DISABLE_MATH_FUNCTIONS // Renamed in 1.74
#error Use IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS
#endif
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
struct ImBitVector; // Store 1-bit per value
struct ImRect; // An axis-aligned rectangle (2 points)
struct ImDrawDataBuilder; // Helper to build a ImDrawData instance
struct ImDrawListSharedData; // Data shared between all ImDrawList instances
struct ImGuiColorMod; // Stacked color modifier, backup of modified data so we can restore it
struct ImGuiColumnData; // Storage data for a single column
struct ImGuiColumns; // Storage data for a columns set
struct ImGuiContext; // Main Dear ImGui context
struct ImGuiDataTypeInfo; // Type information associated to a ImGuiDataType enum
struct ImGuiGroupData; // Stacked storage data for BeginGroup()/EndGroup()
struct ImGuiInputTextState; // Internal state of the currently focused/edited text input box
struct ImGuiItemHoveredDataBackup; // Backup and restore IsItemHovered() internal data
struct ImGuiMenuColumns; // Simple column measurement, currently used for MenuItem() only
struct ImGuiNavMoveResult; // Result of a gamepad/keyboard directional navigation move query result
struct ImGuiNextWindowData; // Storage for SetNextWindow** functions
struct ImGuiNextItemData; // Storage for SetNextItem** functions
struct ImGuiPopupData; // Storage for current popup stack
struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file
struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it
struct ImGuiTabBar; // Storage for a tab bar
struct ImGuiTabItem; // Storage for a tab item (within a tab bar)
struct ImGuiWindow; // Storage for one window
struct ImGuiWindowTempData; // Temporary storage for one window (that's the data which in theory we could ditch at the end of the frame)
struct ImGuiWindowSettings; // Storage for a window .ini settings (we keep one of those even if the actual window wasn't instanced during this session)
// Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists.
typedef int ImGuiLayoutType; // -> enum ImGuiLayoutType_ // Enum: Horizontal or vertical
typedef int ImGuiButtonFlags; // -> enum ImGuiButtonFlags_ // Flags: for ButtonEx(), ButtonBehavior()
typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: BeginColumns()
typedef int ImGuiDragFlags; // -> enum ImGuiDragFlags_ // Flags: for DragBehavior()
typedef int ImGuiItemFlags; // -> enum ImGuiItemFlags_ // Flags: for PushItemFlag()
typedef int ImGuiItemStatusFlags; // -> enum ImGuiItemStatusFlags_ // Flags: for DC.LastItemStatusFlags
typedef int ImGuiNavHighlightFlags; // -> enum ImGuiNavHighlightFlags_ // Flags: for RenderNavHighlight()
typedef int ImGuiNavDirSourceFlags; // -> enum ImGuiNavDirSourceFlags_ // Flags: for GetNavInputAmount2d()
typedef int ImGuiNavMoveFlags; // -> enum ImGuiNavMoveFlags_ // Flags: for navigation requests
typedef int ImGuiNextItemDataFlags; // -> enum ImGuiNextItemDataFlags_ // Flags: for SetNextItemXXX() functions
typedef int ImGuiNextWindowDataFlags; // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions
typedef int ImGuiSeparatorFlags; // -> enum ImGuiSeparatorFlags_ // Flags: for SeparatorEx()
typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for SliderBehavior()
typedef int ImGuiTextFlags; // -> enum ImGuiTextFlags_ // Flags: for TextEx()
typedef int ImGuiTooltipFlags; // -> enum ImGuiTooltipFlags_ // Flags: for BeginTooltipEx()
//-------------------------------------------------------------------------
// STB libraries includes
//-------------------------------------------------------------------------
namespace ImStb
{
#undef STB_TEXTEDIT_STRING
#undef STB_TEXTEDIT_CHARTYPE
#define STB_TEXTEDIT_STRING ImGuiInputTextState
#define STB_TEXTEDIT_CHARTYPE ImWchar
#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f
#define STB_TEXTEDIT_UNDOSTATECOUNT 99
#define STB_TEXTEDIT_UNDOCHARCOUNT 999
#include "imstb_textedit.h"
} // namespace ImStb
//-----------------------------------------------------------------------------
// Context pointer
//-----------------------------------------------------------------------------
#ifndef GImGui
extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer
#endif
//-----------------------------------------------------------------------------
// Macros
//-----------------------------------------------------------------------------
// Debug Logging
#ifndef IMGUI_DEBUG_LOG
#define IMGUI_DEBUG_LOG(_FMT,...) printf("[%05d] " _FMT, GImGui->FrameCount, __VA_ARGS__)
#endif
// Static Asserts
#if (__cplusplus >= 201100)
#define IM_STATIC_ASSERT(_COND) static_assert(_COND, "")
#else
#define IM_STATIC_ASSERT(_COND) typedef char static_assertion_##__line__[(_COND)?1:-1]
#endif
// "Paranoid" Debug Asserts are meant to only be enabled during specific debugging/work, otherwise would slow down the code too much.
// We currently don't have many of those so the effect is currently negligible, but onward intent to add more aggressive ones in the code.
//#define IMGUI_DEBUG_PARANOID
#ifdef IMGUI_DEBUG_PARANOID
#define IM_ASSERT_PARANOID(_EXPR) IM_ASSERT(_EXPR)
#else
#define IM_ASSERT_PARANOID(_EXPR)
#endif
// Error handling
// Down the line in some frameworks/languages we would like to have a way to redirect those to the programmer and recover from more faults.
#ifndef IM_ASSERT_USER_ERROR
#define IM_ASSERT_USER_ERROR(_EXP,_MSG) IM_ASSERT((_EXP) && _MSG) // Recoverable User Error
#endif
// Misc Macros
#define IM_PI 3.14159265358979323846f
#ifdef _WIN32
#define IM_NEWLINE "\r\n" // Play it nice with Windows users (Update: since 2018-05, Notepad finally appears to support Unix-style carriage returns!)
#else
#define IM_NEWLINE "\n"
#endif
#define IM_TABSIZE (4)
#define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose
#define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255
#define IM_FLOOR(_VAL) ((float)(int)(_VAL)) // ImFloor() is not inlined in MSVC debug builds
#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) //
// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall
#ifdef _MSC_VER
#define IMGUI_CDECL __cdecl
#else
#define IMGUI_CDECL
#endif
//-----------------------------------------------------------------------------
// Generic helpers
// Note that the ImXXX helpers functions are lower-level than ImGui functions.
// ImGui functions or the ImGui context are never called/used from other ImXXX functions.
//-----------------------------------------------------------------------------
// - Helpers: Misc
// - Helpers: Bit manipulation
// - Helpers: String, Formatting
// - Helpers: UTF-8 <> wchar conversions
// - Helpers: ImVec2/ImVec4 operators
// - Helpers: Maths
// - Helpers: Geometry
// - Helpers: Bit arrays
// - Helper: ImBitVector
// - Helper: ImPool<>
// - Helper: ImChunkStream<>
//-----------------------------------------------------------------------------
// Helpers: Misc
#define ImQsort qsort
IMGUI_API ImU32 ImHashData(const void* data, size_t data_size, ImU32 seed = 0);
IMGUI_API ImU32 ImHashStr(const char* data, size_t data_size = 0, ImU32 seed = 0);
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
static inline ImU32 ImHash(const void* data, int size, ImU32 seed = 0) { return size ? ImHashData(data, (size_t)size, seed) : ImHashStr((const char*)data, 0, seed); } // [moved to ImHashStr/ImHashData in 1.68]
#endif
// Helpers: Color Blending
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b);
// Helpers: Bit manipulation
static inline bool ImIsPowerOfTwo(int v) { return v != 0 && (v & (v - 1)) == 0; }
static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; }
// Helpers: String, Formatting
IMGUI_API int ImStricmp(const char* str1, const char* str2);
IMGUI_API int ImStrnicmp(const char* str1, const char* str2, size_t count);
IMGUI_API void ImStrncpy(char* dst, const char* src, size_t count);
IMGUI_API char* ImStrdup(const char* str);
IMGUI_API char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* str);
IMGUI_API const char* ImStrchrRange(const char* str_begin, const char* str_end, char c);
IMGUI_API int ImStrlenW(const ImWchar* str);
IMGUI_API const char* ImStreolRange(const char* str, const char* str_end); // End end-of-line
IMGUI_API const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line
IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end);
IMGUI_API void ImStrTrimBlanks(char* str);
IMGUI_API const char* ImStrSkipBlank(const char* str);
IMGUI_API int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) IM_FMTARGS(3);
IMGUI_API int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) IM_FMTLIST(3);
IMGUI_API const char* ImParseFormatFindStart(const char* format);
IMGUI_API const char* ImParseFormatFindEnd(const char* format);
IMGUI_API const char* ImParseFormatTrimDecorations(const char* format, char* buf, size_t buf_size);
IMGUI_API int ImParseFormatPrecision(const char* format, int default_value);
static inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; }
static inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; }
// Helpers: UTF-8 <> wchar conversions
IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count
IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // read one character. return input UTF-8 bytes count
IMGUI_API int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count
IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count)
IMGUI_API int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end); // return number of bytes to express one char in UTF-8
IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string in UTF-8
// Helpers: ImVec2/ImVec4 operators
// We are keeping those disabled by default so they don't leak in user space, to allow user enabling implicit cast operators between ImVec2 and their own types (using IM_VEC2_CLASS_EXTRA etc.)
// We unfortunately don't have a unary- operator for ImVec2 because this would needs to be defined inside the class itself.
#ifdef IMGUI_DEFINE_MATH_OPERATORS
static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x * rhs, lhs.y * rhs); }
static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x / rhs, lhs.y / rhs); }
static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); }
static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); }
static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }
static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); }
static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; }
static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; }
static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; }
static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; }
static inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs) { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; }
static inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs) { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; }
static inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); }
static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); }
static inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); }
#endif
// Helpers: File System
#ifdef IMGUI_DISABLE_FILE_FUNCTIONS
#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
typedef void* ImFileHandle;
static inline ImFileHandle ImFileOpen(const char*, const char*) { return NULL; }
static inline bool ImFileClose(ImFileHandle) { return false; }
static inline ImU64 ImFileGetSize(ImFileHandle) { return (ImU64)-1; }
static inline ImU64 ImFileRead(void*, ImU64, ImU64, ImFileHandle) { return 0; }
static inline ImU64 ImFileWrite(const void*, ImU64, ImU64, ImFileHandle) { return 0; }
#endif
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
typedef FILE* ImFileHandle;
IMGUI_API ImFileHandle ImFileOpen(const char* filename, const char* mode);
IMGUI_API bool ImFileClose(ImFileHandle file);
IMGUI_API ImU64 ImFileGetSize(ImFileHandle file);
IMGUI_API ImU64 ImFileRead(void* data, ImU64 size, ImU64 count, ImFileHandle file);
IMGUI_API ImU64 ImFileWrite(const void* data, ImU64 size, ImU64 count, ImFileHandle file);
#else
#define IMGUI_DISABLE_TTY_FUNCTIONS // Can't use stdout, fflush if we are not using default file functions
#endif
IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size = NULL, int padding_bytes = 0);
// Helpers: Maths
// - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy)
#ifndef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS
#define ImFabs(X) fabsf(X)
#define ImSqrt(X) sqrtf(X)
#define ImFmod(X, Y) fmodf((X), (Y))
#define ImCos(X) cosf(X)
#define ImSin(X) sinf(X)
#define ImAcos(X) acosf(X)
#define ImAtan2(Y, X) atan2f((Y), (X))
#define ImAtof(STR) atof(STR)
#define ImFloorStd(X) floorf(X) // We already uses our own ImFloor() { return (float)(int)v } internally so the standard one wrapper is named differently (it's used by e.g. stb_truetype)
#define ImCeil(X) ceilf(X)
static inline float ImPow(float x, float y) { return powf(x, y); } // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision
static inline double ImPow(double x, double y) { return pow(x, y); }
#endif
// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double
// (Exceptionally using templates here but we could also redefine them for those types)
template<typename T> static inline T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; }
template<typename T> static inline T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; }
template<typename T> static inline T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; }
template<typename T> static inline T ImLerp(T a, T b, float t) { return (T)(a + (b - a) * t); }
template<typename T> static inline void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; }
template<typename T> static inline T ImAddClampOverflow(T a, T b, T mn, T mx) { if (b < 0 && (a < mn - b)) return mn; if (b > 0 && (a > mx - b)) return mx; return a + b; }
template<typename T> static inline T ImSubClampOverflow(T a, T b, T mn, T mx) { if (b > 0 && (a < mn + b)) return mn; if (b < 0 && (a > mx + b)) return mx; return a - b; }
// - Misc maths helpers
static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); }
static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); }
static inline ImVec2 ImClamp(const ImVec2& v, const ImVec2& mn, ImVec2 mx) { return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x : v.x, (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y : v.y); }
static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); }
static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); }
static inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); }
static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; }
static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x * lhs.x + lhs.y * lhs.y; }
static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x * lhs.x + lhs.y * lhs.y + lhs.z * lhs.z + lhs.w * lhs.w; }
static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x * lhs.x + lhs.y * lhs.y; if (d > 0.0f) return 1.0f / ImSqrt(d); return fail_value; }
static inline float ImFloor(float f) { return (float)(int)(f); }
static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); }
static inline int ImModPositive(int a, int b) { return (a + b) % b; }
static inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; }
static inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); }
static inline float ImLinearSweep(float current, float target, float speed) { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; }
static inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }
// Helpers: Geometry
IMGUI_API ImVec2 ImBezierCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t); // Cubic Bezier
IMGUI_API ImVec2 ImBezierClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments); // For curves with explicit number of segments
IMGUI_API ImVec2 ImBezierClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol);// For auto-tessellated curves you can use tess_tol = style.CurveTessellationTol
IMGUI_API ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p);
IMGUI_API bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);
IMGUI_API ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);
IMGUI_API void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w);
inline float ImTriangleArea(const ImVec2& a, const ImVec2& b, const ImVec2& c) { return ImFabs((a.x * (b.y - c.y)) + (b.x * (c.y - a.y)) + (c.x * (a.y - b.y))) * 0.5f; }
IMGUI_API ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy);
// Helpers: Bit arrays
inline bool ImBitArrayTestBit(const ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); return (arr[n >> 5] & mask) != 0; }
inline void ImBitArrayClearBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] &= ~mask; }
inline void ImBitArraySetBit(ImU32* arr, int n) { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] |= mask; }
inline void ImBitArraySetBitRange(ImU32* arr, int n, int n2)
{
while (n <= n2)
{
int a_mod = (n & 31);
int b_mod = ((n2 >= n + 31) ? 31 : (n2 & 31)) + 1;
ImU32 mask = (ImU32)(((ImU64)1 << b_mod) - 1) & ~(ImU32)(((ImU64)1 << a_mod) - 1);
arr[n >> 5] |= mask;
n = (n + 32) & ~31;
}
}
// Helper: ImBitVector
// Store 1-bit per value.
struct IMGUI_API ImBitVector
{
ImVector<ImU32> Storage;
void Create(int sz) { Storage.resize((sz + 31) >> 5); memset(Storage.Data, 0, (size_t)Storage.Size * sizeof(Storage.Data[0])); }
void Clear() { Storage.clear(); }
bool TestBit(int n) const { IM_ASSERT(n < (Storage.Size << 5)); return ImBitArrayTestBit(Storage.Data, n); }
void SetBit(int n) { IM_ASSERT(n < (Storage.Size << 5)); ImBitArraySetBit(Storage.Data, n); }
void ClearBit(int n) { IM_ASSERT(n < (Storage.Size << 5)); ImBitArrayClearBit(Storage.Data, n); }
};
// Helper: ImPool<>
// Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer,
// Honor constructor/destructor. Add/remove invalidate all pointers. Indexes have the same lifetime as the associated object.
typedef int ImPoolIdx;
template<typename T>
struct IMGUI_API ImPool
{
ImVector<T> Buf; // Contiguous data
ImGuiStorage Map; // ID->Index
ImPoolIdx FreeIdx; // Next free idx to use
ImPool() { FreeIdx = 0; }
~ImPool() { Clear(); }
T* GetByKey(ImGuiID key) { int idx = Map.GetInt(key, -1); return (idx != -1) ? &Buf[idx] : NULL; }
T* GetByIndex(ImPoolIdx n) { return &Buf[n]; }
ImPoolIdx GetIndex(const T* p) const { IM_ASSERT(p >= Buf.Data && p < Buf.Data + Buf.Size); return (ImPoolIdx)(p - Buf.Data); }
T* GetOrAddByKey(ImGuiID key) { int* p_idx = Map.GetIntRef(key, -1); if (*p_idx != -1) return &Buf[*p_idx]; *p_idx = FreeIdx; return Add(); }
bool Contains(const T* p) const { return (p >= Buf.Data && p < Buf.Data + Buf.Size); }
void Clear() { for (int n = 0; n < Map.Data.Size; n++) { int idx = Map.Data[n].val_i; if (idx != -1) Buf[idx].~T(); } Map.Clear(); Buf.clear(); FreeIdx = 0; }
T* Add() { int idx = FreeIdx; if (idx == Buf.Size) { Buf.resize(Buf.Size + 1); FreeIdx++; } else { FreeIdx = *(int*)&Buf[idx]; } IM_PLACEMENT_NEW(&Buf[idx]) T(); return &Buf[idx]; }
void Remove(ImGuiID key, const T* p) { Remove(key, GetIndex(p)); }
void Remove(ImGuiID key, ImPoolIdx idx) { Buf[idx].~T(); *(int*)&Buf[idx] = FreeIdx; FreeIdx = idx; Map.SetInt(key, -1); }
void Reserve(int capacity) { Buf.reserve(capacity); Map.Data.reserve(capacity); }
int GetSize() const { return Buf.Size; }
};
// Helper: ImChunkStream<>
// Build and iterate a contiguous stream of variable-sized structures.
// This is used by Settings to store persistent data while reducing allocation count.
// We store the chunk size first, and align the final size on 4 bytes boundaries (this what the '(X + 3) & ~3' statement is for)
// The tedious/zealous amount of casting is to avoid -Wcast-align warnings.
template<typename T>
struct IMGUI_API ImChunkStream
{
ImVector<char> Buf;
void clear() { Buf.clear(); }
bool empty() const { return Buf.Size == 0; }
int size() const { return Buf.Size; }
T* alloc_chunk(size_t sz) { size_t HDR_SZ = 4; sz = ((HDR_SZ + sz) + 3u) & ~3u; int off = Buf.Size; Buf.resize(off + (int)sz); ((int*)(void*)(Buf.Data + off))[0] = (int)sz; return (T*)(void*)(Buf.Data + off + (int)HDR_SZ); }
T* begin() { size_t HDR_SZ = 4; if (!Buf.Data) return NULL; return (T*)(void*)(Buf.Data + HDR_SZ); }
T* next_chunk(T* p) { size_t HDR_SZ = 4; IM_ASSERT(p >= begin() && p < end()); p = (T*)(void*)((char*)(void*)p + chunk_size(p)); if (p == (T*)(void*)((char*)end() + HDR_SZ)) return (T*)0; IM_ASSERT(p < end()); return p; }
int chunk_size(const T* p) { return ((const int*)p)[-1]; }
T* end() { return (T*)(void*)(Buf.Data + Buf.Size); }
int offset_from_ptr(const T* p) { IM_ASSERT(p >= begin() && p < end()); const ptrdiff_t off = (const char*)p - Buf.Data; return (int)off; }
T* ptr_from_offset(int off) { IM_ASSERT(off >= 4 && off < Buf.Size); return (T*)(void*)(Buf.Data + off); }
};
//-----------------------------------------------------------------------------
// Misc data structures
//-----------------------------------------------------------------------------
enum ImGuiButtonFlags_
{
ImGuiButtonFlags_None = 0,
ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat
ImGuiButtonFlags_PressedOnClick = 1 << 1, // return true on click (mouse down event)
ImGuiButtonFlags_PressedOnClickRelease = 1 << 2, // [Default] return true on click + release on same item <-- this is what the majority of Button are using
ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 3, // return true on click + release even if the release event is not done while hovering the item
ImGuiButtonFlags_PressedOnRelease = 1 << 4, // return true on release (default requires click+release)
ImGuiButtonFlags_PressedOnDoubleClick = 1 << 5, // return true on double-click (default requires click+release)
ImGuiButtonFlags_PressedOnDragDropHold = 1 << 6, // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers)
ImGuiButtonFlags_FlattenChildren = 1 << 7, // allow interactions even if a child window is overlapping
ImGuiButtonFlags_AllowItemOverlap = 1 << 8, // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap()
ImGuiButtonFlags_DontClosePopups = 1 << 9, // disable automatically closing parent popup on press // [UNUSED]
ImGuiButtonFlags_Disabled = 1 << 10, // disable interactions
ImGuiButtonFlags_AlignTextBaseLine = 1 << 11, // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine
ImGuiButtonFlags_NoKeyModifiers = 1 << 12, // disable mouse interaction if a key modifier is held
ImGuiButtonFlags_NoHoldingActiveId = 1 << 13, // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only)
ImGuiButtonFlags_NoNavFocus = 1 << 14, // don't override navigation focus when activated
ImGuiButtonFlags_NoHoveredOnFocus = 1 << 15, // don't report as hovered when nav focus is on this item
ImGuiButtonFlags_MouseButtonLeft = 1 << 16, // [Default] react on left mouse button
ImGuiButtonFlags_MouseButtonRight = 1 << 17, // react on right mouse button
ImGuiButtonFlags_MouseButtonMiddle = 1 << 18, // react on center mouse button
ImGuiButtonFlags_MouseButtonMask_ = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle,
ImGuiButtonFlags_MouseButtonShift_ = 16,
ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft,
ImGuiButtonFlags_PressedOnMask_ = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold,
ImGuiButtonFlags_PressedOnDefault_ = ImGuiButtonFlags_PressedOnClickRelease
};
enum ImGuiSliderFlags_
{
ImGuiSliderFlags_None = 0,
ImGuiSliderFlags_Vertical = 1 << 0
};
enum ImGuiDragFlags_
{
ImGuiDragFlags_None = 0,
ImGuiDragFlags_Vertical = 1 << 0
};
enum ImGuiColumnsFlags_
{
// Default: 0
ImGuiColumnsFlags_None = 0,
ImGuiColumnsFlags_NoBorder = 1 << 0, // Disable column dividers
ImGuiColumnsFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers
ImGuiColumnsFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns
ImGuiColumnsFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window
ImGuiColumnsFlags_GrowParentContentsSize = 1 << 4 // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove.
};
// Extend ImGuiSelectableFlags_
enum ImGuiSelectableFlagsPrivate_
{
// NB: need to be in sync with last value of ImGuiSelectableFlags_
ImGuiSelectableFlags_NoHoldingActiveID = 1 << 20,
ImGuiSelectableFlags_SelectOnClick = 1 << 21, // Override button behavior to react on Click (default is Click+Release)
ImGuiSelectableFlags_SelectOnRelease = 1 << 22, // Override button behavior to react on Release (default is Click+Release)
ImGuiSelectableFlags_SpanAvailWidth = 1 << 23, // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus)
ImGuiSelectableFlags_DrawHoveredWhenHeld = 1 << 24, // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow.
ImGuiSelectableFlags_SetNavIdOnHover = 1 << 25
};
// Extend ImGuiTreeNodeFlags_
enum ImGuiTreeNodeFlagsPrivate_
{
ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 20
};
enum ImGuiSeparatorFlags_
{
ImGuiSeparatorFlags_None = 0,
ImGuiSeparatorFlags_Horizontal = 1 << 0, // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar
ImGuiSeparatorFlags_Vertical = 1 << 1,
ImGuiSeparatorFlags_SpanAllColumns = 1 << 2
};
// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin().
// This is going to be exposed in imgui.h when stabilized enough.
enum ImGuiItemFlags_
{
ImGuiItemFlags_None = 0,
ImGuiItemFlags_NoTabStop = 1 << 0, // false
ImGuiItemFlags_ButtonRepeat = 1 << 1, // false // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings.
ImGuiItemFlags_Disabled = 1 << 2, // false // [BETA] Disable interactions but doesn't affect visuals yet. See github.com/ocornut/imgui/issues/211
ImGuiItemFlags_NoNav = 1 << 3, // false
ImGuiItemFlags_NoNavDefaultFocus = 1 << 4, // false
ImGuiItemFlags_SelectableDontClosePopup = 1 << 5, // false // MenuItem/Selectable() automatically closes current Popup window
ImGuiItemFlags_MixedValue = 1 << 6, // false // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets)
ImGuiItemFlags_Default_ = 0
};
// Storage for LastItem data
enum ImGuiItemStatusFlags_
{
ImGuiItemStatusFlags_None = 0,
ImGuiItemStatusFlags_HoveredRect = 1 << 0,
ImGuiItemStatusFlags_HasDisplayRect = 1 << 1,
ImGuiItemStatusFlags_Edited = 1 << 2, // Value exposed by item was edited in the current frame (should match the bool return value of most widgets)
ImGuiItemStatusFlags_ToggledSelection = 1 << 3, // Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected" because reporting the change allows us to handle clipping with less issues.
ImGuiItemStatusFlags_ToggledOpen = 1 << 4, // Set when TreeNode() reports toggling their open state.
ImGuiItemStatusFlags_HasDeactivated = 1 << 5, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag.
ImGuiItemStatusFlags_Deactivated = 1 << 6 // Only valid if ImGuiItemStatusFlags_HasDeactivated is set.
#ifdef IMGUI_ENABLE_TEST_ENGINE
, // [imgui_tests only]
ImGuiItemStatusFlags_Openable = 1 << 10, //
ImGuiItemStatusFlags_Opened = 1 << 11, //
ImGuiItemStatusFlags_Checkable = 1 << 12, //
ImGuiItemStatusFlags_Checked = 1 << 13 //
#endif
};
enum ImGuiTextFlags_
{
ImGuiTextFlags_None = 0,
ImGuiTextFlags_NoWidthForLargeClippedText = 1 << 0
};
enum ImGuiTooltipFlags_
{
ImGuiTooltipFlags_None = 0,
ImGuiTooltipFlags_OverridePreviousTooltip = 1 << 0 // Override will clear/ignore previously submitted tooltip (defaults to append)
};
// FIXME: this is in development, not exposed/functional as a generic feature yet.
// Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2
enum ImGuiLayoutType_
{
ImGuiLayoutType_Horizontal = 0,
ImGuiLayoutType_Vertical = 1
};
enum ImGuiLogType
{
ImGuiLogType_None = 0,
ImGuiLogType_TTY,
ImGuiLogType_File,
ImGuiLogType_Buffer,
ImGuiLogType_Clipboard
};
// X/Y enums are fixed to 0/1 so they may be used to index ImVec2
enum ImGuiAxis
{
ImGuiAxis_None = -1,
ImGuiAxis_X = 0,
ImGuiAxis_Y = 1
};
enum ImGuiPlotType
{
ImGuiPlotType_Lines,
ImGuiPlotType_Histogram
};
enum ImGuiInputSource
{
ImGuiInputSource_None = 0,
ImGuiInputSource_Mouse,
ImGuiInputSource_Nav,
ImGuiInputSource_NavKeyboard, // Only used occasionally for storage, not tested/handled by most code
ImGuiInputSource_NavGamepad, // "
ImGuiInputSource_COUNT
};
// FIXME-NAV: Clarify/expose various repeat delay/rate
enum ImGuiInputReadMode
{
ImGuiInputReadMode_Down,
ImGuiInputReadMode_Pressed,
ImGuiInputReadMode_Released,
ImGuiInputReadMode_Repeat,
ImGuiInputReadMode_RepeatSlow,
ImGuiInputReadMode_RepeatFast
};
enum ImGuiNavHighlightFlags_
{
ImGuiNavHighlightFlags_None = 0,
ImGuiNavHighlightFlags_TypeDefault = 1 << 0,
ImGuiNavHighlightFlags_TypeThin = 1 << 1,
ImGuiNavHighlightFlags_AlwaysDraw = 1 << 2, // Draw rectangular highlight if (g.NavId == id) _even_ when using the mouse.
ImGuiNavHighlightFlags_NoRounding = 1 << 3
};
enum ImGuiNavDirSourceFlags_
{
ImGuiNavDirSourceFlags_None = 0,
ImGuiNavDirSourceFlags_Keyboard = 1 << 0,
ImGuiNavDirSourceFlags_PadDPad = 1 << 1,
ImGuiNavDirSourceFlags_PadLStick = 1 << 2
};
enum ImGuiNavMoveFlags_
{
ImGuiNavMoveFlags_None = 0,
ImGuiNavMoveFlags_LoopX = 1 << 0, // On failed request, restart from opposite side
ImGuiNavMoveFlags_LoopY = 1 << 1,
ImGuiNavMoveFlags_WrapX = 1 << 2, // On failed request, request from opposite side one line down (when NavDir==right) or one line up (when NavDir==left)
ImGuiNavMoveFlags_WrapY = 1 << 3, // This is not super useful for provided for completeness
ImGuiNavMoveFlags_AllowCurrentNavId = 1 << 4, // Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place)
ImGuiNavMoveFlags_AlsoScoreVisibleSet = 1 << 5, // Store alternate result in NavMoveResultLocalVisibleSet that only comprise elements that are already fully visible.
ImGuiNavMoveFlags_ScrollToEdge = 1 << 6
};
enum ImGuiNavForward
{
ImGuiNavForward_None,
ImGuiNavForward_ForwardQueued,
ImGuiNavForward_ForwardActive
};
enum ImGuiNavLayer
{
ImGuiNavLayer_Main = 0, // Main scrolling layer
ImGuiNavLayer_Menu = 1, // Menu layer (access with Alt/ImGuiNavInput_Menu)
ImGuiNavLayer_COUNT
};
enum ImGuiPopupPositionPolicy
{
ImGuiPopupPositionPolicy_Default,
ImGuiPopupPositionPolicy_ComboBox
};
// 1D vector (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches)
struct ImVec1
{
float x;
ImVec1() { x = 0.0f; }
ImVec1(float _x) { x = _x; }
};
// 2D vector (half-size integer)
struct ImVec2ih
{
short x, y;
ImVec2ih() { x = y = 0; }
ImVec2ih(short _x, short _y) { x = _x; y = _y; }
explicit ImVec2ih(const ImVec2& rhs) { x = (short)rhs.x; y = (short)rhs.y; }
};
// 2D axis aligned bounding-box
// NB: we can't rely on ImVec2 math operators being available here
struct IMGUI_API ImRect
{
ImVec2 Min; // Upper-left
ImVec2 Max; // Lower-right
ImRect() : Min(0.0f, 0.0f), Max(0.0f, 0.0f) {}
ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {}
ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {}
ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {}
ImVec2 GetCenter() const { return ImVec2((Min.x + Max.x) * 0.5f, (Min.y + Max.y) * 0.5f); }
ImVec2 GetSize() const { return ImVec2(Max.x - Min.x, Max.y - Min.y); }
float GetWidth() const { return Max.x - Min.x; }
float GetHeight() const { return Max.y - Min.y; }
ImVec2 GetTL() const { return Min; } // Top-left
ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right
ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left
ImVec2 GetBR() const { return Max; } // Bottom-right
bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x&& p.y < Max.y; }
bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; }
bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y&& r.Max.y > Min.y && r.Min.x < Max.x&& r.Max.x > Min.x; }
void Add(const ImVec2& p) { if (Min.x > p.x) Min.x = p.x; if (Min.y > p.y) Min.y = p.y; if (Max.x < p.x) Max.x = p.x; if (Max.y < p.y) Max.y = p.y; }
void Add(const ImRect& r) { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; }
void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; }
void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; }
void Translate(const ImVec2& d) { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; }
void TranslateX(float dx) { Min.x += dx; Max.x += dx; }
void TranslateY(float dy) { Min.y += dy; Max.y += dy; }
void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display.
void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped.
void Floor() { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); }
bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; }
};
// Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo().
struct ImGuiDataTypeInfo
{
size_t Size; // Size in byte
const char* PrintFmt; // Default printf format for the type
const char* ScanFmt; // Default scanf format for the type
};
// Extend ImGuiDataType_
enum ImGuiDataTypePrivate_
{
ImGuiDataType_String = ImGuiDataType_COUNT + 1,
ImGuiDataType_Pointer,
ImGuiDataType_ID
};
// Stacked color modifier, backup of modified data so we can restore it
struct ImGuiColorMod
{
ImGuiCol Col;
ImVec4 BackupValue;
};
// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable.
struct ImGuiStyleMod
{
ImGuiStyleVar VarIdx;
union { int BackupInt[2]; float BackupFloat[2]; };
ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; }
ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; }
ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; }
};
// Stacked storage data for BeginGroup()/EndGroup()
struct ImGuiGroupData
{
ImVec2 BackupCursorPos;
ImVec2 BackupCursorMaxPos;
ImVec1 BackupIndent;
ImVec1 BackupGroupOffset;
ImVec2 BackupCurrLineSize;
float BackupCurrLineTextBaseOffset;
ImGuiID BackupActiveIdIsAlive;
bool BackupActiveIdPreviousFrameIsAlive;
bool EmitItem;
};
// Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper.
struct IMGUI_API ImGuiMenuColumns
{
float Spacing;
float Width, NextWidth;
float Pos[3], NextWidths[3];
ImGuiMenuColumns();
void Update(int count, float spacing, bool clear);
float DeclColumns(float w0, float w1, float w2);
float CalcExtraSpace(float avail_w) const;
};
// Internal state of the currently focused/edited text input box
// For a given item ID, access with ImGui::GetInputTextState()
struct IMGUI_API ImGuiInputTextState
{
ImGuiID ID; // widget id owning the text state
int CurLenW, CurLenA; // we need to maintain our buffer length in both UTF-8 and wchar format. UTF-8 length is valid even if TextA is not.
ImVector<ImWchar> TextW; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer.
ImVector<char> TextA; // temporary UTF8 buffer for callbacks and other operations. this is not updated in every code-path! size=capacity.
ImVector<char> InitialTextA; // backup of end-user buffer at the time of focus (in UTF-8, unaltered)
bool TextAIsValid; // temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument)
int BufCapacityA; // end-user buffer capacity
float ScrollX; // horizontal scrolling/offset
ImStb::STB_TexteditState Stb; // state for stb_textedit.h
float CursorAnim; // timer for cursor blink, reset on every user action so the cursor reappears immediately
bool CursorFollow; // set when we want scrolling to follow the current cursor position (not always!)
bool SelectedAllMouseLock; // after a double-click to select all, we ignore further mouse drags to update selection
ImGuiInputTextFlags UserFlags; // Temporarily set while we call user's callback
ImGuiInputTextCallback UserCallback; // "
void* UserCallbackData; // "
ImGuiInputTextState() { memset(this, 0, sizeof(*this)); }
void ClearText() { CurLenW = CurLenA = 0; TextW[0] = 0; TextA[0] = 0; CursorClamp(); }
void ClearFreeMemory() { TextW.clear(); TextA.clear(); InitialTextA.clear(); }
int GetUndoAvailCount() const { return Stb.undostate.undo_point; }
int GetRedoAvailCount() const { return STB_TEXTEDIT_UNDOSTATECOUNT - Stb.undostate.redo_point; }
void OnKeyPressed(int key); // Cannot be inline because we call in code in stb_textedit.h implementation
// Cursor & Selection
void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking
void CursorClamp() { Stb.cursor = ImMin(Stb.cursor, CurLenW); Stb.select_start = ImMin(Stb.select_start, CurLenW); Stb.select_end = ImMin(Stb.select_end, CurLenW); }
bool HasSelection() const { return Stb.select_start != Stb.select_end; }
void ClearSelection() { Stb.select_start = Stb.select_end = Stb.cursor; }
void SelectAll() { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; }
};
// Windows data saved in imgui.ini file
// Because we never destroy or rename ImGuiWindowSettings, we can store the names in a separate buffer easily.
// (this is designed to be stored in a ImChunkStream buffer, with the variable-length Name following our structure)
struct ImGuiWindowSettings
{
ImGuiID ID;
ImVec2ih Pos;
ImVec2ih Size;
bool Collapsed;
ImGuiWindowSettings() { ID = 0; Pos = Size = ImVec2ih(0, 0); Collapsed = false; }
char* GetName() { return (char*)(this + 1); }
};
struct ImGuiSettingsHandler
{
const char* TypeName; // Short description stored in .ini file. Disallowed characters: '[' ']'
ImGuiID TypeHash; // == ImHashStr(TypeName)
void* (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name); // Read: Called when entering into a new ini entry e.g. "[Window][Name]"
void (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry
void (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf); // Write: Output every entries into 'out_buf'
void* UserData;
ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); }
};
// Storage for current popup stack
struct ImGuiPopupData
{
ImGuiID PopupId; // Set on OpenPopup()
ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup()
ImGuiWindow* SourceWindow; // Set on OpenPopup() copy of NavWindow at the time of opening the popup
int OpenFrameCount; // Set on OpenPopup()
ImGuiID OpenParentId; // Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items)
ImVec2 OpenPopupPos; // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse)
ImVec2 OpenMousePos; // Set on OpenPopup(), copy of mouse position at the time of opening popup
ImGuiPopupData() { PopupId = 0; Window = SourceWindow = NULL; OpenFrameCount = -1; OpenParentId = 0; }
};
struct ImGuiColumnData
{
float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right)
float OffsetNormBeforeResize;
ImGuiColumnsFlags Flags; // Not exposed
ImRect ClipRect;
ImGuiColumnData() { OffsetNorm = OffsetNormBeforeResize = 0.0f; Flags = ImGuiColumnsFlags_None; }
};
struct ImGuiColumns
{
ImGuiID ID;
ImGuiColumnsFlags Flags;
bool IsFirstFrame;
bool IsBeingResized;
int Current;
int Count;
float OffMinX, OffMaxX; // Offsets from HostWorkRect.Min.x
float LineMinY, LineMaxY;
float HostCursorPosY; // Backup of CursorPos at the time of BeginColumns()
float HostCursorMaxPosX; // Backup of CursorMaxPos at the time of BeginColumns()
ImRect HostClipRect; // Backup of ClipRect at the time of BeginColumns()
ImRect HostWorkRect; // Backup of WorkRect at the time of BeginColumns()
ImVector<ImGuiColumnData> Columns;
ImDrawListSplitter Splitter;
ImGuiColumns() { Clear(); }
void Clear()
{
ID = 0;
Flags = ImGuiColumnsFlags_None;
IsFirstFrame = false;
IsBeingResized = false;
Current = 0;
Count = 1;
OffMinX = OffMaxX = 0.0f;
LineMinY = LineMaxY = 0.0f;
HostCursorPosY = 0.0f;
HostCursorMaxPosX = 0.0f;
Columns.clear();
}
};
// ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value.
#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN 12
#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX 512
#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD,_MAXERROR) ImClamp((int)((IM_PI * 2.0f) / ImAcos(((_RAD) - (_MAXERROR)) / (_RAD))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX)
// ImDrawList: You may set this to higher values (e.g. 2 or 3) to increase tessellation of fast rounded corners path.
#ifndef IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER
#define IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER 1
#endif
// Data shared between all ImDrawList instances
// You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure.
struct IMGUI_API ImDrawListSharedData
{
ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas
ImFont* Font; // Current/default font (optional, for simplified AddText overload)
float FontSize; // Current/default font size (optional, for simplified AddText overload)
float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo()
float CircleSegmentMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc
ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen()
ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards)
// [Internal] Lookup tables
ImVec2 ArcFastVtx[12 * IM_DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER]; // FIXME: Bake rounded corners fill/borders in atlas
ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius (array index + 1) before we calculate it dynamically (to avoid calculation overhead)
ImDrawListSharedData();
void SetCircleSegmentMaxError(float max_error);
};
struct ImDrawDataBuilder
{
ImVector<ImDrawList*> Layers[2]; // Global layers for: regular, tooltip
void Clear() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].resize(0); }
void ClearFreeMemory() { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].clear(); }
IMGUI_API void FlattenIntoSingleLayer();
};
struct ImGuiNavMoveResult
{
ImGuiWindow* Window; // Best candidate window
ImGuiID ID; // Best candidate ID
ImGuiID FocusScopeId; // Best candidate focus scope ID
float DistBox; // Best candidate box distance to current NavId
float DistCenter; // Best candidate center distance to current NavId
float DistAxial;
ImRect RectRel; // Best candidate bounding box in window relative space
ImGuiNavMoveResult() { Clear(); }
void Clear() { Window = NULL; ID = FocusScopeId = 0; DistBox = DistCenter = DistAxial = FLT_MAX; RectRel = ImRect(); }
};
enum ImGuiNextWindowDataFlags_
{
ImGuiNextWindowDataFlags_None = 0,
ImGuiNextWindowDataFlags_HasPos = 1 << 0,
ImGuiNextWindowDataFlags_HasSize = 1 << 1,
ImGuiNextWindowDataFlags_HasContentSize = 1 << 2,
ImGuiNextWindowDataFlags_HasCollapsed = 1 << 3,
ImGuiNextWindowDataFlags_HasSizeConstraint = 1 << 4,
ImGuiNextWindowDataFlags_HasFocus = 1 << 5,
ImGuiNextWindowDataFlags_HasBgAlpha = 1 << 6,
ImGuiNextWindowDataFlags_HasScroll = 1 << 7
};
// Storage for SetNexWindow** functions
struct ImGuiNextWindowData
{
ImGuiNextWindowDataFlags Flags;
ImGuiCond PosCond;
ImGuiCond SizeCond;
ImGuiCond CollapsedCond;
ImVec2 PosVal;
ImVec2 PosPivotVal;
ImVec2 SizeVal;
ImVec2 ContentSizeVal;
ImVec2 ScrollVal;
bool CollapsedVal;
ImRect SizeConstraintRect;
ImGuiSizeCallback SizeCallback;
void* SizeCallbackUserData;
float BgAlphaVal; // Override background alpha
ImVec2 MenuBarOffsetMinVal; // *Always on* This is not exposed publicly, so we don't clear it.
ImGuiNextWindowData() { memset(this, 0, sizeof(*this)); }
inline void ClearFlags() { Flags = ImGuiNextWindowDataFlags_None; }
};
enum ImGuiNextItemDataFlags_
{
ImGuiNextItemDataFlags_None = 0,
ImGuiNextItemDataFlags_HasWidth = 1 << 0,
ImGuiNextItemDataFlags_HasOpen = 1 << 1
};
struct ImGuiNextItemData
{
ImGuiNextItemDataFlags Flags;
float Width; // Set by SetNextItemWidth()
ImGuiID FocusScopeId; // Set by SetNextItemMultiSelectData() (!= 0 signify value has been set, so it's an alternate version of HasSelectionData, we don't use Flags for this because they are cleared too early. This is mostly used for debugging)
ImGuiCond OpenCond;
bool OpenVal; // Set by SetNextItemOpen()
ImGuiNextItemData() { memset(this, 0, sizeof(*this)); }
inline void ClearFlags() { Flags = ImGuiNextItemDataFlags_None; } // Also cleared manually by ItemAdd()!
};
//-----------------------------------------------------------------------------
// Tabs
//-----------------------------------------------------------------------------
struct ImGuiShrinkWidthItem
{
int Index;
float Width;
};
struct ImGuiPtrOrIndex
{
void* Ptr; // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool.
int Index; // Usually index in a main pool.
ImGuiPtrOrIndex(void* ptr) { Ptr = ptr; Index = -1; }
ImGuiPtrOrIndex(int index) { Ptr = NULL; Index = index; }
};
//-----------------------------------------------------------------------------
// Main Dear ImGui context
//-----------------------------------------------------------------------------
struct ImGuiContext
{
bool Initialized;
bool FontAtlasOwnedByContext; // IO.Fonts-> is owned by the ImGuiContext and will be destructed along with it.
ImGuiIO IO;
ImGuiStyle Style;
ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back()
float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window.
float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height.
ImDrawListSharedData DrawListSharedData;
double Time;
int FrameCount;
int FrameCountEnded;
int FrameCountRendered;
bool WithinFrameScope; // Set by NewFrame(), cleared by EndFrame()
bool WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed
bool WithinEndChild; // Set within EndChild()
bool TestEngineHookItems; // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log()
ImGuiID TestEngineHookIdInfo; // Will call test engine hooks: ImGuiTestEngineHook_IdInfo() from GetID()
void* TestEngine; // Test engine user data
// Windows state
ImVector<ImGuiWindow*> Windows; // Windows, sorted in display order, back to front
ImVector<ImGuiWindow*> WindowsFocusOrder; // Windows, sorted in focus order, back to front. (FIXME: We could only store root windows here! Need to sort out the Docking equivalent which is RootWindowDockStop and is unfortunately a little more dynamic)
ImVector<ImGuiWindow*> WindowsTempSortBuffer; // Temporary buffer used in EndFrame() to reorder windows so parents are kept before their child
ImVector<ImGuiWindow*> CurrentWindowStack;
ImGuiStorage WindowsById; // Map window's ImGuiID to ImGuiWindow*
int WindowsActiveCount; // Number of unique windows submitted by frame
ImGuiWindow* CurrentWindow; // Window being drawn into
ImGuiWindow* HoveredWindow; // Will catch mouse inputs
ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only)
ImGuiWindow* MovingWindow; // Track the window we clicked on (in order to preserve focus). The actually window that is moved is generally MovingWindow->RootWindow.
ImGuiWindow* WheelingWindow; // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window.
ImVec2 WheelingWindowRefMousePos;
float WheelingWindowTimer;
// Item/widgets state and tracking information
ImGuiID HoveredId; // Hovered widget
bool HoveredIdAllowOverlap;
ImGuiID HoveredIdPreviousFrame;
float HoveredIdTimer; // Measure contiguous hovering time
float HoveredIdNotActiveTimer; // Measure contiguous hovering time where the item has not been active
ImGuiID ActiveId; // Active widget
ImGuiID ActiveIdIsAlive; // Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame)
float ActiveIdTimer;
bool ActiveIdIsJustActivated; // Set at the time of activation for one frame
bool ActiveIdAllowOverlap; // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always)
bool ActiveIdHasBeenPressedBefore; // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch.
bool ActiveIdHasBeenEditedBefore; // Was the value associated to the widget Edited over the course of the Active state.
bool ActiveIdHasBeenEditedThisFrame;
ImU32 ActiveIdUsingNavDirMask; // Active widget will want to read those nav move requests (e.g. can activate a button and move away from it)
ImU32 ActiveIdUsingNavInputMask; // Active widget will want to read those nav inputs.
ImU64 ActiveIdUsingKeyInputMask; // Active widget will want to read those key inputs. When we grow the ImGuiKey enum we'll need to either to order the enum to make useful keys come first, either redesign this into e.g. a small array.
ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior)
ImGuiWindow* ActiveIdWindow;
ImGuiInputSource ActiveIdSource; // Activating with mouse or nav (gamepad/keyboard)
int ActiveIdMouseButton;
ImGuiID ActiveIdPreviousFrame;
bool ActiveIdPreviousFrameIsAlive;
bool ActiveIdPreviousFrameHasBeenEditedBefore;
ImGuiWindow* ActiveIdPreviousFrameWindow;
ImGuiID LastActiveId; // Store the last non-zero ActiveId, useful for animation.
float LastActiveIdTimer; // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation.
// Next window/item data
ImGuiNextWindowData NextWindowData; // Storage for SetNextWindow** functions
ImGuiNextItemData NextItemData; // Storage for SetNextItem** functions
// Shared stacks
ImVector<ImGuiColorMod> ColorModifiers; // Stack for PushStyleColor()/PopStyleColor()
ImVector<ImGuiStyleMod> StyleModifiers; // Stack for PushStyleVar()/PopStyleVar()
ImVector<ImFont*> FontStack; // Stack for PushFont()/PopFont()
ImVector<ImGuiPopupData>OpenPopupStack; // Which popups are open (persistent)
ImVector<ImGuiPopupData>BeginPopupStack; // Which level of BeginPopup() we are in (reset every frame)
// Gamepad/keyboard Navigation
ImGuiWindow* NavWindow; // Focused window for navigation. Could be called 'FocusWindow'
ImGuiID NavId; // Focused item for navigation
ImGuiID NavFocusScopeId;
ImGuiID NavActivateId; // ~~ (g.ActiveId == 0) && IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0, also set when calling ActivateItem()
ImGuiID NavActivateDownId; // ~~ IsNavInputDown(ImGuiNavInput_Activate) ? NavId : 0
ImGuiID NavActivatePressedId; // ~~ IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0
ImGuiID NavInputId; // ~~ IsNavInputPressed(ImGuiNavInput_Input) ? NavId : 0
ImGuiID NavJustTabbedId; // Just tabbed to this id.
ImGuiID NavJustMovedToId; // Just navigated to this id (result of a successfully MoveRequest).
ImGuiID NavJustMovedToFocusScopeId; // Just navigated to this focus scope id (result of a successfully MoveRequest).
ImGuiKeyModFlags NavJustMovedToKeyMods;
ImGuiID NavNextActivateId; // Set by ActivateItem(), queued until next frame.
ImGuiInputSource NavInputSource; // Keyboard or Gamepad mode? THIS WILL ONLY BE None or NavGamepad or NavKeyboard.
ImRect NavScoringRect; // Rectangle used for scoring, in screen space. Based of window->DC.NavRefRectRel[], modified for directional navigation scoring.
int NavScoringCount; // Metrics for debugging
ImGuiNavLayer NavLayer; // Layer we are navigating on. For now the system is hard-coded for 0=main contents and 1=menu/title bar, may expose layers later.
int NavIdTabCounter; // == NavWindow->DC.FocusIdxTabCounter at time of NavId processing
bool NavIdIsAlive; // Nav widget has been seen this frame ~~ NavRefRectRel is valid
bool NavMousePosDirty; // When set we will update mouse position if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) if set (NB: this not enabled by default)
bool NavDisableHighlight; // When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover)
bool NavDisableMouseHover; // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again.
bool NavAnyRequest; // ~~ NavMoveRequest || NavInitRequest
bool NavInitRequest; // Init request for appearing window to select first item
bool NavInitRequestFromMove;
ImGuiID NavInitResultId;
ImRect NavInitResultRectRel;
bool NavMoveFromClampedRefRect; // Set by manual scrolling, if we scroll to a point where NavId isn't visible we reset navigation from visible items
bool NavMoveRequest; // Move request for this frame
ImGuiNavMoveFlags NavMoveRequestFlags;
ImGuiNavForward NavMoveRequestForward; // None / ForwardQueued / ForwardActive (this is used to navigate sibling parent menus from a child menu)
ImGuiKeyModFlags NavMoveRequestKeyMods;
ImGuiDir NavMoveDir, NavMoveDirLast; // Direction of the move request (left/right/up/down), direction of the previous move request
ImGuiDir NavMoveClipDir; // FIXME-NAV: Describe the purpose of this better. Might want to rename?
ImGuiNavMoveResult NavMoveResultLocal; // Best move request candidate within NavWindow
ImGuiNavMoveResult NavMoveResultLocalVisibleSet; // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag)
ImGuiNavMoveResult NavMoveResultOther; // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag)
// Navigation: Windowing (CTRL+TAB, holding Menu button + directional pads to move/resize)
ImGuiWindow* NavWindowingTarget; // When selecting a window (holding Menu+FocusPrev/Next, or equivalent of CTRL-TAB) this window is temporarily displayed top-most.
ImGuiWindow* NavWindowingTargetAnim; // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f
ImGuiWindow* NavWindowingList;
float NavWindowingTimer;
float NavWindowingHighlightAlpha;
bool NavWindowingToggleLayer;
// Legacy Focus/Tabbing system (older than Nav, active even if Nav is disabled, misnamed. FIXME-NAV: This needs a redesign!)
ImGuiWindow* FocusRequestCurrWindow; //
ImGuiWindow* FocusRequestNextWindow; //
int FocusRequestCurrCounterRegular; // Any item being requested for focus, stored as an index (we on layout to be stable between the frame pressing TAB and the next frame, semi-ouch)
int FocusRequestCurrCounterTabStop; // Tab item being requested for focus, stored as an index
int FocusRequestNextCounterRegular; // Stored for next frame
int FocusRequestNextCounterTabStop; // "
bool FocusTabPressed; //
// Render
ImDrawData DrawData; // Main ImDrawData instance to pass render information to the user
ImDrawDataBuilder DrawDataBuilder;
float DimBgRatio; // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list)
ImDrawList BackgroundDrawList; // First draw list to be rendered.
ImDrawList ForegroundDrawList; // Last draw list to be rendered. This is where we the render software mouse cursor (if io.MouseDrawCursor is set) and most debug overlays.
ImGuiMouseCursor MouseCursor;
// Drag and Drop
bool DragDropActive;
bool DragDropWithinSource; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag source.
bool DragDropWithinTarget; // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag target.
ImGuiDragDropFlags DragDropSourceFlags;
int DragDropSourceFrameCount;
int DragDropMouseButton;
ImGuiPayload DragDropPayload;
ImRect DragDropTargetRect; // Store rectangle of current target candidate (we favor small targets when overlapping)
ImGuiID DragDropTargetId;
ImGuiDragDropFlags DragDropAcceptFlags;
float DragDropAcceptIdCurrRectSurface; // Target item surface (we resolve overlapping targets by prioritizing the smaller surface)
ImGuiID DragDropAcceptIdCurr; // Target item id (set at the time of accepting the payload)
ImGuiID DragDropAcceptIdPrev; // Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets)
int DragDropAcceptFrameCount; // Last time a target expressed a desire to accept the source
ImGuiID DragDropHoldJustPressedId; // Set when holding a payload just made ButtonBehavior() return a press.
ImVector<unsigned char> DragDropPayloadBufHeap; // We don't expose the ImVector<> directly, ImGuiPayload only holds pointer+size
unsigned char DragDropPayloadBufLocal[16]; // Local buffer for small payloads
// Tab bars
ImGuiTabBar* CurrentTabBar;
ImPool<ImGuiTabBar> TabBars;
ImVector<ImGuiPtrOrIndex> CurrentTabBarStack;
ImVector<ImGuiShrinkWidthItem> ShrinkWidthBuffer;
// Widget state
ImVec2 LastValidMousePos;
ImGuiInputTextState InputTextState;
ImFont InputTextPasswordFont;
ImGuiID TempInputId; // Temporary text input when CTRL+clicking on a slider, etc.
ImGuiColorEditFlags ColorEditOptions; // Store user options for color edit widgets
float ColorEditLastHue; // Backup of last Hue associated to LastColor[3], so we can restore Hue in lossy RGB<>HSV round trips
float ColorEditLastSat; // Backup of last Saturation associated to LastColor[3], so we can restore Saturation in lossy RGB<>HSV round trips
float ColorEditLastColor[3];
ImVec4 ColorPickerRef; // Initial/reference color at the time of opening the color picker.
bool DragCurrentAccumDirty;
float DragCurrentAccum; // Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings
float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio
float ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage?
int TooltipOverrideCount;
ImVector<char> ClipboardHandlerData; // If no custom clipboard handler is defined
ImVector<ImGuiID> MenusIdSubmittedThisFrame; // A list of menu IDs that were rendered at least once
// Platform support
ImVec2 PlatformImePos; // Cursor position request & last passed to the OS Input Method Editor
ImVec2 PlatformImeLastPos;
// Settings
bool SettingsLoaded;
float SettingsDirtyTimer; // Save .ini Settings to memory when time reaches zero
ImGuiTextBuffer SettingsIniData; // In memory .ini settings
ImVector<ImGuiSettingsHandler> SettingsHandlers; // List of .ini settings handlers
ImChunkStream<ImGuiWindowSettings> SettingsWindows; // ImGuiWindow .ini settings entries
// Capture/Logging
bool LogEnabled;
ImGuiLogType LogType;
ImFileHandle LogFile; // If != NULL log to stdout/ file
ImGuiTextBuffer LogBuffer; // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators.
float LogLinePosY;
bool LogLineFirstItem;
int LogDepthRef;
int LogDepthToExpand;
int LogDepthToExpandDefault; // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call.
// Debug Tools
bool DebugItemPickerActive;
ImGuiID DebugItemPickerBreakId; // Will call IM_DEBUG_BREAK() when encountering this id
// Misc
float FramerateSecPerFrame[120]; // Calculate estimate of framerate for user over the last 2 seconds.
int FramerateSecPerFrameIdx;
float FramerateSecPerFrameAccum;
int WantCaptureMouseNextFrame; // Explicit capture via CaptureKeyboardFromApp()/CaptureMouseFromApp() sets those flags
int WantCaptureKeyboardNextFrame;
int WantTextInputNextFrame;
char TempBuffer[1024 * 3 + 1]; // Temporary text buffer
ImGuiContext(ImFontAtlas* shared_font_atlas) : BackgroundDrawList(&DrawListSharedData), ForegroundDrawList(&DrawListSharedData)
{
Initialized = false;
FontAtlasOwnedByContext = shared_font_atlas ? false : true;
Font = NULL;
FontSize = FontBaseSize = 0.0f;
IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();
Time = 0.0f;
FrameCount = 0;
FrameCountEnded = FrameCountRendered = -1;
WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false;
TestEngineHookItems = false;
TestEngineHookIdInfo = 0;
TestEngine = NULL;
WindowsActiveCount = 0;
CurrentWindow = NULL;
HoveredWindow = NULL;
HoveredRootWindow = NULL;
MovingWindow = NULL;
WheelingWindow = NULL;
WheelingWindowTimer = 0.0f;
HoveredId = 0;
HoveredIdAllowOverlap = false;
HoveredIdPreviousFrame = 0;
HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;
ActiveId = 0;
ActiveIdIsAlive = 0;
ActiveIdTimer = 0.0f;
ActiveIdIsJustActivated = false;
ActiveIdAllowOverlap = false;
ActiveIdHasBeenPressedBefore = false;
ActiveIdHasBeenEditedBefore = false;
ActiveIdHasBeenEditedThisFrame = false;
ActiveIdUsingNavDirMask = 0x00;
ActiveIdUsingNavInputMask = 0x00;
ActiveIdUsingKeyInputMask = 0x00;
ActiveIdClickOffset = ImVec2(-1, -1);
ActiveIdWindow = NULL;
ActiveIdSource = ImGuiInputSource_None;
ActiveIdMouseButton = 0;
ActiveIdPreviousFrame = 0;
ActiveIdPreviousFrameIsAlive = false;
ActiveIdPreviousFrameHasBeenEditedBefore = false;
ActiveIdPreviousFrameWindow = NULL;
LastActiveId = 0;
LastActiveIdTimer = 0.0f;
NavWindow = NULL;
NavId = NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavInputId = 0;
NavJustTabbedId = NavJustMovedToId = NavJustMovedToFocusScopeId = NavNextActivateId = 0;
NavJustMovedToKeyMods = ImGuiKeyModFlags_None;
NavInputSource = ImGuiInputSource_None;
NavScoringRect = ImRect();
NavScoringCount = 0;
NavLayer = ImGuiNavLayer_Main;
NavIdTabCounter = INT_MAX;
NavIdIsAlive = false;
NavMousePosDirty = false;
NavDisableHighlight = true;
NavDisableMouseHover = false;
NavAnyRequest = false;
NavInitRequest = false;
NavInitRequestFromMove = false;
NavInitResultId = 0;
NavMoveFromClampedRefRect = false;
NavMoveRequest = false;
NavMoveRequestFlags = ImGuiNavMoveFlags_None;
NavMoveRequestForward = ImGuiNavForward_None;
NavMoveRequestKeyMods = ImGuiKeyModFlags_None;
NavMoveDir = NavMoveDirLast = NavMoveClipDir = ImGuiDir_None;
NavWindowingTarget = NavWindowingTargetAnim = NavWindowingList = NULL;
NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;
NavWindowingToggleLayer = false;
FocusRequestCurrWindow = FocusRequestNextWindow = NULL;
FocusRequestCurrCounterRegular = FocusRequestCurrCounterTabStop = INT_MAX;
FocusRequestNextCounterRegular = FocusRequestNextCounterTabStop = INT_MAX;
FocusTabPressed = false;
DimBgRatio = 0.0f;
BackgroundDrawList._OwnerName = "##Background"; // Give it a name for debugging
ForegroundDrawList._OwnerName = "##Foreground"; // Give it a name for debugging
MouseCursor = ImGuiMouseCursor_Arrow;
DragDropActive = DragDropWithinSource = DragDropWithinTarget = false;
DragDropSourceFlags = ImGuiDragDropFlags_None;
DragDropSourceFrameCount = -1;
DragDropMouseButton = -1;
DragDropTargetId = 0;
DragDropAcceptFlags = ImGuiDragDropFlags_None;
DragDropAcceptIdCurrRectSurface = 0.0f;
DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;
DragDropAcceptFrameCount = -1;
DragDropHoldJustPressedId = 0;
memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));
CurrentTabBar = NULL;
LastValidMousePos = ImVec2(0.0f, 0.0f);
TempInputId = 0;
ColorEditOptions = ImGuiColorEditFlags__OptionsDefault;
ColorEditLastHue = ColorEditLastSat = 0.0f;
ColorEditLastColor[0] = ColorEditLastColor[1] = ColorEditLastColor[2] = FLT_MAX;
DragCurrentAccumDirty = false;
DragCurrentAccum = 0.0f;
DragSpeedDefaultRatio = 1.0f / 100.0f;
ScrollbarClickDeltaToGrabCenter = 0.0f;
TooltipOverrideCount = 0;
PlatformImePos = PlatformImeLastPos = ImVec2(FLT_MAX, FLT_MAX);
SettingsLoaded = false;
SettingsDirtyTimer = 0.0f;
LogEnabled = false;
LogType = ImGuiLogType_None;
LogFile = NULL;
LogLinePosY = FLT_MAX;
LogLineFirstItem = false;
LogDepthRef = 0;
LogDepthToExpand = LogDepthToExpandDefault = 2;
DebugItemPickerActive = false;
DebugItemPickerBreakId = 0;
memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));
FramerateSecPerFrameIdx = 0;
FramerateSecPerFrameAccum = 0.0f;
WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;
memset(TempBuffer, 0, sizeof(TempBuffer));
}
};
//-----------------------------------------------------------------------------
// ImGuiWindow
//-----------------------------------------------------------------------------
// Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow.
// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered.
struct IMGUI_API ImGuiWindowTempData
{
// Layout
ImVec2 CursorPos; // Current emitting position, in absolute coordinates.
ImVec2 CursorPosPrevLine;
ImVec2 CursorStartPos; // Initial position after Begin(), generally ~ window position + WindowPadding.
ImVec2 CursorMaxPos; // Used to implicitly calculate the size of our contents, always growing during the frame. Used to calculate window->ContentSize at the beginning of next frame
ImVec2 CurrLineSize;
ImVec2 PrevLineSize;
float CurrLineTextBaseOffset; // Baseline offset (0.0f by default on a new line, generally == style.FramePadding.y when a framed item has been added).
float PrevLineTextBaseOffset;
ImVec1 Indent; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.)
ImVec1 ColumnsOffset; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API.
ImVec1 GroupOffset;
// Last item status
ImGuiID LastItemId; // ID for last item
ImGuiItemStatusFlags LastItemStatusFlags; // Status flags for last item (see ImGuiItemStatusFlags_)
ImRect LastItemRect; // Interaction rect for last item
ImRect LastItemDisplayRect; // End-user display rect for last item (only valid if LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect)
// Keyboard/Gamepad navigation
ImGuiNavLayer NavLayerCurrent; // Current layer, 0..31 (we currently only use 0..1)
int NavLayerCurrentMask; // = (1 << NavLayerCurrent) used by ItemAdd prior to clipping.
int NavLayerActiveMask; // Which layer have been written to (result from previous frame)
int NavLayerActiveMaskNext; // Which layer have been written to (buffer for current frame)
ImGuiID NavFocusScopeIdCurrent; // Current focus scope ID while appending
bool NavHideHighlightOneFrame;
bool NavHasScroll; // Set when scrolling can be used (ScrollMax > 0.0f)
// Miscellaneous
bool MenuBarAppending; // FIXME: Remove this
ImVec2 MenuBarOffset; // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs.
ImGuiMenuColumns MenuColumns; // Simplified columns storage for menu items measurement
int TreeDepth; // Current tree depth.
ImU32 TreeJumpToParentOnPopMask; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31.. Could be turned into a ImU64 if necessary.
ImVector<ImGuiWindow*> ChildWindows;
ImGuiStorage* StateStorage; // Current persistent per-window storage (store e.g. tree node open/close state)
ImGuiColumns* CurrentColumns; // Current columns set
ImGuiLayoutType LayoutType;
ImGuiLayoutType ParentLayoutType; // Layout type of parent window at the time of Begin()
int FocusCounterRegular; // (Legacy Focus/Tabbing system) Sequential counter, start at -1 and increase as assigned via FocusableItemRegister() (FIXME-NAV: Needs redesign)
int FocusCounterTabStop; // (Legacy Focus/Tabbing system) Same, but only count widgets which you can Tab through.
// Local parameters stacks
// We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings.
ImGuiItemFlags ItemFlags; // == ItemFlagsStack.back() [empty == ImGuiItemFlags_Default]
float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window
float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f]
ImVector<ImGuiItemFlags>ItemFlagsStack;
ImVector<float> ItemWidthStack;
ImVector<float> TextWrapPosStack;
ImVector<ImGuiGroupData>GroupStack;
short StackSizesBackup[6]; // Store size of various stacks for asserting
ImGuiWindowTempData()
{
CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f);
CurrLineSize = PrevLineSize = ImVec2(0.0f, 0.0f);
CurrLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f;
Indent = ImVec1(0.0f);
ColumnsOffset = ImVec1(0.0f);
GroupOffset = ImVec1(0.0f);
LastItemId = 0;
LastItemStatusFlags = ImGuiItemStatusFlags_None;
LastItemRect = LastItemDisplayRect = ImRect();
NavLayerActiveMask = NavLayerActiveMaskNext = 0x00;
NavLayerCurrent = ImGuiNavLayer_Main;
NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
NavFocusScopeIdCurrent = 0;
NavHideHighlightOneFrame = false;
NavHasScroll = false;
MenuBarAppending = false;
MenuBarOffset = ImVec2(0.0f, 0.0f);
TreeDepth = 0;
TreeJumpToParentOnPopMask = 0x00;
StateStorage = NULL;
CurrentColumns = NULL;
LayoutType = ParentLayoutType = ImGuiLayoutType_Vertical;
FocusCounterRegular = FocusCounterTabStop = -1;
ItemFlags = ImGuiItemFlags_Default_;
ItemWidth = 0.0f;
TextWrapPos = -1.0f;
memset(StackSizesBackup, 0, sizeof(StackSizesBackup));
}
};
// Storage for one window
struct IMGUI_API ImGuiWindow
{
char* Name; // Window name, owned by the window.
ImGuiID ID; // == ImHashStr(Name)
ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_
ImVec2 Pos; // Position (always rounded-up to nearest pixel)
ImVec2 Size; // Current size (==SizeFull or collapsed title bar size)
ImVec2 SizeFull; // Size when non collapsed
ImVec2 ContentSize; // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding.
ImVec2 ContentSizeExplicit; // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize().
ImVec2 WindowPadding; // Window padding at the time of Begin().
float WindowRounding; // Window rounding at the time of Begin().
float WindowBorderSize; // Window border size at the time of Begin().
int NameBufLen; // Size of buffer storing Name. May be larger than strlen(Name)!
ImGuiID MoveId; // == window->GetID("#MOVE")
ImGuiID ChildId; // ID of corresponding item in parent window (for navigation to return from child window to parent window)
ImVec2 Scroll;
ImVec2 ScrollMax;
ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change)
ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered
ImVec2 ScrollbarSizes; // Size taken by each scrollbars on their smaller axis. Pay attention! ScrollbarSizes.x == width of the vertical scrollbar, ScrollbarSizes.y = height of the horizontal scrollbar.
bool ScrollbarX, ScrollbarY; // Are scrollbars visible?
bool Active; // Set to true on Begin(), unless Collapsed
bool WasActive;
bool WriteAccessed; // Set to true when any widget access the current window
bool Collapsed; // Set when collapsing window to become only title-bar
bool WantCollapseToggle;
bool SkipItems; // Set when items can safely be all clipped (e.g. window not visible or collapsed)
bool Appearing; // Set during the frame where the window is appearing (or re-appearing)
bool Hidden; // Do not display (== (HiddenFrames*** > 0))
bool IsFallbackWindow; // Set on the "Debug##Default" window.
bool HasCloseButton; // Set when the window has a close button (p_open != NULL)
signed char ResizeBorderHeld; // Current border being held for resize (-1: none, otherwise 0-3)
short BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs)
short BeginOrderWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0.
short BeginOrderWithinContext; // Order within entire imgui context. This is mostly used for debugging submission order related issues.
ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling)
ImS8 AutoFitFramesX, AutoFitFramesY;
ImS8 AutoFitChildAxises;
bool AutoFitOnlyGrows;
ImGuiDir AutoPosLastDirection;
int HiddenFramesCanSkipItems; // Hide the window for N frames
int HiddenFramesCannotSkipItems; // Hide the window for N frames while allowing items to be submitted so we can measure their size
ImGuiCond SetWindowPosAllowFlags; // store acceptable condition flags for SetNextWindowPos() use.
ImGuiCond SetWindowSizeAllowFlags; // store acceptable condition flags for SetNextWindowSize() use.
ImGuiCond SetWindowCollapsedAllowFlags; // store acceptable condition flags for SetNextWindowCollapsed() use.
ImVec2 SetWindowPosVal; // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size)
ImVec2 SetWindowPosPivot; // store window pivot for positioning. ImVec2(0,0) when positioning from top-left corner; ImVec2(0.5f,0.5f) for centering; ImVec2(1,1) for bottom right.
ImVector<ImGuiID> IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure)
ImGuiWindowTempData DC; // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name.
// The best way to understand what those rectangles are is to use the 'Metrics -> Tools -> Show windows rectangles' viewer.
// The main 'OuterRect', omitted as a field, is window->Rect().
ImRect OuterRectClipped; // == Window->Rect() just after setup in Begin(). == window->Rect() for root window.
ImRect InnerRect; // Inner rectangle (omit title bar, menu bar, scroll bar)
ImRect InnerClipRect; // == InnerRect shrunk by WindowPadding*0.5f on each side, clipped within viewport or parent clip rect.
ImRect WorkRect; // Cover the whole scrolling region, shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward).
ImRect ClipRect; // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back().
ImRect ContentRegionRect; // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on.
int LastFrameActive; // Last frame number the window was Active.
float LastTimeActive; // Last timestamp the window was Active (using float as we don't need high precision there)
float ItemWidthDefault;
ImGuiStorage StateStorage;
ImVector<ImGuiColumns> ColumnsStorage;
float FontWindowScale; // User scale multiplier per-window, via SetWindowFontScale()
int SettingsOffset; // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back)
ImDrawList* DrawList; // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer)
ImDrawList DrawListInst;
ImGuiWindow* ParentWindow; // If we are a child _or_ popup window, this is pointing to our parent. Otherwise NULL.
ImGuiWindow* RootWindow; // Point to ourself or first ancestor that is not a child window.
ImGuiWindow* RootWindowForTitleBarHighlight; // Point to ourself or first ancestor which will display TitleBgActive color when this window is active.
ImGuiWindow* RootWindowForNav; // Point to ourself or first ancestor which doesn't have the NavFlattened flag.
ImGuiWindow* NavLastChildNavWindow; // When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.)
ImGuiID NavLastIds[ImGuiNavLayer_COUNT]; // Last known NavId for this window, per layer (0/1)
ImRect NavRectRel[ImGuiNavLayer_COUNT]; // Reference rectangle, in window relative space
bool MemoryCompacted;
int MemoryDrawListIdxCapacity;
int MemoryDrawListVtxCapacity;
public:
ImGuiWindow(ImGuiContext* context, const char* name);
~ImGuiWindow();
ImGuiID GetID(const char* str, const char* str_end = NULL);
ImGuiID GetID(const void* ptr);
ImGuiID GetID(int n);
ImGuiID GetIDNoKeepAlive(const char* str, const char* str_end = NULL);
ImGuiID GetIDNoKeepAlive(const void* ptr);
ImGuiID GetIDNoKeepAlive(int n);
ImGuiID GetIDFromRectangle(const ImRect& r_abs);
// We don't use g.FontSize because the window may be != g.CurrentWidow.
ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); }
float CalcFontSize() const { ImGuiContext& g = *GImGui; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; }
float TitleBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; }
ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); }
float MenuBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + g.Style.FramePadding.y * 2.0f : 0.0f; }
ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); }
};
// Backup and restore just enough data to be able to use IsItemHovered() on item A after another B in the same window has overwritten the data.
struct ImGuiItemHoveredDataBackup
{
ImGuiID LastItemId;
ImGuiItemStatusFlags LastItemStatusFlags;
ImRect LastItemRect;
ImRect LastItemDisplayRect;
ImGuiItemHoveredDataBackup() { Backup(); }
void Backup() { ImGuiWindow* window = GImGui->CurrentWindow; LastItemId = window->DC.LastItemId; LastItemStatusFlags = window->DC.LastItemStatusFlags; LastItemRect = window->DC.LastItemRect; LastItemDisplayRect = window->DC.LastItemDisplayRect; }
void Restore() const { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.LastItemId = LastItemId; window->DC.LastItemStatusFlags = LastItemStatusFlags; window->DC.LastItemRect = LastItemRect; window->DC.LastItemDisplayRect = LastItemDisplayRect; }
};
//-----------------------------------------------------------------------------
// Tab bar, tab item
//-----------------------------------------------------------------------------
// Extend ImGuiTabBarFlags_
enum ImGuiTabBarFlagsPrivate_
{
ImGuiTabBarFlags_DockNode = 1 << 20, // Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around]
ImGuiTabBarFlags_IsFocused = 1 << 21,
ImGuiTabBarFlags_SaveSettings = 1 << 22 // FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs
};
// Extend ImGuiTabItemFlags_
enum ImGuiTabItemFlagsPrivate_
{
ImGuiTabItemFlags_NoCloseButton = 1 << 20 // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout)
};
// Storage for one active tab item (sizeof() 26~32 bytes)
struct ImGuiTabItem
{
ImGuiID ID;
ImGuiTabItemFlags Flags;
int LastFrameVisible;
int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance
int NameOffset; // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames
float Offset; // Position relative to beginning of tab
float Width; // Width currently displayed
float ContentWidth; // Width of actual contents, stored during BeginTabItem() call
ImGuiTabItem() { ID = 0; Flags = ImGuiTabItemFlags_None; LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; Offset = Width = ContentWidth = 0.0f; }
};
// Storage for a tab bar (sizeof() 92~96 bytes)
struct ImGuiTabBar
{
ImVector<ImGuiTabItem> Tabs;
ImGuiID ID; // Zero for tab-bars used by docking
ImGuiID SelectedTabId; // Selected tab/window
ImGuiID NextSelectedTabId;
ImGuiID VisibleTabId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for CTRL+TAB preview)
int CurrFrameVisible;
int PrevFrameVisible;
ImRect BarRect;
float LastTabContentHeight; // Record the height of contents submitted below the tab bar
float OffsetMax; // Distance from BarRect.Min.x, locked during layout
float OffsetMaxIdeal; // Ideal offset if all tabs were visible and not clipped
float OffsetNextTab; // Distance from BarRect.Min.x, incremented with each BeginTabItem() call, not used if ImGuiTabBarFlags_Reorderable if set.
float ScrollingAnim;
float ScrollingTarget;
float ScrollingTargetDistToVisibility;
float ScrollingSpeed;
ImGuiTabBarFlags Flags;
ImGuiID ReorderRequestTabId;
ImS8 ReorderRequestDir;
bool WantLayout;
bool VisibleTabWasSubmitted;
short LastTabItemIdx; // For BeginTabItem()/EndTabItem()
ImVec2 FramePadding; // style.FramePadding locked at the time of BeginTabBar()
ImGuiTextBuffer TabsNames; // For non-docking tab bar we re-append names in a contiguous buffer.
ImGuiTabBar();
int GetTabOrder(const ImGuiTabItem* tab) const { return Tabs.index_from_ptr(tab); }
const char* GetTabName(const ImGuiTabItem* tab) const
{
IM_ASSERT(tab->NameOffset != -1 && tab->NameOffset < TabsNames.Buf.Size);
return TabsNames.Buf.Data + tab->NameOffset;
}
};
//-----------------------------------------------------------------------------
// Internal API
// No guarantee of forward compatibility here.
//-----------------------------------------------------------------------------
namespace ImGui
{
// Windows
// We should always have a CurrentWindow in the stack (there is an implicit "Debug" window)
// If this ever crash because g.CurrentWindow is NULL it means that either
// - ImGui::NewFrame() has never been called, which is illegal.
// - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal.
inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; }
inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; }
IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id);
IMGUI_API ImGuiWindow* FindWindowByName(const char* name);
IMGUI_API void UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window);
IMGUI_API ImVec2 CalcWindowExpectedSize(ImGuiWindow* window);
IMGUI_API bool IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent);
IMGUI_API bool IsWindowNavFocusable(ImGuiWindow* window);
IMGUI_API ImRect GetWindowAllowedExtentRect(ImGuiWindow* window);
IMGUI_API void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0);
IMGUI_API void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0);
IMGUI_API void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0);
// Windows: Display Order and Focus Order
IMGUI_API void FocusWindow(ImGuiWindow* window);
IMGUI_API void FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window);
IMGUI_API void BringWindowToFocusFront(ImGuiWindow* window);
IMGUI_API void BringWindowToDisplayFront(ImGuiWindow* window);
IMGUI_API void BringWindowToDisplayBack(ImGuiWindow* window);
// Fonts, drawing
IMGUI_API void SetCurrentFont(ImFont* font);
inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; }
inline ImDrawList* GetForegroundDrawList(ImGuiWindow* window) { IM_UNUSED(window); ImGuiContext& g = *GImGui; return &g.ForegroundDrawList; } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches.
// Init
IMGUI_API void Initialize(ImGuiContext* context);
IMGUI_API void Shutdown(ImGuiContext* context); // Since 1.60 this is a _private_ function. You can call DestroyContext() to destroy the context created by CreateContext().
// NewFrame
IMGUI_API void UpdateHoveredWindowAndCaptureFlags();
IMGUI_API void StartMouseMovingWindow(ImGuiWindow* window);
IMGUI_API void UpdateMouseMovingWindowNewFrame();
IMGUI_API void UpdateMouseMovingWindowEndFrame();
// Settings
IMGUI_API void MarkIniSettingsDirty();
IMGUI_API void MarkIniSettingsDirty(ImGuiWindow* window);
IMGUI_API ImGuiWindowSettings* CreateNewWindowSettings(const char* name);
IMGUI_API ImGuiWindowSettings* FindWindowSettings(ImGuiID id);
IMGUI_API ImGuiWindowSettings* FindOrCreateWindowSettings(const char* name);
IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name);
// Scrolling
IMGUI_API void SetNextWindowScroll(const ImVec2& scroll); // Use -1.0f on one axis to leave as-is
IMGUI_API void SetScrollX(ImGuiWindow* window, float new_scroll_x);
IMGUI_API void SetScrollY(ImGuiWindow* window, float new_scroll_y);
IMGUI_API void SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio = 0.5f);
IMGUI_API void SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio = 0.5f);
IMGUI_API ImVec2 ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect);
// Basic Accessors
inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; }
inline ImGuiItemStatusFlags GetItemStatusFlags() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemStatusFlags; }
inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; }
inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; }
IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window);
IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow* window);
IMGUI_API void ClearActiveID();
IMGUI_API ImGuiID GetHoveredID();
IMGUI_API void SetHoveredID(ImGuiID id);
IMGUI_API void KeepAliveID(ImGuiID id);
IMGUI_API void MarkItemEdited(ImGuiID id); // Mark data associated to given item as "edited", used by IsItemDeactivatedAfterEdit() function.
IMGUI_API void PushOverrideID(ImGuiID id); // Push given value at the top of the ID stack (whereas PushID combines old and new hashes)
// Basic Helpers for widget code
IMGUI_API void ItemSize(const ImVec2& size, float text_baseline_y = -1.0f);
IMGUI_API void ItemSize(const ImRect& bb, float text_baseline_y = -1.0f);
IMGUI_API bool ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb = NULL);
IMGUI_API bool ItemHoverable(const ImRect& bb, ImGuiID id);
IMGUI_API bool IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged);
IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id); // Return true if focus is requested
IMGUI_API void FocusableItemUnregister(ImGuiWindow* window);
IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_w, float default_h);
IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x);
IMGUI_API void PushMultiItemsWidths(int components, float width_full);
IMGUI_API void PushItemFlag(ImGuiItemFlags option, bool enabled);
IMGUI_API void PopItemFlag();
IMGUI_API bool IsItemToggledSelection(); // Was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly)
IMGUI_API ImVec2 GetContentRegionMaxAbs();
IMGUI_API void ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess);
// Logging/Capture
IMGUI_API void LogBegin(ImGuiLogType type, int auto_open_depth); // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name.
IMGUI_API void LogToBuffer(int auto_open_depth = -1); // Start logging/capturing to internal buffer
// Popups, Modals, Tooltips
IMGUI_API bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags);
IMGUI_API void OpenPopupEx(ImGuiID id);
IMGUI_API void ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup);
IMGUI_API void ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup);
IMGUI_API bool IsPopupOpen(ImGuiID id); // Test for id within current popup stack level (currently begin-ed into); this doesn't scan the whole popup stack!
IMGUI_API bool BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags);
IMGUI_API void BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags);
IMGUI_API ImGuiWindow* GetTopMostPopupModal();
IMGUI_API ImVec2 FindBestWindowPosForPopup(ImGuiWindow* window);
IMGUI_API ImVec2 FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default);
// Navigation
IMGUI_API void NavInitWindow(ImGuiWindow* window, bool force_reinit);
IMGUI_API bool NavMoveRequestButNoResultYet();
IMGUI_API void NavMoveRequestCancel();
IMGUI_API void NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags);
IMGUI_API void NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags);
IMGUI_API float GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode);
IMGUI_API ImVec2 GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor = 0.0f, float fast_factor = 0.0f);
IMGUI_API int CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate);
IMGUI_API void ActivateItem(ImGuiID id); // Remotely activate a button, checkbox, tree node etc. given its unique ID. activation is queued and processed on the next frame when the item is encountered again.
IMGUI_API void SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id);
IMGUI_API void SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel);
// Focus scope (WIP)
IMGUI_API void PushFocusScope(ImGuiID id); // Note: this is storing in same stack as IDStack, so Push/Pop mismatch will be reported there.
IMGUI_API void PopFocusScope();
inline ImGuiID GetFocusScopeID() { ImGuiContext& g = *GImGui; return g.NavFocusScopeId; }
// Inputs
// FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions.
inline bool IsActiveIdUsingNavDir(ImGuiDir dir) { ImGuiContext& g = *GImGui; return (g.ActiveIdUsingNavDirMask & (1 << dir)) != 0; }
inline bool IsActiveIdUsingNavInput(ImGuiNavInput input) { ImGuiContext& g = *GImGui; return (g.ActiveIdUsingNavInputMask & (1 << input)) != 0; }
inline bool IsActiveIdUsingKey(ImGuiKey key) { ImGuiContext& g = *GImGui; IM_ASSERT(key < 64); return (g.ActiveIdUsingKeyInputMask & ((ImU64)1 << key)) != 0; }
IMGUI_API bool IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold = -1.0f);
inline bool IsKeyPressedMap(ImGuiKey key, bool repeat = true) { ImGuiContext& g = *GImGui; const int key_index = g.IO.KeyMap[key]; return (key_index >= 0) ? IsKeyPressed(key_index, repeat) : false; }
inline bool IsNavInputDown(ImGuiNavInput n) { ImGuiContext& g = *GImGui; return g.IO.NavInputs[n] > 0.0f; }
inline bool IsNavInputTest(ImGuiNavInput n, ImGuiInputReadMode rm) { return (GetNavInputAmount(n, rm) > 0.0f); }
IMGUI_API ImGuiKeyModFlags GetMergedKeyModFlags();
// Drag and Drop
IMGUI_API bool BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id);
IMGUI_API void ClearDragDrop();
IMGUI_API bool IsDragDropPayloadBeingAccepted();
// Internal Columns API (this is not exposed because we will encourage transitioning to the Tables api)
IMGUI_API void BeginColumns(const char* str_id, int count, ImGuiColumnsFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns().
IMGUI_API void EndColumns(); // close columns
IMGUI_API void PushColumnClipRect(int column_index);
IMGUI_API void PushColumnsBackground();
IMGUI_API void PopColumnsBackground();
IMGUI_API ImGuiID GetColumnsID(const char* str_id, int count);
IMGUI_API ImGuiColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id);
IMGUI_API float GetColumnOffsetFromNorm(const ImGuiColumns* columns, float offset_norm);
IMGUI_API float GetColumnNormFromOffset(const ImGuiColumns* columns, float offset);
// Tab Bars
IMGUI_API bool BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags);
IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id);
IMGUI_API void TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id);
IMGUI_API void TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab);
IMGUI_API void TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir);
IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags);
IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button);
IMGUI_API void TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col);
IMGUI_API bool TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible);
// Render helpers
// AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT.
// NB: All position are in absolute pixels coordinates (we are never using window coordinates internally)
IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true);
IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width);
IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL);
IMGUI_API void RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL);
IMGUI_API void RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known);
IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f);
IMGUI_API void RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f);
IMGUI_API void RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, int rounding_corners_flags = ~0);
IMGUI_API void RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_TypeDefault); // Navigation highlight
IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text.
IMGUI_API void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL);
// Render helpers (those functions don't access any ImGui state!)
IMGUI_API void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f);
IMGUI_API void RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col);
IMGUI_API void RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz);
IMGUI_API void RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow);
IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col);
IMGUI_API void RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding);
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
// [1.71: 2019/06/07: Updating prototypes of some of the internal functions. Leaving those for reference for a short while]
inline void RenderArrow(ImVec2 pos, ImGuiDir dir, float scale = 1.0f) { ImGuiWindow* window = GetCurrentWindow(); RenderArrow(window->DrawList, pos, GetColorU32(ImGuiCol_Text), dir, scale); }
inline void RenderBullet(ImVec2 pos) { ImGuiWindow* window = GetCurrentWindow(); RenderBullet(window->DrawList, pos, GetColorU32(ImGuiCol_Text)); }
#endif
// Widgets
IMGUI_API void TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0);
IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0);
IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos);
IMGUI_API bool CollapseButton(ImGuiID id, const ImVec2& pos);
IMGUI_API bool ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0);
IMGUI_API void Scrollbar(ImGuiAxis axis);
IMGUI_API bool ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* p_scroll_v, float avail_v, float contents_v, ImDrawCornerFlags rounding_corners);
IMGUI_API ImRect GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis);
IMGUI_API ImGuiID GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis);
IMGUI_API ImGuiID GetWindowResizeID(ImGuiWindow* window, int n); // 0..3: corners, 4..7: borders
IMGUI_API void SeparatorEx(ImGuiSeparatorFlags flags);
// Widgets low-level behaviors
IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0);
IMGUI_API bool DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags);
IMGUI_API bool SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb);
IMGUI_API bool SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f);
IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL);
IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextItemOpen() data, if any. May return true when logging
IMGUI_API void TreePushOverrideID(ImGuiID id);
// Template functions are instantiated in imgui_widgets.cpp for a finite number of types.
// To use them externally (for custom widget) you may need an "extern template" statement in your code in order to link to existing instances and silence Clang warnings (see #2036).
// e.g. " extern template IMGUI_API float RoundScalarWithFormatT<float, float>(const char* format, ImGuiDataType data_type, float v); "
template<typename T, typename SIGNED_T, typename FLOAT_T> IMGUI_API bool DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, float power, ImGuiDragFlags flags);
template<typename T, typename SIGNED_T, typename FLOAT_T> IMGUI_API bool SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb);
template<typename T, typename FLOAT_T> IMGUI_API float SliderCalcRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, float power, float linear_zero_pos);
template<typename T, typename SIGNED_T> IMGUI_API T RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v);
// Data type helpers
IMGUI_API const ImGuiDataTypeInfo* DataTypeGetInfo(ImGuiDataType data_type);
IMGUI_API int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format);
IMGUI_API void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2);
IMGUI_API bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* p_data, const char* format);
// InputText
IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
IMGUI_API bool TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags);
IMGUI_API bool TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format);
inline bool TempInputIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); }
inline ImGuiInputTextState* GetInputTextState(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active
// Color
IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags);
IMGUI_API void ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags);
IMGUI_API void ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags);
// Plot
IMGUI_API int PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size);
// Shade functions (write over already created vertices)
IMGUI_API void ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1);
IMGUI_API void ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp);
// Garbage collection
IMGUI_API void GcCompactTransientWindowBuffers(ImGuiWindow* window);
IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow* window);
// Debug Tools
inline void DebugDrawItemRect(ImU32 col = IM_COL32(255, 0, 0, 255)) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; GetForegroundDrawList(window)->AddRect(window->DC.LastItemRect.Min, window->DC.LastItemRect.Max, col); }
inline void DebugStartItemPicker() { ImGuiContext& g = *GImGui; g.DebugItemPickerActive = true; }
} // namespace ImGui
// ImFontAtlas internals
IMGUI_API bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas);
IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas);
IMGUI_API void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent);
IMGUI_API void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque);
IMGUI_API void ImFontAtlasBuildFinish(ImFontAtlas* atlas);
IMGUI_API void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor);
IMGUI_API void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride);
// Debug Tools
// Use 'Metrics->Tools->Item Picker' to break into the call-stack of a specific item.
#ifndef IM_DEBUG_BREAK
#if defined(__clang__)
#define IM_DEBUG_BREAK() __builtin_debugtrap()
#elif defined (_MSC_VER)
#define IM_DEBUG_BREAK() __debugbreak()
#else
#define IM_DEBUG_BREAK() IM_ASSERT(0) // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger!
#endif
#endif // #ifndef IM_DEBUG_BREAK
// Test Engine Hooks (imgui_tests)
//#define IMGUI_ENABLE_TEST_ENGINE
#ifdef IMGUI_ENABLE_TEST_ENGINE
extern void ImGuiTestEngineHook_PreNewFrame(ImGuiContext* ctx);
extern void ImGuiTestEngineHook_PostNewFrame(ImGuiContext* ctx);
extern void ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id);
extern void ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags);
extern void ImGuiTestEngineHook_IdInfo(ImGuiContext* ctx, ImGuiDataType data_type, ImGuiID id, const void* data_id);
extern void ImGuiTestEngineHook_IdInfo(ImGuiContext* ctx, ImGuiDataType data_type, ImGuiID id, const void* data_id, const void* data_id_end);
extern void ImGuiTestEngineHook_Log(ImGuiContext* ctx, const char* fmt, ...);
#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID) // Register item bounding box
#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS) // Register item label and status flags (optional)
#define IMGUI_TEST_ENGINE_LOG(_FMT,...) if (g.TestEngineHookItems) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__) // Custom log entry from user land into test log
#define IMGUI_TEST_ENGINE_ID_INFO(_ID,_TYPE,_DATA) if (g.TestEngineHookIdInfo == id) ImGuiTestEngineHook_IdInfo(&g, _TYPE, _ID, (const void*)(_DATA));
#define IMGUI_TEST_ENGINE_ID_INFO2(_ID,_TYPE,_DATA,_DATA2) if (g.TestEngineHookIdInfo == id) ImGuiTestEngineHook_IdInfo(&g, _TYPE, _ID, (const void*)(_DATA), (const void*)(_DATA2));
#else
#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID) do { } while (0)
#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS) do { } while (0)
#define IMGUI_TEST_ENGINE_LOG(_FMT,...) do { } while (0)
#define IMGUI_TEST_ENGINE_ID_INFO(_ID,_TYPE,_DATA) do { } while (0)
#define IMGUI_TEST_ENGINE_ID_INFO2(_ID,_TYPE,_DATA,_DATA2) do { } while (0)
#endif
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#ifdef _MSC_VER
#pragma warning (pop)
#endif
#endif // #ifndef IMGUI_DISABLE | [
"61205459+sailent704@users.noreply.github.com"
] | 61205459+sailent704@users.noreply.github.com |
9e0a2e6fe1b947baaa31adfe5060f8c1e04a7946 | e0feac125fb92c3d1834f9c9c89baf4ab9428fc6 | /rpdf/public/rpdf/I3RecoLLH.h | 71a8d922b8d0e8403bee9b757e6c590073dcdd79 | [] | no_license | AlexHarn/bfrv1_icetray | e6b04d04694376488cec93bb4b2d649734ae8344 | 91f939afecf4a9297999b022cea807dea407abe9 | refs/heads/master | 2022-12-04T13:35:02.495569 | 2020-08-27T22:14:40 | 2020-08-27T22:14:40 | 275,841,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,911 | h | #ifndef I3RECOLLH_H_INCLUDED
#define I3RECOLLH_H_INCLUDED
/**
* @brief Provides a Gulliver likelihood service for muon based reconstructions
*
* (c) 2018 the IceCube Collaboration
*
* @file I3RecoLLH.h
* @author Kevin Meagher
* @date January 2018
*
*/
#include "dataclasses/geometry/I3Geometry.h"
#include "gulliver/I3EventLogLikelihoodBase.h"
#include "rpdf/pandel.h"
#include "rpdf/geometry.h"
/**
* @class I3RecoLLH
* @brief A gulliver likelihood service for reconstructions which use
* the Pandel function.
*
* It calculates the
* likelihood of a muon track hypothesis using an analytic description of light
* propagation through the ice. This analytic description is referred to as the
* Pandel function. This implementation assumes all ice in the detector has
* uniform optical properties.
*
*/
class I3RecoLLH : public I3EventLogLikelihoodBase {
private:
/**
* Structure for caching the information needed to calculate the likelihood.
* This data is the same regardless of the hypothesis so it is computed once
* per event and cached so it doesn't have to be calculated for each iteration
*/
struct I3HitCache
{
///Total number of Photoelectrons observed by the DOM in the event
double total_npe;
///The time of the first pulsse
double first_pulse_time;
///position of the DOM
I3Position pos;
};
///A descriptive string representing the instance of this class
std::string name_;
///The name of the I3FrameObject to read from the frame
const std::string inputReadout_;
///The name of the likelihood function to use: SPE1st or MPE
const std::string likelihood_;
///The name of the Photoelectron probability to use: FastConvoluted or Unconvoluted
const std::string peprob_;
///The time scale of the DOM jitter to consider when reconstructing
const double jitter_;
///The frequency of noise hits to use in the reconstruction
const double noise_;
///The ice model object to store the optical properties in
const rpdf::IceModel ice_model_;
///Instance of the DOM likelihood function object
rpdf::DOMLikelihoodFunction dom_likelihood_func_;
///Instance of the Photoelectron probability function object
std::shared_ptr<rpdf::PhotoElectronProbability> pe_prob_;
///A pointer to the geometry to store
I3GeometryConstPtr geoptr_;
///a list of the pertinent information for each hit in an event stored in a vector for fast access
std::vector<I3HitCache> hit_cache_;
public:
/**
* @brief Create a new I3RecoLLH object
*
* @param input_readout The name of the I3RecoPulseSeriesMap to read from the frame
* @param likelihood The name of the DOM likelihood algorithm to use.
* Options are "GaussConvoluted" or "UnconvolutedPandel"
* @param peprob The name of the photoelectron probability calculation to use
* Options are "SPE1st" or "MPE"
* @param jitter the width of the Gaussian which is convoluted with the pandel function
* @param noise The frequency of noise hits to use in the reconstruction
* @param ice_model A struct containing the description of optical properties of the ice
*/
I3RecoLLH( const std::string &input_readout,
const std::string &likelihood,
const std::string &peprob,
const double jitter,const double noise,
const rpdf::IceModel &ice);
virtual ~I3RecoLLH();
/**
* This is called when the reader gets a new geometry.
* It saves the geometry for SetEvent() to save the location
* of each DOM in the hit cache
*
* @param geo the Geometry to use to calculate likelihoods
*/
void SetGeometry( const I3Geometry &geo);
/**
* Called when a new event occurs, this reads the new event
* and the pulse map in the frame. and calls SetHitCache()
*
* @param frame the frame to extract the I3RecoPulseSeriesMap from
*/
void SetEvent( const I3Frame &frame );
/**
* Calculates the hit cache from the geometry and given pulse map
*
* @param pulse_map map containing the pulses for calculating the likelihood
*/
void SetPulseMap(const I3RecoPulseSeriesMap& pulse_map);
/**
* Calculate the log likelihood of an event hypothesis
* for the current event
*
* @param event_hypothesis the gulliver event hypothesis (which contains an
* I3Particle) with which to calculate the likelihood
*
* @returns the likelihood of the hypothesis
*/
double GetLogLikelihood( const I3EventHypothesis &event_hypothesis);
/**
* @returns the multiplicity of the event in question:
* the number of hit DOMs
*/
unsigned int GetMultiplicity();
/**
* changes the name of this particular instance of I3RecoLLH
*/
void SetName(std::string name);
/**
* @returns a string which describes this particular instance of I3RecoLLH
*/
const std::string GetName() const;
SET_LOGGER( "I3RecoLLH" );
};
#endif
| [
"olivas@icecube.umd.edu"
] | olivas@icecube.umd.edu |
c7d35d545e15aa008ca778b31d32202418a81aa7 | f3caca21856698192203e25e7df7fd7300135eb7 | /src/vm/vmlua.h | 73eb090a3b439d9a32d5f8cd1ac340d68377e8f3 | [
"MIT"
] | permissive | sheenshane/WaykiChain | e8b9e059030f0f782b1388f7321623163dd6897f | c37f23556a45dc22e06c874afb0baef323125e80 | refs/heads/master | 2020-04-23T13:53:10.444698 | 2019-02-16T17:52:09 | 2019-02-16T17:52:09 | 171,212,733 | 2 | 0 | MIT | 2019-02-18T04:09:18 | 2019-02-18T04:09:17 | null | GB18030 | C++ | false | false | 564 | h | #ifndef VMLUA_H_
#define VMLUA_H_
#include <cstdio>
#include <vector>
#include <string>
#include <memory>
using namespace std;
class CVmRunEvn;
class CVmlua {
public:
CVmlua(const vector<unsigned char> & vRom,const vector<unsigned char> &InputData);
~CVmlua();
tuple<uint64_t,string> run(uint64_t maxstep,CVmRunEvn *pVmScriptRun);
static tuple<bool,string> syntaxcheck(const char* filePath);
private:
unsigned char m_ExRam[65536]; //存放的是合约交易的contact内容
unsigned char m_ExeFile[65536];//可执行文件 IpboApp.lua
};
#endif
| [
"walker@iblocktech.com"
] | walker@iblocktech.com |
397b1ebab68beaf6686d4e543ce41f9b124aeb01 | 81f2b85a9542b8fd365b44d0caa39f2fb6f8e122 | /leetcode/Array/Plus One/main.cpp | 6154c53e4334c0dbf8fe6697eb6fa87f5589ea9b | [] | no_license | setsal/coding | c66aa55e43805240c95e1c4f330f08b0fb0df7ba | 7ee094b8b680107efe88a0abb3aba5c18d148665 | refs/heads/master | 2023-08-26T20:03:03.723747 | 2021-09-24T18:04:14 | 2021-09-24T18:04:14 | 298,565,963 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 521 | cpp | class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int len = digits.size();
digits[len-1] = digits[len-1] + 1;
int i;
for ( i=len-1; i>0; i-- ) {
if ( digits[i] == 10 ) {
digits[i] = 0;
digits[i-1] = digits[i-1] + 1;
}
}
if ( digits[0] == 10 ) {
digits.insert( digits.begin(), 1 );
digits[1] = 0;
}
return digits;
}
}; | [
"contact@setsal.dev"
] | contact@setsal.dev |
7b752695da3205d766068be0542812c576ba6036 | c18dcd79934b07fdbc7b7b8568ec8af8c9beab91 | /0513/OJ396.cpp | cf5a4fbfac9d3534f77e534df7a7a9ea3af8ed8d | [] | no_license | xsun89/MenTou | 725fbbabb75dd85003af30e05ffb43d9c5dd2eae | 4047757d3ef2d8fbd3204b02ad6cd59882b80318 | refs/heads/master | 2023-05-31T22:22:18.942773 | 2021-06-16T17:40:35 | 2021-06-16T17:40:35 | 345,441,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,153 | cpp | //
// Created by Xin Sun on 2021-05-26.
//
#include <iostream>
#include <queue>
using namespace std;
struct node {
int x, y;
};
int n;
int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
int mmap[50][50];
int main() {
cin >> n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++) {
cin >> mmap[i][j];
}
}
queue<node> que;
que.push((node){0, 0});
mmap[0][0] = 3;
while(!que.empty()){
node tmp = que.front();
que.pop();
for(int i = 0; i < 4; i++){
int x = tmp.x + dir[i][0];
int y = tmp.y + dir[i][1];
if(x < 0 || y < 0 || x > n + 1 || y > n + 1 || mmap[x][y] != 0) {
continue;
}
mmap[x][y] = 3;
que.push((node){x, y});
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(j != 1) cout << " ";
if(mmap[i][j] == 0){
cout << 2;
}else if(mmap[i][j] == 1){
cout << 1;
}else{
cout << 0;
}
}
cout << endl;
}
return 0;
} | [
"sunxin89@gmail.com"
] | sunxin89@gmail.com |
1fb578da628a323daeebe36f861b05c9e0358844 | 512044f62cb6f432b67a7809b98e58e055572ae3 | /ext/asio/src/tests/unit/signal_set_service.cpp | 1e2098600317feba7fcf6f939214bcc647e99bcb | [
"MIT",
"BSL-1.0"
] | permissive | laxtools/lax | b53c47e7482c6230d6bb06525ff9beb0422bc28a | 4b6ac5e042787f1c66e6f4771ec9aafe6b2df26b | refs/heads/master | 2021-01-20T06:14:48.794893 | 2018-04-23T10:23:26 | 2018-04-23T10:23:26 | 101,494,689 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 639 | cpp | //
// signal_set_service.cpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot 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)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include "asio/signal_set_service.hpp"
#include "unit_test.hpp"
ASIO_TEST_SUITE
(
"signal_set_service",
ASIO_TEST_CASE(null_test)
)
| [
"laxtools@gmail.com"
] | laxtools@gmail.com |
452342c9978134356f49afdec6a519af2e8f19a5 | 4ec7b04f235824d73de99370a4fb293e60b30ebe | /RBTree.h | e924d92909320e4eb9dc828b400296524fc2387c | [] | no_license | wzpchris/cexample | 93c841cf287671ee5985c1478d978e0b683ccd36 | b529438212295f48c14f7a943b51ce0905b22b75 | refs/heads/master | 2018-10-15T00:33:30.237981 | 2018-07-12T02:02:29 | 2018-07-12T02:02:29 | 123,370,486 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,184 | h | //file RBTree.h
//July and saturnman
#ifndef _RB_TREE_H_
#define _RB_TREE_H_
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
template<class KEY, class U>
class RB_Tree {
private:
RB_Tree(const RB_Tree& input) {}
const RB_Tree& operator= (const RB_Tree& input) {}
private:
enum COLOR { RED, BLACK };
class RB_Node
{
public:
RB_Node() {
right = NULL;
left = NULL;
parent = NULL;
}
COLOR RB_COLOR;
RB_Node* right;
RB_Node* left;
RB_Node* parent;
KEY key;
U data;
};
public:
RB_Tree() {
this->m_nullNode = new RB_Node();
this->m_root = m_nullNode;
this->m_nullNode->right = this->m_root;
this->m_nullNode->left = this->m_root;
this->m_nullNode->parent = this->m_root;
this->m_nullNode->RB_COLOR = BLACK;
}
//是否为空
bool Empty() {
if(this->m_root == this->m_nullNode) {
return true;
}else {
return false;
}
}
//查找key
RB_Node* find(KEY key) {
RB_Node *index = m_root;
while(index != m_nullNode) {
if(key < index->key) {
index = index->left;
}else if(key > index->key) {
index = index->right;
}else {
break;
}
}
return index;
}
//插入节点
//总操作
/*RB_INSERT(T, z)
*y <- nil[T] //y始终指向x的父节点
*x <- root[T] //x指向当前树的根节点
×while x != nil[T]
* do y <- x
* if key[z] < key[x] //向左,向右
× then x <- left[x]
* else x <- right[x] //为了找到合适的插入点,x探路跟踪路径,直到x成为nil为止
*p[z] <- y
*if y = nil[T]
* then root[T] <- z
* else if key[z] < key[y]
* then left[y] <- z
* else right[y] <- z //置z相关的指针
*left[z] <- nil[T]
*right[z] <- nil[T] //设置空
*color[z] <- RED //将新插入的节点z作为红色
*RB_INSERT_FIXUP(T, z) //修复性质
*/
bool Insert(KEY key, U data) {
RB_Node* insert_point = m_nullNode;
RB_Node* index = m_root;
while(index != m_nullNode) {
insert_point = index;
if(key < index->key) {
index = index->left;
}else if(key > index->key) {
index = index->right;
}else {
return false;
}
}
RB_Node *insert_node = new RB_Node();
insert_node->key = key;
insert_node->data = data;
insert_node->RB_COLOR = RED;
insert_node->right = m_nullNode;
insert_node->left = m_nullNode;
if(insert_point == m_nullNode) { //插入的是一颗空树
m_root = insert_node;
m_root->parent = m_nullNode;
m_nullNode->left = m_root;
m_nullNode->right = m_root;
m_nullNode->parent = m_root;
}else {
if(key < insert_point->key) {
insert_point->left = insert_node;
}else {
insert_point->right = insert_node;
}
insert_node->parent = insert_point;
}
InsertFixUp(insert_node);
}
//插入节点性质修复
//3中插入情况
/*RB_INSERT_FIXUP(T, z)
*while color[p[z]] = RED
* do if p[z] = left[p[p[z]]]
* then y <- right[p[p[z]]]
if color[y] = RED
then color[p[z]] <- BLACK //case 1
color[y] <- BLACK //case 1
color[p[p[z]]] <- RED //case 1
z <- p[p[z]] //case 1
else if z = right[p[z]]
then z <- p[z] //case 2
LEFT_ROTATE(T,z) //case 2
color[p[z]] <- BLACK //case 3
color[p[p[z]]] <- RED //case 3
RIGHT_ROTATE(T, p[p[z]]) //case 3
else (same as then clause with "right" and "left" exchanged)
color[root[T]] <- BLACK
*/
void InsertFixUp(RB_Node* node) {
while(node->parent->RB_COLOR == RED){
if(node->parent == node->parent->parent->left)
{
RB_Node *uncle = node->parent->parent->right;
if(uncle->RB_COLOR == RED) //插入情况1,z的叔叔y是红色的
{
node->parent->RB_COLOR = BLACK;
uncle->RB_COLOR = BLACK;
node->parent->parent->RB_COLOR = RED;
node = node->parent->parent;
}else if(uncle->RB_COLOR == BLACK) //插入情况2:z的叔叔y是黑色
{
if(node == node->parent->right) //且z时右孩子
{
node = node->parent;
RotateLeft(node);
}
//插入情况3:z的叔叔y时黑色的,但z是左孩子
node->parent->RB_COLOR = BLACK;
node->parent->parent->RB_COLOR = RED;
RotateRight(node->parent->parent);
}
}
else { //这部分是针对插入情况1中,z的父亲现在作为祖父的右孩子的情况
RB_Node *uncle = node->parent->parent->left;
if(uncle->RB_COLOR == RED)
{
node->parent->RB_COLOR = BLACK;
uncle->RB_COLOR = BLACK;
uncle->parent->RB_COLOR = RED;
node = node->parent->parent;
}else if(uncle->RB_COLOR == BLACK) {
if(node == node->parent->left) {
node = node->parent;
RotateRight(node);
}
node->parent->RB_COLOR = BLACK;
node->parent->parent->RB_COLOR = RED;
RotateLeft(node->parent->parent);
}
}
}
m_root->RB_COLOR = BLACK;
}
//左旋
bool RotateLeft(RB_Node* node) {
if(node == m_nullNode || node->right == m_nullNode) {
return false;
}
RB_Node *lower_right = node->right;
lower_right->parent = node->parent;
node->right = lower_right->left;
if(lower_right->left != m_nullNode) {
lower_right->left->parent = node;
}
if(node->parent == m_nullNode) {
m_root = lower_right;
m_nullNode->left = m_root;
m_nullNode->right = m_root;
}else {
if(node == node->parent->left) {
node->parent->left = lower_right;
}else {
node->parent->right = lower_right;
}
}
node->parent = lower_right;
lower_right->left = node;
}
//右旋
bool RotateRight(RB_Node *node) {
if(node == m_nullNode || node->left == m_nullNode) {
return false;
}
RB_Node *lower_left = node->left;
node->left = lower_left->right;
lower_left->parent = node->parent;
if(lower_left->right != m_nullNode) {
lower_left->right->parent = node;
}
if(node->parent == m_nullNode) { //node is root
m_root = lower_left;
m_nullNode->left = m_root;
m_nullNode->right = m_root;
}else {
if(node == node->parent->right) {
node->parent->right = lower_left;
}else {
node->parent->left = lower_left;
}
}
node->parent = lower_left;
lower_left->right = node;
}
//删除节点
bool Delete(KEY key) {
RB_Node *delete_point = find(key);
if(delete_point == m_nullNode) {
return false;
}
if(delete_point->left != m_nullNode && delete_point->right != m_nullNode) {
RB_Node *successor = InOrderSuccessor(delete_point);
delete_point->data = successor->data;
delete_point->key = successor->key;
delete_point = successor;
}
RB_Node *delete_point_child;
if(delete_point->right != m_nullNode) {
delete_point_child = delete_point->right;
}else if(delete_point->left != m_nullNode) {
delete_point_child = delete_point->left;
}else {
delete_point_child = m_nullNode;
}
delete_point_child->parent = delete_point->parent;
if(delete_point->parent == m_nullNode) { //delete root node
m_root = delete_point_child;
m_nullNode->parent = m_root;
m_nullNode->left = m_root;
m_nullNode->right = m_root;
}else if(delete_point == delete_point->parent->right) {
delete_point->parent->right = delete_point_child;
}else {
delete_point->parent->left = delete_point_child;
}
if(delete_point->RB_COLOR == BLACK && !(delete_point_child == m_nullNode && delete_point_child->parent == m_nullNode)) {
DeleteFixUp(delete_point_child);
}
delete delete_point;
return true;
}
//删除节点性质修复
/*RB_DELETE_FIXUP(T,x)
*while x != root[T] and color[x] = BLACK
* do if x = left[p[x]]
then w <- right[p[x]]
if color[w] = RED
then color[w] <- BLACK //case 1
color[p[x]] <- RED //case 1
LeftRotate(T, p[x]) //case 1
w <- right[p[x]] //case 1
if color[left[w]] = BLACK and color[right[w]] = BLACK
then color[w] <- RED //case 2
x <- p[x] //case 2
else if color[right[w]] = BLACK
then color[left[w]] <- BLACK //case 3
color[w] <- RED //case 3
RightRotate(T,w) //case 3
w <- right[p[x]] //case 3
color[w] <- color[p[x]] //case 4
color[p[x]] <- BLACK //case 4
color[right[w]] <- BLACK //case 4
LeftRotate(T,p[x]) //case 4
x <- root[T]
else (same as then clause with "right" and "left" exchanged)
color[x] <- BLACK
*/
void DeleteFixUp(RB_Node *node) {
while(node != m_root && node->RB_COLOR == BLACK) {
if(node == node->parent->left) {
RB_Node *brother = node->parent->right;
if(brother->RB_COLOR == RED) //情况1:x的兄弟w是红色的
{
brother->RB_COLOR = BLACK;
node->parent->RB_COLOR = RED;
RotateLeft(node->parent);
}else { //情况2:x的兄弟w是黑色的
if(brother->left->RB_COLOR == BLACK && brother->right->RB_COLOR == BLACK) {
//且w的两个孩子都是黑色的
brother->RB_COLOR = RED;
node = node->parent;
}else if(brother->right->RB_COLOR == BLACK) {
//情况3:x的兄弟w是黑色的,w的右孩子是黑色(w的左孩子是红色)
brother->RB_COLOR = RED;
brother->left->RB_COLOR = BLACK;
RotateRight(brother);
}
//情况4:x的兄弟w是黑色的,且w的右孩子是红色的
brother->RB_COLOR = node->parent->RB_COLOR;
node->parent->RB_COLOR = BLACK;
brother->right->RB_COLOR = BLACK;
RotateLeft(node->parent);
node = m_root;
}
}else { //下述情况针对上面情况1中,node作为右孩子而阐述的
RB_Node *brother = node->parent->left;
if(brother->RB_COLOR == RED) {
brother->RB_COLOR = BLACK;
node->parent->RB_COLOR = RED;
RotateRight(node->parent);
}else {
if(brother->left->RB_COLOR == BLACK && brother->right->RB_COLOR == BLACK) {
brother->RB_COLOR = RED;
node = node->parent;
}else if(brother->left->RB_COLOR == BLACK) {
brother->RB_COLOR = RED;
brother->right->RB_COLOR = BLACK;
RotateLeft(brother);
}
brother->RB_COLOR = node->parent->RB_COLOR;
node->parent->RB_COLOR = BLACK;
brother->left->RB_COLOR = BLACK;
RotateRight(node->parent);
node = m_root;
}
}
}
m_nullNode->parent = m_root; //最后将node置为根节点
node->RB_COLOR = BLACK; //并改为黑色
}
//
inline RB_Node* InOrderPredecessor(RB_Node *node) {
if(node == m_nullNode) {
return m_nullNode;
}
RB_Node *result = node->left;
while(result != m_nullNode) {
if(result->right != m_nullNode) {
result = result->right;
}else {
break;
}
}
if(result == m_nullNode) {
RB_Node *index = node->parent;
result = node;
while(index != m_nullNode && result == index->left) {
result = index;
index = index->parent;
}
result = index;
}
return result;
}
//
inline RB_Node *InOrderSuccessor(RB_Node *node) {
if(node == m_nullNode) {
return m_nullNode;
}
RB_Node *result = node->right;
while(result != m_nullNode) {
if(result->left != m_nullNode) {
result = result->left;
}else {
break;
}
}
if(result == m_nullNode) {
RB_Node *index = node->parent;
result = node;
while(index != m_nullNode && result == index->right) {
result = index;
index = index->parent;
}
result = index;
}
return result;
}
//debug
void InOrderTraverse() {
cout << "the tree root:" << endl;
cout << "key=" << m_root->key << "\tdata=" << m_root->data << "\tcolor=" << (m_root->RB_COLOR == RED ? "Red" : "Black") << endl;
cout << "------------------------------------" << endl;
InOrderTraverse(m_root);
}
void CreateGraph(string filename) {
}
void InOrderCreate(ofstream& file, RB_Node *node) {
}
void InOrderTraverse(RB_Node *node) {
if(node == m_nullNode) {
return;
}else {
InOrderTraverse(node->left);
cout << "key=" << node->key << "\tdata=" << node->data << "\tcolor=" << (node->RB_COLOR == RED ? "Red" : "Black") << endl;
InOrderTraverse(node->right);
}
}
~RB_Tree() {
clear(m_root);
delete m_nullNode;
}
private:
void clear(RB_Node *node) {
if(node == m_nullNode) {
return;
}else {
clear(node->left);
clear(node->right);
delete node;
}
}
private:
RB_Node *m_nullNode;
RB_Node *m_root;
};
#endif /*_RB_TREE_H_*/
| [
"271737050@qq.com"
] | 271737050@qq.com |
138e4010585dc193666d0eafe8a36d2f6d02721e | e2bb8568b21bb305de3b896cf81786650b1a11f9 | /SDK/SCUM_Stew1_classes.hpp | 423ae4d420b33c66310cdb1176c9148fc71b8319 | [] | no_license | Buttars/SCUM-SDK | 822e03fe04c30e04df0ba2cb4406fe2c18a6228e | 954f0ab521b66577097a231dab2bdc1dd35861d3 | refs/heads/master | 2020-03-28T02:45:14.719920 | 2018-09-05T17:53:23 | 2018-09-05T17:53:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | hpp | #pragma once
// SCUM (0.1.17) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SCUM_Stew1_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Stew1.Stew1_C
// 0x0000 (0x0880 - 0x0880)
class AStew1_C : public ACookedFoodItem
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass Stew1.Stew1_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
bce677453da59692c6f6e9c332baa66925f30bf7 | 4ab8668539499bf571443198d9f9512f5208ac8e | /800/231A.cpp | 487bd0521d2e86c5ca5cb5cc3d79c64b453ba7f7 | [] | no_license | Andruixxd31/Competitive-Programming | 9d7edf220a6d44cca4da9c62f00465b04282d555 | 732f8ddea5b534fca05b2071277f0752bdb48b39 | refs/heads/master | 2022-12-18T03:53:31.713167 | 2020-09-22T17:15:48 | 2020-09-22T17:15:48 | 275,478,486 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | #include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int n = 0;
int problems = 0;
int count;
int votes[3];
cin >> n;
for (int i = 0; i < n; ++i)
{
count = 0;
for (int j = 0; j < 3; ++j)
{
cin >> votes[j];
if(votes[j] == 1) {
++count;
if(count == 2) ++problems;
}
}
}
cout << problems;
return 0;
}
// 62 ms 3700 KB | [
"andruix93@gmail.com"
] | andruix93@gmail.com |
66054f8b1e75d0185a774b45e11027aa981b28f4 | fab3558facbc6d6f5f9ffba1d99d33963914027f | /include/fcppt/signal/base_impl.hpp | 5ba8fe9481e5e4ec511343a80ca06027eec33751 | [] | no_license | pmiddend/sgedoxy | 315aa941979a26c6f840c6ce6b3765c78613593b | 00b8a4aaf97c2c927a008929fb4892a1729853d7 | refs/heads/master | 2021-01-20T04:32:43.027585 | 2011-10-28T17:30:23 | 2011-10-28T17:30:23 | 2,666,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,093 | hpp | // Copyright Carl Philipp Reh 2009 - 2011.
// 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)
#ifndef FCPPT_SIGNAL_BASE_IMPL_HPP_INCLUDED
#define FCPPT_SIGNAL_BASE_IMPL_HPP_INCLUDED
#include <fcppt/make_unique_ptr.hpp>
#include <fcppt/move.hpp>
#include <fcppt/signal/base_decl.hpp>
#include <fcppt/signal/detail/concrete_connection_impl.hpp>
template<
typename T
>
fcppt::signal::auto_connection
fcppt::signal::base<T>::connect(
function_type const &_function
)
{
auto_connection con(
fcppt::make_unique_ptr<
concrete_connection
>(
_function
)
);
connections_.push_back(
static_cast<
concrete_connection &
>(
*con
)
);
return
fcppt::move(
con
);
}
template<
typename T
>
fcppt::signal::base<T>::base()
{}
template<
typename T
>
fcppt::signal::base<T>::~base()
{}
template<
typename T
>
typename fcppt::signal::base<T>::connection_list &
fcppt::signal::base<T>::connections() const
{
return connections_;
}
#endif
| [
"pmidden@gmx.net"
] | pmidden@gmx.net |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.