hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b0406195430797ea217d148983fe972a1779f69a | 2,304 | hpp | C++ | include/ocpp1_6/messages/GetConfiguration.hpp | EVerest/libocpp | e2378e4fcef88e4be82b057626086c899a186b14 | [
"Apache-2.0"
] | 9 | 2022-01-16T05:13:16.000Z | 2022-03-18T22:15:16.000Z | include/ocpp1_6/messages/GetConfiguration.hpp | EVerest/libocpp | e2378e4fcef88e4be82b057626086c899a186b14 | [
"Apache-2.0"
] | null | null | null | include/ocpp1_6/messages/GetConfiguration.hpp | EVerest/libocpp | e2378e4fcef88e4be82b057626086c899a186b14 | [
"Apache-2.0"
] | 3 | 2022-01-20T04:51:01.000Z | 2022-03-13T07:16:49.000Z | // SPDX-License-Identifier: Apache-2.0
// Copyright 2020 - 2022 Pionix GmbH and Contributors to EVerest
#ifndef OCPP1_6_GETCONFIGURATION_HPP
#define OCPP1_6_GETCONFIGURATION_HPP
#include <boost/optional.hpp>
#include <ocpp1_6/ocpp_types.hpp>
#include <ocpp1_6/types.hpp>
namespace ocpp1_6 {
/// \brief Contains a OCPP 1.6 GetConfiguration message
struct GetConfigurationRequest : public Message {
boost::optional<std::vector<CiString50Type>> key;
/// \brief Provides the type of this GetConfiguration message as a human readable string
/// \returns the message type as a human readable string
std::string get_type() const;
};
/// \brief Conversion from a given GetConfigurationRequest \p k to a given json object \p j
void to_json(json& j, const GetConfigurationRequest& k);
/// \brief Conversion from a given json object \p j to a given GetConfigurationRequest \p k
void from_json(const json& j, GetConfigurationRequest& k);
/// \brief Writes the string representation of the given GetConfigurationRequest \p k to the given output stream \p os
/// \returns an output stream with the GetConfigurationRequest written to
std::ostream& operator<<(std::ostream& os, const GetConfigurationRequest& k);
/// \brief Contains a OCPP 1.6 GetConfigurationResponse message
struct GetConfigurationResponse : public Message {
boost::optional<std::vector<KeyValue>> configurationKey;
boost::optional<std::vector<CiString50Type>> unknownKey;
/// \brief Provides the type of this GetConfigurationResponse message as a human readable string
/// \returns the message type as a human readable string
std::string get_type() const;
};
/// \brief Conversion from a given GetConfigurationResponse \p k to a given json object \p j
void to_json(json& j, const GetConfigurationResponse& k);
/// \brief Conversion from a given json object \p j to a given GetConfigurationResponse \p k
void from_json(const json& j, GetConfigurationResponse& k);
/// \brief Writes the string representation of the given GetConfigurationResponse \p k to the given output stream \p os
/// \returns an output stream with the GetConfigurationResponse written to
std::ostream& operator<<(std::ostream& os, const GetConfigurationResponse& k);
} // namespace ocpp1_6
#endif // OCPP1_6_GETCONFIGURATION_HPP
| 41.890909 | 119 | 0.769097 | EVerest |
b04080ac7f0f9724f0155e4a6983d13609cc17c4 | 17,549 | cpp | C++ | EntityLib/Core/GPUEntityMgr.cpp | Calvin-Ruiz/LaserBombon | 404bea5b95393b3d011902a0d1458bd86efdc5a5 | [
"MIT"
] | null | null | null | EntityLib/Core/GPUEntityMgr.cpp | Calvin-Ruiz/LaserBombon | 404bea5b95393b3d011902a0d1458bd86efdc5a5 | [
"MIT"
] | null | null | null | EntityLib/Core/GPUEntityMgr.cpp | Calvin-Ruiz/LaserBombon | 404bea5b95393b3d011902a0d1458bd86efdc5a5 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2020
** Vulkan-Engine
** File description:
** GPUEntityMgr.cpp
*/
#include "EntityCore/Core/VulkanMgr.hpp"
#include "EntityCore/Core/BufferMgr.hpp"
#include "EntityCore/Resource/SetMgr.hpp"
#include "EntityCore/Resource/Set.hpp"
#include "EntityCore/Resource/PipelineLayout.hpp"
#include "EntityCore/Resource/ComputePipeline.hpp"
#include "EntityCore/Resource/SyncEvent.hpp"
#include "EntityLib.hpp"
#include "GPUEntityMgr.hpp"
#include <cstring>
#include <chrono>
GPUEntityMgr::GPUEntityMgr(std::shared_ptr<EntityLib> master) : vkmgr(*VulkanMgr::instance), localBuffer(master->getLocalBuffer()), master(master)
{
entityMgr = std::make_unique<BufferMgr>(vkmgr, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, sizeof(EntityData) * END_ALL);
entityMgr->setName("Entity datas");
vertexMgr = std::make_unique<BufferMgr>(vkmgr, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, sizeof(EntityVertexGroup) * END_ALL);
vertexMgr->setName("Entity vertices");
readbackMgr = std::make_unique<BufferMgr>(vkmgr, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT, sizeof(EntityState) * END_ALL);
readbackMgr->setName("ReadBack buffer");
readbackBuffer = readbackMgr->acquireBuffer(sizeof(EntityState) * END_ALL);
gpuEntities = entityMgr->acquireBuffer(sizeof(EntityData) * END_ALL);
gpuVertices = vertexMgr->acquireBuffer(sizeof(EntityVertexGroup) * END_ALL);
readback = (EntityState *) readbackMgr->getPtr(readbackBuffer);
computeQueueFamily = vkmgr.acquireQueue(computeQueue, VulkanMgr::QueueType::COMPUTE, "GPUEntityMgr");
if (computeQueueFamily == nullptr) {
vkmgr.putLog("GPU not supported (expected 1 graphic and 1 compute queue)", LogType::ERROR);
if (master->graphicQueueFamily->compute) {
vkmgr.putLog("Unique graphic queue support compute operation, using it (may cause random crash)", LogType::WARNING);
computeQueueFamily = master->graphicQueueFamily;
computeQueue = master->graphicQueue;
}
}
// if (vkmgr.getComputeQueues().size() > 0) {
// computeQueue = vkmgr.getComputeQueues()[0];
// } else if (vkmgr.getGraphicQueues().size() > 1) {
// vkmgr.putLog("No dedicated compute queue found, assume graphic queue support compute", LogType::WARNING);
// computeQueue = vkmgr.getGraphicQueues()[1];
// } else {
// vkmgr.putLog("No dedicated compute queue found, assume graphic queue support compute", LogType::WARNING);
// vkmgr.putLog("Only one graphic & compute queue is available", LogType::WARNING);
// vkmgr.putLog("Queue submission may conflict", LogType::WARNING);
// computeQueue = vkmgr.getGraphicQueues()[0];
// }
syncExt = new SyncEvent[2] {{&vkmgr, true}, {&vkmgr, true}};
syncInt = new SyncEvent[4] {{&vkmgr}, {&vkmgr}, {&vkmgr}, {&vkmgr}};
syncExt[0].bufferBarrier(gpuEntities, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR, VK_PIPELINE_STAGE_2_COPY_BIT_KHR, VK_ACCESS_2_SHADER_STORAGE_READ_BIT_KHR | VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT_KHR, VK_ACCESS_2_TRANSFER_WRITE_BIT_KHR);
syncExt[1].bufferBarrier(gpuEntities, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR, VK_PIPELINE_STAGE_2_COPY_BIT_KHR, VK_ACCESS_2_SHADER_STORAGE_READ_BIT_KHR | VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT_KHR, VK_ACCESS_2_TRANSFER_WRITE_BIT_KHR);
syncInt[0].bufferBarrier(gpuEntities, VK_PIPELINE_STAGE_2_COPY_BIT_KHR, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR, VK_ACCESS_2_TRANSFER_WRITE_BIT_KHR, VK_ACCESS_2_SHADER_STORAGE_READ_BIT_KHR);
syncInt[1].bufferBarrier(gpuEntities, VK_PIPELINE_STAGE_2_COPY_BIT_KHR, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR, VK_ACCESS_2_TRANSFER_WRITE_BIT_KHR, VK_ACCESS_2_SHADER_STORAGE_READ_BIT_KHR);
syncInt[2].bufferBarrier(gpuEntities, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT_KHR, VK_ACCESS_2_SHADER_STORAGE_READ_BIT_KHR);
syncInt[3].bufferBarrier(gpuEntities, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT_KHR, VK_ACCESS_2_SHADER_STORAGE_READ_BIT_KHR);
for (int i = 0; i < 2; ++i)
syncExt[i].build();
for (int i = 0; i < 4; ++i)
syncInt[i].build();
syncInt[0].combineDstDependencies(syncInt[3]);
syncInt[1].combineDstDependencies(syncInt[2]);
VkCommandPoolCreateInfo poolInfo {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, nullptr, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, computeQueueFamily->id};
vkCreateCommandPool(vkmgr.refDevice, &poolInfo, nullptr, &transferPool);
poolInfo.flags = 0;
vkCreateCommandPool(vkmgr.refDevice, &poolInfo, nullptr, &computePool);
VkCommandBufferAllocateInfo allocInfo {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, nullptr, transferPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1};
vkAllocateCommandBuffers(vkmgr.refDevice, &allocInfo, cmds);
vkAllocateCommandBuffers(vkmgr.refDevice, &allocInfo, cmds + 2);
allocInfo.commandPool = computePool;
vkAllocateCommandBuffers(vkmgr.refDevice, &allocInfo, cmds + 1);
vkAllocateCommandBuffers(vkmgr.refDevice, &allocInfo, cmds + 3);
buildCompute();
VkFenceCreateInfo fenceInfo {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, nullptr, VK_FENCE_CREATE_SIGNALED_BIT};
vkCreateFence(vkmgr.refDevice, &fenceInfo, nullptr, fences);
vkCreateFence(vkmgr.refDevice, &fenceInfo, nullptr, fences + 1);
}
GPUEntityMgr::~GPUEntityMgr()
{
stop();
vkQueueWaitIdle(computeQueue);
vkDestroyCommandPool(vkmgr.refDevice, computePool, nullptr);
vkDestroyCommandPool(vkmgr.refDevice, transferPool, nullptr);
localBuffer.releaseBuffer(entityPushBuffer);
delete[] syncExt;
delete[] syncInt;
vkDestroyFence(vkmgr.refDevice, fences[0], nullptr);
vkDestroyFence(vkmgr.refDevice, fences[1], nullptr);
}
void GPUEntityMgr::stop()
{
if (alive) {
alive = false;
active = true;
updater->join();
}
}
void GPUEntityMgr::init()
{
entityPushBuffer = localBuffer.acquireBuffer(sizeof(EntityData) * END_ALL);
entityPush = (EntityData *) localBuffer.getPtr(entityPushBuffer);
}
void GPUEntityMgr::buildCompute()
{
SyncEvent tmpSc;
tmpSc.bufferBarrier(readbackBuffer, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR, VK_PIPELINE_STAGE_2_HOST_BIT_KHR, VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT_KHR, VK_ACCESS_2_HOST_WRITE_BIT_KHR);
tmpSc.build();
setMgr = std::make_unique<SetMgr>(vkmgr, 2, 0, 0, 3);
updatePLayout = std::make_unique<PipelineLayout>(vkmgr);
collidePLayout = std::make_unique<PipelineLayout>(vkmgr);
updatePLayout->setStorageBufferLocation(VK_SHADER_STAGE_COMPUTE_BIT, 0);
updatePLayout->buildLayout();
updatePLayout->setStorageBufferLocation(VK_SHADER_STAGE_COMPUTE_BIT, 0);
updatePLayout->setStorageBufferLocation(VK_SHADER_STAGE_COMPUTE_BIT, 1);
updatePLayout->buildLayout();
updatePLayout->build();
collidePLayout->setGlobalPipelineLayout(updatePLayout.get(), 0);
collidePLayout->build();
globalSet = std::make_unique<Set>(vkmgr, *setMgr, updatePLayout.get(), 0);
updateSet = std::make_unique<Set>(vkmgr, *setMgr, updatePLayout.get(), 1);
globalSet->bindStorageBuffer(gpuEntities, 0, sizeof(EntityData) * END_ALL);
updateSet->bindStorageBuffer(gpuVertices, 0, sizeof(EntityVertexGroup) * END_ALL);
updateSet->bindStorageBuffer(readbackBuffer, 1, sizeof(EntityState) * END_ALL);
ComputePipeline::setShaderDir("./shader/");
updatePipeline = std::make_unique<ComputePipeline>(vkmgr, updatePLayout.get());
updatePipeline->bindShader("update.comp.spv");
updatePipeline->build();
collidePipeline = std::make_unique<ComputePipeline>(vkmgr, collidePLayout.get(), VK_PIPELINE_CREATE_DISPATCH_BASE);
collidePipeline->bindShader("collide.comp.spv");
collidePipeline->build();
pcollidePipeline = std::make_unique<ComputePipeline>(vkmgr, collidePLayout.get(), VK_PIPELINE_CREATE_DISPATCH_BASE);
pcollidePipeline->bindShader("pcollide.comp.spv");
pcollidePipeline->build();
VkCommandBufferBeginInfo tmp {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, 0, nullptr};
for (int i = 0; i < 2; ++i) {
cmd = cmds[i * 2 | 1];
vkBeginCommandBuffer(cmd, &tmp);
syncInt[i].multiDstDependency(cmd); // Transfer write completion and compute write completion before reading
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pcollidePipeline->get());
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, collidePLayout->getPipelineLayout(), 0, 1, globalSet->get(), 0, nullptr);
vkCmdDispatchBase(cmd, BEG_PLAYER/2, 1, 0, 1, 1, 1);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, collidePipeline->get());
vkCmdDispatchBase(cmd, BEG_CANDY/2, 0, 0, 256, 1, 1);
syncInt[2].placeBarrier(cmd); // Compute read after previous write completion
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, updatePipeline->get());
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, updatePLayout->getPipelineLayout(), 1, 1, updateSet->get(), 0, nullptr);
vkCmdDispatch(cmd, 2, 1, 1);
syncInt[i].resetDependency(cmd, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR);
syncInt[3 - i].resetDependency(cmd, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR);
syncExt[!i].resetDependency(cmd, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT_KHR);
syncExt[i].srcDependency(cmd); // Transfer write after
tmpSc.placeBarrier(cmd); // Host sync
syncInt[i | 2].srcDependency(cmd); // Compute write after
vkEndCommandBuffer(cmd);
}
}
void GPUEntityMgr::resetAll()
{
psidx = BEG_PLAYER_SHOOT;
csidx = BEG_CANDY_SHOOT;
bidx = BEG_BONUS;
cidx = BEG_CANDY;
if (vertexInitialized) {
for (int i = 0; i < END_ALL; ++i) {
attachment[i].alive = false;
entityPush[i].health = -1;
entityPush[i].aliveNow = VK_TRUE;
entityPush[i].newlyInserted = VK_FALSE;
}
} else {
for (int i = 0; i < END_ALL; ++i)
entityPush[i] = EntityData({0, 0, 0, 0, -1, -1, 0.01, 0.01, 0, 0, 0, 0, VK_FALSE, VK_TRUE});
}
// Record a transfer command which reset everything
cmd = cmds[frameparity << 1];
vkWaitForFences(vkmgr.refDevice, 1, fences + frameparity, VK_TRUE, UINT32_MAX);
vkResetFences(vkmgr.refDevice, 1, fences + frameparity);
vkBeginCommandBuffer(cmd, &begInfo);
VkBufferCopy tmp = {(VkDeviceSize) entityPushBuffer.offset, 0, END_ALL*sizeof(EntityData)};
vkCmdCopyBuffer(cmd, entityPushBuffer.buffer, gpuEntities.buffer, 1, &tmp);
syncInt[frameparity].srcDependency(cmd);
if (initDep) {
syncInt[3].srcDependency(cmd); // This could fail because the compute stage is unused
initDep = false;
}
vkEndCommandBuffer(cmd);
vkQueueSubmit(computeQueue, 1, sinfo + frameparity, fences[frameparity]);
frameparity = !frameparity;
regionsBase.clear();
if (!vertexInitialized) {
vertexInitialized = true;
vkQueueWaitIdle(computeQueue);
resetAll();
vkQueueWaitIdle(computeQueue);
}
}
void GPUEntityMgr::start(void (*update)(void *, GPUEntityMgr &), void (*updatePlayer)(void *, GPUEntityMgr &), void *data)
{
if (!alive) {
alive = true;
updater = std::make_unique<std::thread>(&GPUEntityMgr::mainloop, this, update, updatePlayer, data);
}
}
void GPUEntityMgr::mainloop(void (*update)(void *, GPUEntityMgr &), void (*updatePlayer)(void *, GPUEntityMgr &), void *data)
{
resetAll();
auto delay = std::chrono::duration<int, std::ratio<1,1000000>>(1000000/100);
auto delayOverride = std::chrono::duration<int, std::ratio<1,1000000>>(1000000/1000);
bool prevLimit = limit;
auto clock = std::chrono::system_clock::now();
int cnt = 0;
while (alive) {
// vkmgr.putLog(std::string("Compute Cycle ") + std::to_string(cnt++), LogType::INFO);
while (!active) {
std::this_thread::sleep_for(std::chrono::microseconds(400));
clock = std::chrono::system_clock::now();
}
cmd = cmds[frameparity << 1];
regions.resize(regionsBase.size());
memcpy(regions.data(), regionsBase.data(), regionsBase.size() * sizeof(VkBufferCopy));
lastPush = 0;
vkWaitForFences(vkmgr.refDevice, 1, fences + frameparity, VK_TRUE, UINT32_MAX);
vkResetFences(vkmgr.refDevice, 1, fences + frameparity);
vkBeginCommandBuffer(cmd, &begInfo);
syncExt[!frameparity].dstDependency(cmd);
update(data, *this); // Update game // Record transfer due to local event
if (prevLimit != limit) {
clock = std::chrono::system_clock::now();
prevLimit = limit;
}
if (limit) {
clock += delay;
std::this_thread::sleep_until(clock);
} else {
clock += delayOverride;
std::this_thread::sleep_until(clock); // Don't go over 1000 fps (x10 speed)
}
// while (!syncExt[!frameparity].isSet())
// std::this_thread::sleep_for(std::chrono::microseconds(400));
updateChanges(); // Read back changes
updatePlayer(data, *this); // Update player shield // Record transfer due to GPU event // Write player changes
vkCmdCopyBuffer(cmd, entityPushBuffer.buffer, gpuEntities.buffer, regions.size(), regions.data());
syncInt[frameparity].srcDependency(cmd);
vkEndCommandBuffer(cmd);
vkQueueSubmit(computeQueue, 1, sinfo + frameparity, fences[frameparity]);
frameparity = !frameparity;
}
pidx = 0;
}
void GPUEntityMgr::updateChanges()
{
readbackMgr->invalidate(readbackBuffer);
nbDead = 0;
for (int i = 0; i < END_ALL; ++i) {
switch (attachment[i].alive) {
case 2:
attachment[i].alive = 1;
break;
case 1:
if (readback[i].health < 0) {
// vkmgr.putLog("Destroyed " + std::to_string(i), LogType::INFO);
attachment[i].alive = false;
deadFlags[nbDead].first = i;
deadFlags[nbDead++].second = attachment[i].flag;
}
break;
default:;
}
}
psidx = BEG_PLAYER_SHOOT;
csidx = BEG_CANDY_SHOOT;
bidx = BEG_BONUS;
cidx = BEG_CANDY;
}
EntityData &GPUEntityMgr::pushPlayerShoot(unsigned char flag)
{
while (psidx < BEG_CANDY_SHOOT) {
if (attachment[psidx].alive) {
++psidx;
continue;
}
attachment[psidx].flag = flag;
attachment[psidx].alive = 2;
pushRegion(psidx);
return entityPush[psidx++];
}
vkmgr.putLog("Failed to insert player shoot", LogType::WARNING);
return deft;
}
EntityData &GPUEntityMgr::pushCandyShoot(unsigned char flag)
{
while (csidx < BEG_BONUS) {
if (attachment[csidx].alive) {
++csidx;
continue;
}
attachment[csidx].flag = flag;
attachment[csidx].alive = 2;
pushRegion(csidx);
return entityPush[csidx++];
}
vkmgr.putLog("Failed to insert candy shoot", LogType::WARNING);
return deft;
}
EntityData &GPUEntityMgr::pushBonus(unsigned char flag)
{
while (bidx < BEG_CANDY) {
if (attachment[bidx].alive) {
++bidx;
continue;
}
attachment[bidx].flag = flag;
attachment[bidx].alive = 2;
pushRegion(bidx);
return entityPush[bidx++];
}
vkmgr.putLog("Failed to insert bonus or special candy shoot", LogType::WARNING);
return deft;
}
EntityData &GPUEntityMgr::pushCandy(unsigned char flag)
{
while (cidx < END_ALL) {
if (attachment[cidx].alive) {
++cidx;
continue;
}
attachment[cidx].flag = flag;
attachment[cidx].alive = 2;
pushRegion(cidx);
return entityPush[cidx++];
}
vkmgr.putLog("Failed to insert candy", LogType::WARNING);
return deft;
}
EntityData &GPUEntityMgr::pushPlayer(short idx, bool revive)
{
if (!(pidx & (1 << idx))) {
pidx |= (1 << idx);
idx |= BEG_PLAYER;
regionsBase.push_back({entityPushBuffer.offset + sizeof(EntityData) * idx, sizeof(EntityData) * idx, 5 * sizeof(float)});
regions.push_back({entityPushBuffer.offset + sizeof(EntityData) * idx, sizeof(EntityData) * idx, sizeof(EntityData)});
}
idx |= BEG_PLAYER;
if (revive) {
regions.push_back({entityPushBuffer.offset + sizeof(EntityData) * idx + offsetof(EntityData, aliveNow), sizeof(EntityData) * idx + offsetof(EntityData, aliveNow), sizeof(VkBool32) * 2});
}
return entityPush[idx];
}
EntityState &GPUEntityMgr::readPlayer(short idx)
{
return readback[idx | BEG_PLAYER];
}
EntityState &GPUEntityMgr::readEntity(short idx)
{
return readback[idx];
}
void GPUEntityMgr::pushRegion(short idx)
{
if (lastPush + 1 == idx) {
regions.back().size += sizeof(EntityData);
} else {
regions.push_back({entityPushBuffer.offset + idx * sizeof(EntityData), idx * sizeof(EntityData), sizeof(EntityData)});
}
lastPush = idx;
}
| 44.997436 | 240 | 0.691606 | Calvin-Ruiz |
b0429a36809a29c3971aff9087508d233c12ffe0 | 6,861 | cpp | C++ | cgame/fx_proton.cpp | kugelrund/Elite-Reinforce | a2fe0c0480ff2d9cdc241b9e5416ee7f298f00ca | [
"DOC"
] | 10 | 2017-07-04T14:38:48.000Z | 2022-03-08T22:46:39.000Z | cgame/fx_proton.cpp | UberGames/SP-Mod-Source-Code | 04e0e618d1ee57a2919f1a852a688c03b1aa155d | [
"DOC"
] | null | null | null | cgame/fx_proton.cpp | UberGames/SP-Mod-Source-Code | 04e0e618d1ee57a2919f1a852a688c03b1aa155d | [
"DOC"
] | 2 | 2017-04-23T18:24:44.000Z | 2021-11-19T23:27:03.000Z | #include "cg_local.h"
#include "FX_Public.h"
/*
-------------------------
-------------------------
// PROTON GUN
-------------------------
-------------------------
*/
/*
-------------------------
FX_ProtonShockRing
-------------------------
*/
void FX_ProtonShockRing( vec3_t start, vec3_t end )
{
vec3_t shot_dir, org;
// Faint shock ring created by shooting..looks like start and end got switched around...sigh
VectorSubtract( start, end, shot_dir );
VectorNormalize( shot_dir );
VectorMA( end, 8, shot_dir, org );
FX_AddSprite( start,
NULL, NULL,
64.0f, -128.0f,
1.0f, 1.0,
0.0, 0.0,
200,
cgs.media.rippleShader );
}
/*
-------------------------
FX_ProtonShot
-------------------------
*/
void FX_ProtonShot( vec3_t start, vec3_t end )
{
float length,
repeat;
vec3_t dir;
VectorSubtract( end, start, dir );
length = VectorNormalize( dir );
// thin inner line
FX_AddLine( end, start,
1.0f,
2.0f, -3.0f,
1.0f, 0.0f,
350.0f,
cgs.media.whiteLaserShader );
// thick outer glow
FX_AddLine( end, start,
1.0f,
4.0f, 0.0f,
0.4f, 0.0f,
250.0f,
cgs.media.whiteLaserShader );
// concentric rings
FXCylinder *fx = FX_AddCylinder( start, dir, length, 0, 1.0f, 3.0f, 1.0f, 2.0f,
0.4f, 0.0f, 300, cgs.media.protonBeamShader, 0.5f );
FX_AddSprite( end, NULL, NULL, 5, 0, 1, 0, 0, 0, 400, cgs.media.waterDropShader );
FX_AddSprite( end, NULL, NULL, 3, 0, 1, 0, 0, 0, 400, cgs.media.waterDropShader );
FX_AddSprite( end, NULL, NULL, 2, 0, 1, 0, 0, 0, 400, cgs.media.waterDropShader );
FX_AddSprite( end, NULL, NULL, 1, 0, 1, 0, 0, 0, 400, cgs.media.waterDropShader );
if( fx )
{
repeat = length / 12.0f;
fx->SetFlags( FXF_WRAP | FXF_STRETCH | FXF_NON_LINEAR_FADE );
fx->SetSTScale( repeat );
}
// FX_ProtonShockRing( start, end );
}
/*
-------------------------
FX_ProtonAltShot
-------------------------
*/
void FX_ProtonAltShot( vec3_t start, vec3_t end )
{
float length = 20;
vec3_t white = {1.0,1.0,1.0};
vec3_t dir;
FX_AddLine( start, end,
1.0f,
4.0f, -8.0f,
1.0f, 1.0f,
white, white,
325.0f,
cgs.media.whiteLaserShader );
FX_AddLine( start, end,
1.0f,
2.0f, -1.0f,
1.0f, 0.2f,
white, white,
300.0f,
cgs.media.whiteLaserShader );
VectorSubtract( end, start, dir );
length = VectorNormalize( dir );
FXCylinder *fx = FX_AddCylinder( start, dir, length, 0, 1, 3, 1, 3,
0.6f, 0.1f, 500 , cgs.media.protonAltBeamShader, 0.2f );
if( fx )
{
fx->SetFlags( FXF_WRAP | FXF_STRETCH );
fx->SetSTScale( length / 56.0f );
}
fx = FX_AddCylinder( start, dir, length, 0, 2, 5, 2, 5,
0.3f, 0.0, 600, cgs.media.protonAltBeamShader, 0.5f );
if( fx )
{
fx->SetFlags( FXF_WRAP | FXF_STRETCH );
fx->SetSTScale( length / 128.0f );
}
}
/*
-------------------------
FX_ProtonExplosion
-------------------------
*/
void FX_ProtonExplosion( vec3_t end, vec3_t dir )
{
vec3_t org;
// Move me away from the wall a bit so that I don't z-buffer into it
VectorMA( end, 0.5, dir, org );
// Expanding rings
// FX_AddQuad( org, dir, NULL, NULL, 1, 24, 0.8f, 0.2f, random() * 360, 360, 0, 400, cgs.media.protonRingShader );
// FX_AddQuad( org, dir, NULL, NULL, 1, 60, 0.8f, 0.2f, random() * 360, -360, 0, 300, cgs.media.protonRingShader );
// Impact effect
// FX_AddQuad( org, dir, NULL, NULL, 7, 35, 1.0, 0.0, random() * 360, 0, 0, 500, cgs.media.blueParticleShader );
// FX_AddQuad( org, dir, NULL, NULL, 5, 25, 1.0, 0.0, random() * 360, 0, 0, 420, cgs.media.ltblueParticleShader );
// Test of using the ripple shader......
FX_AddQuad( org, dir, NULL, NULL, 13, 16, 1.0f, 0.1f, random() * 360, 360, 0, 400, cgs.media.rippleShader );
FX_AddQuad( org, dir, NULL, NULL, 9, 20, 0.8f, 0.1f, random() * 360, -360, 0, 300, cgs.media.rippleShader );
FX_AddQuad( org, dir, NULL, NULL, 20, 8, 1.0f, 0.1f, random() * 360, 0, 0, 300, cgs.media.rippleShader );
FX_AddQuad( org, dir, NULL, NULL, 30, -20, 1.0f, 0.8f, random() * 360, 0, 0, 300, cgs.media.waterDropShader );
/*
localEntity_t *le;
FXTrail *particle;
vec3_t direction, new_org;
vec3_t velocity = { 0, 0, 8 };
float scale, dscale;
int i, numSparks;
//Sparks
numSparks = 4 + (random() * 4.0f);
for ( i = 0; i < numSparks; i++ )
{
scale = 0.25f + (random() * 2.0f);
dscale = -scale * 0.5f;
particle = FX_AddTrail( origin,
NULL,
NULL,
16.0f,
-32.0f,
scale,
-scale,
1.0f,
1.0f,
0.25f,
2000.0f,
cgs.media.sparkShader,
rand() & FXF_BOUNCE );
if ( particle == NULL )
return;
FXE_Spray( normal, 200, 50, 0.5f, 512, (FXPrimitive *) particle );
}
// Smoke puff
VectorMA( origin, 8, normal, new_org );
FX_AddSprite( new_org,
velocity, NULL,
16.0f, 16.0f,
1.0f, 0.0f,
random()*45.0f,
0.0f,
1000.0f,
cgs.media.steamShader );
scale = 0.4f + ( random() * 0.2f);
//Orient the explosions to face the camera
VectorSubtract( cg.refdef.vieworg, origin, direction );
VectorNormalize( direction );
// Add in the explosion and tag it with a light
le = CG_MakeExplosion( origin, direction, cgs.media.explosionModel, 6, cgs.media.electricalExplosionSlowShader, 475, qfalse, scale );
le->light = 150;
le->refEntity.renderfx |= RF_NOSHADOW;
VectorSet( le->lightColor, 0.8f, 0.8f, 1.0f );
// Scorch mark
CG_ImpactMark( cgs.media.compressionMarkShader, origin, normal, random()*360, 1,1,1,1, qfalse, 4, qfalse );
CG_ExplosionEffects( origin, 1.0f, 150 );
*/
}
/*
-------------------------
FX_ProtonHit
-------------------------
*/
void FX_ProtonHit( vec3_t origin )
{
FX_AddSprite( origin,
NULL,
NULL,
32.0f,
-128.0f,
1.0f,
1.0f,
random()*360,
0.0f,
250.0f,
cgs.media.prifleImpactShader );
}
/*
-------------------------
FX_ProtonAltMiss
-------------------------
*/
void FX_ProtonAltMiss( vec3_t origin, vec3_t normal )
{
vec3_t new_org;
vec3_t velocity;
float scale, dscale;
int i;
// Smoke puffs
for ( i = 0; i < 8; i++ )
{
scale = random() * 12.0f + 4.0f;
dscale = random() * 12.0f + 8.0f;
VectorMA( origin, random() * 8.0f, normal, new_org );
velocity[0] = normal[0] * crandom() * 24.0f;
velocity[1] = normal[1] * crandom() * 24.0f;
velocity[2] = normal[2] * ( random() * 24.0f + 8.0f ) + 8.0f; // move mostly up
FX_AddSprite( new_org,
velocity, NULL,
scale, dscale,
random() * 0.5f + 0.5f, 0.0f,
random() * 45.0f,
0.0f,
800 + random() * 300.0f,
cgs.media.steamShader );
}
// Scorch mark
CG_ImpactMark( cgs.media.bulletmarksShader, origin, normal, random()*360, 1,1,1,1, qfalse, 6, qfalse );
// FX_ProtonHit( origin );
CG_ExplosionEffects( origin, 1.0f, 150 );
} | 22.718543 | 134 | 0.571491 | kugelrund |
b04338d5b534abf70639507ffe72bef388bd6b10 | 2,012 | cpp | C++ | gtsam/inference/IndexFactor.cpp | sdmiller/gtsam_pcl | 1e607bd75090d35e325a8fb37a6c5afe630f1207 | [
"BSD-3-Clause"
] | 11 | 2015-02-04T16:41:47.000Z | 2021-12-10T07:02:44.000Z | gtsam/inference/IndexFactor.cpp | sdmiller/gtsam_pcl | 1e607bd75090d35e325a8fb37a6c5afe630f1207 | [
"BSD-3-Clause"
] | null | null | null | gtsam/inference/IndexFactor.cpp | sdmiller/gtsam_pcl | 1e607bd75090d35e325a8fb37a6c5afe630f1207 | [
"BSD-3-Clause"
] | 6 | 2015-09-10T12:06:08.000Z | 2021-12-10T07:02:48.000Z | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file IndexFactor.cpp
* @author Richard Roberts
* @date Oct 17, 2010
*/
#include <gtsam/inference/IndexFactor.h>
#include <gtsam/inference/Factor-inl.h>
#include <gtsam/inference/IndexConditional.h>
using namespace std;
namespace gtsam {
template class Factor<Index> ;
/* ************************************************************************* */
void IndexFactor::assertInvariants() const {
Base::assertInvariants();
}
/* ************************************************************************* */
IndexFactor::IndexFactor(const IndexConditional& c) :
Base(c) {
assertInvariants();
}
/* ************************************************************************* */
#ifdef TRACK_ELIMINATE
boost::shared_ptr<IndexConditional> IndexFactor::eliminateFirst() {
boost::shared_ptr<IndexConditional> result(Base::eliminateFirst<
IndexConditional>());
assertInvariants();
return result;
}
/* ************************************************************************* */
boost::shared_ptr<BayesNet<IndexConditional> > IndexFactor::eliminate(
size_t nrFrontals) {
boost::shared_ptr<BayesNet<IndexConditional> > result(Base::eliminate<
IndexConditional>(nrFrontals));
assertInvariants();
return result;
}
#endif
/* ************************************************************************* */
void IndexFactor::permuteWithInverse(const Permutation& inversePermutation) {
BOOST_FOREACH(Index& key, keys())
key = inversePermutation[key];
assertInvariants();
}
/* ************************************************************************* */
} // gtsam
| 30.484848 | 80 | 0.500994 | sdmiller |
b04710b459e76e180d6b1076eae57b2ef779063c | 483 | hpp | C++ | contrib/autoboost/autoboost/chrono/chrono.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 87 | 2015-01-18T00:43:06.000Z | 2022-02-11T17:40:50.000Z | contrib/autoboost/autoboost/chrono/chrono.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 274 | 2015-01-03T04:50:49.000Z | 2021-03-08T09:01:09.000Z | contrib/autoboost/autoboost/chrono/chrono.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 15 | 2015-09-30T20:58:43.000Z | 2020-12-19T21:24:56.000Z | // chrono.hpp --------------------------------------------------------------//
// Copyright 2009-2011 Vicente J. Botet Escriba
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
#ifndef AUTOBOOST_CHRONO_CHRONO_HPP
#define AUTOBOOST_CHRONO_CHRONO_HPP
#include <autoboost/chrono/duration.hpp>
#include <autoboost/chrono/time_point.hpp>
#include <autoboost/chrono/system_clocks.hpp>
#endif // AUTOBOOST_CHRONO_CHRONO_HPP
| 30.1875 | 80 | 0.68323 | CaseyCarter |
b0496ad24efd9ec95a1966b32ddd2b733e835216 | 1,413 | cpp | C++ | Active/CodeForces/Count_Subarrays.cpp | pawan-nirpal-031/Algorithms-And-ProblemSolving | 24ce9649345dabe7275920f6912e410efc2c8e84 | [
"Apache-2.0"
] | 2 | 2021-03-05T08:40:01.000Z | 2021-04-25T13:58:42.000Z | Active/Codechef/Count_Subarrays.cpp | pawan-nirpal-031/Algorithms-And-ProblemSolving | 24ce9649345dabe7275920f6912e410efc2c8e84 | [
"Apache-2.0"
] | null | null | null | Active/Codechef/Count_Subarrays.cpp | pawan-nirpal-031/Algorithms-And-ProblemSolving | 24ce9649345dabe7275920f6912e410efc2c8e84 | [
"Apache-2.0"
] | null | null | null | // Problem Link : https://www.codechef.com/problems/SUBINC
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long int ull;
typedef long long int ll;
typedef long double ld;
#define Mod 1000000007
#define Infinity (ll)1e18
#define Append(a) push_back(a)
#define Pair(a,b) make_pair(a,b)
#define Clear(a) for(ll &x : a){x=0;}
#define Point(x) std::fixed<<setprecision(15)<<x
#define SetBits(x) __builtin_popcount(x);
#define DebugCase(i,x) cout<<"Case #"<<i<<": "<<x<<'\n'
#define FastIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define Status(b) (cout<<(b?"YES\n":"NO\n"));
#define Print(x) cout<<x
#define Input(x) cin>>x
/*
Problem Statement :
Given an array A1,A2,...,AN, count the number of subarrays of array A which are non-decreasing.
A subarray A[i,j], where 1≤i≤j≤N is a sequence of integers Ai,Ai+1,...,Aj.
A subarray A[i,j] is non-decreasing if Ai≤Ai+1≤Ai+2≤...≤Aj. You have to count the total number of such subarrays.
*/
void solve(){
int n;
cin>>n;
ll a[n];
vector<ll>num_of_subarrys_end(n,0);
for(ll &x : a) cin>>x;
ll ans = num_of_subarrys_end[0] = 1;
for(int i =1;i<n;i++){
num_of_subarrys_end[i] = 1 + (a[i]>=a[i-1]?num_of_subarrys_end[i-1]:0);
ans+=num_of_subarrys_end[i];
}
cout<<ans<<'\n';
}
int main(){
FastIO;
int t;
cin>>t;
while(t--) solve();
return 0;
}
// If Solved Mark (0/1) here => [1] | 26.166667 | 113 | 0.64402 | pawan-nirpal-031 |
b04b7c7fae4ad1f1dd17bf35259b5dcf0fbe3a52 | 1,033 | cpp | C++ | Lab6/timer/timer.cpp | HanlinHu/CS210_LAB_code | c0f2d89cb6b1d2047bd6fea7e2a041660245dc32 | [
"MIT"
] | null | null | null | Lab6/timer/timer.cpp | HanlinHu/CS210_LAB_code | c0f2d89cb6b1d2047bd6fea7e2a041660245dc32 | [
"MIT"
] | null | null | null | Lab6/timer/timer.cpp | HanlinHu/CS210_LAB_code | c0f2d89cb6b1d2047bd6fea7e2a041660245dc32 | [
"MIT"
] | null | null | null | //--------------------------------------------------------------------
//
// Laboratory C timer.cpp
//
// SOLUTION: Implementation of the Timer ADT
//
//
// from "A Laboratory Course in C++ Data Structures" (Roberge,Brandle,Whittington)
//--------------------------------------------------------------------
#include <iostream>
#include <ctime>
#include "timer.h"
//--------------------------------------------------------------------
void Timer::start ()
// Starts the timer.
{
//startTime = times( NULL );
startTime = clock();
}
//--------------------------------------------------------------------
void Timer::stop ()
// Stops the timer.
{
//stopTime = times( NULL );
stopTime = clock();
}
//--------------------------------------------------------------------
double Timer::getElapsedTime () const
// Computes the length of the time interval from startTime to
// stopTime (in seconds).
{
return double ( stopTime - startTime ) / (CLOCKS_PER_SEC) ;
}
| 21.978723 | 83 | 0.398838 | HanlinHu |
b0531130bb331b441af45927d8b8b8af52e452cc | 5,174 | cpp | C++ | source/rho/crypt/tReadableAES.cpp | Rhobota/librho | d540cba6227e15ac6ef3dcb6549ed9557f6fee04 | [
"BSD-3-Clause"
] | 1 | 2016-09-22T03:27:33.000Z | 2016-09-22T03:27:33.000Z | source/rho/crypt/tReadableAES.cpp | Rhobota/librho | d540cba6227e15ac6ef3dcb6549ed9557f6fee04 | [
"BSD-3-Clause"
] | null | null | null | source/rho/crypt/tReadableAES.cpp | Rhobota/librho | d540cba6227e15ac6ef3dcb6549ed9557f6fee04 | [
"BSD-3-Clause"
] | null | null | null | #include <rho/crypt/tReadableAES.h>
#include <rho/eRho.h>
#include <algorithm>
#include <cstdlib>
namespace rho
{
namespace crypt
{
tReadableAES::tReadableAES(iReadable* internalStream, nOperationModeAES opmode,
const u8 key[], nKeyLengthAES keylen)
: m_stream(internalStream),
m_buf(NULL), m_bufSize(0),
m_bufUsed(0), m_pos(0),
m_seq(0),
m_opmode(opmode),
m_aes(opmode, key, keylen)
{
// Check the op mode.
if (m_opmode == kOpModeCBC)
{
m_hasReadInitializationVector = false;
}
// Alloc the chunk buffer.
m_bufSize = 512*AES_BLOCK_SIZE;
m_buf = new u8[m_bufSize];
}
tReadableAES::~tReadableAES()
{
delete [] m_buf;
m_buf = NULL;
m_bufSize = 0;
m_bufUsed = 0;
m_pos = 0;
}
i32 tReadableAES::read(u8* buffer, i32 length)
{
if (length <= 0)
throw eInvalidArgument("Stream read/write length must be >0");
if (m_pos >= m_bufUsed)
if (! m_refill()) // sets m_pos and m_bufUsed
return -1;
u32 rem = m_bufUsed - m_pos;
if (rem > (u32)length)
rem = (u32)length;
memcpy(buffer, m_buf+m_pos, rem);
m_pos += rem;
return (i32)rem;
}
i32 tReadableAES::readAll(u8* buffer, i32 length)
{
if (length <= 0)
throw eInvalidArgument("Stream read/write length must be >0");
i32 amountRead = 0;
while (amountRead < length)
{
i32 n = read(buffer+amountRead, length-amountRead);
if (n <= 0)
return (amountRead>0) ? amountRead : n;
amountRead += n;
}
return amountRead;
}
bool tReadableAES::m_refill()
{
// Reset indices.
m_pos = 0;
m_bufUsed = 0;
// If in cbc mode and this is the first time m_refill is called, read the
// initialization vector off the stream and decrypt it.
if (m_opmode == kOpModeCBC && !m_hasReadInitializationVector)
{
u8 initVectorCt[AES_BLOCK_SIZE];
i32 r = m_stream.readAll(initVectorCt, AES_BLOCK_SIZE);
if (r != AES_BLOCK_SIZE)
{
return (r >= 0); // <-- makes read() give the expected behavior
}
m_aes.dec(initVectorCt, m_last_ct, 1);
m_hasReadInitializationVector = true;
}
// Read an AES block from the stream.
u8 ct[AES_BLOCK_SIZE];
i32 r = m_stream.readAll(ct, AES_BLOCK_SIZE);
if (r != AES_BLOCK_SIZE)
{
return (r >= 0); // <-- makes read() give the expected behavior
}
// Decrypt the ct buffer into the pt buffer.
u8 pt[AES_BLOCK_SIZE];
m_aes.dec(ct, pt, 1, m_last_ct);
// Pointer aliasing.
u8* buf = m_buf;
// We just read the first block (16 bytes) of a chunk from the stream.
// This block contains the chunk's length, sequence number, and parity.
// Extract the chunk length.
u32 chunkLen = 0;
chunkLen |= pt[0]; chunkLen <<= 8;
chunkLen |= pt[1]; chunkLen <<= 8;
chunkLen |= pt[2]; chunkLen <<= 8;
chunkLen |= pt[3];
// Extract the sequence number.
u64 seq = 0;
seq |= pt[ 4]; seq <<= 8;
seq |= pt[ 5]; seq <<= 8;
seq |= pt[ 6]; seq <<= 8;
seq |= pt[ 7]; seq <<= 8;
seq |= pt[ 8]; seq <<= 8;
seq |= pt[ 9]; seq <<= 8;
seq |= pt[10]; seq <<= 8;
seq |= pt[11];
// Verify that these values are correct.
if (chunkLen <= 16)
throw eRuntimeError("This stream is not a valid AES stream. The chunk length is <=16.");
if (chunkLen > m_bufSize)
throw eRuntimeError("This stream is not a valid AES stream. The chunk length is too large.");
if (seq != m_seq)
throw eRuntimeError("This stream is not a valid AES stream. The sequence number is not what was expected.");
m_seq += chunkLen;
// Start the parity check.
u8 parity[4] = { 0, 0, 0, 0 };
for (u32 i = 0; i < AES_BLOCK_SIZE; i++)
parity[i%4] ^= pt[i];
// Read the rest of the chunk into our buffer.
chunkLen -= AES_BLOCK_SIZE;
u32 extraBytes = (chunkLen % AES_BLOCK_SIZE);
u32 bytesToRead = (extraBytes > 0) ? (chunkLen + (AES_BLOCK_SIZE-extraBytes)) : (chunkLen);
r = m_stream.readAll(buf, bytesToRead);
if (r < 0 || ((u32)r) != bytesToRead)
{
return (r >= 0); // <-- makes read() give the expected behavior
}
// Decrypt the bytes we just read.
m_aes.dec(buf, buf, bytesToRead/AES_BLOCK_SIZE, m_last_ct);
// Calculate the parity.
for (u32 i = 0; i < bytesToRead; i += AES_BLOCK_SIZE)
{
for (int j = 0; j < AES_BLOCK_SIZE; j++)
{
parity[(i+j)%4] ^= buf[i+j];
}
}
// Make sure the parity works out.
for (u32 i = chunkLen; i < bytesToRead; i++)
parity[i%4] ^= buf[i];
for (u32 i = 0; i < 4; i++)
if (parity[i] != 0)
throw eRuntimeError("This stream is not a valid AES stream. The parity is broken.");
// All must have worked, so set the state up for reading.
m_bufUsed = chunkLen;
return true;
}
void tReadableAES::reset()
{
m_pos = 0;
m_bufUsed = 0;
m_seq = 0;
if (m_opmode == kOpModeCBC)
m_hasReadInitializationVector = false;
}
} // namespace crypt
} // namespace rho
| 26.533333 | 116 | 0.587746 | Rhobota |
b05728ae2eed9351197d6e300f9c667d53475c61 | 4,961 | cpp | C++ | src/hgs-TV/Decomposition/RouteSequenceDecomposition.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | src/hgs-TV/Decomposition/RouteSequenceDecomposition.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | src/hgs-TV/Decomposition/RouteSequenceDecomposition.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | //
// Created by alberto on 13/03/19.
//
#include "RouteSequenceDecomposition.h"
namespace genvrp {
void RouteSequenceDecomposition::operator()(genvrp::Population& population, const SolverStatus& status) {
// If the problem does not have enough individuals, skip decomposition.
if(params.data.nbClients <= params.deco.targetMaxSpCustomers) {
#ifndef BATCH_MODE
std::cout << status.outPrefix << "[Decomposition] Not enough customers for decomposition (" << params.data.nbClients << " < "
<< params.deco.targetMaxSpCustomers << ")\n";
#endif
return;
}
// Get an elite individual.
eliteIndividual.emplace(population.getEliteIndividual(params.deco.eliteFraction));
// Get the subproblems to solve. Method getSubproblems needs to be implemented
// by any class deriving from RouteSequenceDecomposition.
auto subproblems = getSubproblems(*eliteIndividual, status);
#ifndef BATCH_MODE
std::cout << status.outPrefix << "[Decomposition] Created " << subproblems.size() << " subproblems.\n";
#endif
// Skip if there is only one subproblem.
if(subproblems.size() < 2u) {
#ifndef BATCH_MODE
std::cout << status.outPrefix << "[Decomposition] Not enough subproblems (<2).\n";
#endif
return;
}
// New individual that we want to build starting from the subproblems solutions.
auto mpIndividual = Individual{¶ms};
mpIndividual.routes.clear();
mpIndividual.giantTour.clear();
for(auto& subproblem : subproblems) {
const std::optional<Individual> spSolution = subproblem->solve();
if(spSolution) {
// Add the partial solution obtained in the subproblem to the complete
// solution in the master problem individual.
mergeSpSolutionIntoMpIndividual(*spSolution, mpIndividual, *subproblem);
}
}
// Add empty routes in case the number of used vehicles decreased.
for(auto r = mpIndividual.routes.size(); r < params.data.nbVehicles; ++r) {
mpIndividual.routes.emplace_back();
}
// Evaluate the costs of the new MP individual.
mpIndividual.evaluateCompleteCost();
#ifndef BATCH_MODE
std::cout << status.outPrefix << "[Decomposition] Obtained new solution of cost " << mpIndividual.cost.penalizedCost << "\n";
#endif
if(mpIndividual.cost.penalizedCost >= eliteIndividual->cost.penalizedCost) {
// New solution worse, or same, than elite starting one.
// Because we keep the elite parts if the subproblems did not improve
// on them, the new solution is never strictly worse, it can only be
// the same as the elite one - in the worse case.
params.stats.nSpWorsened += 1u;
} else if(mpIndividual.cost.penalizedCost < eliteIndividual->cost.penalizedCost) {
// New solution strictly better than elite starting one.
params.stats.nSpImproved += 1u;
}
// Add the new individual to the population.
population.addIndividualLS(&mpIndividual, true);
}
RouteSequenceDecomposition::SPList RouteSequenceDecomposition::getSubproblemsFromRouteIndices(const Individual& mpIndividual, const SolverStatus& status,
const std::vector<int>& routeIndices) const {
// List where we store the subproblems.
auto sps = SPList{};
// Number of customers in the open subproblem.
auto currentCustomersInSP = 0;
// Indices of routes that go in the open subproblem.
auto currentRoutesIds = std::vector<int>{};
for(const auto& i : routeIndices) {
const auto& mpRoute = mpIndividual.routes.at(i);
if(currentCustomersInSP + mpRoute.size() > params.deco.targetMaxSpCustomers) {
// Adding the route would lead to too many customers: "close" the current SP.
assert(!currentRoutesIds.empty());
sps.push_back(std::make_unique<SubProblem>(params, mpIndividual, status, currentRoutesIds));
// Reset current customers.
currentCustomersInSP = 0;
currentRoutesIds.clear();
}
// Add the current route to the list of routes going into the current SP.
currentRoutesIds.push_back(i);
// Increase the number of customers in the open SP accordingly.
currentCustomersInSP += mpRoute.size();
}
// Check if we left the last subproblem open. In this case, close it.
if(!currentRoutesIds.empty()) {
sps.push_back(std::make_unique<SubProblem>(params, mpIndividual, status, currentRoutesIds));
}
return sps;
}
} // namespace genvrp | 41.689076 | 157 | 0.627293 | alberto-santini |
b057c834a9a81285ef0e662b6decf1a8d9b86531 | 1,727 | cpp | C++ | src/prod/test/LinuxRetailTests/FabricRuntime.Test.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/test/LinuxRetailTests/FabricRuntime.Test.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/test/LinuxRetailTests/FabricRuntime.Test.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
#include "FabricRuntime.h"
#include "FabricRuntime_.h"
int TestFabricRuntime ()
{
IID iid;
FABRIC_PARTITION_ID pid;
FABRIC_URI serviceName;
FabricBeginCreateRuntime(iid, nullptr, 0, nullptr, nullptr);
FabricEndCreateRuntime(nullptr, nullptr);
FabricCreateRuntime(iid, nullptr);
FabricBeginGetActivationContext(iid, 0, nullptr, nullptr);
FabricEndGetActivationContext(nullptr, nullptr);
FabricGetActivationContext(iid, nullptr);
FabricRegisterCodePackageHost(nullptr);
FabricCreateKeyValueStoreReplica(iid, nullptr, pid, 0, nullptr, (FABRIC_LOCAL_STORE_KIND) 0, nullptr, nullptr, nullptr);
FabricCreateKeyValueStoreReplica2(iid, nullptr, pid, 0, nullptr, (FABRIC_LOCAL_STORE_KIND) 0, nullptr, nullptr, nullptr, (FABRIC_KEY_VALUE_STORE_NOTIFICATION_MODE) 0, nullptr);
FabricCreateKeyValueStoreReplica3(iid, nullptr, pid, 0, nullptr, (FABRIC_LOCAL_STORE_KIND) 0, nullptr, nullptr, nullptr, (FABRIC_KEY_VALUE_STORE_NOTIFICATION_MODE) 0, nullptr);
FabricCreateKeyValueStoreReplica4(iid, nullptr, pid, 0, serviceName, nullptr, (FABRIC_LOCAL_STORE_KIND) 0, nullptr, nullptr, nullptr, (FABRIC_KEY_VALUE_STORE_NOTIFICATION_MODE) 0, nullptr);
FabricCreateKeyValueStoreReplica5(iid, nullptr, pid, 0, serviceName, nullptr, nullptr, (FABRIC_LOCAL_STORE_KIND) 0, nullptr, nullptr, nullptr, nullptr);
FabricLoadReplicatorSettings(nullptr, nullptr, nullptr, nullptr);
}
| 59.551724 | 193 | 0.727852 | vishnuk007 |
b05d29bf79f5becd8a33c7ff52e004972fc454ce | 3,271 | hpp | C++ | src/Serialization/OptionalSerialization.hpp | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | src/Serialization/OptionalSerialization.hpp | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | src/Serialization/OptionalSerialization.hpp | ElSamaritan/blockchain-OLD | ca3422c8873613226db99b7e6735c5ea1fac9f1a | [
"Apache-2.0"
] | null | null | null | /* ============================================================================================== *
* *
* Galaxia Blockchain *
* *
* ---------------------------------------------------------------------------------------------- *
* This file is part of the Xi framework. *
* ---------------------------------------------------------------------------------------------- *
* *
* Copyright 2018-2019 Xi Project Developers <support.xiproject.io> *
* *
* This program is free software: you can redistribute it and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; *
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with this program. *
* If not, see <https://www.gnu.org/licenses/>. *
* *
* ============================================================================================== */
#pragma once
#include <optional>
#include <type_traits>
#include <cassert>
#include <Xi/ExternalIncludePush.h>
#include <boost/utility/value_init.hpp>
#include <Xi/ExternalIncludePop.h>
#include <Xi/Global.hh>
#include "Serialization/ISerializer.h"
namespace CryptoNote {
template <typename _ValueT>
[[nodiscard]] bool serialize(std::optional<_ValueT> &value, Common::StringView name, ISerializer &serializer) {
using native_t = typename std::remove_cv_t<_ValueT>;
static_assert(std::is_default_constructible_v<native_t>,
"optional serialization expects default constructible types");
bool hasValue = value.has_value();
XI_RETURN_EC_IF_NOT(serializer.maybe(hasValue, name), false);
if (serializer.isInput()) {
if (hasValue) {
value.emplace();
return serializer(*value, name);
} else {
value = std::nullopt;
return true;
}
} else {
assert(serializer.isOutput());
if (hasValue) {
return serializer(*value, name);
} else {
return true;
}
}
}
} // namespace CryptoNote
| 48.820896 | 111 | 0.404769 | ElSamaritan |
b063cb22f43a50d261766d5683f084c7254b05e2 | 108,161 | cpp | C++ | Source/effects.cpp | pionere/devilutionX | 63f8deb298a00b040010fc299c0568eae19522e1 | [
"Unlicense"
] | 2 | 2021-02-02T19:27:20.000Z | 2022-03-07T16:50:55.000Z | Source/effects.cpp | pionere/devilutionX | 63f8deb298a00b040010fc299c0568eae19522e1 | [
"Unlicense"
] | null | null | null | Source/effects.cpp | pionere/devilutionX | 63f8deb298a00b040010fc299c0568eae19522e1 | [
"Unlicense"
] | 1 | 2022-03-07T16:51:16.000Z | 2022-03-07T16:51:16.000Z | /**
* @file effects.cpp
*
* Implementation of functions for loading and playing sounds.
*/
#include "all.h"
#ifndef NOSOUND
#include <SDL_mixer.h>
#include "utils/soundsample.h"
#endif
DEVILUTION_BEGIN_NAMESPACE
int sfxdelay;
int sfxdnum;
#ifdef NOSOUND
const int sgSFXSets[NUM_SFXSets][NUM_CLASSES] = { };
#else
/** Specifies the sound file and the playback state of the current sound effect. */
static SFXStruct* sgpStreamSFX = NULL;
/** Maps from monster sfx to monster sound letter. */
static const char MonstSndChar[NUM_MON_SFX] = { 'a', 'h', 'd', 's' };
/** List of all sounds, except monsters and music */
SFXStruct sgSFX[] = {
// clang-format off
//_sfx_id bFlags, pszName, pSnd
/*PS_WALK1*/ { sfx_MISC, "Sfx\\Misc\\Walk1.wav", { 0, NULL } },
/*PS_WALK2*/// { sfx_MISC, "Sfx\\Misc\\Walk2.wav", { 0, NULL } },
/*PS_WALK3*/// { sfx_MISC, "Sfx\\Misc\\Walk3.wav", { 0, NULL } },
/*PS_WALK4*/// { sfx_MISC, "Sfx\\Misc\\Walk4.wav", { 0, NULL } },
/*PS_BFIRE*/ { sfx_MISC, "Sfx\\Misc\\BFire.wav", { 0, NULL } },
/*PS_FMAG*/// { sfx_MISC, "Sfx\\Misc\\Fmag.wav", { 0, NULL } },
/*PS_TMAG*/// { sfx_MISC, "Sfx\\Misc\\Tmag.wav", { 0, NULL } },
/*PS_LGHIT*/// { sfx_MISC, "Sfx\\Misc\\Lghit.wav", { 0, NULL } },
/*PS_LGHIT1*/// { sfx_MISC, "Sfx\\Misc\\Lghit1.wav", { 0, NULL } },
/*PS_SWING*/ { sfx_MISC, "Sfx\\Misc\\Swing.wav", { 0, NULL } },
/*PS_SWING2*/ { sfx_MISC, "Sfx\\Misc\\Swing2.wav", { 0, NULL } },
/*PS_DEAD*/ { sfx_MISC, "Sfx\\Misc\\Dead.wav", { 0, NULL } }, // Aaauh...
/*IS_STING1*/// { sfx_MISC | sfx_HELLFIRE, "Sfx\\Misc\\Sting1.wav", { 0, NULL } },
/*IS_FBALLBOW*///{ sfx_MISC | sfx_HELLFIRE, "Sfx\\Misc\\FBallBow.wav", { 0, NULL } },
/*IS_QUESTDN*/ { sfx_STREAM, "Sfx\\Misc\\Questdon.wav", { 0, NULL } },
/*IS_ARMRFKD*/// { sfx_MISC, "Sfx\\Items\\Armrfkd.wav", { 0, NULL } },
/*IS_BARLFIRE*/ { sfx_MISC, "Sfx\\Items\\Barlfire.wav", { 0, NULL } },
/*IS_BARREL*/ { sfx_MISC, "Sfx\\Items\\Barrel.wav", { 0, NULL } },
/*IS_POPPOP8*/ { sfx_MISC | sfx_HELLFIRE, "Sfx\\Items\\PodPop8.wav", { 0, NULL } },
/*IS_POPPOP5*/ { sfx_MISC | sfx_HELLFIRE, "Sfx\\Items\\PodPop5.wav", { 0, NULL } },
/*IS_POPPOP3*/ { sfx_MISC | sfx_HELLFIRE, "Sfx\\Items\\UrnPop3.wav", { 0, NULL } },
/*IS_POPPOP2*/ { sfx_MISC | sfx_HELLFIRE, "Sfx\\Items\\UrnPop2.wav", { 0, NULL } },
/*IS_CRCLOS*/ { sfx_MISC | sfx_HELLFIRE, "Sfx\\Items\\Crclos.wav", { 0, NULL } },
/*IS_CROPEN*/ { sfx_MISC | sfx_HELLFIRE, "Sfx\\Items\\Cropen.wav", { 0, NULL } },
/*IS_BHIT*/// { sfx_MISC, "Sfx\\Items\\Bhit.wav", { 0, NULL } },
/*IS_BHIT1*/// { sfx_MISC, "Sfx\\Items\\Bhit1.wav", { 0, NULL } },
/*IS_CHEST*/ { sfx_MISC, "Sfx\\Items\\Chest.wav", { 0, NULL } },
/*IS_DOORCLOS*/ { sfx_MISC, "Sfx\\Items\\Doorclos.wav", { 0, NULL } },
/*IS_DOOROPEN*/ { sfx_MISC, "Sfx\\Items\\Dooropen.wav", { 0, NULL } },
/*IS_FANVL*/ { sfx_MISC, "Sfx\\Items\\Flipanvl.wav", { 0, NULL } },
/*IS_FAXE*/ { sfx_MISC, "Sfx\\Items\\Flipaxe.wav", { 0, NULL } },
/*IS_FBLST*/ { sfx_MISC, "Sfx\\Items\\Flipblst.wav", { 0, NULL } },
/*IS_FBODY*/ { sfx_MISC, "Sfx\\Items\\Flipbody.wav", { 0, NULL } },
/*IS_FBOOK*/ { sfx_MISC, "Sfx\\Items\\Flipbook.wav", { 0, NULL } },
/*IS_FBOW*/ { sfx_MISC, "Sfx\\Items\\Flipbow.wav", { 0, NULL } },
/*IS_FCAP*/ { sfx_MISC, "Sfx\\Items\\Flipcap.wav", { 0, NULL } },
/*IS_FHARM*/ { sfx_MISC, "Sfx\\Items\\Flipharm.wav", { 0, NULL } },
/*IS_FLARM*/ { sfx_MISC, "Sfx\\Items\\Fliplarm.wav", { 0, NULL } },
/*IS_FMAG*/// { sfx_MISC, "Sfx\\Items\\Flipmag.wav", { 0, NULL } },
/*IS_FMAG1*/// { sfx_MISC, "Sfx\\Items\\Flipmag1.wav", { 0, NULL } },
/*IS_FMUSH*/ { sfx_MISC, "Sfx\\Items\\Flipmush.wav", { 0, NULL } },
/*IS_FPOT*/ { sfx_MISC, "Sfx\\Items\\Flippot.wav", { 0, NULL } },
/*IS_FRING*/ { sfx_MISC, "Sfx\\Items\\Flipring.wav", { 0, NULL } },
/*IS_FROCK*/ { sfx_MISC, "Sfx\\Items\\Fliprock.wav", { 0, NULL } },
/*IS_FSCRL*/ { sfx_MISC, "Sfx\\Items\\Flipscrl.wav", { 0, NULL } },
/*IS_FSHLD*/ { sfx_MISC, "Sfx\\Items\\Flipshld.wav", { 0, NULL } },
/*IS_FSIGN*/// { sfx_MISC, "Sfx\\Items\\Flipsign.wav", { 0, NULL } },
/*IS_FSTAF*/ { sfx_MISC, "Sfx\\Items\\Flipstaf.wav", { 0, NULL } },
/*IS_FSWOR*/ { sfx_MISC, "Sfx\\Items\\Flipswor.wav", { 0, NULL } },
/*IS_GOLD*/ { sfx_MISC, "Sfx\\Items\\Gold.wav", { 0, NULL } },
/*IS_HLMTFKD*/// { sfx_MISC, "Sfx\\Items\\Hlmtfkd.wav", { 0, NULL } },
/*IS_IANVL*/ { sfx_MISC, "Sfx\\Items\\Invanvl.wav", { 0, NULL } },
/*IS_IAXE*/ { sfx_MISC, "Sfx\\Items\\Invaxe.wav", { 0, NULL } },
/*IS_IBLST*/ { sfx_MISC, "Sfx\\Items\\Invblst.wav", { 0, NULL } },
/*IS_IBODY*/ { sfx_MISC, "Sfx\\Items\\Invbody.wav", { 0, NULL } },
/*IS_IBOOK*/ { sfx_MISC, "Sfx\\Items\\Invbook.wav", { 0, NULL } },
/*IS_IBOW*/ { sfx_MISC, "Sfx\\Items\\Invbow.wav", { 0, NULL } },
/*IS_ICAP*/ { sfx_MISC, "Sfx\\Items\\Invcap.wav", { 0, NULL } },
/*IS_IGRAB*/ { sfx_MISC, "Sfx\\Items\\Invgrab.wav", { 0, NULL } },
/*IS_IHARM*/ { sfx_MISC, "Sfx\\Items\\Invharm.wav", { 0, NULL } },
/*IS_ILARM*/ { sfx_MISC, "Sfx\\Items\\Invlarm.wav", { 0, NULL } },
/*IS_IMUSH*/ { sfx_MISC, "Sfx\\Items\\Invmush.wav", { 0, NULL } },
/*IS_IPOT*/ { sfx_MISC, "Sfx\\Items\\Invpot.wav", { 0, NULL } },
/*IS_IRING*/ { sfx_MISC, "Sfx\\Items\\Invring.wav", { 0, NULL } },
/*IS_IROCK*/ { sfx_MISC, "Sfx\\Items\\Invrock.wav", { 0, NULL } },
/*IS_ISCROL*/ { sfx_MISC, "Sfx\\Items\\Invscrol.wav", { 0, NULL } },
/*IS_ISHIEL*/ { sfx_MISC, "Sfx\\Items\\Invshiel.wav", { 0, NULL } },
/*IS_ISIGN*/ { sfx_MISC, "Sfx\\Items\\Invsign.wav", { 0, NULL } },
/*IS_ISTAF*/ { sfx_MISC, "Sfx\\Items\\Invstaf.wav", { 0, NULL } },
/*IS_ISWORD*/ { sfx_MISC, "Sfx\\Items\\Invsword.wav", { 0, NULL } },
/*IS_LEVER*/ { sfx_MISC, "Sfx\\Items\\Lever.wav", { 0, NULL } },
/*IS_MAGIC*/ { sfx_MISC, "Sfx\\Items\\Magic.wav", { 0, NULL } },
/*IS_MAGIC1*/ { sfx_MISC, "Sfx\\Items\\Magic1.wav", { 0, NULL } },
/*IS_RBOOK*/ { sfx_MISC, "Sfx\\Items\\Readbook.wav", { 0, NULL } },
/*IS_SARC*/ { sfx_MISC, "Sfx\\Items\\Sarc.wav", { 0, NULL } },
/*IS_SHLDFKD*/// { sfx_MISC, "Sfx\\Items\\Shielfkd.wav", { 0, NULL } },
/*IS_SWRDFKD*/// { sfx_MISC, "Sfx\\Items\\Swrdfkd.wav", { 0, NULL } },
/*IS_TITLEMOV*/ { sfx_UI, "Sfx\\Items\\Titlemov.wav", { 0, NULL } },
/*IS_TITLSLCT*/ { sfx_UI, "Sfx\\Items\\Titlslct.wav", { 0, NULL } },
/*SFX_SILENCE*/ { sfx_UI, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*IS_TRAP*/ { sfx_MISC, "Sfx\\Items\\Trap.wav", { 0, NULL } },
/*IS_CAST1*/// { sfx_MISC, "Sfx\\Misc\\Cast1.wav", { 0, NULL } },
/*IS_CAST10*/// { sfx_MISC, "Sfx\\Misc\\Cast10.wav", { 0, NULL } },
/*IS_CAST12*/// { sfx_MISC, "Sfx\\Misc\\Cast12.wav", { 0, NULL } },
/*IS_CAST2*/ { sfx_MISC, "Sfx\\Misc\\Cast2.wav", { 0, NULL } },
/*IS_CAST3*/// { sfx_MISC, "Sfx\\Misc\\Cast3.wav", { 0, NULL } },
/*IS_CAST4*/ { sfx_MISC, "Sfx\\Misc\\Cast4.wav", { 0, NULL } },
/*IS_CAST5*/// { sfx_MISC, "Sfx\\Misc\\Cast5.wav", { 0, NULL } },
/*IS_CAST6*/ { sfx_MISC, "Sfx\\Misc\\Cast6.wav", { 0, NULL } },
/*IS_CAST7*/// { sfx_MISC, "Sfx\\Misc\\Cast7.wav", { 0, NULL } },
/*IS_CAST8*/ { sfx_MISC, "Sfx\\Misc\\Cast8.wav", { 0, NULL } },
/*IS_CAST9*/// { sfx_MISC, "Sfx\\Misc\\Cast9.wav", { 0, NULL } },
/*LS_HEALING*/// { sfx_MISC, "Sfx\\Misc\\Healing.wav", { 0, NULL } },
/*IS_REPAIR*/ { sfx_MISC, "Sfx\\Misc\\Repair.wav", { 0, NULL } },
/*LS_ACID*/ { sfx_MISC, "Sfx\\Misc\\Acids1.wav", { 0, NULL } },
/*LS_ACIDS*/ { sfx_MISC, "Sfx\\Misc\\Acids2.wav", { 0, NULL } },
/*LS_APOC*/// { sfx_MISC, "Sfx\\Misc\\Apoc.wav", { 0, NULL } },
/*LS_ARROWALL*///{ sfx_MISC, "Sfx\\Misc\\Arrowall.wav", { 0, NULL } },
/*LS_BLODBOIL*///{ sfx_MISC, "Sfx\\Misc\\Bldboil.wav", { 0, NULL } },
/*LS_BLODSTAR*/ { sfx_MISC, "Sfx\\Misc\\Blodstar.wav", { 0, NULL } },
/*LS_BLSIMPT*/// { sfx_MISC, "Sfx\\Misc\\Blsimpt.wav", { 0, NULL } },
/*LS_BONESP*/ { sfx_MISC, "Sfx\\Misc\\Bonesp.wav", { 0, NULL } },
/*LS_BSIMPCT*/// { sfx_MISC, "Sfx\\Misc\\Bsimpct.wav", { 0, NULL } },
/*LS_CALDRON*/ { sfx_MISC, "Sfx\\Misc\\Caldron.wav", { 0, NULL } },
/*LS_CBOLT*/ { sfx_MISC, "Sfx\\Misc\\Cbolt.wav", { 0, NULL } },
/*LS_CHLTNING*///{ sfx_MISC, "Sfx\\Misc\\Chltning.wav", { 0, NULL } },
/*LS_DSERP*/// { sfx_MISC, "Sfx\\Misc\\DSerp.wav", { 0, NULL } },
/*LS_ELECIMP1*/ { sfx_MISC, "Sfx\\Misc\\Elecimp1.wav", { 0, NULL } },
/*LS_ELEMENTL*/ { sfx_MISC, "Sfx\\Misc\\Elementl.wav", { 0, NULL } },
/*LS_ETHEREAL*/ { sfx_MISC, "Sfx\\Misc\\Ethereal.wav", { 0, NULL } },
/*LS_FBALL*/// { sfx_MISC, "Sfx\\Misc\\Fball.wav", { 0, NULL } },
/*LS_FBOLT1*/ { sfx_MISC, "Sfx\\Misc\\Fbolt1.wav", { 0, NULL } },
/*LS_FBOLT2*/// { sfx_MISC, "Sfx\\Misc\\Fbolt2.wav", { 0, NULL } },
/*LS_FIRIMP1*/// { sfx_MISC, "Sfx\\Misc\\Firimp1.wav", { 0, NULL } },
/*LS_FIRIMP2*/ { sfx_MISC, "Sfx\\Misc\\Firimp2.wav", { 0, NULL } },
/*LS_FLAMWAVE*/ { sfx_MISC, "Sfx\\Misc\\Flamwave.wav", { 0, NULL } },
/*LS_FLASH*/// { sfx_MISC, "Sfx\\Misc\\Flash.wav", { 0, NULL } },
/*LS_FOUNTAIN*/ { sfx_MISC, "Sfx\\Misc\\Fountain.wav", { 0, NULL } },
/*LS_GOLUM*/ { sfx_MISC, "Sfx\\Misc\\Golum.wav", { 0, NULL } },
/*LS_GOLUMDED*///{ sfx_MISC, "Sfx\\Misc\\Golumded.wav", { 0, NULL } },
/*LS_GSHRINE*/ { sfx_MISC, "Sfx\\Misc\\Gshrine.wav", { 0, NULL } },
/*LS_GUARD*/ { sfx_MISC, "Sfx\\Misc\\Guard.wav", { 0, NULL } },
/*LS_GUARDLAN*///{ sfx_MISC, "Sfx\\Misc\\Grdlanch.wav", { 0, NULL } },
/*LS_HOLYBOLT*/ { sfx_MISC, "Sfx\\Misc\\Holybolt.wav", { 0, NULL } },
/*LS_HYPER*/// { sfx_MISC, "Sfx\\Misc\\Hyper.wav", { 0, NULL } },
/*LS_INFRAVIS*/ { sfx_MISC, "Sfx\\Misc\\Infravis.wav", { 0, NULL } },
/*LS_INVISIBL*///{ sfx_MISC, "Sfx\\Misc\\Invisibl.wav", { 0, NULL } },
/*LS_INVPOT*/// { sfx_MISC, "Sfx\\Misc\\Invpot.wav", { 0, NULL } },
/*LS_LNING1*/ { sfx_MISC, "Sfx\\Misc\\Lning1.wav", { 0, NULL } },
/*LS_LTNING*/// { sfx_MISC, "Sfx\\Misc\\Ltning.wav", { 0, NULL } },
/*LS_MSHIELD*/ { sfx_MISC, "Sfx\\Misc\\Mshield.wav", { 0, NULL } },
/*LS_NESTXPLD*///{ sfx_MISC | sfx_HELLFIRE, "Sfx\\Misc\\NestXpld.wav", { 0, NULL } },
/*LS_NOVA*/ { sfx_MISC, "Sfx\\Misc\\Nova.wav", { 0, NULL } },
/*LS_PORTAL*/// { sfx_MISC, "Sfx\\Misc\\Portal.wav", { 0, NULL } },
/*LS_PUDDLE*/ { sfx_MISC, "Sfx\\Misc\\Puddle.wav", { 0, NULL } },
/*LS_RESUR*/ { sfx_MISC, "Sfx\\Misc\\Resur.wav", { 0, NULL } },
/*LS_SCURSE*/// { sfx_MISC, "Sfx\\Misc\\Scurse.wav", { 0, NULL } },
/*LS_SCURIMP*/ { sfx_MISC, "Sfx\\Misc\\Scurimp.wav", { 0, NULL } },
/*LS_SENTINEL*/ { sfx_MISC, "Sfx\\Misc\\Sentinel.wav", { 0, NULL } },
/*LS_SHATTER*/// { sfx_MISC, "Sfx\\Misc\\Shatter.wav", { 0, NULL } },
/*LS_SOULFIRE*///{ sfx_MISC, "Sfx\\Misc\\Soulfire.wav", { 0, NULL } },
/*LS_SPOUTLOP*///{ sfx_MISC, "Sfx\\Misc\\Spoutlop.wav", { 0, NULL } },
/*LS_SPOUTSTR*/ { sfx_MISC, "Sfx\\Misc\\Spoutstr.wav", { 0, NULL } },
/*LS_STORM*/// { sfx_MISC, "Sfx\\Misc\\Storm.wav", { 0, NULL } },
/*LS_TRAPDIS*/ { sfx_MISC, "Sfx\\Misc\\Trapdis.wav", { 0, NULL } },
/*LS_TELEPORT*/ { sfx_MISC, "Sfx\\Misc\\Teleport.wav", { 0, NULL } },
/*LS_VTHEFT*/// { sfx_MISC, "Sfx\\Misc\\Vtheft.wav", { 0, NULL } },
/*LS_WALLLOOP*/ { sfx_MISC, "Sfx\\Misc\\Wallloop.wav", { 0, NULL } },
/*LS_WALLSTRT*///{ sfx_MISC, "Sfx\\Misc\\Wallstrt.wav", { 0, NULL } },
/*LS_LMAG*/// { sfx_MISC | sfx_HELLFIRE, "Sfx\\Misc\\LMag.wav", { 0, NULL } },
/*TSFX_BMAID1*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid01.wav", { 0, NULL } },
/*TSFX_BMAID2*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid02.wav", { 0, NULL } },
/*TSFX_BMAID3*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid03.wav", { 0, NULL } },
/*TSFX_BMAID4*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid04.wav", { 0, NULL } },
/*TSFX_BMAID5*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid05.wav", { 0, NULL } },
/*TSFX_BMAID6*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid06.wav", { 0, NULL } },
/*TSFX_BMAID7*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid07.wav", { 0, NULL } },
/*TSFX_BMAID8*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid08.wav", { 0, NULL } },
/*TSFX_BMAID9*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid09.wav", { 0, NULL } },
/*TSFX_BMAID10*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid10.wav", { 0, NULL } },
/*TSFX_BMAID11*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid11.wav", { 0, NULL } },
/*TSFX_BMAID12*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid12.wav", { 0, NULL } },
/*TSFX_BMAID13*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid13.wav", { 0, NULL } },
/*TSFX_BMAID14*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid14.wav", { 0, NULL } },
/*TSFX_BMAID15*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid15.wav", { 0, NULL } },
/*TSFX_BMAID16*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid16.wav", { 0, NULL } },
/*TSFX_BMAID17*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid17.wav", { 0, NULL } },
/*TSFX_BMAID18*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid18.wav", { 0, NULL } },
/*TSFX_BMAID19*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid19.wav", { 0, NULL } },
/*TSFX_BMAID20*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid20.wav", { 0, NULL } },
/*TSFX_BMAID21*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid21.wav", { 0, NULL } },
/*TSFX_BMAID22*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid22.wav", { 0, NULL } },
/*TSFX_BMAID23*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid23.wav", { 0, NULL } },
/*TSFX_BMAID24*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid24.wav", { 0, NULL } },
/*TSFX_BMAID25*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid25.wav", { 0, NULL } },
/*TSFX_BMAID26*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid26.wav", { 0, NULL } },
/*TSFX_BMAID27*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid27.wav", { 0, NULL } },
/*TSFX_BMAID28*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid28.wav", { 0, NULL } },
/*TSFX_BMAID29*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid29.wav", { 0, NULL } },
/*TSFX_BMAID30*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid30.wav", { 0, NULL } },
/*TSFX_BMAID31*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid31.wav", { 0, NULL } },
/*TSFX_BMAID32*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid32.wav", { 0, NULL } },
/*TSFX_BMAID33*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid33.wav", { 0, NULL } },
/*TSFX_BMAID34*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid34.wav", { 0, NULL } },
/*TSFX_BMAID35*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid35.wav", { 0, NULL } },
/*TSFX_BMAID36*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid36.wav", { 0, NULL } },
/*TSFX_BMAID37*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid37.wav", { 0, NULL } },
/*TSFX_BMAID38*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid38.wav", { 0, NULL } },
/*TSFX_BMAID39*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid39.wav", { 0, NULL } },
/*TSFX_BMAID40*/ { sfx_STREAM, "Sfx\\Towners\\Bmaid40.wav", { 0, NULL } },
/*TSFX_SMITH1*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith01.wav", { 0, NULL } },
/*TSFX_SMITH2*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith02.wav", { 0, NULL } },
/*TSFX_SMITH3*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith03.wav", { 0, NULL } },
/*TSFX_SMITH4*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith04.wav", { 0, NULL } },
/*TSFX_SMITH5*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith05.wav", { 0, NULL } },
/*TSFX_SMITH6*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith06.wav", { 0, NULL } },
/*TSFX_SMITH7*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith07.wav", { 0, NULL } },
/*TSFX_SMITH8*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith08.wav", { 0, NULL } },
/*TSFX_SMITH9*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith09.wav", { 0, NULL } },
/*TSFX_SMITH10*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith10.wav", { 0, NULL } },
/*TSFX_SMITH11*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith11.wav", { 0, NULL } },
/*TSFX_SMITH12*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith12.wav", { 0, NULL } },
/*TSFX_SMITH13*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith13.wav", { 0, NULL } },
/*TSFX_SMITH14*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith14.wav", { 0, NULL } },
/*TSFX_SMITH15*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith15.wav", { 0, NULL } },
/*TSFX_SMITH16*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith16.wav", { 0, NULL } },
/*TSFX_SMITH17*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith17.wav", { 0, NULL } },
/*TSFX_SMITH18*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith18.wav", { 0, NULL } },
/*TSFX_SMITH19*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith19.wav", { 0, NULL } },
/*TSFX_SMITH20*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith20.wav", { 0, NULL } },
/*TSFX_SMITH21*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith21.wav", { 0, NULL } },
/*TSFX_SMITH22*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith22.wav", { 0, NULL } },
/*TSFX_SMITH23*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith23.wav", { 0, NULL } },
/*TSFX_SMITH24*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith24.wav", { 0, NULL } },
/*TSFX_SMITH25*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith25.wav", { 0, NULL } },
/*TSFX_SMITH26*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith26.wav", { 0, NULL } },
/*TSFX_SMITH27*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith27.wav", { 0, NULL } },
/*TSFX_SMITH28*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith28.wav", { 0, NULL } },
/*TSFX_SMITH29*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith29.wav", { 0, NULL } },
/*TSFX_SMITH30*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith30.wav", { 0, NULL } },
/*TSFX_SMITH31*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith31.wav", { 0, NULL } },
/*TSFX_SMITH32*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith32.wav", { 0, NULL } },
/*TSFX_SMITH33*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith33.wav", { 0, NULL } },
/*TSFX_SMITH34*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith34.wav", { 0, NULL } },
/*TSFX_SMITH35*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith35.wav", { 0, NULL } },
/*TSFX_SMITH36*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith36.wav", { 0, NULL } },
/*TSFX_SMITH37*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith37.wav", { 0, NULL } },
/*TSFX_SMITH38*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith38.wav", { 0, NULL } },
/*TSFX_SMITH39*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith39.wav", { 0, NULL } },
/*TSFX_SMITH40*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith40.wav", { 0, NULL } },
/*TSFX_SMITH41*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith41.wav", { 0, NULL } },
/*TSFX_SMITH42*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith42.wav", { 0, NULL } },
/*TSFX_SMITH43*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith43.wav", { 0, NULL } },
/*TSFX_SMITH44*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith44.wav", { 0, NULL } },
/*TSFX_SMITH45*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith45.wav", { 0, NULL } },
/*TSFX_SMITH46*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith46.wav", { 0, NULL } },
/*TSFX_SMITH47*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith47.wav", { 0, NULL } },
/*TSFX_SMITH48*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith48.wav", { 0, NULL } },
/*TSFX_SMITH49*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith49.wav", { 0, NULL } },
/*TSFX_SMITH50*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith50.wav", { 0, NULL } },
/*TSFX_SMITH51*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith51.wav", { 0, NULL } },
/*TSFX_SMITH52*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith52.wav", { 0, NULL } },
/*TSFX_SMITH53*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith53.wav", { 0, NULL } },
/*TSFX_SMITH54*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith54.wav", { 0, NULL } },
/*TSFX_SMITH55*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith55.wav", { 0, NULL } },
/*TSFX_SMITH56*/ { sfx_STREAM, "Sfx\\Towners\\Bsmith56.wav", { 0, NULL } },
/*TSFX_COW1*/ { sfx_STREAM, "Sfx\\Towners\\Cow1.wav", { 0, NULL } },
/*TSFX_COW2*/ { sfx_STREAM, "Sfx\\Towners\\Cow2.wav", { 0, NULL } },
/*TSFX_COW3*/// { sfx_MISC, "Sfx\\Towners\\Cow3.wav", { 0, NULL } },
/*TSFX_COW4*/// { sfx_MISC, "Sfx\\Towners\\Cow4.wav", { 0, NULL } },
/*TSFX_COW5*/// { sfx_MISC, "Sfx\\Towners\\Cow5.wav", { 0, NULL } },
/*TSFX_COW6*/// { sfx_MISC, "Sfx\\Towners\\Cow6.wav", { 0, NULL } },
/*TSFX_COW7*/// { sfx_MISC, "Sfx\\Towners\\Cow7.wav", { 0, NULL } },
/*TSFX_COW8*/// { sfx_MISC, "Sfx\\Towners\\Cow8.wav", { 0, NULL } },
/*TSFX_DEADGUY*/ { sfx_STREAM, "Sfx\\Towners\\Deadguy2.wav", { 0, NULL } },
/*TSFX_DRUNK1*/ { sfx_STREAM, "Sfx\\Towners\\Drunk01.wav", { 0, NULL } },
/*TSFX_DRUNK2*/ { sfx_STREAM, "Sfx\\Towners\\Drunk02.wav", { 0, NULL } },
/*TSFX_DRUNK3*/ { sfx_STREAM, "Sfx\\Towners\\Drunk03.wav", { 0, NULL } },
/*TSFX_DRUNK4*/ { sfx_STREAM, "Sfx\\Towners\\Drunk04.wav", { 0, NULL } },
/*TSFX_DRUNK5*/ { sfx_STREAM, "Sfx\\Towners\\Drunk05.wav", { 0, NULL } },
/*TSFX_DRUNK6*/ { sfx_STREAM, "Sfx\\Towners\\Drunk06.wav", { 0, NULL } },
/*TSFX_DRUNK7*/ { sfx_STREAM, "Sfx\\Towners\\Drunk07.wav", { 0, NULL } },
/*TSFX_DRUNK8*/ { sfx_STREAM, "Sfx\\Towners\\Drunk08.wav", { 0, NULL } },
/*TSFX_DRUNK9*/ { sfx_STREAM, "Sfx\\Towners\\Drunk09.wav", { 0, NULL } },
/*TSFX_DRUNK10*/ { sfx_STREAM, "Sfx\\Towners\\Drunk10.wav", { 0, NULL } },
/*TSFX_DRUNK11*/ { sfx_STREAM, "Sfx\\Towners\\Drunk11.wav", { 0, NULL } },
/*TSFX_DRUNK12*/ { sfx_STREAM, "Sfx\\Towners\\Drunk12.wav", { 0, NULL } },
/*TSFX_DRUNK13*/ { sfx_STREAM, "Sfx\\Towners\\Drunk13.wav", { 0, NULL } },
/*TSFX_DRUNK14*/ { sfx_STREAM, "Sfx\\Towners\\Drunk14.wav", { 0, NULL } },
/*TSFX_DRUNK15*/ { sfx_STREAM, "Sfx\\Towners\\Drunk15.wav", { 0, NULL } },
/*TSFX_DRUNK16*/ { sfx_STREAM, "Sfx\\Towners\\Drunk16.wav", { 0, NULL } },
/*TSFX_DRUNK17*/ { sfx_STREAM, "Sfx\\Towners\\Drunk17.wav", { 0, NULL } },
/*TSFX_DRUNK18*/ { sfx_STREAM, "Sfx\\Towners\\Drunk18.wav", { 0, NULL } },
/*TSFX_DRUNK19*/ { sfx_STREAM, "Sfx\\Towners\\Drunk19.wav", { 0, NULL } },
/*TSFX_DRUNK20*/ { sfx_STREAM, "Sfx\\Towners\\Drunk20.wav", { 0, NULL } },
/*TSFX_DRUNK21*/ { sfx_STREAM, "Sfx\\Towners\\Drunk21.wav", { 0, NULL } },
/*TSFX_DRUNK22*/ { sfx_STREAM, "Sfx\\Towners\\Drunk22.wav", { 0, NULL } },
/*TSFX_DRUNK23*/ { sfx_STREAM, "Sfx\\Towners\\Drunk23.wav", { 0, NULL } },
/*TSFX_DRUNK24*/ { sfx_STREAM, "Sfx\\Towners\\Drunk24.wav", { 0, NULL } },
/*TSFX_DRUNK25*/ { sfx_STREAM, "Sfx\\Towners\\Drunk25.wav", { 0, NULL } },
/*TSFX_DRUNK26*/ { sfx_STREAM, "Sfx\\Towners\\Drunk26.wav", { 0, NULL } },
/*TSFX_DRUNK27*/ { sfx_STREAM, "Sfx\\Towners\\Drunk27.wav", { 0, NULL } },
/*TSFX_DRUNK28*/ { sfx_STREAM, "Sfx\\Towners\\Drunk28.wav", { 0, NULL } },
/*TSFX_DRUNK29*/ { sfx_STREAM, "Sfx\\Towners\\Drunk29.wav", { 0, NULL } },
/*TSFX_DRUNK30*/ { sfx_STREAM, "Sfx\\Towners\\Drunk30.wav", { 0, NULL } },
/*TSFX_DRUNK31*/ { sfx_STREAM, "Sfx\\Towners\\Drunk31.wav", { 0, NULL } },
/*TSFX_DRUNK32*/ { sfx_STREAM, "Sfx\\Towners\\Drunk32.wav", { 0, NULL } },
/*TSFX_DRUNK33*/ { sfx_STREAM, "Sfx\\Towners\\Drunk33.wav", { 0, NULL } },
/*TSFX_DRUNK34*/ { sfx_STREAM, "Sfx\\Towners\\Drunk34.wav", { 0, NULL } },
/*TSFX_DRUNK35*/ { sfx_STREAM, "Sfx\\Towners\\Drunk35.wav", { 0, NULL } },
/*TSFX_HEALER1*/ { sfx_STREAM, "Sfx\\Towners\\Healer01.wav", { 0, NULL } },
/*TSFX_HEALER2*/ { sfx_STREAM, "Sfx\\Towners\\Healer02.wav", { 0, NULL } },
/*TSFX_HEALER3*/ { sfx_STREAM, "Sfx\\Towners\\Healer03.wav", { 0, NULL } },
/*TSFX_HEALER4*/ { sfx_STREAM, "Sfx\\Towners\\Healer04.wav", { 0, NULL } },
/*TSFX_HEALER5*/ { sfx_STREAM, "Sfx\\Towners\\Healer05.wav", { 0, NULL } },
/*TSFX_HEALER6*/ { sfx_STREAM, "Sfx\\Towners\\Healer06.wav", { 0, NULL } },
/*TSFX_HEALER7*/ { sfx_STREAM, "Sfx\\Towners\\Healer07.wav", { 0, NULL } },
/*TSFX_HEALER8*/ { sfx_STREAM, "Sfx\\Towners\\Healer08.wav", { 0, NULL } },
/*TSFX_HEALER9*/ { sfx_STREAM, "Sfx\\Towners\\Healer09.wav", { 0, NULL } },
/*TSFX_HEALER10*/{ sfx_STREAM, "Sfx\\Towners\\Healer10.wav", { 0, NULL } },
/*TSFX_HEALER11*/{ sfx_STREAM, "Sfx\\Towners\\Healer11.wav", { 0, NULL } },
/*TSFX_HEALER12*/{ sfx_STREAM, "Sfx\\Towners\\Healer12.wav", { 0, NULL } },
/*TSFX_HEALER13*/{ sfx_STREAM, "Sfx\\Towners\\Healer13.wav", { 0, NULL } },
/*TSFX_HEALER14*/{ sfx_STREAM, "Sfx\\Towners\\Healer14.wav", { 0, NULL } },
/*TSFX_HEALER15*/{ sfx_STREAM, "Sfx\\Towners\\Healer15.wav", { 0, NULL } },
/*TSFX_HEALER16*/{ sfx_STREAM, "Sfx\\Towners\\Healer16.wav", { 0, NULL } },
/*TSFX_HEALER17*/{ sfx_STREAM, "Sfx\\Towners\\Healer17.wav", { 0, NULL } },
/*TSFX_HEALER18*/{ sfx_STREAM, "Sfx\\Towners\\Healer18.wav", { 0, NULL } },
/*TSFX_HEALER19*/{ sfx_STREAM, "Sfx\\Towners\\Healer19.wav", { 0, NULL } },
/*TSFX_HEALER20*/{ sfx_STREAM, "Sfx\\Towners\\Healer20.wav", { 0, NULL } },
/*TSFX_HEALER21*/{ sfx_STREAM, "Sfx\\Towners\\Healer21.wav", { 0, NULL } },
/*TSFX_HEALER22*/{ sfx_STREAM, "Sfx\\Towners\\Healer22.wav", { 0, NULL } },
/*TSFX_HEALER23*/{ sfx_STREAM, "Sfx\\Towners\\Healer23.wav", { 0, NULL } },
/*TSFX_HEALER24*/{ sfx_STREAM, "Sfx\\Towners\\Healer24.wav", { 0, NULL } },
/*TSFX_HEALER25*/{ sfx_STREAM, "Sfx\\Towners\\Healer25.wav", { 0, NULL } },
/*TSFX_HEALER26*/{ sfx_STREAM, "Sfx\\Towners\\Healer26.wav", { 0, NULL } },
/*TSFX_HEALER27*/{ sfx_STREAM, "Sfx\\Towners\\Healer27.wav", { 0, NULL } },
/*TSFX_HEALER28*/{ sfx_STREAM, "Sfx\\Towners\\Healer28.wav", { 0, NULL } },
/*TSFX_HEALER29*/{ sfx_STREAM, "Sfx\\Towners\\Healer29.wav", { 0, NULL } },
/*TSFX_HEALER30*/{ sfx_STREAM, "Sfx\\Towners\\Healer30.wav", { 0, NULL } },
/*TSFX_HEALER31*/{ sfx_STREAM, "Sfx\\Towners\\Healer31.wav", { 0, NULL } },
/*TSFX_HEALER32*/{ sfx_STREAM, "Sfx\\Towners\\Healer32.wav", { 0, NULL } },
/*TSFX_HEALER33*/{ sfx_STREAM, "Sfx\\Towners\\Healer33.wav", { 0, NULL } },
/*TSFX_HEALER34*/{ sfx_STREAM, "Sfx\\Towners\\Healer34.wav", { 0, NULL } },
/*TSFX_HEALER35*/{ sfx_STREAM, "Sfx\\Towners\\Healer35.wav", { 0, NULL } },
/*TSFX_HEALER36*/{ sfx_STREAM, "Sfx\\Towners\\Healer36.wav", { 0, NULL } },
/*TSFX_HEALER37*/{ sfx_STREAM, "Sfx\\Towners\\Healer37.wav", { 0, NULL } },
/*TSFX_HEALER38*/{ sfx_STREAM, "Sfx\\Towners\\Healer38.wav", { 0, NULL } },
/*TSFX_HEALER39*/{ sfx_STREAM, "Sfx\\Towners\\Healer39.wav", { 0, NULL } },
/*TSFX_HEALER40*/{ sfx_STREAM, "Sfx\\Towners\\Healer40.wav", { 0, NULL } },
/*TSFX_HEALER41*/{ sfx_STREAM, "Sfx\\Towners\\Healer41.wav", { 0, NULL } },
/*TSFX_HEALER42*/{ sfx_STREAM, "Sfx\\Towners\\Healer42.wav", { 0, NULL } },
/*TSFX_HEALER43*/{ sfx_STREAM, "Sfx\\Towners\\Healer43.wav", { 0, NULL } },
/*TSFX_HEALER44*/{ sfx_STREAM, "Sfx\\Towners\\Healer44.wav", { 0, NULL } },
/*TSFX_HEALER45*/{ sfx_STREAM, "Sfx\\Towners\\Healer45.wav", { 0, NULL } },
/*TSFX_HEALER46*/{ sfx_STREAM, "Sfx\\Towners\\Healer46.wav", { 0, NULL } },
/*TSFX_HEALER47*/{ sfx_STREAM, "Sfx\\Towners\\Healer47.wav", { 0, NULL } },
/*TSFX_PEGBOY1*/ { sfx_STREAM, "Sfx\\Towners\\Pegboy01.wav", { 0, NULL } },
/*TSFX_PEGBOY2*/ { sfx_STREAM, "Sfx\\Towners\\Pegboy02.wav", { 0, NULL } },
/*TSFX_PEGBOY3*/ { sfx_STREAM, "Sfx\\Towners\\Pegboy03.wav", { 0, NULL } },
/*TSFX_PEGBOY4*/ { sfx_STREAM, "Sfx\\Towners\\Pegboy04.wav", { 0, NULL } },
/*TSFX_PEGBOY5*/ { sfx_STREAM, "Sfx\\Towners\\Pegboy05.wav", { 0, NULL } },
/*TSFX_PEGBOY6*/ { sfx_STREAM, "Sfx\\Towners\\Pegboy06.wav", { 0, NULL } },
/*TSFX_PEGBOY7*/ { sfx_STREAM, "Sfx\\Towners\\Pegboy07.wav", { 0, NULL } },
/*TSFX_PEGBOY8*/ { sfx_STREAM, "Sfx\\Towners\\Pegboy08.wav", { 0, NULL } },
/*TSFX_PEGBOY9*/ { sfx_STREAM, "Sfx\\Towners\\Pegboy09.wav", { 0, NULL } },
/*TSFX_PEGBOY10*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy10.wav", { 0, NULL } },
/*TSFX_PEGBOY11*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy11.wav", { 0, NULL } },
/*TSFX_PEGBOY12*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy12.wav", { 0, NULL } },
/*TSFX_PEGBOY13*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy13.wav", { 0, NULL } },
/*TSFX_PEGBOY14*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy14.wav", { 0, NULL } },
/*TSFX_PEGBOY15*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy15.wav", { 0, NULL } },
/*TSFX_PEGBOY16*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy16.wav", { 0, NULL } },
/*TSFX_PEGBOY17*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy17.wav", { 0, NULL } },
/*TSFX_PEGBOY18*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy18.wav", { 0, NULL } },
/*TSFX_PEGBOY19*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy19.wav", { 0, NULL } },
/*TSFX_PEGBOY20*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy20.wav", { 0, NULL } },
/*TSFX_PEGBOY21*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy21.wav", { 0, NULL } },
/*TSFX_PEGBOY22*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy22.wav", { 0, NULL } },
/*TSFX_PEGBOY23*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy23.wav", { 0, NULL } },
/*TSFX_PEGBOY24*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy24.wav", { 0, NULL } },
/*TSFX_PEGBOY25*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy25.wav", { 0, NULL } },
/*TSFX_PEGBOY26*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy26.wav", { 0, NULL } },
/*TSFX_PEGBOY27*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy27.wav", { 0, NULL } },
/*TSFX_PEGBOY28*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy28.wav", { 0, NULL } },
/*TSFX_PEGBOY29*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy29.wav", { 0, NULL } },
/*TSFX_PEGBOY30*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy30.wav", { 0, NULL } },
/*TSFX_PEGBOY31*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy31.wav", { 0, NULL } },
/*TSFX_PEGBOY32*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy32.wav", { 0, NULL } },
/*TSFX_PEGBOY33*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy33.wav", { 0, NULL } },
/*TSFX_PEGBOY34*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy34.wav", { 0, NULL } },
/*TSFX_PEGBOY35*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy35.wav", { 0, NULL } },
/*TSFX_PEGBOY36*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy36.wav", { 0, NULL } },
/*TSFX_PEGBOY37*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy37.wav", { 0, NULL } },
/*TSFX_PEGBOY38*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy38.wav", { 0, NULL } },
/*TSFX_PEGBOY39*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy39.wav", { 0, NULL } },
/*TSFX_PEGBOY40*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy40.wav", { 0, NULL } },
/*TSFX_PEGBOY41*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy41.wav", { 0, NULL } },
/*TSFX_PEGBOY42*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy42.wav", { 0, NULL } },
/*TSFX_PEGBOY43*/{ sfx_STREAM, "Sfx\\Towners\\Pegboy43.wav", { 0, NULL } },
/*TSFX_PRIEST0*/ { sfx_STREAM, "Sfx\\Towners\\Priest00.wav", { 0, NULL } },
/*TSFX_PRIEST1*/ { sfx_STREAM, "Sfx\\Towners\\Priest01.wav", { 0, NULL } },
/*TSFX_PRIEST2*/ { sfx_STREAM, "Sfx\\Towners\\Priest02.wav", { 0, NULL } },
/*TSFX_PRIEST3*/ { sfx_STREAM, "Sfx\\Towners\\Priest03.wav", { 0, NULL } },
/*TSFX_PRIEST4*/ { sfx_STREAM, "Sfx\\Towners\\Priest04.wav", { 0, NULL } },
/*TSFX_PRIEST5*/ { sfx_STREAM, "Sfx\\Towners\\Priest05.wav", { 0, NULL } },
/*TSFX_PRIEST6*/ { sfx_STREAM, "Sfx\\Towners\\Priest06.wav", { 0, NULL } },
/*TSFX_PRIEST7*/ { sfx_STREAM, "Sfx\\Towners\\Priest07.wav", { 0, NULL } },
/*TSFX_STORY0*/ { sfx_STREAM, "Sfx\\Towners\\Storyt00.wav", { 0, NULL } },
/*TSFX_STORY1*/ { sfx_STREAM, "Sfx\\Towners\\Storyt01.wav", { 0, NULL } },
/*TSFX_STORY2*/ { sfx_STREAM, "Sfx\\Towners\\Storyt02.wav", { 0, NULL } },
/*TSFX_STORY3*/ { sfx_STREAM, "Sfx\\Towners\\Storyt03.wav", { 0, NULL } },
/*TSFX_STORY4*/ { sfx_STREAM, "Sfx\\Towners\\Storyt04.wav", { 0, NULL } },
/*TSFX_STORY5*/ { sfx_STREAM, "Sfx\\Towners\\Storyt05.wav", { 0, NULL } },
/*TSFX_STORY6*/ { sfx_STREAM, "Sfx\\Towners\\Storyt06.wav", { 0, NULL } },
/*TSFX_STORY7*/ { sfx_STREAM, "Sfx\\Towners\\Storyt07.wav", { 0, NULL } },
/*TSFX_STORY8*/ { sfx_STREAM, "Sfx\\Towners\\Storyt08.wav", { 0, NULL } },
/*TSFX_STORY9*/ { sfx_STREAM, "Sfx\\Towners\\Storyt09.wav", { 0, NULL } },
/*TSFX_STORY10*/ { sfx_STREAM, "Sfx\\Towners\\Storyt10.wav", { 0, NULL } },
/*TSFX_STORY11*/ { sfx_STREAM, "Sfx\\Towners\\Storyt11.wav", { 0, NULL } },
/*TSFX_STORY12*/ { sfx_STREAM, "Sfx\\Towners\\Storyt12.wav", { 0, NULL } },
/*TSFX_STORY13*/ { sfx_STREAM, "Sfx\\Towners\\Storyt13.wav", { 0, NULL } },
/*TSFX_STORY14*/ { sfx_STREAM, "Sfx\\Towners\\Storyt14.wav", { 0, NULL } },
/*TSFX_STORY15*/ { sfx_STREAM, "Sfx\\Towners\\Storyt15.wav", { 0, NULL } },
/*TSFX_STORY16*/ { sfx_STREAM, "Sfx\\Towners\\Storyt16.wav", { 0, NULL } },
/*TSFX_STORY17*/ { sfx_STREAM, "Sfx\\Towners\\Storyt17.wav", { 0, NULL } },
/*TSFX_STORY18*/ { sfx_STREAM, "Sfx\\Towners\\Storyt18.wav", { 0, NULL } },
/*TSFX_STORY19*/ { sfx_STREAM, "Sfx\\Towners\\Storyt19.wav", { 0, NULL } },
/*TSFX_STORY20*/ { sfx_STREAM, "Sfx\\Towners\\Storyt20.wav", { 0, NULL } },
/*TSFX_STORY21*/ { sfx_STREAM, "Sfx\\Towners\\Storyt21.wav", { 0, NULL } },
/*TSFX_STORY22*/ { sfx_STREAM, "Sfx\\Towners\\Storyt22.wav", { 0, NULL } },
/*TSFX_STORY23*/ { sfx_STREAM, "Sfx\\Towners\\Storyt23.wav", { 0, NULL } },
/*TSFX_STORY24*/ { sfx_STREAM, "Sfx\\Towners\\Storyt24.wav", { 0, NULL } },
/*TSFX_STORY25*/ { sfx_STREAM, "Sfx\\Towners\\Storyt25.wav", { 0, NULL } },
/*TSFX_STORY26*/ { sfx_STREAM, "Sfx\\Towners\\Storyt26.wav", { 0, NULL } },
/*TSFX_STORY27*/ { sfx_STREAM, "Sfx\\Towners\\Storyt27.wav", { 0, NULL } },
/*TSFX_STORY28*/ { sfx_STREAM, "Sfx\\Towners\\Storyt28.wav", { 0, NULL } },
/*TSFX_STORY29*/ { sfx_STREAM, "Sfx\\Towners\\Storyt29.wav", { 0, NULL } },
/*TSFX_STORY30*/ { sfx_STREAM, "Sfx\\Towners\\Storyt30.wav", { 0, NULL } },
/*TSFX_STORY31*/ { sfx_STREAM, "Sfx\\Towners\\Storyt31.wav", { 0, NULL } },
/*TSFX_STORY32*/ { sfx_STREAM, "Sfx\\Towners\\Storyt32.wav", { 0, NULL } },
/*TSFX_STORY33*/ { sfx_STREAM, "Sfx\\Towners\\Storyt33.wav", { 0, NULL } },
/*TSFX_STORY34*/ { sfx_STREAM, "Sfx\\Towners\\Storyt34.wav", { 0, NULL } },
/*TSFX_STORY35*/ { sfx_STREAM, "Sfx\\Towners\\Storyt35.wav", { 0, NULL } },
/*TSFX_STORY36*/ { sfx_STREAM, "Sfx\\Towners\\Storyt36.wav", { 0, NULL } },
/*TSFX_STORY37*/ { sfx_STREAM, "Sfx\\Towners\\Storyt37.wav", { 0, NULL } },
/*TSFX_STORY38*/ { sfx_STREAM, "Sfx\\Towners\\Storyt38.wav", { 0, NULL } },
/*TSFX_TAVERN0*/ { sfx_STREAM, "Sfx\\Towners\\Tavown00.wav", { 0, NULL } },
/*TSFX_TAVERN1*/ { sfx_STREAM, "Sfx\\Towners\\Tavown01.wav", { 0, NULL } },
/*TSFX_TAVERN2*/ { sfx_STREAM, "Sfx\\Towners\\Tavown02.wav", { 0, NULL } },
/*TSFX_TAVERN3*/ { sfx_STREAM, "Sfx\\Towners\\Tavown03.wav", { 0, NULL } },
/*TSFX_TAVERN4*/ { sfx_STREAM, "Sfx\\Towners\\Tavown04.wav", { 0, NULL } },
/*TSFX_TAVERN5*/ { sfx_STREAM, "Sfx\\Towners\\Tavown05.wav", { 0, NULL } },
/*TSFX_TAVERN6*/ { sfx_STREAM, "Sfx\\Towners\\Tavown06.wav", { 0, NULL } },
/*TSFX_TAVERN7*/ { sfx_STREAM, "Sfx\\Towners\\Tavown07.wav", { 0, NULL } },
/*TSFX_TAVERN8*/ { sfx_STREAM, "Sfx\\Towners\\Tavown08.wav", { 0, NULL } },
/*TSFX_TAVERN9*/ { sfx_STREAM, "Sfx\\Towners\\Tavown09.wav", { 0, NULL } },
/*TSFX_TAVERN10*/{ sfx_STREAM, "Sfx\\Towners\\Tavown10.wav", { 0, NULL } },
/*TSFX_TAVERN11*/{ sfx_STREAM, "Sfx\\Towners\\Tavown11.wav", { 0, NULL } },
/*TSFX_TAVERN12*/{ sfx_STREAM, "Sfx\\Towners\\Tavown12.wav", { 0, NULL } },
/*TSFX_TAVERN13*/{ sfx_STREAM, "Sfx\\Towners\\Tavown13.wav", { 0, NULL } },
/*TSFX_TAVERN14*/{ sfx_STREAM, "Sfx\\Towners\\Tavown14.wav", { 0, NULL } },
/*TSFX_TAVERN15*/{ sfx_STREAM, "Sfx\\Towners\\Tavown15.wav", { 0, NULL } },
/*TSFX_TAVERN16*/{ sfx_STREAM, "Sfx\\Towners\\Tavown16.wav", { 0, NULL } },
/*TSFX_TAVERN17*/{ sfx_STREAM, "Sfx\\Towners\\Tavown17.wav", { 0, NULL } },
/*TSFX_TAVERN18*/{ sfx_STREAM, "Sfx\\Towners\\Tavown18.wav", { 0, NULL } },
/*TSFX_TAVERN19*/{ sfx_STREAM, "Sfx\\Towners\\Tavown19.wav", { 0, NULL } },
/*TSFX_TAVERN20*/{ sfx_STREAM, "Sfx\\Towners\\Tavown20.wav", { 0, NULL } },
/*TSFX_TAVERN21*/{ sfx_STREAM, "Sfx\\Towners\\Tavown21.wav", { 0, NULL } },
/*TSFX_TAVERN22*/{ sfx_STREAM, "Sfx\\Towners\\Tavown22.wav", { 0, NULL } },
/*TSFX_TAVERN23*/{ sfx_STREAM, "Sfx\\Towners\\Tavown23.wav", { 0, NULL } },
/*TSFX_TAVERN24*/{ sfx_STREAM, "Sfx\\Towners\\Tavown24.wav", { 0, NULL } },
/*TSFX_TAVERN25*/{ sfx_STREAM, "Sfx\\Towners\\Tavown25.wav", { 0, NULL } },
/*TSFX_TAVERN26*/{ sfx_STREAM, "Sfx\\Towners\\Tavown26.wav", { 0, NULL } },
/*TSFX_TAVERN27*/{ sfx_STREAM, "Sfx\\Towners\\Tavown27.wav", { 0, NULL } },
/*TSFX_TAVERN28*/{ sfx_STREAM, "Sfx\\Towners\\Tavown28.wav", { 0, NULL } },
/*TSFX_TAVERN29*/{ sfx_STREAM, "Sfx\\Towners\\Tavown29.wav", { 0, NULL } },
/*TSFX_TAVERN30*/{ sfx_STREAM, "Sfx\\Towners\\Tavown30.wav", { 0, NULL } },
/*TSFX_TAVERN31*/{ sfx_STREAM, "Sfx\\Towners\\Tavown31.wav", { 0, NULL } },
/*TSFX_TAVERN32*/{ sfx_STREAM, "Sfx\\Towners\\Tavown32.wav", { 0, NULL } },
/*TSFX_TAVERN33*/{ sfx_STREAM, "Sfx\\Towners\\Tavown33.wav", { 0, NULL } },
/*TSFX_TAVERN34*/{ sfx_STREAM, "Sfx\\Towners\\Tavown34.wav", { 0, NULL } },
/*TSFX_TAVERN35*/{ sfx_STREAM, "Sfx\\Towners\\Tavown35.wav", { 0, NULL } },
/*TSFX_TAVERN36*/{ sfx_STREAM, "Sfx\\Towners\\Tavown36.wav", { 0, NULL } },
/*TSFX_TAVERN37*/{ sfx_STREAM, "Sfx\\Towners\\Tavown37.wav", { 0, NULL } },
/*TSFX_TAVERN38*/{ sfx_STREAM, "Sfx\\Towners\\Tavown38.wav", { 0, NULL } },
/*TSFX_TAVERN39*/{ sfx_STREAM, "Sfx\\Towners\\Tavown39.wav", { 0, NULL } },
/*TSFX_TAVERN40*/{ sfx_STREAM, "Sfx\\Towners\\Tavown40.wav", { 0, NULL } },
/*TSFX_TAVERN41*/{ sfx_STREAM, "Sfx\\Towners\\Tavown41.wav", { 0, NULL } },
/*TSFX_TAVERN42*/{ sfx_STREAM, "Sfx\\Towners\\Tavown42.wav", { 0, NULL } },
/*TSFX_TAVERN43*/{ sfx_STREAM, "Sfx\\Towners\\Tavown43.wav", { 0, NULL } },
/*TSFX_TAVERN44*/{ sfx_STREAM, "Sfx\\Towners\\Tavown44.wav", { 0, NULL } },
/*TSFX_TAVERN45*/{ sfx_STREAM, "Sfx\\Towners\\Tavown45.wav", { 0, NULL } },
/*TSFX_WITCH1*/ { sfx_STREAM, "Sfx\\Towners\\Witch01.wav", { 0, NULL } },
/*TSFX_WITCH2*/ { sfx_STREAM, "Sfx\\Towners\\Witch02.wav", { 0, NULL } },
/*TSFX_WITCH3*/ { sfx_STREAM, "Sfx\\Towners\\Witch03.wav", { 0, NULL } },
/*TSFX_WITCH4*/ { sfx_STREAM, "Sfx\\Towners\\Witch04.wav", { 0, NULL } },
/*TSFX_WITCH5*/ { sfx_STREAM, "Sfx\\Towners\\Witch05.wav", { 0, NULL } },
/*TSFX_WITCH6*/ { sfx_STREAM, "Sfx\\Towners\\Witch06.wav", { 0, NULL } },
/*TSFX_WITCH7*/ { sfx_STREAM, "Sfx\\Towners\\Witch07.wav", { 0, NULL } },
/*TSFX_WITCH8*/ { sfx_STREAM, "Sfx\\Towners\\Witch08.wav", { 0, NULL } },
/*TSFX_WITCH9*/ { sfx_STREAM, "Sfx\\Towners\\Witch09.wav", { 0, NULL } },
/*TSFX_WITCH10*/ { sfx_STREAM, "Sfx\\Towners\\Witch10.wav", { 0, NULL } },
/*TSFX_WITCH11*/ { sfx_STREAM, "Sfx\\Towners\\Witch11.wav", { 0, NULL } },
/*TSFX_WITCH12*/ { sfx_STREAM, "Sfx\\Towners\\Witch12.wav", { 0, NULL } },
/*TSFX_WITCH13*/ { sfx_STREAM, "Sfx\\Towners\\Witch13.wav", { 0, NULL } },
/*TSFX_WITCH14*/ { sfx_STREAM, "Sfx\\Towners\\Witch14.wav", { 0, NULL } },
/*TSFX_WITCH15*/ { sfx_STREAM, "Sfx\\Towners\\Witch15.wav", { 0, NULL } },
/*TSFX_WITCH16*/ { sfx_STREAM, "Sfx\\Towners\\Witch16.wav", { 0, NULL } },
/*TSFX_WITCH17*/ { sfx_STREAM, "Sfx\\Towners\\Witch17.wav", { 0, NULL } },
/*TSFX_WITCH18*/ { sfx_STREAM, "Sfx\\Towners\\Witch18.wav", { 0, NULL } },
/*TSFX_WITCH19*/ { sfx_STREAM, "Sfx\\Towners\\Witch19.wav", { 0, NULL } },
/*TSFX_WITCH20*/ { sfx_STREAM, "Sfx\\Towners\\Witch20.wav", { 0, NULL } },
/*TSFX_WITCH21*/ { sfx_STREAM, "Sfx\\Towners\\Witch21.wav", { 0, NULL } },
/*TSFX_WITCH22*/ { sfx_STREAM, "Sfx\\Towners\\Witch22.wav", { 0, NULL } },
/*TSFX_WITCH23*/ { sfx_STREAM, "Sfx\\Towners\\Witch23.wav", { 0, NULL } },
/*TSFX_WITCH24*/ { sfx_STREAM, "Sfx\\Towners\\Witch24.wav", { 0, NULL } },
/*TSFX_WITCH25*/ { sfx_STREAM, "Sfx\\Towners\\Witch25.wav", { 0, NULL } },
/*TSFX_WITCH26*/ { sfx_STREAM, "Sfx\\Towners\\Witch26.wav", { 0, NULL } },
/*TSFX_WITCH27*/ { sfx_STREAM, "Sfx\\Towners\\Witch27.wav", { 0, NULL } },
/*TSFX_WITCH28*/ { sfx_STREAM, "Sfx\\Towners\\Witch28.wav", { 0, NULL } },
/*TSFX_WITCH29*/ { sfx_STREAM, "Sfx\\Towners\\Witch29.wav", { 0, NULL } },
/*TSFX_WITCH30*/ { sfx_STREAM, "Sfx\\Towners\\Witch30.wav", { 0, NULL } },
/*TSFX_WITCH31*/ { sfx_STREAM, "Sfx\\Towners\\Witch31.wav", { 0, NULL } },
/*TSFX_WITCH32*/ { sfx_STREAM, "Sfx\\Towners\\Witch32.wav", { 0, NULL } },
/*TSFX_WITCH33*/ { sfx_STREAM, "Sfx\\Towners\\Witch33.wav", { 0, NULL } },
/*TSFX_WITCH34*/ { sfx_STREAM, "Sfx\\Towners\\Witch34.wav", { 0, NULL } },
/*TSFX_WITCH35*/ { sfx_STREAM, "Sfx\\Towners\\Witch35.wav", { 0, NULL } },
/*TSFX_WITCH36*/ { sfx_STREAM, "Sfx\\Towners\\Witch36.wav", { 0, NULL } },
/*TSFX_WITCH37*/ { sfx_STREAM, "Sfx\\Towners\\Witch37.wav", { 0, NULL } },
/*TSFX_WITCH38*/ { sfx_STREAM, "Sfx\\Towners\\Witch38.wav", { 0, NULL } },
/*TSFX_WITCH39*/ { sfx_STREAM, "Sfx\\Towners\\Witch39.wav", { 0, NULL } },
/*TSFX_WITCH40*/ { sfx_STREAM, "Sfx\\Towners\\Witch40.wav", { 0, NULL } },
/*TSFX_WITCH41*/ { sfx_STREAM, "Sfx\\Towners\\Witch41.wav", { 0, NULL } },
/*TSFX_WITCH42*/ { sfx_STREAM, "Sfx\\Towners\\Witch42.wav", { 0, NULL } },
/*TSFX_WITCH43*/ { sfx_STREAM, "Sfx\\Towners\\Witch43.wav", { 0, NULL } },
/*TSFX_WITCH44*/ { sfx_STREAM, "Sfx\\Towners\\Witch44.wav", { 0, NULL } },
/*TSFX_WITCH45*/ { sfx_STREAM, "Sfx\\Towners\\Witch45.wav", { 0, NULL } },
/*TSFX_WITCH46*/ { sfx_STREAM, "Sfx\\Towners\\Witch46.wav", { 0, NULL } },
/*TSFX_WITCH47*/ { sfx_STREAM, "Sfx\\Towners\\Witch47.wav", { 0, NULL } },
/*TSFX_WITCH48*/ { sfx_STREAM, "Sfx\\Towners\\Witch48.wav", { 0, NULL } },
/*TSFX_WITCH49*/ { sfx_STREAM, "Sfx\\Towners\\Witch49.wav", { 0, NULL } },
/*TSFX_WITCH50*/ { sfx_STREAM, "Sfx\\Towners\\Witch50.wav", { 0, NULL } },
/*TSFX_WOUND*/ { sfx_STREAM, "Sfx\\Towners\\Wound01.wav", { 0, NULL } },
/*PS_MAGE1*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage01.wav", { 0, NULL } },
/*PS_MAGE2*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage02.wav", { 0, NULL } },
/*PS_MAGE3*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage03.wav", { 0, NULL } },
/*PS_MAGE4*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage04.wav", { 0, NULL } },
/*PS_MAGE5*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage05.wav", { 0, NULL } },
/*PS_MAGE6*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage06.wav", { 0, NULL } },
/*PS_MAGE7*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage07.wav", { 0, NULL } },
/*PS_MAGE8*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage08.wav", { 0, NULL } },
/*PS_MAGE9*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage09.wav", { 0, NULL } },
/*PS_MAGE10*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage10.wav", { 0, NULL } },
/*PS_MAGE11*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage11.wav", { 0, NULL } },
/*PS_MAGE12*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage12.wav", { 0, NULL } },
/*PS_MAGE13*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage13.wav", { 0, NULL } }, // I can not use this yet.
/*PS_MAGE14*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage14.wav", { 0, NULL } }, // I can not carry any more
/*PS_MAGE15*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage15.wav", { 0, NULL } }, // I have no room.
/*PS_MAGE16*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage16.wav", { 0, NULL } }, // Where would I put this?
/*PS_MAGE17*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage17.wav", { 0, NULL } }, // No way.
/*PS_MAGE18*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage18.wav", { 0, NULL } }, // Not a chance.
/*PS_MAGE19*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage19.wav", { 0, NULL } },
/*PS_MAGE20*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage20.wav", { 0, NULL } },
/*PS_MAGE21*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage21.wav", { 0, NULL } },
/*PS_MAGE22*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage22.wav", { 0, NULL } },
/*PS_MAGE23*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage23.wav", { 0, NULL } },
/*PS_MAGE24*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage24.wav", { 0, NULL } }, // I can not open this. Yet.
/*PS_MAGE25*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage25.wav", { 0, NULL } },
/*PS_MAGE26*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage26.wav", { 0, NULL } },
/*PS_MAGE27*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage27.wav", { 0, NULL } }, // I can not cast that here.
/*PS_MAGE28*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage28.wav", { 0, NULL } },
/*PS_MAGE29*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage29.wav", { 0, NULL } },
/*PS_MAGE30*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage30.wav", { 0, NULL } },
/*PS_MAGE31*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage31.wav", { 0, NULL } },
/*PS_MAGE32*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage32.wav", { 0, NULL } },
/*PS_MAGE33*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage33.wav", { 0, NULL } },
/*PS_MAGE34*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage34.wav", { 0, NULL } }, // I do not have a spell ready.
/*PS_MAGE35*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage35.wav", { 0, NULL } }, // Not enough mana.
/*PS_MAGE36*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage36.wav", { 0, NULL } },
/*PS_MAGE37*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage37.wav", { 0, NULL } },
/*PS_MAGE38*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage38.wav", { 0, NULL } },
/*PS_MAGE39*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage39.wav", { 0, NULL } },
/*PS_MAGE40*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage40.wav", { 0, NULL } },
/*PS_MAGE41*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage41.wav", { 0, NULL } },
/*PS_MAGE42*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage42.wav", { 0, NULL } },
/*PS_MAGE43*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage43.wav", { 0, NULL } },
/*PS_MAGE44*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage44.wav", { 0, NULL } },
/*PS_MAGE45*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage45.wav", { 0, NULL } },
/*PS_MAGE46*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage46.wav", { 0, NULL } },
/*PS_MAGE47*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage47.wav", { 0, NULL } },
/*PS_MAGE48*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage48.wav", { 0, NULL } },
/*PS_MAGE49*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage49.wav", { 0, NULL } },
/*PS_MAGE50*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage50.wav", { 0, NULL } },
/*PS_MAGE51*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage51.wav", { 0, NULL } },
/*PS_MAGE52*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage52.wav", { 0, NULL } },
/*PS_MAGE53*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage53.wav", { 0, NULL } },
/*PS_MAGE54*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage54.wav", { 0, NULL } },
/*PS_MAGE55*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage55.wav", { 0, NULL } },
/*PS_MAGE56*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage56.wav", { 0, NULL } },
/*PS_MAGE57*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage57.wav", { 0, NULL } },
/*PS_MAGE58*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage58.wav", { 0, NULL } },
/*PS_MAGE59*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage59.wav", { 0, NULL } },
/*PS_MAGE60*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage60.wav", { 0, NULL } },
/*PS_MAGE61*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage61.wav", { 0, NULL } },
/*PS_MAGE62*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage62.wav", { 0, NULL } },
/*PS_MAGE63*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage63.wav", { 0, NULL } },
/*PS_MAGE64*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage64.wav", { 0, NULL } },
/*PS_MAGE65*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage65.wav", { 0, NULL } },
/*PS_MAGE66*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage66.wav", { 0, NULL } },
/*PS_MAGE67*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage67.wav", { 0, NULL } },
/*PS_MAGE68*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage68.wav", { 0, NULL } },
/*PS_MAGE69*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage69.wav", { 0, NULL } }, // Ouhm..
/*PS_MAGE69B*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage69b.wav", { 0, NULL } }, // Umm..
/*PS_MAGE70*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage70.wav", { 0, NULL } }, // Argh...
/*PS_MAGE71*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage71.wav", { 0, NULL } }, // Ouah.
/*PS_MAGE72*/ { sfx_SORCERER, "Sfx\\Sorceror\\Mage72.wav", { 0, NULL } }, // Huh ah..
/*PS_MAGE73*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage73.wav", { 0, NULL } },
/*PS_MAGE74*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage74.wav", { 0, NULL } },
/*PS_MAGE75*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage75.wav", { 0, NULL } },
/*PS_MAGE76*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage76.wav", { 0, NULL } },
/*PS_MAGE77*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage77.wav", { 0, NULL } },
/*PS_MAGE78*/// { sfx_SORCERER, "Sfx\\Sorceror\\Mage78.wav", { 0, NULL } },
/*PS_MAGE79*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage79.wav", { 0, NULL } },
/*PS_MAGE80*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage80.wav", { 0, NULL } },
/*PS_MAGE81*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage81.wav", { 0, NULL } },
/*PS_MAGE82*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage82.wav", { 0, NULL } },
/*PS_MAGE83*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage83.wav", { 0, NULL } },
/*PS_MAGE84*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage84.wav", { 0, NULL } },
/*PS_MAGE85*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage85.wav", { 0, NULL } },
/*PS_MAGE86*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage86.wav", { 0, NULL } },
/*PS_MAGE87*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage87.wav", { 0, NULL } },
/*PS_MAGE88*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage88.wav", { 0, NULL } },
/*PS_MAGE89*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage89.wav", { 0, NULL } },
/*PS_MAGE90*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage90.wav", { 0, NULL } },
/*PS_MAGE91*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage91.wav", { 0, NULL } },
/*PS_MAGE92*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage92.wav", { 0, NULL } },
/*PS_MAGE93*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage93.wav", { 0, NULL } },
/*PS_MAGE94*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage94.wav", { 0, NULL } },
/*PS_MAGE95*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage95.wav", { 0, NULL } },
/*PS_MAGE96*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage96.wav", { 0, NULL } },
/*PS_MAGE97*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage97.wav", { 0, NULL } },
/*PS_MAGE98*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage98.wav", { 0, NULL } },
/*PS_MAGE99*/ { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage99.wav", { 0, NULL } },
/*PS_MAGE100*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage100.wav", { 0, NULL } },
/*PS_MAGE101*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage101.wav", { 0, NULL } },
/*PS_MAGE102*/// { sfx_STREAM | sfx_SORCERER, "Sfx\\Sorceror\\Mage102.wav", { 0, NULL } },
/*PS_ROGUE1*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue01.wav", { 0, NULL } },
/*PS_ROGUE2*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue02.wav", { 0, NULL } },
/*PS_ROGUE3*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue03.wav", { 0, NULL } },
/*PS_ROGUE4*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue04.wav", { 0, NULL } },
/*PS_ROGUE5*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue05.wav", { 0, NULL } },
/*PS_ROGUE6*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue06.wav", { 0, NULL } },
/*PS_ROGUE7*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue07.wav", { 0, NULL } },
/*PS_ROGUE8*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue08.wav", { 0, NULL } },
/*PS_ROGUE9*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue09.wav", { 0, NULL } },
/*PS_ROGUE10*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue10.wav", { 0, NULL } },
/*PS_ROGUE11*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue11.wav", { 0, NULL } },
/*PS_ROGUE12*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue12.wav", { 0, NULL } },
/*PS_ROGUE13*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue13.wav", { 0, NULL } }, // I can't use this yet.
/*PS_ROGUE14*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue14.wav", { 0, NULL } }, // I can't carry any more.
/*PS_ROGUE15*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue15.wav", { 0, NULL } }, // I have no room.
/*PS_ROGUE16*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue16.wav", { 0, NULL } }, // Now where would I put this?
/*PS_ROGUE17*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue17.wav", { 0, NULL } }, // No way...
/*PS_ROGUE18*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue18.wav", { 0, NULL } }, // Not a chance
/*PS_ROGUE19*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue19.wav", { 0, NULL } },
/*PS_ROGUE20*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue20.wav", { 0, NULL } },
/*PS_ROGUE21*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue21.wav", { 0, NULL } },
/*PS_ROGUE22*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue22.wav", { 0, NULL } },
/*PS_ROGUE23*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue23.wav", { 0, NULL } },
/*PS_ROGUE24*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue24.wav", { 0, NULL } }, // I can't open this. .. Yet.
/*PS_ROGUE25*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue25.wav", { 0, NULL } },
/*PS_ROGUE26*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue26.wav", { 0, NULL } },
/*PS_ROGUE27*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue27.wav", { 0, NULL } }, // I can't cast that here.
/*PS_ROGUE28*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue28.wav", { 0, NULL } },
/*PS_ROGUE29*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue29.wav", { 0, NULL } }, // That did not do anything.
/*PS_ROGUE30*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue30.wav", { 0, NULL } },
/*PS_ROGUE31*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue31.wav", { 0, NULL } },
/*PS_ROGUE32*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue32.wav", { 0, NULL } },
/*PS_ROGUE33*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue33.wav", { 0, NULL } },
/*PS_ROGUE34*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue34.wav", { 0, NULL } }, // I don't have a spell ready.
/*PS_ROGUE35*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue35.wav", { 0, NULL } }, // Not enough mana.
/*PS_ROGUE36*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue36.wav", { 0, NULL } },
/*PS_ROGUE37*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue37.wav", { 0, NULL } },
/*PS_ROGUE38*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue38.wav", { 0, NULL } },
/*PS_ROGUE39*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue39.wav", { 0, NULL } },
/*PS_ROGUE40*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue40.wav", { 0, NULL } },
/*PS_ROGUE41*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue41.wav", { 0, NULL } },
/*PS_ROGUE42*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue42.wav", { 0, NULL } },
/*PS_ROGUE43*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue43.wav", { 0, NULL } },
/*PS_ROGUE44*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue44.wav", { 0, NULL } },
/*PS_ROGUE45*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue45.wav", { 0, NULL } },
/*PS_ROGUE46*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue46.wav", { 0, NULL } }, // Just what I was looking for.
/*PS_ROGUE47*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue47.wav", { 0, NULL } },
/*PS_ROGUE48*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue48.wav", { 0, NULL } },
/*PS_ROGUE49*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue49.wav", { 0, NULL } }, // I'm not thirsty.
/*PS_ROGUE50*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue50.wav", { 0, NULL } }, // Hey, I'm no milkmaid.
/*PS_ROGUE51*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue51.wav", { 0, NULL } },
/*PS_ROGUE52*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue52.wav", { 0, NULL } }, // Yep, that's a cow, alright.
/*PS_ROGUE53*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue53.wav", { 0, NULL } },
/*PS_ROGUE54*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue54.wav", { 0, NULL } },
/*PS_ROGUE55*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue55.wav", { 0, NULL } },
/*PS_ROGUE56*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue56.wav", { 0, NULL } },
/*PS_ROGUE57*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue57.wav", { 0, NULL } },
/*PS_ROGUE58*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue58.wav", { 0, NULL } },
/*PS_ROGUE59*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue59.wav", { 0, NULL } },
/*PS_ROGUE60*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue60.wav", { 0, NULL } },
/*PS_ROGUE61*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue61.wav", { 0, NULL } },
/*PS_ROGUE62*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue62.wav", { 0, NULL } },
/*PS_ROGUE63*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue63.wav", { 0, NULL } },
/*PS_ROGUE64*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue64.wav", { 0, NULL } },
/*PS_ROGUE65*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue65.wav", { 0, NULL } },
/*PS_ROGUE66*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue66.wav", { 0, NULL } },
/*PS_ROGUE67*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue67.wav", { 0, NULL } },
/*PS_ROGUE68*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue68.wav", { 0, NULL } },
/*PS_ROGUE69*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue69.wav", { 0, NULL } }, // Aeh...
/*PS_ROGUE69B*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue69b.wav", { 0, NULL } }, // Oah...
/*PS_ROGUE70*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue70.wav", { 0, NULL } }, // Ouhuh..
/*PS_ROGUE71*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue71.wav", { 0, NULL } }, // Aaaaauh.
/*PS_ROGUE72*/ { sfx_ROGUE, "Sfx\\Rogue\\Rogue72.wav", { 0, NULL } }, // Huuhuhh.
/*PS_ROGUE73*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue73.wav", { 0, NULL } },
/*PS_ROGUE74*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue74.wav", { 0, NULL } },
/*PS_ROGUE75*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue75.wav", { 0, NULL } },
/*PS_ROGUE76*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue76.wav", { 0, NULL } },
/*PS_ROGUE77*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue77.wav", { 0, NULL } },
/*PS_ROGUE78*/// { sfx_ROGUE, "Sfx\\Rogue\\Rogue78.wav", { 0, NULL } },
/*PS_ROGUE79*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue79.wav", { 0, NULL } },
/*PS_ROGUE80*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue80.wav", { 0, NULL } },
/*PS_ROGUE81*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue81.wav", { 0, NULL } },
/*PS_ROGUE82*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue82.wav", { 0, NULL } },
/*PS_ROGUE83*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue83.wav", { 0, NULL } },
/*PS_ROGUE84*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue84.wav", { 0, NULL } },
/*PS_ROGUE85*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue85.wav", { 0, NULL } },
/*PS_ROGUE86*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue86.wav", { 0, NULL } },
/*PS_ROGUE87*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue87.wav", { 0, NULL } },
/*PS_ROGUE88*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue88.wav", { 0, NULL } },
/*PS_ROGUE89*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue89.wav", { 0, NULL } },
/*PS_ROGUE90*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue90.wav", { 0, NULL } },
/*PS_ROGUE91*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue91.wav", { 0, NULL } },
/*PS_ROGUE92*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue92.wav", { 0, NULL } },
/*PS_ROGUE93*/// { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue93.wav", { 0, NULL } },
/*PS_ROGUE94*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue94.wav", { 0, NULL } },
/*PS_ROGUE95*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue95.wav", { 0, NULL } },
/*PS_ROGUE96*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue96.wav", { 0, NULL } },
/*PS_ROGUE97*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue97.wav", { 0, NULL } },
/*PS_ROGUE98*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue98.wav", { 0, NULL } },
/*PS_ROGUE99*/ { sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue99.wav", { 0, NULL } },
/*PS_ROGUE100*///{ sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue100.wav", { 0, NULL } },
/*PS_ROGUE101*///{ sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue101.wav", { 0, NULL } },
/*PS_ROGUE102*///{ sfx_STREAM | sfx_ROGUE, "Sfx\\Rogue\\Rogue102.wav", { 0, NULL } },
/*PS_WARR1*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior01.wav", { 0, NULL } },
/*PS_WARR2*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior02.wav", { 0, NULL } },
/*PS_WARR3*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior03.wav", { 0, NULL } },
/*PS_WARR4*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior04.wav", { 0, NULL } },
/*PS_WARR5*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior05.wav", { 0, NULL } },
/*PS_WARR6*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior06.wav", { 0, NULL } },
/*PS_WARR7*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior07.wav", { 0, NULL } },
/*PS_WARR8*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior08.wav", { 0, NULL } },
/*PS_WARR9*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior09.wav", { 0, NULL } },
/*PS_WARR10*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior10.wav", { 0, NULL } },
/*PS_WARR11*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior11.wav", { 0, NULL } },
/*PS_WARR12*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior12.wav", { 0, NULL } },
/*PS_WARR13*/ { sfx_WARRIOR, "Sfx\\Warrior\\Warior13.wav", { 0, NULL } }, // I can't use this. .. Yet.
/*PS_WARR14*/ { sfx_WARRIOR, "Sfx\\Warrior\\Warior14.wav", { 0, NULL } }, // I can't carry any more.
/*PS_WARR14B*/ { sfx_WARRIOR, "Sfx\\Warrior\\Wario14b.wav", { 0, NULL } }, // I've got to pawn some of this stuff.
/*PS_WARR14C*/ { sfx_WARRIOR, "Sfx\\Warrior\\Wario14c.wav", { 0, NULL } }, // Too much baggage.
/*PS_WARR15*/ { sfx_WARRIOR, "Sfx\\Warrior\\Warior15.wav", { 0, NULL } },
/*PS_WARR15B*/// { sfx_WARRIOR, "Sfx\\Warrior\\Wario15b.wav", { 0, NULL } },
/*PS_WARR15C*/// { sfx_WARRIOR, "Sfx\\Warrior\\Wario15c.wav", { 0, NULL } },
/*PS_WARR16*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior16.wav", { 0, NULL } }, // Where would I put this?
/*PS_WARR16B*/// { sfx_WARRIOR, "Sfx\\Warrior\\Wario16b.wav", { 0, NULL } }, // Where you want me to put this?
/*PS_WARR16C*/// { sfx_WARRIOR, "Sfx\\Warrior\\Wario16c.wav", { 0, NULL } }, // What am I a pack rat?
/*PS_WARR17*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior17.wav", { 0, NULL } },
/*PS_WARR18*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior18.wav", { 0, NULL } },
/*PS_WARR19*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior19.wav", { 0, NULL } },
/*PS_WARR20*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior20.wav", { 0, NULL } },
/*PS_WARR21*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior21.wav", { 0, NULL } },
/*PS_WARR22*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior22.wav", { 0, NULL } },
/*PS_WARR23*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior23.wav", { 0, NULL } },
/*PS_WARR24*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior24.wav", { 0, NULL } }, // I can not open this. Yet.
/*PS_WARR25*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior25.wav", { 0, NULL } },
/*PS_WARR26*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior26.wav", { 0, NULL } },
/*PS_WARR27*/ { sfx_WARRIOR, "Sfx\\Warrior\\Warior27.wav", { 0, NULL } }, // I can't cast that here.
/*PS_WARR28*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior28.wav", { 0, NULL } },
/*PS_WARR29*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior29.wav", { 0, NULL } },
/*PS_WARR30*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior30.wav", { 0, NULL } },
/*PS_WARR31*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior31.wav", { 0, NULL } },
/*PS_WARR32*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior32.wav", { 0, NULL } },
/*PS_WARR33*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior33.wav", { 0, NULL } },
/*PS_WARR34*/ { sfx_WARRIOR, "Sfx\\Warrior\\Warior34.wav", { 0, NULL } }, // I don't have a spell ready.
/*PS_WARR35*/ { sfx_WARRIOR, "Sfx\\Warrior\\Warior35.wav", { 0, NULL } }, // Not enough mana.
/*PS_WARR36*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior36.wav", { 0, NULL } },
/*PS_WARR37*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior37.wav", { 0, NULL } },
/*PS_WARR38*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior38.wav", { 0, NULL } },
/*PS_WARR39*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior39.wav", { 0, NULL } },
/*PS_WARR40*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior40.wav", { 0, NULL } },
/*PS_WARR41*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior41.wav", { 0, NULL } },
/*PS_WARR42*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior42.wav", { 0, NULL } },
/*PS_WARR43*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior43.wav", { 0, NULL } },
/*PS_WARR44*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior44.wav", { 0, NULL } },
/*PS_WARR45*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior45.wav", { 0, NULL } },
/*PS_WARR46*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior46.wav", { 0, NULL } },
/*PS_WARR47*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior47.wav", { 0, NULL } },
/*PS_WARR48*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior48.wav", { 0, NULL } },
/*PS_WARR49*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior49.wav", { 0, NULL } },
/*PS_WARR50*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior50.wav", { 0, NULL } },
/*PS_WARR51*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior51.wav", { 0, NULL } },
/*PS_WARR52*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior52.wav", { 0, NULL } },
/*PS_WARR53*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior53.wav", { 0, NULL } },
/*PS_WARR54*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior54.wav", { 0, NULL } },
/*PS_WARR55*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior55.wav", { 0, NULL } },
/*PS_WARR56*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior56.wav", { 0, NULL } },
/*PS_WARR57*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior57.wav", { 0, NULL } },
/*PS_WARR58*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior58.wav", { 0, NULL } },
/*PS_WARR59*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior59.wav", { 0, NULL } },
/*PS_WARR60*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior60.wav", { 0, NULL } },
/*PS_WARR61*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior61.wav", { 0, NULL } },
/*PS_WARR62*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior62.wav", { 0, NULL } },
/*PS_WARR63*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior63.wav", { 0, NULL } },
/*PS_WARR64*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior64.wav", { 0, NULL } },
/*PS_WARR65*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior65.wav", { 0, NULL } },
/*PS_WARR66*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior66.wav", { 0, NULL } },
/*PS_WARR67*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior67.wav", { 0, NULL } },
/*PS_WARR68*/ { sfx_WARRIOR, "Sfx\\Warrior\\Warior68.wav", { 0, NULL } },
/*PS_WARR69*/ { sfx_WARRIOR, "Sfx\\Warrior\\Warior69.wav", { 0, NULL } }, // Ahh..
/*PS_WARR69B*/ { sfx_WARRIOR, "Sfx\\Warrior\\Wario69b.wav", { 0, NULL } }, // Ouh...
/*PS_WARR70*/ { sfx_WARRIOR, "Sfx\\Warrior\\Warior70.wav", { 0, NULL } }, // Ouah..
/*PS_WARR71*/ { sfx_WARRIOR, "Sfx\\Warrior\\Warior71.wav", { 0, NULL } }, // Auuahh..
/*PS_WARR72*/ { sfx_WARRIOR, "Sfx\\Warrior\\Warior72.wav", { 0, NULL } }, // Huhhuhh.
/*PS_WARR73*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior73.wav", { 0, NULL } },
/*PS_WARR74*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior74.wav", { 0, NULL } },
/*PS_WARR75*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior75.wav", { 0, NULL } },
/*PS_WARR76*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior76.wav", { 0, NULL } },
/*PS_WARR77*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior77.wav", { 0, NULL } },
/*PS_WARR78*/// { sfx_WARRIOR, "Sfx\\Warrior\\Warior78.wav", { 0, NULL } },
/*PS_WARR79*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior79.wav", { 0, NULL } },
/*PS_WARR80*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior80.wav", { 0, NULL } },
/*PS_WARR81*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior81.wav", { 0, NULL } },
/*PS_WARR82*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior82.wav", { 0, NULL } },
/*PS_WARR83*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior83.wav", { 0, NULL } },
/*PS_WARR84*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior84.wav", { 0, NULL } },
/*PS_WARR85*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior85.wav", { 0, NULL } },
/*PS_WARR86*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior86.wav", { 0, NULL } },
/*PS_WARR87*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior87.wav", { 0, NULL } },
/*PS_WARR88*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior88.wav", { 0, NULL } },
/*PS_WARR89*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior89.wav", { 0, NULL } },
/*PS_WARR90*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior90.wav", { 0, NULL } },
/*PS_WARR91*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior91.wav", { 0, NULL } },
/*PS_WARR92*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior92.wav", { 0, NULL } },
/*PS_WARR93*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior93.wav", { 0, NULL } },
/*PS_WARR94*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior94.wav", { 0, NULL } },
/*PS_WARR95*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior95.wav", { 0, NULL } },
/*PS_WARR95B*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Wario95b.wav", { 0, NULL } },
/*PS_WARR95C*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Wario95c.wav", { 0, NULL } },
/*PS_WARR95D*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Wario95d.wav", { 0, NULL } },
/*PS_WARR95E*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Wario95e.wav", { 0, NULL } },
/*PS_WARR95F*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Wario95f.wav", { 0, NULL } },
/*PS_WARR96B*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Wario96b.wav", { 0, NULL } },
/*PS_WARR97*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Wario97.wav", { 0, NULL } },
/*PS_WARR98*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Wario98.wav", { 0, NULL } },
/*PS_WARR99*/ { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Warior99.wav", { 0, NULL } },
/*PS_WARR100*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Wario100.wav", { 0, NULL } },
/*PS_WARR101*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Wario101.wav", { 0, NULL } },
/*PS_WARR102*/// { sfx_STREAM | sfx_WARRIOR, "Sfx\\Warrior\\Wario102.wav", { 0, NULL } },
/*PS_MONK1*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk01.wav", { 0, NULL } },
/*PS_MONK2*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK3*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK4*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK5*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK6*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK7*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK8*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk08.wav", { 0, NULL } },
/*PS_MONK9*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk09.wav", { 0, NULL } },
/*PS_MONK10*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk10.wav", { 0, NULL } },
/*PS_MONK11*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk11.wav", { 0, NULL } },
/*PS_MONK12*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk12.wav", { 0, NULL } },
/*PS_MONK13*/ { sfx_MONK, "Sfx\\Monk\\Monk13.wav", { 0, NULL } }, // I can not use this. yet.
/*PS_MONK14*/ { sfx_MONK, "Sfx\\Monk\\Monk14.wav", { 0, NULL } }, // I can not carry any more.
/*PS_MONK15*/ { sfx_MONK, "Sfx\\Monk\\Monk15.wav", { 0, NULL } }, // I have no room.
/*PS_MONK16*/ { sfx_MONK, "Sfx\\Monk\\Monk16.wav", { 0, NULL } }, // Where would I put this?
/*PS_MONK17*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK18*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK19*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK20*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK21*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK22*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK23*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK24*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk24.wav", { 0, NULL } }, // I can not open this. .. Yet.
/*PS_MONK25*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK26*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK27*/ { sfx_MONK, "Sfx\\Monk\\Monk27.wav", { 0, NULL } }, // I can not cast that here.
/*PS_MONK28*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK29*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk29.wav", { 0, NULL } },
/*PS_MONK30*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK31*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK32*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK33*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK34*/ { sfx_MONK, "Sfx\\Monk\\Monk34.wav", { 0, NULL } }, // I do not have a spell ready.
/*PS_MONK35*/ { sfx_MONK, "Sfx\\Monk\\Monk35.wav", { 0, NULL } }, // Not enough mana.
/*PS_MONK36*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK37*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK38*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK39*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK40*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK41*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK42*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK43*/// { sfx_MONK, "Sfx\\Monk\\Monk43.wav", { 0, NULL } },
/*PS_MONK44*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK45*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK46*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk46.wav", { 0, NULL } },
/*PS_MONK47*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK48*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK49*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk49.wav", { 0, NULL } },
/*PS_MONK50*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk50.wav", { 0, NULL } },
/*PS_MONK51*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK52*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk52.wav", { 0, NULL } },
/*PS_MONK53*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK54*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk54.wav", { 0, NULL } },
/*PS_MONK55*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk55.wav", { 0, NULL } },
/*PS_MONK56*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk56.wav", { 0, NULL } },
/*PS_MONK57*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK58*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK59*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK60*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK61*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk61.wav", { 0, NULL } },
/*PS_MONK62*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk62.wav", { 0, NULL } },
/*PS_MONK63*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK64*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK65*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK66*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK67*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK68*/ { sfx_MONK, "Sfx\\Monk\\Monk68.wav", { 0, NULL } },
/*PS_MONK69*/ { sfx_MONK, "Sfx\\Monk\\Monk69.wav", { 0, NULL } }, // Umm..
/*PS_MONK69B*/ { sfx_MONK, "Sfx\\Monk\\Monk69b.wav", { 0, NULL } }, // Ouch..
/*PS_MONK70*/ { sfx_MONK, "Sfx\\Monk\\Monk70.wav", { 0, NULL } }, // Oahhahh.
/*PS_MONK71*/ { sfx_MONK, "Sfx\\Monk\\Monk71.wav", { 0, NULL } }, // Oaah ah.
/*PS_MONK72*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK73*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK74*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK75*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK76*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK77*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK78*/// { sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK79*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk79.wav", { 0, NULL } },
/*PS_MONK80*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk80.wav", { 0, NULL } },
/*PS_MONK81*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK82*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk82.wav", { 0, NULL } },
/*PS_MONK83*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk83.wav", { 0, NULL } },
/*PS_MONK84*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK85*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK86*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK87*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk87.wav", { 0, NULL } },
/*PS_MONK88*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk88.wav", { 0, NULL } },
/*PS_MONK89*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk89.wav", { 0, NULL } },
/*PS_MONK90*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK91*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk91.wav", { 0, NULL } },
/*PS_MONK92*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk92.wav", { 0, NULL } },
/*PS_MONK93*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK94*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk94.wav", { 0, NULL } },
/*PS_MONK95*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk95.wav", { 0, NULL } },
/*PS_MONK96*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk96.wav", { 0, NULL } },
/*PS_MONK97*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk97.wav", { 0, NULL } },
/*PS_MONK98*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk98.wav", { 0, NULL } },
/*PS_MONK99*/ { sfx_STREAM | sfx_MONK, "Sfx\\Monk\\Monk99.wav", { 0, NULL } },
/*PS_MONK100*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK101*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_MONK102*/// { sfx_STREAM | sfx_MONK, "Sfx\\Misc\\blank.wav", { 0, NULL } },
/*PS_NAR1*/ { sfx_STREAM, "Sfx\\Narrator\\Nar01.wav", { 0, NULL } },
/*PS_NAR2*/ { sfx_STREAM, "Sfx\\Narrator\\Nar02.wav", { 0, NULL } },
/*PS_NAR3*/ { sfx_STREAM, "Sfx\\Narrator\\Nar03.wav", { 0, NULL } },
/*PS_NAR4*/ { sfx_STREAM, "Sfx\\Narrator\\Nar04.wav", { 0, NULL } },
/*PS_NAR5*/ { sfx_STREAM, "Sfx\\Narrator\\Nar05.wav", { 0, NULL } },
/*PS_NAR6*/ { sfx_STREAM, "Sfx\\Narrator\\Nar06.wav", { 0, NULL } },
/*PS_NAR7*/ { sfx_STREAM, "Sfx\\Narrator\\Nar07.wav", { 0, NULL } },
/*PS_NAR8*/ { sfx_STREAM, "Sfx\\Narrator\\Nar08.wav", { 0, NULL } },
/*PS_NAR9*/ { sfx_STREAM, "Sfx\\Narrator\\Nar09.wav", { 0, NULL } },
/*PS_DIABLVLINT*/{ sfx_STREAM, "Sfx\\Misc\\Lvl16int.wav", { 0, NULL } },
/*USFX_CLEAVER*/ { sfx_STREAM, "Sfx\\Monsters\\Butcher.wav", { 0, NULL } },
/*USFX_GARBUD1*/ { sfx_STREAM, "Sfx\\Monsters\\Garbud01.wav", { 0, NULL } },
/*USFX_GARBUD2*/ { sfx_STREAM, "Sfx\\Monsters\\Garbud02.wav", { 0, NULL } },
/*USFX_GARBUD3*/ { sfx_STREAM, "Sfx\\Monsters\\Garbud03.wav", { 0, NULL } },
/*USFX_GARBUD4*/ { sfx_STREAM, "Sfx\\Monsters\\Garbud04.wav", { 0, NULL } },
/*USFX_IZUAL1*///{ sfx_STREAM, "Sfx\\Monsters\\Izual01.wav", { 0, NULL } },
/*USFX_LACH1*/ { sfx_STREAM, "Sfx\\Monsters\\Lach01.wav", { 0, NULL } },
/*USFX_LACH2*/ { sfx_STREAM, "Sfx\\Monsters\\Lach02.wav", { 0, NULL } },
/*USFX_LACH3*/ { sfx_STREAM, "Sfx\\Monsters\\Lach03.wav", { 0, NULL } },
/*USFX_LAZ1*/ { sfx_STREAM, "Sfx\\Monsters\\Laz01.wav", { 0, NULL } },
/*USFX_LAZ2*/ { sfx_STREAM, "Sfx\\Monsters\\Laz02.wav", { 0, NULL } },
/*USFX_SKING1*/ { sfx_STREAM, "Sfx\\Monsters\\Sking01.wav", { 0, NULL } },
/*USFX_SNOT1*/ { sfx_STREAM, "Sfx\\Monsters\\Snot01.wav", { 0, NULL } },
/*USFX_SNOT2*/ { sfx_STREAM, "Sfx\\Monsters\\Snot02.wav", { 0, NULL } },
/*USFX_SNOT3*/ { sfx_STREAM, "Sfx\\Monsters\\Snot03.wav", { 0, NULL } },
/*USFX_WARLRD1*/ { sfx_STREAM, "Sfx\\Monsters\\Warlrd01.wav", { 0, NULL } },
/*USFX_WLOCK1*/ { sfx_STREAM, "Sfx\\Monsters\\Wlock01.wav", { 0, NULL } },
/*USFX_ZHAR1*/ { sfx_STREAM, "Sfx\\Monsters\\Zhar01.wav", { 0, NULL } },
/*USFX_ZHAR2*/ { sfx_STREAM, "Sfx\\Monsters\\Zhar02.wav", { 0, NULL } },
/*USFX_DIABLOD*/ { sfx_STREAM, "Sfx\\Monsters\\DiabloD.wav", { 0, NULL } },
/*TSFX_FARMER1*/ { sfx_STREAM, "Sfx\\Hellfire\\Farmer1.wav", { 0, NULL } },
/*TSFX_FARMER2*/ { sfx_STREAM, "Sfx\\Hellfire\\Farmer2.wav", { 0, NULL } },
/*TSFX_FARMER2A*/{ sfx_STREAM, "Sfx\\Hellfire\\Farmer2A.wav", { 0, NULL } },
/*TSFX_FARMER3*/ { sfx_STREAM, "Sfx\\Hellfire\\Farmer3.wav", { 0, NULL } },
/*TSFX_FARMER4*/ { sfx_STREAM, "Sfx\\Hellfire\\Farmer4.wav", { 0, NULL } },
/*TSFX_FARMER5*/ { sfx_STREAM, "Sfx\\Hellfire\\Farmer5.wav", { 0, NULL } },
/*TSFX_FARMER6*/ { sfx_STREAM, "Sfx\\Hellfire\\Farmer6.wav", { 0, NULL } },
/*TSFX_FARMER7*/ { sfx_STREAM, "Sfx\\Hellfire\\Farmer7.wav", { 0, NULL } },
/*TSFX_FARMER8*/ { sfx_STREAM, "Sfx\\Hellfire\\Farmer8.wav", { 0, NULL } },
/*TSFX_FARMER9*/ { sfx_STREAM, "Sfx\\Hellfire\\Farmer9.wav", { 0, NULL } },
/*TSFX_TEDDYBR1*/{ sfx_STREAM, "Sfx\\Hellfire\\TEDDYBR1.wav", { 0, NULL } },
/*TSFX_TEDDYBR2*/{ sfx_STREAM, "Sfx\\Hellfire\\TEDDYBR2.wav", { 0, NULL } },
/*TSFX_TEDDYBR3*/{ sfx_STREAM, "Sfx\\Hellfire\\TEDDYBR3.wav", { 0, NULL } },
/*TSFX_TEDDYBR4*/{ sfx_STREAM, "Sfx\\Hellfire\\TEDDYBR4.wav", { 0, NULL } },
/*USFX_DEFILER1*///{ sfx_STREAM, "Sfx\\Hellfire\\DEFILER1.wav", { 0, NULL } },
/*USFX_DEFILER2*///{ sfx_STREAM, "Sfx\\Hellfire\\DEFILER2.wav", { 0, NULL } },
/*USFX_DEFILER3*///{ sfx_STREAM, "Sfx\\Hellfire\\DEFILER3.wav", { 0, NULL } },
/*USFX_DEFILER4*///{ sfx_STREAM, "Sfx\\Hellfire\\DEFILER4.wav", { 0, NULL } },
/*USFX_DEFILER8*/{ sfx_STREAM, "Sfx\\Hellfire\\DEFILER8.wav", { 0, NULL } },
/*USFX_DEFILER6*/{ sfx_STREAM, "Sfx\\Hellfire\\DEFILER6.wav", { 0, NULL } },
/*USFX_DEFILER7*/{ sfx_STREAM, "Sfx\\Hellfire\\DEFILER7.wav", { 0, NULL } },
/*USFX_NAKRUL1*///{ sfx_STREAM, "Sfx\\Hellfire\\NAKRUL1.wav", { 0, NULL } },
/*USFX_NAKRUL2*///{ sfx_STREAM, "Sfx\\Hellfire\\NAKRUL2.wav", { 0, NULL } },
/*USFX_NAKRUL3*///{ sfx_STREAM, "Sfx\\Hellfire\\NAKRUL3.wav", { 0, NULL } },
/*USFX_NAKRUL4*/ { sfx_STREAM, "Sfx\\Hellfire\\NAKRUL4.wav", { 0, NULL } },
/*USFX_NAKRUL5*/ { sfx_STREAM, "Sfx\\Hellfire\\NAKRUL5.wav", { 0, NULL } },
/*USFX_NAKRUL6*/ { sfx_STREAM, "Sfx\\Hellfire\\NAKRUL6.wav", { 0, NULL } },
/*PS_NARATR3*/// { sfx_STREAM, "Sfx\\Hellfire\\NARATR3.wav", { 0, NULL } },
/*TSFX_COWSUT1*/ { sfx_STREAM, "Sfx\\Hellfire\\COWSUT1.wav", { 0, NULL } },
/*TSFX_COWSUT2*/ { sfx_STREAM, "Sfx\\Hellfire\\COWSUT2.wav", { 0, NULL } },
/*TSFX_COWSUT3*/ { sfx_STREAM, "Sfx\\Hellfire\\COWSUT3.wav", { 0, NULL } },
/*TSFX_COWSUT4*/ { sfx_STREAM, "Sfx\\Hellfire\\COWSUT4.wav", { 0, NULL } },
/*TSFX_COWSUT4A*/{ sfx_STREAM, "Sfx\\Hellfire\\COWSUT4A.wav", { 0, NULL } },
/*TSFX_COWSUT5*/ { sfx_STREAM, "Sfx\\Hellfire\\COWSUT5.wav", { 0, NULL } },
/*TSFX_COWSUT6*/ { sfx_STREAM, "Sfx\\Hellfire\\COWSUT6.wav", { 0, NULL } },
/*TSFX_COWSUT7*/ { sfx_STREAM, "Sfx\\Hellfire\\COWSUT7.wav", { 0, NULL } },
/*TSFX_COWSUT8*/ { sfx_STREAM, "Sfx\\Hellfire\\COWSUT8.wav", { 0, NULL } },
/*TSFX_COWSUT9*/ { sfx_STREAM, "Sfx\\Hellfire\\COWSUT9.wav", { 0, NULL } },
/*TSFX_COWSUT10*/{ sfx_STREAM, "Sfx\\Hellfire\\COWSUT10.wav", { 0, NULL } },
/*TSFX_COWSUT11*/{ sfx_STREAM, "Sfx\\Hellfire\\COWSUT11.wav", { 0, NULL } },
/*TSFX_COWSUT12*/{ sfx_STREAM, "Sfx\\Hellfire\\COWSUT12.wav", { 0, NULL } },
/*USFX_SKLJRN1*///{ sfx_STREAM, "Sfx\\Hellfire\\Skljrn1.wav", { 0, NULL } },
/*PS_NARATR6*/ { sfx_STREAM, "Sfx\\Hellfire\\Naratr6.wav", { 0, NULL } },
/*PS_NARATR7*/ { sfx_STREAM, "Sfx\\Hellfire\\Naratr7.wav", { 0, NULL } },
/*PS_NARATR8*/ { sfx_STREAM, "Sfx\\Hellfire\\Naratr8.wav", { 0, NULL } },
/*PS_NARATR5*/ { sfx_STREAM, "Sfx\\Hellfire\\Naratr5.wav", { 0, NULL } },
/*PS_NARATR9*/ { sfx_STREAM, "Sfx\\Hellfire\\Naratr9.wav", { 0, NULL } },
/*PS_NARATR4*/ { sfx_STREAM, "Sfx\\Hellfire\\Naratr4.wav", { 0, NULL } },
/*TSFX_TRADER1*///{ sfx_STREAM, "Sfx\\Hellfire\\TRADER1.wav", { 0, NULL } },
// clang-format on
};
const int sgSFXSets[NUM_SFXSets][NUM_CLASSES] {
// clang-format off
#ifdef HELLFIRE
{ sfx_WARRIOR, sfx_ROGUE, sfx_SORCERER, sfx_MONK, sfx_ROGUE, sfx_WARRIOR },
{ PS_WARR1, PS_ROGUE1, PS_MAGE1, PS_MONK1, PS_ROGUE1, PS_WARR1 },
{ PS_WARR8, PS_ROGUE8, PS_MAGE8, PS_MONK8, PS_ROGUE8, PS_WARR8 },
{ PS_WARR9, PS_ROGUE9, PS_MAGE9, PS_MONK9, PS_ROGUE9, PS_WARR9 },
{ PS_WARR10, PS_ROGUE10, PS_MAGE10, PS_MONK10, PS_ROGUE10, PS_WARR10 },
{ PS_WARR11, PS_ROGUE11, PS_MAGE11, PS_MONK11, PS_ROGUE11, PS_WARR11 },
{ PS_WARR12, PS_ROGUE12, PS_MAGE12, PS_MONK12, PS_ROGUE12, PS_WARR12 },
{ PS_WARR13, PS_ROGUE13, PS_MAGE13, PS_MONK13, PS_ROGUE13, PS_WARR13 },
{ PS_WARR14, PS_ROGUE14, PS_MAGE14, PS_MONK14, PS_ROGUE14, PS_WARR14 },
//{ PS_WARR16, PS_ROGUE16, PS_MAGE16, PS_MONK16, PS_ROGUE16, PS_WARR16 },
{ PS_WARR24, PS_ROGUE24, PS_MAGE24, PS_MONK24, PS_ROGUE24, PS_WARR24 },
{ PS_WARR27, PS_ROGUE27, PS_MAGE27, PS_MONK27, PS_ROGUE27, PS_WARR27 },
{ PS_WARR29, PS_ROGUE29, PS_MAGE29, PS_MONK29, PS_ROGUE29, PS_WARR29 },
{ PS_WARR34, PS_ROGUE34, PS_MAGE34, PS_MONK34, PS_ROGUE34, PS_WARR34 },
{ PS_WARR35, PS_ROGUE35, PS_MAGE35, PS_MONK35, PS_ROGUE35, PS_WARR35 },
{ PS_WARR46, PS_ROGUE46, PS_MAGE46, PS_MONK46, PS_ROGUE46, PS_WARR46 },
{ PS_WARR54, PS_ROGUE54, PS_MAGE54, PS_MONK54, PS_ROGUE54, PS_WARR54 },
{ PS_WARR55, PS_ROGUE55, PS_MAGE55, PS_MONK55, PS_ROGUE55, PS_WARR55 },
{ PS_WARR56, PS_ROGUE56, PS_MAGE56, PS_MONK56, PS_ROGUE56, PS_WARR56 },
{ PS_WARR61, PS_ROGUE61, PS_MAGE61, PS_MONK61, PS_ROGUE61, PS_WARR61 },
{ PS_WARR62, PS_ROGUE62, PS_MAGE62, PS_MONK62, PS_ROGUE62, PS_WARR62 },
{ PS_WARR68, PS_ROGUE68, PS_MAGE68, PS_MONK68, PS_ROGUE68, PS_WARR68 },
{ PS_WARR69, PS_ROGUE69, PS_MAGE69, PS_MONK69, PS_ROGUE69, PS_WARR69 },
{ PS_WARR70, PS_ROGUE70, PS_MAGE70, PS_MONK70, PS_ROGUE70, PS_WARR70 },
{ PS_DEAD, PS_ROGUE71, PS_MAGE71, PS_MONK71, PS_ROGUE71, PS_WARR71 }, // BUGFIX: should use `PS_WARR71` like other classes
{ PS_WARR72, PS_ROGUE72, PS_MAGE72, PS_MAGE72, PS_ROGUE72, PS_WARR72 }, // BUGFIX: should be PS_MONK72, but it is blank...
{ PS_WARR79, PS_ROGUE79, PS_MAGE79, PS_MONK79, PS_ROGUE79, PS_WARR79 },
{ PS_WARR80, PS_ROGUE80, PS_MAGE80, PS_MONK80, PS_ROGUE80, PS_WARR80 },
{ PS_WARR82, PS_ROGUE82, PS_MAGE82, PS_MONK82, PS_ROGUE82, PS_WARR82 },
{ PS_WARR83, PS_ROGUE83, PS_MAGE83, PS_MONK83, PS_ROGUE83, PS_WARR83 },
{ PS_WARR87, PS_ROGUE87, PS_MAGE87, PS_MONK87, PS_ROGUE87, PS_WARR87 },
{ PS_WARR88, PS_ROGUE88, PS_MAGE88, PS_MONK88, PS_ROGUE88, PS_WARR88 },
{ PS_WARR89, PS_ROGUE89, PS_MAGE89, PS_MONK89, PS_ROGUE89, PS_WARR89 },
{ PS_WARR91, PS_ROGUE91, PS_MAGE91, PS_MONK91, PS_ROGUE91, PS_WARR91 },
{ PS_WARR92, PS_ROGUE92, PS_MAGE92, PS_MONK92, PS_ROGUE92, PS_WARR92 },
{ PS_WARR94, PS_ROGUE94, PS_MAGE94, PS_MONK94, PS_ROGUE94, PS_WARR94 },
{ PS_WARR95, PS_ROGUE95, PS_MAGE95, PS_MONK95, PS_ROGUE95, PS_WARR95 },
{ PS_WARR96B,PS_ROGUE96, PS_MAGE96, PS_MONK96, PS_ROGUE96, PS_WARR96B},
{ PS_WARR97, PS_ROGUE97, PS_MAGE97, PS_MONK97, PS_ROGUE97, PS_WARR97 },
{ PS_WARR98, PS_ROGUE98, PS_MAGE98, PS_MONK98, PS_ROGUE98, PS_WARR98 },
{ PS_WARR99, PS_ROGUE99, PS_MAGE99, PS_MONK99, PS_ROGUE99, PS_WARR99 },
#else
{ sfx_WARRIOR, sfx_ROGUE, sfx_SORCERER },
{ PS_WARR1, PS_ROGUE1, PS_MAGE1 },
{ PS_WARR8, PS_ROGUE8, PS_MAGE8 },
{ PS_WARR9, PS_ROGUE9, PS_MAGE9 },
{ PS_WARR10, PS_ROGUE10, PS_MAGE10 },
{ PS_WARR11, PS_ROGUE11, PS_MAGE11 },
{ PS_WARR12, PS_ROGUE12, PS_MAGE12 },
{ PS_WARR13, PS_ROGUE13, PS_MAGE13 },
{ PS_WARR14, PS_ROGUE14, PS_MAGE14 },
//{ PS_WARR16, PS_ROGUE16, PS_MAGE16 },
{ PS_WARR24, PS_ROGUE24, PS_MAGE24 },
{ PS_WARR27, PS_ROGUE27, PS_MAGE27 },
{ PS_WARR29, PS_ROGUE29, PS_MAGE29 },
{ PS_WARR34, PS_ROGUE34, PS_MAGE34 },
{ PS_WARR35, PS_ROGUE35, PS_MAGE35 },
{ PS_WARR46, PS_ROGUE46, PS_MAGE46 },
{ PS_WARR54, PS_ROGUE54, PS_MAGE54 },
{ PS_WARR55, PS_ROGUE55, PS_MAGE55 },
{ PS_WARR56, PS_ROGUE56, PS_MAGE56 },
{ PS_WARR61, PS_ROGUE61, PS_MAGE61 },
{ PS_WARR62, PS_ROGUE62, PS_MAGE62 },
{ PS_WARR68, PS_ROGUE68, PS_MAGE68 },
{ PS_WARR69, PS_ROGUE69, PS_MAGE69 },
{ PS_WARR70, PS_ROGUE70, PS_MAGE70 },
{ PS_DEAD, PS_ROGUE71, PS_MAGE71 }, // BUGFIX: should use `PS_WARR71` like other classes
{ PS_WARR72, PS_ROGUE72, PS_MAGE72 },
{ PS_WARR79, PS_ROGUE79, PS_MAGE79 },
{ PS_WARR80, PS_ROGUE80, PS_MAGE80 },
{ PS_WARR82, PS_ROGUE82, PS_MAGE82 },
{ PS_WARR83, PS_ROGUE83, PS_MAGE83 },
{ PS_WARR87, PS_ROGUE87, PS_MAGE87 },
{ PS_WARR88, PS_ROGUE88, PS_MAGE88 },
{ PS_WARR89, PS_ROGUE89, PS_MAGE89 },
{ PS_WARR91, PS_ROGUE91, PS_MAGE91 },
{ PS_WARR92, PS_ROGUE92, PS_MAGE92 },
{ PS_WARR94, PS_ROGUE94, PS_MAGE94 },
{ PS_WARR95, PS_ROGUE95, PS_MAGE95 },
{ PS_WARR96B,PS_ROGUE96, PS_MAGE96 },
{ PS_WARR97, PS_ROGUE97, PS_MAGE97 },
{ PS_WARR98, PS_ROGUE98, PS_MAGE98 },
{ PS_WARR99, PS_ROGUE99, PS_MAGE99 },
#endif
// clang-format on
};
bool effect_is_playing(int nSFX)
{
SFXStruct* sfx = &sgSFX[nSFX];
if (sfx->bFlags & sfx_STREAM)
return sfx == sgpStreamSFX;
return sfx->pSnd.IsPlaying();
}
void stream_stop()
{
if (sgpStreamSFX != NULL) {
Mix_HaltChannel(SFX_STREAM_CHANNEL);
sgpStreamSFX->pSnd.Release();
sgpStreamSFX = NULL;
}
}
static void stream_play(SFXStruct* pSFX, int lVolume, int lPan)
{
// assert(pSFX != NULL);
// assert(pSFX->bFlags & sfx_STREAM);
// assert(pSFX->pSnd != NULL);
if (pSFX == sgpStreamSFX)
return;
stream_stop();
sgpStreamSFX = pSFX;
sound_stream(pSFX->pszName, &pSFX->pSnd, lVolume, lPan);
}
static void stream_update()
{
if (sgpStreamSFX != NULL && !sgpStreamSFX->pSnd.IsPlaying()) {
stream_stop();
}
}
void InitMonsterSND(int midx)
{
char name[MAX_PATH];
int i, n, j;
MapMonData* cmon;
const MonsterData* mdata;
const MonFileData* mfdata;
assert(gbSndInited);
cmon = &mapMonTypes[midx];
mdata = &monsterdata[cmon->cmType];
mfdata = &monfiledata[mdata->moFileNum];
static_assert((int)MS_SPECIAL + 1 == NUM_MON_SFX, "InitMonsterSND requires MS_SPECIAL at the end of the enum.");
n = mfdata->moSndSpecial ? NUM_MON_SFX : MS_SPECIAL;
for (i = 0; i < n; i++) {
for (j = 0; j < lengthof(cmon->cmSnds[i]); j++) {
snprintf(name, sizeof(name), mfdata->moSndFile, MonstSndChar[i], j + 1);
assert(!cmon->cmSnds[i][j].IsLoaded());
sound_file_load(name, &cmon->cmSnds[i][j]);
assert(cmon->cmSnds[i][j].IsLoaded());
}
}
}
void FreeMonsterSnd()
{
MapMonData* cmon;
int i, j, k;
cmon = mapMonTypes;
for (i = 0; i < nummtypes; i++, cmon++) {
for (j = 0; j < NUM_MON_SFX; ++j) {
for (k = 0; k < lengthof(cmon->cmSnds[j]); ++k) {
//if (cmon->cmSnds[j][k].IsLoaded())
cmon->cmSnds[j][k].Release();
}
}
}
}
static bool calc_snd_position(int x, int y, int* plVolume, int* plPan)
{
int pan, volume;
x -= myplr._px;
y -= myplr._py;
pan = (x - y);
*plPan = pan;
if (abs(pan) > SFX_DIST_MAX)
return false;
volume = std::max(abs(x), abs(y));
if (volume >= SFX_DIST_MAX)
return false;
static_assert(((VOLUME_MAX - VOLUME_MIN) % SFX_DIST_MAX) == 0, "Volume calculation in calc_snd_position requires matching VOLUME_MIN/MAX and SFX_DIST_MAX values.");
static_assert(((((VOLUME_MAX - VOLUME_MIN) / SFX_DIST_MAX)) & ((VOLUME_MAX - VOLUME_MIN) / SFX_DIST_MAX - 1)) == 0, "Volume calculation in calc_snd_position is no longer optimal for performance.");
volume *= (VOLUME_MAX - VOLUME_MIN) / SFX_DIST_MAX;
*plVolume = VOLUME_MAX - volume;
return true;
}
static void PlaySFX_priv(int psfx, bool loc, int x, int y)
{
int lPan, lVolume;
SFXStruct* pSFX;
if (!gbSoundOn || gbLvlLoad != 0)
return;
lPan = 0;
lVolume = VOLUME_MAX;
if (loc && !calc_snd_position(x, y, &lVolume, &lPan)) {
return;
}
pSFX = &sgSFX[psfx];
/* not necessary, since non-streamed sfx should be loaded at this time
streams are loaded in stream_play
if (!pSFX->pSnd.IsLoaded()) {
sound_file_load(pSFX->pszName, &pSFX->pSnd);
// assert(pSFX->pSnd.IsLoaded());
}*/
if (pSFX->bFlags & sfx_STREAM) {
stream_play(pSFX, lVolume, lPan);
return;
}
assert(pSFX->pSnd.IsLoaded());
if (!(pSFX->bFlags & sfx_MISC) && pSFX->pSnd.IsPlaying()) {
return;
}
sound_play(&pSFX->pSnd, lVolume, lPan);
}
void PlayEffect(int mnum, int mode)
{
MonsterStruct* mon;
int sndIdx, lVolume, lPan;
SoundSample* snd;
sndIdx = random_(164, lengthof(mapMonTypes[0].cmSnds[0]));
if (!gbSoundOn || gbLvlLoad != 0)
return;
mon = &monsters[mnum];
snd = &mapMonTypes[mon->_mMTidx].cmSnds[mode][sndIdx];
assert(snd->IsLoaded());
if (snd->IsPlaying()) {
return;
}
if (!calc_snd_position(mon->_mx, mon->_my, &lVolume, &lPan))
return;
sound_play(snd, lVolume, lPan);
}
void PlaySFX(int psfx, int rndCnt)
{
if (rndCnt != 1)
psfx += random_(165, rndCnt);
PlaySFX_priv(psfx, false, 0, 0);
}
void PlaySfxLoc(int psfx, int x, int y, int rndCnt)
{
if (rndCnt != 1)
psfx += random_(165, rndCnt);
//if (psfx <= PS_WALK4 && psfx >= PS_WALK1) {
if (psfx == PS_WALK1) {
sgSFX[psfx].pSnd.nextTc = 0;
}
PlaySFX_priv(psfx, true, x, y);
}
void sound_stop()
{
Mix_HaltChannel(-1);
}
void sound_pause(bool pause)
{
if (pause)
Mix_Pause(-1);
else
Mix_Resume(-1);
}
void sound_update()
{
assert(gbSndInited);
stream_update();
}
static void priv_sound_free(BYTE bLoadMask)
{
int i;
for (i = 0; i < lengthof(sgSFX); i++) {
if (/*sgSFX[i].pSnd.IsLoaded() &&*/ (sgSFX[i].bFlags & bLoadMask)) {
sgSFX[i].pSnd.Release();
}
}
}
static void priv_sound_init(BYTE bLoadMask)
{
int i;
assert(gbSndInited);
for (i = 0; i < lengthof(sgSFX); i++) {
if ((sgSFX[i].bFlags & bLoadMask) != sgSFX[i].bFlags) {
continue;
}
assert(!sgSFX[i].pSnd.IsLoaded());
sound_file_load(sgSFX[i].pszName, &sgSFX[i].pSnd);
}
}
void InitGameEffects()
{
#ifdef HELLFIRE
BYTE mask = sfx_MISC | sfx_HELLFIRE;
#else
BYTE mask = sfx_MISC;
#endif
if (IsLocalGame) {
mask |= sgSFXSets[SFXS_MASK][myplr._pClass];
} else {
mask |= sfx_WARRIOR | sfx_ROGUE | sfx_SORCERER;
#ifdef HELLFIRE
mask |= sfx_MONK;
#endif
}
priv_sound_init(mask);
}
void InitUiEffects()
{
priv_sound_init(sfx_UI);
}
void FreeGameEffects()
{
priv_sound_free(~(sfx_UI | sfx_STREAM));
}
void FreeUiEffects()
{
priv_sound_free(sfx_UI);
}
#endif // NOSOUND
DEVILUTION_END_NAMESPACE
| 76.492928 | 199 | 0.520271 | pionere |
b067b0b09e46cb29511d2a5542cf1a25897280b0 | 428 | cpp | C++ | solutions-LUOGU/P5714.cpp | Ki-Seki/solutions | e4329712d664180d850e0a48d7d0f637215f13d0 | [
"MIT"
] | 1 | 2022-02-26T10:33:24.000Z | 2022-02-26T10:33:24.000Z | solutions-LUOGU/P5714.cpp | Ki-Seki/solutions | e4329712d664180d850e0a48d7d0f637215f13d0 | [
"MIT"
] | null | null | null | solutions-LUOGU/P5714.cpp | Ki-Seki/solutions | e4329712d664180d850e0a48d7d0f637215f13d0 | [
"MIT"
] | 1 | 2021-12-01T14:54:33.000Z | 2021-12-01T14:54:33.000Z | #include <iostream>
using namespace std;
float getBMI(float weight, float height);
int main()
{
float m, h, bmi;
cin >> m >> h;
bmi = getBMI(m, h);
if (bmi<18.5)
{
cout << "Underweight";
}
else if (bmi>=18.5 && bmi<24)
{
cout << "Normal";
}
else
{
cout << bmi << endl << "Overweight";
}
return 0;
}
float getBMI(float weight, float height)
{
float bmi;
bmi = weight / (height * height);
return bmi;
} | 12.969697 | 41 | 0.586449 | Ki-Seki |
b06affa1b763067421762b4fa6fd97c34aedff68 | 2,944 | hpp | C++ | include/NP-Engine/Container/Container.hpp | naphipps/NP-Engine | 0cac8b2d5e76c839b96f2061bf57434bdc37915e | [
"MIT"
] | null | null | null | include/NP-Engine/Container/Container.hpp | naphipps/NP-Engine | 0cac8b2d5e76c839b96f2061bf57434bdc37915e | [
"MIT"
] | null | null | null | include/NP-Engine/Container/Container.hpp | naphipps/NP-Engine | 0cac8b2d5e76c839b96f2061bf57434bdc37915e | [
"MIT"
] | null | null | null | //##===----------------------------------------------------------------------===##//
//
// Author: Nathan Phipps 12/30/20
//
//##===----------------------------------------------------------------------===##//
#ifndef NP_ENGINE_CONTAINER_HPP
#define NP_ENGINE_CONTAINER_HPP
#include "NP-Engine/Foundation/Foundation.hpp"
#include "NP-Engine/Memory/Memory.hpp"
#include <utility> //pair
#include <array>
#include <deque>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include <forward_list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <initializer_list>
namespace np::container
{
template <class T>
using init_list = ::std::initializer_list<T>;
template <class T, siz SIZE>
using array = ::std::array<T, SIZE>;
template <class T>
using vector = ::std::vector<T, memory::StdAllocator<T>>;
template <class T>
using deque = ::std::deque<T, memory::StdAllocator<T>>;
template <class T, class Container = container::deque<T>>
using stack = ::std::stack<T, Container>;
template <class T, class Container = container::deque<T>>
using queue = ::std::queue<T, Container>;
template <class T, class Container = container::vector<T>, class Compare = ::std::less<typename Container::value_type>>
using pqueue = ::std::priority_queue<T, Container, Compare>;
template <class T>
using flist = ::std::forward_list<T, memory::StdAllocator<T>>;
template <class T>
using list = ::std::list<T, memory::StdAllocator<T>>;
template <class Key, class Compare = ::std::less<Key>>
using oset = ::std::set<Key, Compare, memory::StdAllocator<Key>>;
template <class Key, class Hash = ::std::hash<Key>, class KeyEqualTo = ::std::equal_to<Key>>
using uset = ::std::unordered_set<Key, Hash, KeyEqualTo, memory::StdAllocator<Key>>;
template <class Key, class T, class Compare = ::std::less<Key>>
using omap = ::std::map<Key, T, Compare, memory::StdAllocator<::std::pair<const Key, T>>>;
template <class Key, class T, class Hash = ::std::hash<Key>, class KeyEqualTo = ::std::equal_to<Key>>
using umap = ::std::unordered_map<Key, T, Hash, KeyEqualTo, memory::StdAllocator<::std::pair<const Key, T>>>;
template <class Key, class Compare = ::std::less<Key>>
using omset = ::std::multiset<Key, Compare, memory::StdAllocator<Key>>;
template <class Key, class Hash = ::std::hash<Key>, class KeyEqualTo = ::std::equal_to<Key>>
using umset = ::std::unordered_multiset<Key, Hash, KeyEqualTo, memory::StdAllocator<Key>>;
template <class Key, class T, class Compare = ::std::less<Key>>
using ommap = ::std::multimap<Key, T, Compare, memory::StdAllocator<::std::pair<const Key, T>>>;
template <class Key, class T, class Hash = ::std::hash<Key>, class KeyEqualTo = ::std::equal_to<Key>>
using ummap = ::std::unordered_multimap<Key, T, Hash, KeyEqualTo, memory::StdAllocator<::std::pair<const Key, T>>>;
} // namespace np::container
#endif /* NP_ENGINE_CONTAINER_HPP */ | 35.46988 | 120 | 0.659647 | naphipps |
b07320facb9ebf1254f7d54daedd88912fd9a4b7 | 3,192 | cpp | C++ | c714.cpp | puyuliao/ZJ-d879 | bead48e0a500f21bc78f745992f137706d15abf8 | [
"MIT"
] | null | null | null | c714.cpp | puyuliao/ZJ-d879 | bead48e0a500f21bc78f745992f137706d15abf8 | [
"MIT"
] | null | null | null | c714.cpp | puyuliao/ZJ-d879 | bead48e0a500f21bc78f745992f137706d15abf8 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#include<stdint.h>
using namespace std;
#define IOS {cin.tie(0);ios_base::sync_with_stdio(false);}
#define N 50006
#define int int64_t
const int INF = 1e6;
struct treap{
treap *l,*r;
int key,pri,sz,data,keytag,datatag;
treap(int _k,int _d):key(_k),data(_d),sz(1),pri(rand()),keytag(0),datatag(0),l(NULL),r(NULL){}
treap(){}
void push(){
if(keytag){
if(l) l->key += keytag, l->keytag += keytag;
if(r) r->key += keytag, r->keytag += keytag;
keytag = 0;
}
if(datatag){
if(l) l->data += datatag, l->datatag += datatag;
if(r) r->data += datatag, r->datatag += datatag;
datatag = 0;
}
}
void pull(){
sz = 1;
if(l) sz += l->sz;
if(r) sz += r->sz;
}
}mem[N];
int memcnt = 0;
treap *make(int k,int d){
mem[memcnt] = treap(k,d);
return &mem[memcnt++];
}
int size(treap *t){
if(t) {
t->push();
return t->sz;
}
return 0;
}
treap *merge(treap *a,treap *b){
if(!a) return b;
if(!b) return a;
a->push();
b->push();
if(a->pri < b->pri){
a->r = merge(a->r,b);
a->pull();
return a;
}
b->l = merge(a,b->l);
b->pull();
return b;
}
void splitbykey(treap *t,int k,treap*&a,treap*&b){
if(!t) return a=b=NULL,void();
t->push();
if(t->key <= k){
a = t;
splitbykey(t->r,k,a->r,b);
a->pull();
return;
}
b = t;
splitbykey(t->l,k,a,b->l);
b->pull();
}
void splitbysize(treap *t,int k,treap*&a,treap*&b){
if(!t) return a=b=NULL,void();
t->push();
if(size(t->l) < k){
a = t;
splitbysize(t->r,k - size(t->l) - 1,a->r,b);
a->pull();
return;
}
b = t;
splitbysize(t->l,k,a,b->l);
b->pull();
}
treap *t = NULL, *tl, *tr,*tt;
void addkey(int k){
if(t) t->key += k, t->keytag += k;
}
void adddata(int k){
if(t) t->data += k, t->datatag += k;
}
void insert(int k,int d){
splitbykey(t,k-1,tl,tr);
t = make(k,d);
while(tr){
splitbysize(tr,1,tt,tr);
if(tt->data >= d) continue;
else{
if(tt->key != t->key) t = merge(tl,merge(t,merge(tt,tr)));
else t = merge(tl,merge(tt,tr));
return;
}
}
t = merge(tl,t);
return;
}
int getdp(int k){
splitbykey(t,k-1,t,tr);
splitbysize(t,size(t)-1,tl,t);
if(t == NULL){
cout << "GG";
}
int r = t->data;
t = merge(tl,merge(t,tr));
return r;
}
int l[N],r[N],v[N],w[N],in[N];
int cnt;
void dfs(int x){
if(!x) return;
dfs(l[x]);
in[++cnt] = x;
dfs(r[x]);
}
void print(treap *tt){
if(!tt) return;
print(tt->l);
cout << tt->key << ' ' << tt->keytag << ' ' << tt->data << ' ' << tt->datatag << ' ' << tt->sz << '\n';
print(tt->r);
}
int32_t main()
{
srand(time(NULL));
IOS;
int T,n;
cin >> T;
while(T--){
t = NULL;
memcnt = cnt = 0;
cin >> n;
for(int i=1;i<=n;i++) cin >> l[i] >> r[i];
for(int i=1;i<=n;i++) cin >> v[i];
for(int i=1;i<=n;i++) cin >> w[i];
dfs(1);
insert(-INF,0);
for(int j=1;j<=n;j++){
int i = in[j];
int rr = getdp(v[i]);
addkey(1);
adddata(w[i]);
insert(v[i],rr);
//print(t);
//cout << j << ' ' << i << ' ' << getdp(INF) << '\n';
}
cout << getdp(INF) << '\n';
}
return 0;
}
| 18.136364 | 105 | 0.492794 | puyuliao |
b0800c3f7028c8a89ef7473dc5cd100fbeba9c84 | 5,258 | cpp | C++ | app/main.cpp | VBot2410/A_Star_3D | 9755e14f5fe963bf48610d6dc8915b9f5a4009c8 | [
"MIT"
] | 3 | 2017-10-11T01:14:44.000Z | 2018-07-08T16:45:00.000Z | app/main.cpp | VBot2410/A_Star_3D | 9755e14f5fe963bf48610d6dc8915b9f5a4009c8 | [
"MIT"
] | null | null | null | app/main.cpp | VBot2410/A_Star_3D | 9755e14f5fe963bf48610d6dc8915b9f5a4009c8 | [
"MIT"
] | 1 | 2021-09-24T16:34:15.000Z | 2021-09-24T16:34:15.000Z | /**
* @file main.cpp
* @brief This project builds a discrete 3-D map from environment information
* and Implements the A* algorithm to plan the path from Start to Goal Point.
*
* @author Vaibhav Bhilare
* @copyright 2017, Vaibhav Bhilare
*
* MIT License
* Copyright (c) 2017 Vaibhav Bhilare
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/** --Includes--*/
#include <iostream>
#include <vector>
#include <cmath>
#include "../include/Planner.h"
#include "../include/Build_Map.h"
/**
* @brief main method
*
* Takes the World Boundary and Obstacle Data. Sends them to Build a Discrete
* 3-D Map. This map is sent to the planner which then plans the path from
* Start to Goal point using A* Planner.
*
* @return 0
*/
int main() {
/**
* Initialize the x,y,z resolution values.
* Initialize the Margin Value for Robot Dimensions.
* Initialize the World Boundary and Obstacles.
*/
double xy_res = 0.25; ///< Initialize the x,y resolution.
double z_res = 0.25; ///< Initialize the z resolution.
double margin = 0.2; ///< Initialize the margin value for robot dimensions.
/** Initialize the World Boundary in
* {xmin,ymin,zmin,xmax,ymax,zmax} format.
*/
std::vector<double> Boundary = { 0.0, -5.0, 0.0, 10.0, 20.0, 6.0 };
/** Initialize the Obstacles in {xmin,ymin,zmin,xmax,ymax,zmax} format. */
std::vector<std::vector<double>> Obstacle = {
{ 0.0, 2.0, 0.0, 10.0, 2.5, 1.5 }, { 0.0, 2.0, 4.5, 10.0, 2.5, 6.0 }, {
0.0, 2.0, 1.5, 3.0, 2.5, 4.5 } };
/** Create an Instance of the Build_Map Class named Map. */
Build_Map Map = Build_Map(Boundary, xy_res, z_res, margin);
/** Store the Discretized World Dimensions in World. */
std::vector<int> World = Map.World_Dimensions();
/** Create an Instance of the Planner Class named Plan. */
Planner Plan = Planner({ World[0], World[1], World[2] });
/** Add the nodes inside Obstacles to Collision List. */
for (const std::vector<double> &v : Obstacle) {
std::vector<int> Obstacle_Extrema = Map.Build_Obstacle(v);
for (int Counter_X = Obstacle_Extrema[0]; Counter_X != Obstacle_Extrema[3];
Counter_X++) {
for (int Counter_Y = Obstacle_Extrema[1];
Counter_Y != Obstacle_Extrema[4]; Counter_Y++) {
for (int Counter_Z = Obstacle_Extrema[2];
Counter_Z != Obstacle_Extrema[5]; Counter_Z++) {
Plan.Add_Collision({ Counter_X, Counter_Y, Counter_Z });
}
}
}
}
/** Set Heuristic Function to Euclidean or Manhattan (Default Euclidean). */
Plan.Set_Heuristic(Planner::Manhattan);
std::cout << "Calculating Shortest Path ... \n";
std::vector<double> Start = { 0, 0.5, 3 }; ///< Initialize Start Point.
std::vector<double> Goal = { 3.9, 6.4, 0 }; ///< Initialize Goal Point.
/** Check whether the Start or Goal points lie outside the World. */
if ((Start[0] < Boundary[0] || Start[0] > Boundary[3])
|| (Start[1] < Boundary[1] || Start[1] > Boundary[4])
|| (Start[2] < Boundary[2] || Start[2] > Boundary[5])) {
std::cout << "Start Point Lies Out of Workspace.";
} else if ((Goal[0] < Boundary[0] || Goal[0] > Boundary[3])
|| (Goal[1] < Boundary[1] || Goal[1] > Boundary[4])
|| (Goal[2] < Boundary[2] || Goal[2] > Boundary[5])) {
std::cout << "Goal Point Lies Out of Workspace.";
} else {
/** If Start and Goal Points are inside the world, find their positions
* in the discretized world.
*/
std::vector<int> Start_Node = Map.Build_Node(Start);
std::vector<int> Goal_Node = Map.Build_Node(Goal);
/** Plan the Path from Start to Goal using findPath.
* Get the value in path.
*/
auto path = Plan.findPath({ Start_Node[0], Start_Node[1], Start_Node[2] },
{ Goal_Node[0], Goal_Node[1], Goal_Node[2] });
/** Print the Path */
std::cout << "X\tY\tZ\n";
for (auto& coordinate : path) {
std::vector<int> Discrete_Node = { coordinate.x, coordinate.y, coordinate
.z };
std::vector<double> Coordinates = Map.Get_Coordinate(Discrete_Node);
std::cout << Coordinates[0] << "\t" << Coordinates[1] << "\t"
<< Coordinates[2] << "\n";
}
}
return 0; ///< Return 0.
}
| 40.446154 | 81 | 0.648726 | VBot2410 |
b08d744f3c24e3b86f5c9657adb051c635e8bfcf | 1,343 | cpp | C++ | aws-cpp-sdk-iot/source/model/FleetMetricNameAndArn.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-iot/source/model/FleetMetricNameAndArn.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-iot/source/model/FleetMetricNameAndArn.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iot/model/FleetMetricNameAndArn.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace IoT
{
namespace Model
{
FleetMetricNameAndArn::FleetMetricNameAndArn() :
m_metricNameHasBeenSet(false),
m_metricArnHasBeenSet(false)
{
}
FleetMetricNameAndArn::FleetMetricNameAndArn(JsonView jsonValue) :
m_metricNameHasBeenSet(false),
m_metricArnHasBeenSet(false)
{
*this = jsonValue;
}
FleetMetricNameAndArn& FleetMetricNameAndArn::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("metricName"))
{
m_metricName = jsonValue.GetString("metricName");
m_metricNameHasBeenSet = true;
}
if(jsonValue.ValueExists("metricArn"))
{
m_metricArn = jsonValue.GetString("metricArn");
m_metricArnHasBeenSet = true;
}
return *this;
}
JsonValue FleetMetricNameAndArn::Jsonize() const
{
JsonValue payload;
if(m_metricNameHasBeenSet)
{
payload.WithString("metricName", m_metricName);
}
if(m_metricArnHasBeenSet)
{
payload.WithString("metricArn", m_metricArn);
}
return payload;
}
} // namespace Model
} // namespace IoT
} // namespace Aws
| 17.906667 | 76 | 0.730454 | perfectrecall |
b08f5b84f7b9677ce9ac7e504b16496d7946fa4f | 2,631 | hpp | C++ | rmf_traffic/include/rmf_traffic/agv/LaneClosure.hpp | 0to1/rmf_traffic | 0e641f779e9c7e6d69c316e905df5a51a2c124e1 | [
"Apache-2.0"
] | 10 | 2021-04-14T07:01:56.000Z | 2022-02-21T02:26:58.000Z | rmf_traffic/include/rmf_traffic/agv/LaneClosure.hpp | 0to1/rmf_traffic | 0e641f779e9c7e6d69c316e905df5a51a2c124e1 | [
"Apache-2.0"
] | 63 | 2021-03-10T06:06:13.000Z | 2022-03-25T08:47:07.000Z | rmf_traffic/include/rmf_traffic/agv/LaneClosure.hpp | 0to1/rmf_traffic | 0e641f779e9c7e6d69c316e905df5a51a2c124e1 | [
"Apache-2.0"
] | 10 | 2021-03-17T02:52:14.000Z | 2022-02-21T02:27:02.000Z | /*
* Copyright (C) 2021 Open Source Robotics Foundation
*
* 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 RMF_TRAFFIC__AGV__LANECLOSURE_HPP
#define RMF_TRAFFIC__AGV__LANECLOSURE_HPP
#include <utility>
#include <rmf_utils/impl_ptr.hpp>
namespace rmf_traffic {
namespace agv {
//==============================================================================
/// This class describes the closure status of lanes in a Graph, i.e. whether a
/// lane is open or closed. Open lanes can be used by the planner to reach a
/// goal. The planner will not expand down a lane that is closed.
class LaneClosure
{
public:
/// Default constructor.
///
/// By default, all lanes are open.
LaneClosure();
/// Check whether the lane corresponding to the given index is open.
///
/// \param[in] lane
/// The index for the lane of interest
bool is_open(std::size_t lane) const;
/// Check whether the lane corresponding to the given index is closed.
///
/// \param[in] lane
/// The index for the lane of interest
bool is_closed(std::size_t lane) const;
/// Set the lane corresponding to the given index to be open.
///
/// \param[in] lane
/// The index for the opening lane
LaneClosure& open(std::size_t lane);
/// Set the lane corresponding to the given index to be closed.
///
/// \param[in] lane
/// The index for the closing lane
LaneClosure& close(std::size_t lane);
/// Get an integer that uniquely describes the overall closure status of the
/// graph lanes.
std::size_t hash() const;
/// Equality comparison operator
bool operator==(const LaneClosure& other) const;
class Implementation;
private:
rmf_utils::impl_ptr<Implementation> _pimpl;
};
} // namespace agv
} // namespace rmf_traffic
namespace std {
//==============================================================================
template<>
struct hash<rmf_traffic::agv::LaneClosure>
{
std::size_t operator()(
const rmf_traffic::agv::LaneClosure& closure) const noexcept
{
return closure.hash();
}
};
} // namespace std
#endif // RMF_TRAFFIC__AGV__LANECLOSURE_HPP
| 27.694737 | 80 | 0.666287 | 0to1 |
b093bf85c00e5c421189ecb090f653605be700a0 | 4,477 | cpp | C++ | mail/Email.cpp | phiwen96/SocketsServer | eeff4347f0fc31c5081b7f3f59b3c201f6a4f4e7 | [
"Apache-2.0"
] | null | null | null | mail/Email.cpp | phiwen96/SocketsServer | eeff4347f0fc31c5081b7f3f59b3c201f6a4f4e7 | [
"Apache-2.0"
] | null | null | null | mail/Email.cpp | phiwen96/SocketsServer | eeff4347f0fc31c5081b7f3f59b3c201f6a4f4e7 | [
"Apache-2.0"
] | null | null | null | #include "Email.hpp"
void sendEmail()
{
CURL *curl;
CURLcode res = CURLE_OK;
struct curl_slist *recipients = NULL;
struct upload_status upload_ctx;
upload_ctx.lines_read = 0;
curl = curl_easy_init();
if(curl) {
/* Set username and password */
curl_easy_setopt(curl, CURLOPT_USERNAME, "user");
curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret");
/* This is the URL for your mailserver. Note the use of port 587 here,
* instead of the normal SMTP port (25). Port 587 is commonly used for
* secure mail submission (see RFC4403), but you should use whatever
* matches your server configuration. */
// curl_easy_setopt(curl, CURLOPT_URL, "smtp://mainserver.example.net:587");
curl_easy_setopt(curl, CURLOPT_URL, "smtp://92.34.145.157:54003");
/* In this example, we'll start with a plain text connection, and upgrade
* to Transport Layer Security (TLS) using the STARTTLS command. Be careful
* of using CURLUSESSL_TRY here, because if TLS upgrade fails, the transfer
* will continue anyway - see the security discussion in the libcurl
* tutorial for more details. */
curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);
/* If your server doesn't have a valid certificate, then you can disable
* part of the Transport Layer Security protection by setting the
* CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST options to 0 (false).
* curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
* curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
* That is, in general, a bad idea. It is still better than sending your
* authentication details in plain text though. Instead, you should get
* the issuer certificate (or the host certificate if the certificate is
* self-signed) and add it to the set of certificates that are known to
* libcurl using CURLOPT_CAINFO and/or CURLOPT_CAPATH. See docs/SSLCERTS
* for more information. */
curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/certificate.pem");
/* Note that this option isn't strictly required, omitting it will result
* in libcurl sending the MAIL FROM command with empty sender data. All
* autoresponses should have an empty reverse-path, and should be directed
* to the address in the reverse-path which triggered them. Otherwise,
* they could cause an endless loop. See RFC 5321 Section 4.5.5 for more
* details.
*/
curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM);
/* Add two recipients, in this particular case they correspond to the
* To: and Cc: addressees in the header, but they could be any kind of
* recipient. */
recipients = curl_slist_append(recipients, TO);
recipients = curl_slist_append(recipients, CC);
curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);
/* We're using a callback function to specify the payload (the headers and
* body of the message). You could just use the CURLOPT_READDATA option to
* specify a FILE pointer to read from. */
curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
/* Since the traffic will be encrypted, it is very useful to turn on debug
* information within libcurl to see what is happening during the transfer.
*/
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
/* Send the message */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* Free the list of recipients */
curl_slist_free_all(recipients);
/* Always cleanup */
curl_easy_cleanup(curl);
}
}
| 49.197802 | 87 | 0.601296 | phiwen96 |
b093e01c59186885e11ef283c5de787fe460355f | 8,509 | cpp | C++ | plugins/nonpersistent_voxel_layer.cpp | SteveMacenski/non-persistent-voxel-layer | b09cf66faf8424c6245334b78605d58a2cf95da6 | [
"BSD-3-Clause"
] | null | null | null | plugins/nonpersistent_voxel_layer.cpp | SteveMacenski/non-persistent-voxel-layer | b09cf66faf8424c6245334b78605d58a2cf95da6 | [
"BSD-3-Clause"
] | null | null | null | plugins/nonpersistent_voxel_layer.cpp | SteveMacenski/non-persistent-voxel-layer | b09cf66faf8424c6245334b78605d58a2cf95da6 | [
"BSD-3-Clause"
] | null | null | null | /*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Eitan Marder-Eppstein
* David V. Lu!!
* Steve Macenski
*********************************************************************/
#include <sensor_msgs/point_cloud2_iterator.hpp>
#include <vector>
#include "nonpersistent_voxel_layer/nonpersistent_voxel_layer.hpp"
#define VOXEL_BITS 16
using nav2_costmap_2d::NO_INFORMATION;
using nav2_costmap_2d::LETHAL_OBSTACLE;
using nav2_costmap_2d::FREE_SPACE;
using nav2_costmap_2d::ObservationBuffer;
using nav2_costmap_2d::Observation;
namespace nav2_costmap_2d
{
void NonPersistentVoxelLayer::onInitialize()
{
auto node = node_.lock();
clock_ = node->get_clock();
ObstacleLayer::onInitialize();
footprint_clearing_enabled_ = node->get_parameter(
name_ + ".footprint_clearing_enabled").as_bool();
enabled_ = node->get_parameter(name_ + ".enabled").as_bool();
max_obstacle_height_ = node->get_parameter(
name_ + ".max_obstacle_height").as_double();
combination_method_ = node->get_parameter(
name_ + ".combination_method").as_int();
size_z_ = node->declare_parameter(name_ + ".z_voxels", 16);
origin_z_ = node->declare_parameter(name_ + ".origin_z", 16.0);
z_resolution_ = node->declare_parameter(
name_ + ".z_resolution", 0.05);
unknown_threshold_ = node->declare_parameter(
name_ + ".unknown_threshold", 15) + (VOXEL_BITS - size_z_);
mark_threshold_ = node->declare_parameter(
name_ + ".mark_threshold", 0);
publish_voxel_ = node->declare_parameter(
name_ + ".publish_voxel_map", false);
if (publish_voxel_) {
voxel_pub_ =
rclcpp_node_->create_publisher<nav2_msgs::msg::VoxelGrid>(
"voxel_grid", rclcpp::QoS(1));
}
matchSize();
}
NonPersistentVoxelLayer::~NonPersistentVoxelLayer()
{
}
void NonPersistentVoxelLayer::updateFootprint(
double robot_x, double robot_y, double robot_yaw,
double * min_x, double * min_y, double * max_x, double * max_y)
{
if (!footprint_clearing_enabled_) {
return;
}
transformFootprint(robot_x, robot_y, robot_yaw,
getFootprint(), transformed_footprint_);
for (unsigned int i = 0; i < transformed_footprint_.size(); i++) {
touch(transformed_footprint_[i].x, transformed_footprint_[i].y,
min_x, min_y, max_x, max_y);
}
setConvexPolygonCost(transformed_footprint_, nav2_costmap_2d::FREE_SPACE);
}
void NonPersistentVoxelLayer::matchSize()
{
ObstacleLayer::matchSize();
voxel_grid_.resize(size_x_, size_y_, size_z_);
}
void NonPersistentVoxelLayer::reset()
{
deactivate();
resetMaps();
voxel_grid_.reset();
activate();
}
void NonPersistentVoxelLayer::resetMaps()
{
Costmap2D::resetMaps();
voxel_grid_.reset();
}
void NonPersistentVoxelLayer::updateBounds(
double robot_x, double robot_y, double robot_yaw,
double * min_x, double * min_y, double * max_x, double * max_y)
{
// update origin information for rolling costmap publication
if (rolling_window_) {
updateOrigin(robot_x - getSizeInMetersX() / 2,
robot_y - getSizeInMetersY() / 2);
}
// reset maps each iteration
resetMaps();
// if not enabled, stop here
if (!enabled_) {
return;
}
// get the maximum sized window required to operate
useExtraBounds(min_x, min_y, max_x, max_y);
// get the marking observations
bool current = true;
std::vector<Observation> observations;
current = getMarkingObservations(observations) && current;
// update the global current status
current_ = current;
// place the new obstacles into a priority queue... each with a priority of zero to begin with
for (std::vector<Observation>::const_iterator it = observations.begin();
it != observations.end(); ++it)
{
const Observation & obs = *it;
double sq_obstacle_range = obs.obstacle_max_range_ * obs.obstacle_max_range_;
sensor_msgs::PointCloud2ConstIterator<float> it_x(*obs.cloud_, "x");
sensor_msgs::PointCloud2ConstIterator<float> it_y(*obs.cloud_, "y");
sensor_msgs::PointCloud2ConstIterator<float> it_z(*obs.cloud_, "z");
for (; it_x != it_x.end(); ++it_x, ++it_y, ++it_z)
{
// if the obstacle is too high or too far away from the robot we won't add it
if (*it_z > max_obstacle_height_) {
continue;
}
// compute the squared distance from the hitpoint to the pointcloud's origin
double sq_dist = (*it_x - obs.origin_.x) * (*it_x - obs.origin_.x) +
(*it_y - obs.origin_.y) * (*it_y - obs.origin_.y) +
(*it_z - obs.origin_.z) * (*it_z - obs.origin_.z);
// if the point is far enough away... we won't consider it
if (sq_dist >= sq_obstacle_range) {
continue;
}
// now we need to compute the map coordinates for the observation
unsigned int mx, my, mz;
if (*it_z < origin_z_) {
if (!worldToMap3D(*it_x, *it_y, origin_z_, mx, my, mz)) {
continue;
}
} else if (!worldToMap3D(*it_x, *it_y, *it_z, mx, my, mz)) {
continue;
}
// mark the cell in the voxel grid and check if we should also mark it in the costmap
if (voxel_grid_.markVoxelInMap(mx, my, mz, mark_threshold_)) {
unsigned int index = getIndex(mx, my);
costmap_[index] = LETHAL_OBSTACLE;
touch(static_cast<double>(*it_x),
static_cast<double>(*it_y), min_x, min_y, max_x, max_y);
}
}
}
if (publish_voxel_) {
nav2_msgs::msg::VoxelGrid grid_msg;
unsigned int size = voxel_grid_.sizeX() * voxel_grid_.sizeY();
grid_msg.size_x = voxel_grid_.sizeX();
grid_msg.size_y = voxel_grid_.sizeY();
grid_msg.size_z = voxel_grid_.sizeZ();
grid_msg.data.resize(size);
memcpy(&grid_msg.data[0], voxel_grid_.getData(), size * sizeof(unsigned int));
grid_msg.origin.x = origin_x_;
grid_msg.origin.y = origin_y_;
grid_msg.origin.z = origin_z_;
grid_msg.resolutions.x = resolution_;
grid_msg.resolutions.y = resolution_;
grid_msg.resolutions.z = z_resolution_;
grid_msg.header.frame_id = global_frame_;
grid_msg.header.stamp = clock_->now();
voxel_pub_->publish(grid_msg);
}
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
}
void NonPersistentVoxelLayer::updateOrigin(
double new_origin_x, double new_origin_y)
{
// project the new origin into the grid
int cell_ox, cell_oy;
cell_ox = static_cast<int>((new_origin_x - origin_x_) / resolution_);
cell_oy = static_cast<int>((new_origin_y - origin_y_) / resolution_);
// update the origin with the appropriate world coordinates
origin_x_ = origin_x_ + cell_ox * resolution_;
origin_y_ = origin_y_ + cell_oy * resolution_;
}
} // namespace nav2_costmap_2d
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(nav2_costmap_2d::NonPersistentVoxelLayer,
nav2_costmap_2d::Layer)
| 33.632411 | 96 | 0.695146 | SteveMacenski |
b094644630701c8cefb6af63fb6367e20850660d | 1,878 | cpp | C++ | theory/burrows_wheeler/bw_matching.cpp | ideahitme/coursera | af44c8d817481d4f9025205284f109d95a9bb45d | [
"MIT"
] | null | null | null | theory/burrows_wheeler/bw_matching.cpp | ideahitme/coursera | af44c8d817481d4f9025205284f109d95a9bb45d | [
"MIT"
] | null | null | null | theory/burrows_wheeler/bw_matching.cpp | ideahitme/coursera | af44c8d817481d4f9025205284f109d95a9bb45d | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct t{
int l_index; //index in bwt string
int f_index; //index in suffix array
t(int f_index): f_index(f_index) {};
};
inline int con(char x){
if (x == '$') return 0;
if (x == 'A') return 1;
if (x == 'C') return 2;
if (x == 'G') return 3;
if (x == 'T') return 4;
return -1;
}
int bw_matching(
const string &x,
const string &y,
const vector<int> &last_to_first,
const string &p,
const vector<vector<int>> &count,
const vector<int> &first
)
{
int n = x.length();
int m = p.length();
int cur_match = m - 1;
int l = 0;
int r = n - 1;
while(l <= r){
if (cur_match == -1) break;
char chr = p[cur_match];
int ind = con(chr);
int f_ind = first[ind];
if (f_ind == -1) return 0;
if (l > 0) l = f_ind + count[ind][l-1];
else l = f_ind;
r = f_ind + count[ind][r]-1;
cur_match--;
}
return r - l + 1;
}
int main(int argc, char const *argv[])
{
string x;
cin >> x;
string y = x;
sort(y.begin(), y.end());
vector<int> last_to_first(x.length(), -1);
vector<vector<t>> c(5);
vector<int> _c(5, 0);
vector<vector<int>> count(5, vector<int>(x.length(), 0));
vector<int> first(5, -1);
for(int i = 0; i < y.length(); i++){
char chr = y[i];
int ind = con(chr);
if (first[ind] == -1) first[ind] = i;
c[ind].push_back(t(i));
}
for(int i = 0; i < x.length(); i++){
char chr = x[i];
int ind = con(chr);
for(int j = 0; j < 5; j++){
if (j == ind) count[j][i] = (i == 0) ? 1: count[j][i-1]+1;
else count[j][i] = (i == 0) ? 0: count[j][i-1];
}
last_to_first[i] = c[ind][_c[ind]].f_index;
c[ind][_c[ind]].l_index = i;
_c[ind]++;
}
int t;
cin >> t;
for(int i = 0; i < t; i++){
string p;
cin >> p;
int occ = bw_matching(x, y, last_to_first, p, count, first);
cout << occ << " ";
}
cout << endl;
return 0;
}
| 20.866667 | 62 | 0.554846 | ideahitme |
b09645265b8e106645b7463c776a0713265b8a92 | 2,527 | hpp | C++ | src/camera.hpp | DeNiCoN/ComputerGraphicsLabs | ca02ea69b8dbc2ebeef1068779a0802babc95302 | [
"Unlicense"
] | null | null | null | src/camera.hpp | DeNiCoN/ComputerGraphicsLabs | ca02ea69b8dbc2ebeef1068779a0802babc95302 | [
"Unlicense"
] | null | null | null | src/camera.hpp | DeNiCoN/ComputerGraphicsLabs | ca02ea69b8dbc2ebeef1068779a0802babc95302 | [
"Unlicense"
] | null | null | null | #pragma once
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <array>
#include <string_view>
#include <algorithm>
#include <ranges>
namespace Projection
{
enum Projection
{
ORTHO, PERSPECTIVE
};
const std::array projectionStrings
{
"Ortho", "Perspective"
};
inline const char* ToString(Projection proj)
{
std::size_t value = static_cast<std::size_t>(proj);
assert(value < projectionStrings.size());
return projectionStrings[value];
}
inline Projection FromString(std::string_view sv)
{
auto it = std::ranges::find(projectionStrings, sv);
assert(it != projectionStrings.end());
return static_cast<Projection>(
std::distance(projectionStrings.begin(), it));
}
}
class Camera
{
public:
const glm::mat4& GetProjection() const { return m_proj; }
glm::mat4 GetView() const
{
glm::vec3 posT = transform * glm::vec4(position, 1.f);
glm::vec3 dirT = transform * glm::vec4(direction, 0.f);
glm::vec3 upT = transform * glm::vec4(0.f, 1.f, 0.f, 0.f);
auto look = glm::lookAt(posT, posT + dirT, upT);
return glm::scale(glm::identity<glm::mat4>(), {scale, scale, scale}) * look;
}
glm::vec3 direction = {0.f, 0.f, 1.f};
glm::vec3 position = {0.f, 0.f, 0.f};
float scale = 1.f;
void SetOrtho(float width, float height, unsigned depth)
{
m_proj = glm::ortho(-width/2.f, width/2.f,
-height/2.f, height/2.f,
0.f, depth/1.f);
m_proj[1][1] = -m_proj[1][1];
m_projectionType = Projection::ORTHO;
}
void SetPerspective(float fov, float aspect, float near, float far)
{
m_proj = glm::perspective(fov, aspect, near, far);
m_proj[1][1] = -m_proj[1][1];
m_projectionType = Projection::PERSPECTIVE;
}
Projection::Projection GetProjectionType() const
{
return m_projectionType;
}
void SetViewport(int width, int height)
{
if (GetProjectionType() == Projection::PERSPECTIVE)
{
SetPerspective(m_fov, width / static_cast<float>(height),
0.01f, 100.f);
}
else if (GetProjectionType() == Projection::ORTHO)
{
SetOrtho(width/100.f, height/100.f, 100.f);
}
}
float m_fov = 2.f;
glm::mat4 transform = glm::identity<glm::mat4>();
private:
Projection::Projection m_projectionType = Projection::ORTHO;
glm::mat4 m_proj = glm::identity<glm::mat4>();
};
| 25.785714 | 84 | 0.600712 | DeNiCoN |
b0975cc86125fc253cf28d7cd36406647a43be04 | 2,073 | hpp | C++ | bin/Mediasoup.xcframework/ios-arm64_x86_64-simulator/Mediasoup.framework/PrivateHeaders/ReceiveTransportWrapper.hpp | VLprojects/mediaborsch-client-swift | 34cc664b0f2c95e769fa0d7df01a219bba43ff4f | [
"MIT"
] | null | null | null | bin/Mediasoup.xcframework/ios-arm64_x86_64-simulator/Mediasoup.framework/PrivateHeaders/ReceiveTransportWrapper.hpp | VLprojects/mediaborsch-client-swift | 34cc664b0f2c95e769fa0d7df01a219bba43ff4f | [
"MIT"
] | null | null | null | bin/Mediasoup.xcframework/ios-arm64_x86_64-simulator/Mediasoup.framework/PrivateHeaders/ReceiveTransportWrapper.hpp | VLprojects/mediaborsch-client-swift | 34cc664b0f2c95e769fa0d7df01a219bba43ff4f | [
"MIT"
] | null | null | null | #ifndef ReceiveTransportWrapper_h
#define ReceiveTransportWrapper_h
#import <Foundation/Foundation.h>
#import "MediasoupClientMediaKind.h"
#ifdef __cplusplus
namespace mediasoupclient {
class RecvTransport;
}
class ReceiveTransportListenerAdapter;
#endif
@class ConsumerWrapper;
@class RTCPeerConnectionFactory;
@protocol ReceiveTransportWrapperDelegate;
typedef NS_ENUM(NSInteger, RTCIceTransportPolicy);
@interface ReceiveTransportWrapper : NSObject
@property(nonatomic, nullable, weak) id<ReceiveTransportWrapperDelegate> delegate;
@property(nonatomic, nonnull, readonly, getter = id) NSString *id;
@property(nonatomic, readonly, getter = closed) BOOL closed;
@property(nonatomic, nonnull, readonly, getter = connectionState) NSString *connectionState;
@property(nonatomic, nonnull, readonly, getter = appData) NSString *appData;
@property(nonatomic, nonnull, readonly, getter = stats) NSString *stats;
#ifdef __cplusplus
- (instancetype _Nullable)initWithTransport:(mediasoupclient::RecvTransport *_Nonnull)transport
pcFactory:(RTCPeerConnectionFactory *_Nonnull)pcFactory
listenerAdapter:(ReceiveTransportListenerAdapter *_Nonnull)listenerAdapter;
#endif
- (void)close;
- (void)restartICE:(NSString *_Nonnull)iceParameters
error:(out NSError *__autoreleasing _Nullable *_Nullable)error
__attribute__((swift_error(nonnull_error)));
- (void)updateICEServers:(NSString *_Nonnull)iceServers
error:(out NSError *__autoreleasing _Nullable *_Nullable)error
__attribute__((swift_error(nonnull_error)));
- (void)updateICETransportPolicy:(RTCIceTransportPolicy)iceTransportPolicy
error:(out NSError *__autoreleasing _Nullable *_Nullable)error
__attribute__((swift_error(nonnull_error)));
- (ConsumerWrapper *_Nullable)createConsumerWithId:(NSString *_Nonnull)consumerId
producerId:(NSString *_Nonnull)producerId
kind:(MediasoupClientMediaKind _Nonnull)kind
rtpParameters:(NSString *_Nonnull)rtpParameters
appData:(NSString *_Nullable)appData
error:(out NSError *__autoreleasing _Nullable *_Nullable)error;
@end
#endif /* ReceiveTransportWrapper_h */
| 35.135593 | 95 | 0.826339 | VLprojects |
b09865ad533c07e5d1ddc2b35144a0f361e03072 | 1,726 | cpp | C++ | Unity/vr_arm_ctrl/Library/PackageCache/[email protected]/MockRuntime/Native~/openxr_loader/mock_loader.cpp | BigMeatBaoZi/SDM5002 | 52d60368f3c638d36f63de9e88cca5144b5021a5 | [
"MIT"
] | null | null | null | Unity/vr_arm_ctrl/Library/PackageCache/[email protected]/MockRuntime/Native~/openxr_loader/mock_loader.cpp | BigMeatBaoZi/SDM5002 | 52d60368f3c638d36f63de9e88cca5144b5021a5 | [
"MIT"
] | null | null | null | Unity/vr_arm_ctrl/Library/PackageCache/[email protected]/MockRuntime/Native~/openxr_loader/mock_loader.cpp | BigMeatBaoZi/SDM5002 | 52d60368f3c638d36f63de9e88cca5144b5021a5 | [
"MIT"
] | 2 | 2022-03-14T00:37:10.000Z | 2022-03-14T02:31:38.000Z | #ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif // !WIN32_LEAN_AND_MEAN
#include <d3d11.h>
#include <d3d12.h>
#include <windows.h>
#endif
#include <vulkan/vulkan.h>
#define XR_NO_PROTOTYPES
#include "XR/IUnityXRTrace.h"
#include "openxr/openxr.h"
#include "openxr/openxr_platform.h"
#include "plugin_load.h"
#include <openxr/loader_interfaces.h>
#include <openxr/openxr_reflection.h>
struct IUnityXRTrace;
extern IUnityXRTrace* s_Trace;
IUnityXRTrace* s_Trace = nullptr;
extern "C" XrResult UNITY_INTERFACE_EXPORT XRAPI_PTR xrGetInstanceProcAddr(XrInstance instance, const char* name, PFN_xrVoidFunction* function);
PluginHandle s_PluginHandle = nullptr;
PFN_xrGetInstanceProcAddr s_GetInstanceProcAddr = nullptr;
static bool LoadMockRuntime()
{
if (nullptr != s_GetInstanceProcAddr)
return true;
s_PluginHandle = Plugin_LoadLibrary("mock_runtime");
if (nullptr == s_PluginHandle)
return false;
s_GetInstanceProcAddr = (PFN_xrGetInstanceProcAddr)Plugin_GetSymbol(s_PluginHandle, "xrGetInstanceProcAddr");
return nullptr != s_GetInstanceProcAddr;
}
extern "C" XrResult UNITY_INTERFACE_EXPORT XRAPI_PTR xrGetInstanceProcAddr(XrInstance instance, const char* name, PFN_xrVoidFunction* function)
{
if (!LoadMockRuntime())
return XR_ERROR_RUNTIME_FAILURE;
return s_GetInstanceProcAddr(instance, name, function);
}
extern "C" void UNITY_INTERFACE_EXPORT XRAPI_PTR SetXRTrace(IUnityXRTrace* trace)
{
if (!LoadMockRuntime())
return;
typedef void (*PFN_SetXRTrace)(IUnityXRTrace * trace);
PFN_SetXRTrace set = (PFN_SetXRTrace)Plugin_GetSymbol(s_PluginHandle, "SetXRTrace");
if (set != nullptr)
set(trace);
}
| 27.83871 | 144 | 0.76883 | BigMeatBaoZi |
b09ead2a75fb0c63ed992c9f5df2cded5e5afb2c | 7,944 | cpp | C++ | ESPSloeber/BathFanControl/Configuration.cpp | theater/House | 7220f3d89d6de6a809fa36121dc28754feaf6bc0 | [
"MIT"
] | null | null | null | ESPSloeber/BathFanControl/Configuration.cpp | theater/House | 7220f3d89d6de6a809fa36121dc28754feaf6bc0 | [
"MIT"
] | null | null | null | ESPSloeber/BathFanControl/Configuration.cpp | theater/House | 7220f3d89d6de6a809fa36121dc28754feaf6bc0 | [
"MIT"
] | null | null | null | /*
* Configuration.cpp
*
* Created on: Oct 25, 2019
* Author: theater
*/
#include "Configuration.h"
void Configuration::print() {
Serial.println("###########################################");
String simulated = isSimulated ? "true" : "false";
Serial.printf("Simulated=%s \n", simulated.c_str());
Serial.printf("Configuration serial number=%d \n", serialNumber);
Serial.println("###########################################");
Serial.printf("SSID=%s \n", ssid.c_str());
Serial.printf("SSID Password=%s \n", ssidPassword.c_str());
Serial.println("###########################################");
Serial.printf("MQTT Server/port=%s:%d \n", mqttServerAddress.toString().c_str(), mqttPort);
Serial.printf("MQTT Client name=%s \n", mqttClientName.c_str());
Serial.printf("Fan speed topic=%s \n", fanSpeedMqttTopic.c_str());
Serial.printf("Mirror heating topic=%s \n", mirrorHeatingMqttTopic.c_str());
Serial.printf("Humidity topic=%s \n", humidityMqttTopic.c_str());
Serial.printf("Temperature topic=%s \n", temperatureMqttTopic.c_str());
Serial.printf("Mode topic=%s \n", modeMqttTopic.c_str());
Serial.printf("Desired humidity topic=%s \n", desiredHumidityMqttTopic.c_str());
Serial.println("###########################################");
Serial.printf("Current mode=%d \n", mode);
Serial.printf("Desired humidity=%d%% \n", desiredHumidity);
Serial.printf("High speed humidity threshold=%d%% \n", highSpeedThresholdDelta);
Serial.printf("Humidity threshold tolerance=%d \n", humidityTolerance);
Serial.printf("Sensors refresh interval=%dms \n", sensorsUpdateReocurrenceIntervalMillis);
Serial.printf("Temperature correction=%d \n", temperatureCorrection);
Serial.printf("Humidity Correction=%d \n", humidityCorrection);
}
void Configuration::updateValue(String * configProperty, String value, String parameterName) {
if (!value.equals("") && !value.equals("********")) {
*configProperty = value;
Serial.printf("Parameter %s updated to: %s\n", parameterName.c_str(), value.c_str());
} else {
Serial.printf("Received empty response for parameter %s. Will skip update.\n", parameterName.c_str());
}
}
void Configuration::updateValue(int * configProperty, String value, String parameterName) {
if (!value.equals("") && !value.equals("********")) {
*configProperty = value.toInt();
Serial.printf("Parameter %s updated to: %d\n", parameterName.c_str(), *configProperty);
} else {
Serial.printf("Received empty response for parameter %s. Will skip update.\n", parameterName.c_str());
}
}
void Configuration::updateValue(bool * configProperty, String value, String parameterName) {
if (value.equals("on")) {
*configProperty = true;
} else {
*configProperty = false;
}
Serial.printf("Parameter %s updated to: %s\n", parameterName.c_str(), *configProperty ? "true" : "false");
}
void Configuration::loadEprom() {
int nextAddress = STARTING_ADDRESS;
Serial.printf("Loading config from EPROM...\nStarting with address=%d. Serial number before load=%d\n", nextAddress, serialNumber);
EEPROM.begin(512);
int memSerialNumber;
memSerialNumber = EEPROM.get(nextAddress, memSerialNumber);
Serial.printf("Loaded serial number from EPROM=%d\n", memSerialNumber);
if (memSerialNumber == serialNumber) {
nextAddress+=sizeof(memSerialNumber);
ssid = getStringEprom(&nextAddress);
ssidPassword = getStringEprom(&nextAddress);
mqttServerAddress.fromString(getStringEprom(&nextAddress));
mqttClientName = getStringEprom(&nextAddress);
fanSpeedMqttTopic = getStringEprom(&nextAddress);
mirrorHeatingMqttTopic = getStringEprom(&nextAddress);
humidityMqttTopic = getStringEprom(&nextAddress);
temperatureMqttTopic = getStringEprom(&nextAddress);
modeMqttTopic = getStringEprom(&nextAddress);
desiredHumidityMqttTopic = getStringEprom(&nextAddress);
Serial.printf("Finished loading strings. Last address=%d\n", nextAddress);
isSimulated = EEPROM.get(nextAddress += sizeof(isSimulated), isSimulated);
mode = EEPROM.get(nextAddress += sizeof(mode), mode);
mqttPort = EEPROM.get(nextAddress += sizeof(mqttPort), mqttPort);
desiredHumidity = EEPROM.get(nextAddress += sizeof(desiredHumidity), desiredHumidity);
highSpeedThresholdDelta = EEPROM.get(nextAddress += sizeof(highSpeedThresholdDelta), highSpeedThresholdDelta);
sensorsUpdateReocurrenceIntervalMillis = EEPROM.get(nextAddress += sizeof(sensorsUpdateReocurrenceIntervalMillis),
sensorsUpdateReocurrenceIntervalMillis);
temperatureCorrection = EEPROM.get(nextAddress += sizeof(temperatureCorrection), temperatureCorrection);
humidityCorrection = EEPROM.get(nextAddress += sizeof(humidityCorrection), humidityCorrection);
humidityTolerance = EEPROM.get(nextAddress += sizeof(humidityTolerance), humidityTolerance);
Serial.printf("Finished loading primitives. Last address=%d\n", nextAddress);
} else {
Serial.printf("Configuration serial number from EPROM not equal to expected. Default values will be used. Value expected=%d, Value in EPROM=%d\n", this->serialNumber, memSerialNumber);
}
print();
}
void Configuration::saveEprom() {
int nextAddress = STARTING_ADDRESS;
Serial.printf("Saving config from EPROM...\nStarting with address=%d.\n", nextAddress);
EEPROM.begin(512);
Serial.printf("Before writing configuration serial number. Address=%d, serial number=%d",nextAddress, serialNumber);
EEPROM.put(nextAddress, serialNumber);
nextAddress+=sizeof(serialNumber);
putStringEprom(&nextAddress, ssid);
putStringEprom(&nextAddress, ssidPassword);
putStringEprom(&nextAddress, mqttServerAddress.toString());
putStringEprom(&nextAddress, mqttClientName);
putStringEprom(&nextAddress, fanSpeedMqttTopic);
putStringEprom(&nextAddress, mirrorHeatingMqttTopic);
putStringEprom(&nextAddress, humidityMqttTopic);
putStringEprom(&nextAddress, temperatureMqttTopic);
putStringEprom(&nextAddress, modeMqttTopic);
putStringEprom(&nextAddress, desiredHumidityMqttTopic);
Serial.printf("Finished saving strings. Last address=%d\n", nextAddress);
EEPROM.put(nextAddress += sizeof(isSimulated), isSimulated);
EEPROM.put(nextAddress += sizeof(mode), mode);
EEPROM.put(nextAddress += sizeof(mqttPort), mqttPort);
EEPROM.put(nextAddress += sizeof(desiredHumidity), desiredHumidity);
EEPROM.put(nextAddress += sizeof(highSpeedThresholdDelta), highSpeedThresholdDelta);
EEPROM.put(nextAddress += sizeof(sensorsUpdateReocurrenceIntervalMillis), sensorsUpdateReocurrenceIntervalMillis);
EEPROM.put(nextAddress += sizeof(temperatureCorrection), temperatureCorrection);
EEPROM.put(nextAddress += sizeof(humidityCorrection), humidityCorrection);
EEPROM.put(nextAddress += sizeof(humidityTolerance), humidityTolerance);
Serial.printf("Finished saving primitives. Last address=%d\n", nextAddress);
EEPROM.commit();
Serial.printf("EPROM used=%d bytes\n", nextAddress);
}
void Configuration::putStringEprom(int *address, String property) {
int length = property.length();
Serial.printf("Property %s / length=%d\n", property.c_str(), length);
EEPROM.put(*address, length);
*address += sizeof(length);
for (int i = 0; i < length; i++) {
EEPROM.write(*address + i, property[i]);
}
EEPROM.write(*address + length, '\0');
*address += length + 1;
Serial.printf("Next address = %d\n", *address);
}
String Configuration::getStringEprom(int *address) {
int length = EEPROM.get(*address, length);
*address += sizeof(length);
Serial.printf("Property length=%d, next address=%d\n", length, *address);
char tempArr[100];
Serial.print("Starting EEPROM read. Characters=");
unsigned char tempChar;
for (int i = 0; i < length; i++) {
tempChar = EEPROM.read(*address + i);
tempArr[i] = tempChar;
Serial.printf("%c", tempArr[i]);
}
tempArr[length] = '\0';
*address += length + 1;
return String(tempArr);
}
| 46.186047 | 187 | 0.715005 | theater |
b0bfb70cbacd1f5f7425e2895d28c66003f38a77 | 7,481 | cpp | C++ | samples/snippets/cpp/VS_Snippets_Winforms/ComponentEditorExample/CPP/componenteditorexamplecomponent.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_Winforms/ComponentEditorExample/CPP/componenteditorexamplecomponent.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_Winforms/ComponentEditorExample/CPP/componenteditorexamplecomponent.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z |
//<Snippet1>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
#using <System.dll>
using namespace System;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design;
using namespace System::Collections;
using namespace System::Drawing;
using namespace System::IO;
using namespace System::Runtime::Serialization;
using namespace System::Runtime::Serialization::Formatters::Binary;
using namespace System::Windows::Forms;
using namespace System::Windows::Forms::Design;
// This example demonstrates how to implement a component editor that hosts
// component pages and associate it with a component. This example also
// demonstrates how to implement a component page that provides a panel-based
// control system and Help keyword support.
ref class ExampleComponentEditorPage;
// The ExampleComponentEditor displays two ExampleComponentEditorPage pages.
public ref class ExampleComponentEditor: public System::Windows::Forms::Design::WindowsFormsComponentEditor
{
//<Snippet2>
protected:
// This method override returns an type array containing the type of
// each component editor page to display.
virtual array<Type^>^ GetComponentEditorPages() override
{
array<Type^>^temp0 = {ExampleComponentEditorPage::typeid,ExampleComponentEditorPage::typeid};
return temp0;
}
//</Snippet2>
//<Snippet3>
// This method override returns the index of the page to display when the
// component editor is first displayed.
protected:
virtual int GetInitialComponentEditorPageIndex() override
{
return 1;
}
//</Snippet3>
};
//<Snippet6>
// This example component editor page type provides an example
// ComponentEditorPage implementation.
private ref class ExampleComponentEditorPage: public System::Windows::Forms::Design::ComponentEditorPage
{
private:
Label^ l1;
Button^ b1;
PropertyGrid^ pg1;
// Base64-encoded serialized image data for the required component editor page icon.
String^ icon;
public:
ExampleComponentEditorPage()
{
String^ temp = "AAEAAAD/////AQAAAAAAAAAMAgAAAFRTeXN0ZW0uRHJhd2luZywgVmVyc2lvbj0xLjAuNTAwMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWIwM2Y1ZjdmMTFkNTBhM2EFAQAAABNTeXN0ZW0uRHJhd2luZy5JY29uAgAAAAhJY29uRGF0Y"
"QhJY29uU2l6ZQcEAhNTeXN0ZW0uRHJhd2luZy5TaXplAgAAAAIAAAAJAwAAAAX8////E1N5c3RlbS5EcmF3aW5nLlNpemUCAAAABXdpZHRoBmhlaWdodAAACAgCAAAAAAAAAAAAAAAPAwAAAD4BAAACAAABAAEAEBAQAAAAAAAoAQAAFgAAACgAAAAQAAAAIA"
"AAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAAACAAACAAAAAgIAAgAAAAIAAgADExAAAgICAAMDAwAA+iPcAY77gACh9kwD/AAAAndPoADpw6wD///8AAAAAAAAAAAAHd3d3d3d3d8IiIiIiIiLHKIiIiIiIiCco///////4Jyj5mfIvIvgnKPn"
"p////+Cco+en7u7v4Jyj56f////gnKPmZ8i8i+Cco///////4JyiIiIiIiIgnJmZmZmZmZifCIiIiIiIiwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACw==";
icon = temp;
// Initialize the page, which inherits from Panel, and its controls.
this->Size = System::Drawing::Size( 400, 250 );
this->Icon = DeserializeIconFromBase64Text( icon );
this->Text = "Example Page";
b1 = gcnew Button;
b1->Size = System::Drawing::Size( 200, 20 );
b1->Location = Point(200,0);
b1->Text = "Set a random background color";
b1->Click += gcnew EventHandler( this, &ExampleComponentEditorPage::randomBackColor );
this->Controls->Add( b1 );
l1 = gcnew Label;
l1->Size = System::Drawing::Size( 190, 20 );
l1->Location = Point(4,2);
l1->Text = "Example Component Editor Page";
this->Controls->Add( l1 );
pg1 = gcnew PropertyGrid;
pg1->Size = System::Drawing::Size( 400, 280 );
pg1->Location = Point(0,30);
this->Controls->Add( pg1 );
}
// This method indicates that the Help button should be enabled for this
// component editor page.
virtual bool SupportsHelp() override
{
return true;
}
//<Snippet4>
// This method is called when the Help button for this component editor page is pressed.
// This implementation uses the IHelpService to show the Help topic for a sample keyword.
public:
virtual void ShowHelp() override
{
// The GetSelectedComponent method of a ComponentEditorPage retrieves the
// IComponent associated with the WindowsFormsComponentEditor.
IComponent^ selectedComponent = this->GetSelectedComponent();
// Retrieve the Site of the component, and return if null.
ISite^ componentSite = selectedComponent->Site;
if ( componentSite == nullptr )
return;
// Acquire the IHelpService to display a help topic using a indexed keyword lookup.
IHelpService^ helpService = dynamic_cast<IHelpService^>(componentSite->GetService( IHelpService::typeid ));
if ( helpService != nullptr )
helpService->ShowHelpFromKeyword( "System.Windows.Forms.ComboBox" );
}
//</Snippet4>
protected:
// The LoadComponent method is raised when the ComponentEditorPage is displayed.
virtual void LoadComponent() override
{
this->pg1->SelectedObject = this->Component;
}
// The SaveComponent method is raised when the WindowsFormsComponentEditor is closing
// or the current ComponentEditorPage is closing.
virtual void SaveComponent() override {}
private:
// If the associated component is a Control, this method sets the BackColor to a random color.
// This method is invoked by the button on this ComponentEditorPage.
void randomBackColor( Object^ /*sender*/, EventArgs^ /*e*/ )
{
if ( System::Windows::Forms::Control::typeid->IsAssignableFrom( this->::Component::GetType() ) )
{
// Sets the background color of the Control associated with the
// WindowsFormsComponentEditor to a random color.
Random^ rnd = gcnew Random;
(dynamic_cast<System::Windows::Forms::Control^>(this->Component))->BackColor = Color::FromArgb( rnd->Next( 255 ), rnd->Next( 255 ), rnd->Next( 255 ) );
pg1->Refresh();
}
}
// This method can be used to retrieve an Icon from a block
// of Base64-encoded text.
System::Drawing::Icon^ DeserializeIconFromBase64Text( String^ text )
{
System::Drawing::Icon^ img = nullptr;
array<Byte>^memBytes = Convert::FromBase64String( text );
IFormatter^ formatter = gcnew BinaryFormatter;
MemoryStream^ stream = gcnew MemoryStream( memBytes );
img = dynamic_cast<System::Drawing::Icon^>(formatter->Deserialize( stream ));
stream->Close();
return img;
}
};
//</Snippet6>
//<Snippet5>
// This example control is associated with the ExampleComponentEditor
// through the following EditorAttribute.
[EditorAttribute(ExampleComponentEditor::typeid,ComponentEditor::typeid)]
public ref class ExampleUserControl: public System::Windows::Forms::UserControl{};
//</Snippet5>
//</Snippet1>
| 42.505682 | 220 | 0.670499 | hamarb123 |
b0c269ecd48a8acbbb768b8b2f55d36fb170d983 | 4,386 | cpp | C++ | source code/dvcc/v1.4.2.2/paint/ramqgitem.cpp | HarleyEhrich/DvccSimulationEnvironment | fdb082eb52c18a95015fc12058824345875cf038 | [
"Apache-2.0"
] | null | null | null | source code/dvcc/v1.4.2.2/paint/ramqgitem.cpp | HarleyEhrich/DvccSimulationEnvironment | fdb082eb52c18a95015fc12058824345875cf038 | [
"Apache-2.0"
] | null | null | null | source code/dvcc/v1.4.2.2/paint/ramqgitem.cpp | HarleyEhrich/DvccSimulationEnvironment | fdb082eb52c18a95015fc12058824345875cf038 | [
"Apache-2.0"
] | null | null | null | #include "ramqgitem.h"
QRectF RamQGItem::boundingRect() const
{
return QRectF(this->mapFromScene(200*this->data->zoomXPer,-250*this->data->zoomYPer),
QSizeF(150*this->data->zoomXPer,390*this->data->zoomYPer));
}
void RamQGItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(widget);
if(this->data->load_ram==false){
return;
}
//数据准备
double zoomX=this->data->zoomXPer;
double zoomY=this->data->zoomYPer;
//位置设定
this->setPos(200*zoomX,-250*zoomY);
//Body draw
bodyPath->clear();
bodyPath->moveTo(0,0);
bodyPath->addRoundedRect(QRectF(0,0,150*zoomX,190*zoomY),10,10);
bodyPath->closeSubpath();
this->body->setPath(*this->bodyPath);
//Cir draw
cirPath->clear();
cirPath->addEllipse(QRectF(110*zoomX,10*zoomY,25*zoomX,25*zoomX));
this->cir->setPath(*this->cirPath);
//Name draw
this->nameText->setPos(5*zoomX,0);
//Data draw
if(this->data->signal_ce==true){
this->dataText->setPos(75*zoomX-this->dataText->boundingRect().width()/2,40*zoomY);
if(this->data->signal_we==WRITE){//Write--read data from bus
this->dataText->setText(this->data->data_bus+"H");
}else{//Read--read data from ram
this->dataText->setText(QString("%0%1H")
.arg(this->data->data_ram[this->data->data_ar][0])
.arg(this->data->data_ram[this->data->data_ar][1])
);
}
}else{
this->dataText->setText("");
}
//sig--ce draw
if(this->data->signal_ce){
this->signalsText->setPen(lightSignalsPenAct);
this->signalsText->setBrush(lightSignalsBrushAct);
this->signalsText->setText("CE: Valid");
this->signalsText->setPos(75*zoomX-this->signalsText->boundingRect().width()/2,90*zoomY);
}else{
this->signalsText->setPen(lightSignalsPen);
this->signalsText->setBrush(lightSignalsBrush);
this->signalsText->setText("CE: Invalid");
this->signalsText->setPos(75*zoomX-this->signalsText->boundingRect().width()/2,90*zoomY);
}
//sig--we draw
if(this->data->signal_we==WRITE){
this->signalsText2->setPen(lightSignalsPenAct);
this->signalsText2->setBrush(lightSignalsBrushAct);
this->signalsText2->setText("WE: 1-Write");
this->signalsText2->setPos(75*zoomX-this->signalsText->boundingRect().width()/2,120*zoomY);
}else{
this->signalsText2->setPen(lightSignalsPen);
this->signalsText2->setBrush(lightSignalsBrush);
this->signalsText2->setText("WE: 0-Read");
this->signalsText2->setPos(75*zoomX-this->signalsText->boundingRect().width()/2,120*zoomY);
}
//Ram<--Bus line
if(this->data->signal_ce==true){
this->toBusLine->setPen(linePenAct);
this->setZValue(100);
}else{
this->toBusLine->setPen(linePen);
this->setZValue(0);
}
this->toBusLine->setLine(75*zoomX+3,190*zoomY+4,75*zoomX+3,250*zoomY);
}
RamQGItem::RamQGItem(systemDataSet *data,QGraphicsItem *parent)
:QGraphicsItem(parent)
{
// this->setZValue(0);
this->data=data;
bodyPath=new QPainterPath();
bodyShadowEff=new QGraphicsDropShadowEffect();
bodyShadowEff->setOffset(5,5);
bodyShadowEff->setColor(Qt::gray);
bodyShadowEff->setBlurRadius(15);
body=new QGraphicsPathItem(this);
body->setPen(ramBodyPen);
body->setBrush(ramBodyBrush);
body->setGraphicsEffect(bodyShadowEff);
cirPath=new QPainterPath();
cir=new QGraphicsPathItem(this);
cir->setPen(ramCirPen);
cir->setBrush(ramCirBrush);
nameText=new QGraphicsSimpleTextItem(this);
this->nameText->setText("RAM");
this->nameText->setPen(lightTextPen);
this->nameText->setBrush(ligthTextBrush);
this->nameText->setFont(bigNameTextFont);
dataText=new QGraphicsSimpleTextItem(this);
this->dataText->setPen(lightTextPen);
this->dataText->setBrush(ligthTextBrush);
this->dataText->setFont(bigDataTextFont);
signalsText=new QGraphicsSimpleTextItem(this);
this->signalsText->setFont(bigSignalsFont);
signalsText2=new QGraphicsSimpleTextItem(this);
this->signalsText2->setFont(bigSignalsFont);
toBusLine=new QGraphicsLineItem(this);
}
| 32.488889 | 99 | 0.645919 | HarleyEhrich |
b0c801272d537ad2a94c1bb762a4d0ad52c58a79 | 119 | hpp | C++ | src/QonGPU/include/potentials/Potential3D.hpp | s0vereign/SchroedingerSolver | 83461ef779019ec7944bb2c5ea0a4702f4aeb32f | [
"MIT"
] | 3 | 2017-04-21T12:22:33.000Z | 2019-01-22T13:14:46.000Z | src/QonGPU/include/potentials/Potential3D.hpp | s0vereign/SchroedingerSolver | 83461ef779019ec7944bb2c5ea0a4702f4aeb32f | [
"MIT"
] | 8 | 2016-05-09T09:44:35.000Z | 2017-03-22T15:31:13.000Z | src/QonGPU/include/potentials/Potential3D.hpp | s0vereign/QonGPU | 83461ef779019ec7944bb2c5ea0a4702f4aeb32f | [
"MIT"
] | null | null | null | #ifndef POTENTIAL3D_H
#define POTENTIAL3D_H
#include "Potential.hpp"
class Potential3D: public Potential{};
#endif
| 11.9 | 38 | 0.781513 | s0vereign |
37cede24bfbdc1e91225b35be3c11718492da60d | 1,747 | cpp | C++ | src/AttackFSM.cpp | mikaelmello/story-based-rpg | bc73c24ad0e41512c3e980ca3aad0fc5738af2f2 | [
"Zlib"
] | null | null | null | src/AttackFSM.cpp | mikaelmello/story-based-rpg | bc73c24ad0e41512c3e980ca3aad0fc5738af2f2 | [
"Zlib"
] | null | null | null | src/AttackFSM.cpp | mikaelmello/story-based-rpg | bc73c24ad0e41512c3e980ca3aad0fc5738af2f2 | [
"Zlib"
] | null | null | null | #include "AttackFSM.hpp"
#include <memory>
#include "Antagonist.hpp"
#include "Collider.hpp"
#include "Collision.hpp"
#include "Player.hpp"
#include "Sprite.hpp"
AttackFSM::AttackFSM(GameObject& object) : IFSM(object, ZERO_SPEED) {
auto ant_cpt = object.GetComponent(Types::AntagonistType);
if (!ant_cpt) {
throw std::runtime_error("sem ant em AttackFSM::AttackFSM");
}
ant = std::dynamic_pointer_cast<Antagonist>(ant_cpt);
}
AttackFSM::~AttackFSM() {}
void AttackFSM::OnStateEnter() {
auto sprite_cpt = object.GetComponent(Types::SpriteType);
if (!sprite_cpt) {
throw std::runtime_error("objeto nao possui cpt sprite em AttackFSM");
}
ant.lock()->AssetsManager(Helpers::Action::ATTACKING);
auto sprite = std::dynamic_pointer_cast<Sprite>(sprite_cpt);
execution_time = sprite->GetFrameCount() * sprite->GetFrameTime();
}
void AttackFSM::OnStateExecution(float dt) {
GameData::player_was_hit = IsColliding();
pop_requested = true;
}
void AttackFSM::OnStateExit() {}
void AttackFSM::Update(float dt) {
if (timer.Get() >= execution_time) {
OnStateExecution(dt);
}
timer.Update(dt);
pop_requested |= !IsColliding();
}
bool AttackFSM::IsColliding() {
auto a_col = object.GetComponent(ColliderType);
if (!a_col) {
throw std::runtime_error("ant sem collider em AttackFSM::IsColliding");
}
auto p_col = GameData::PlayerGameObject->GetComponent(ColliderType);
if (!p_col) {
throw std::runtime_error("player sem col em AttackFSM::IsColliding");
}
auto ant_col = std::dynamic_pointer_cast<Collider>(a_col);
auto player_col = std::dynamic_pointer_cast<Collider>(p_col);
Rect a_box = ant_col->box;
Rect p_box = ant_col->box;
return Collision::IsColliding(a_box, p_box);
} | 26.469697 | 75 | 0.717802 | mikaelmello |
37d60679c8399348d97a637379229cc175873ab0 | 447 | cc | C++ | Sliding_Window/1208.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | Sliding_Window/1208.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | Sliding_Window/1208.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | //https://leetcode.com/problems/get-equal-substrings-within-budget/discuss/392837/JavaC%2B%2BPython-Sliding-Window
class Solution {
public:
int equalSubstring(string s, string t, int maxCost) {
int len = s.size();
int i = 0;
for (int j=0; j<len; ++j){
if((maxCost -= abs(s[j]-t[j]))<0){
maxCost += abs(s[i]-t[i]);
++i;
}
}
return len-i;
}
};
| 26.294118 | 114 | 0.505593 | guohaoqiang |
37d88fcebe078f663ad2bdd2163a12602df8a7ae | 10,703 | cpp | C++ | main.cpp | KacperSynator/Process_Scheduler | bdb41fbf8f2fbe473e2aa8fcd34ef5f3fce04428 | [
"MIT"
] | null | null | null | main.cpp | KacperSynator/Process_Scheduler | bdb41fbf8f2fbe473e2aa8fcd34ef5f3fce04428 | [
"MIT"
] | null | null | null | main.cpp | KacperSynator/Process_Scheduler | bdb41fbf8f2fbe473e2aa8fcd34ef5f3fce04428 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
/* Program description:
* Program is simulating a process scheduler. Program executes with three arguments (arguments description below).
* Program works in step mode i.e. firstly it reads input from stdin if there is any, secondly it executes a given
* schedule method, lastly it prints result of scheduling to stdout. (linefeeder.cpp and repeater.cpp not used).
* Program ends if there is no input remaining and all CPUS are in sleep state.
*
* Input data format:
* t id prio exec_t
* t -> time
* id -> process id
* prio -> process priority
* exec_t -> process execution time
* Note: multiple processes might be given in one line. Last input line must be an "enter" ('\n')
*
* Output data format:
* t cpu1_state cpu2_state ...
* t -> time
* cpu_state -> id of executing process or -1 (sleeping)
* Note: number of columns is equal to the number of CPUS
*
* Arguments:
* arg1 -> schedule method (necessary)
* arg2 -> number of CPUS (optional, default 1)
* arg3 -> round robin slice time (optional, default 1)
*
* Implemented schedule methods (arg1):
* 0 -> First Come First Serve (FCFS)
* 1 -> Shortest Job First (SJF)
* 2 -> Shortest Remaining Time First (SRTF)
* 3 -> Round Robin (RR)
* 4 -> Priority with preemption same priorities scheduled using FCFS (lower the priority number higher the executing priority)
* 5 -> Priority with preemption same priorities scheduled using SRTF --"--
* 6 -> Priority without preemption same priorities scheduled using FCFS --"--
*/
/*! structure that contains all necessary process data */
struct proc_data{
int id; /*!< process id */
int priority; /*!< process priority */
unsigned int exec_time; /*!< process execution time */
unsigned int remaining_time; /*!< process remaining execution time */
/*! static function for comparing proc_data structures in term of execution time (same values not swapped) */
static bool compare_exec_time(proc_data pd1, proc_data pd2) {return (pd1.exec_time < pd2.exec_time);}
/*! static function for comparing proc_data structures in term of priority (same values not swapped) */
static bool compare_priority(proc_data pd1, proc_data pd2) {return (pd1.priority < pd2.priority);}
/*! static function for comparing proc_data structures in term of remaining execution time (same values not swapped) */
static bool compare_remaining_time(proc_data pd1, proc_data pd2) {return (pd1.remaining_time < pd2.remaining_time);}
};
/*! input operator >> overload for proc_data structure */
std::istream& operator >> (std::istream& is, proc_data& pd)
{
is >> pd.id >> pd.priority >> pd.exec_time ;
pd.remaining_time = pd.exec_time;
return is;
}
/*! puts scheduled processes on CPU/CPUS */
void update_cpus_state(std::vector<proc_data>& proc_list, std::vector<int>& cpus_state)
{
auto it_proc = proc_list.begin();
for(auto & cpu_state:cpus_state)
{
if(it_proc == proc_list.end())
{
cpu_state = -1;
}
else
{
cpu_state = it_proc->id;
++it_proc;
}
}
/* sort processes on CPUS from lower to higher, negative numbers pushed at the end (-1 -> CPU sleep) */
std::stable_sort(cpus_state.begin(), cpus_state.end(), [](int i, int j){return (i >= 0 && j >= 0) ? i < j : i > j;});
}
/*! First Come First Serve scheduling algorithm */
void fcfs(std::vector<proc_data>& proc_list, std::vector<int>& cpus_state)
{
/* processes are already sorted */
update_cpus_state(proc_list, cpus_state);
}
/*! Shortest Job First scheduling algorithm */
void sjf(std::vector<proc_data>& proc_list, std::vector<int>& cpus_state)
{
/* prevent preemption by moving iterator after executing processes */
auto proc_it = proc_list.begin();
for(auto cpu_state: cpus_state)
{
if(proc_it == proc_list.end() || cpu_state == -1) break;
for(auto proc: proc_list)
if(cpu_state == proc.id) proc_it++;
}
/* sort remaining processes in terms of execution time */
std::stable_sort (proc_it, proc_list.end(), proc_data::compare_exec_time);
update_cpus_state(proc_list, cpus_state);
}
/*! Shortest Remaining Time First scheduling algorithm */
void srtf(std::vector<proc_data>& proc_list, std::vector<int>& cpus_state)
{
/* sort processes in terms of execution time */
std::stable_sort (proc_list.begin(), proc_list.end(), proc_data::compare_remaining_time);
update_cpus_state(proc_list, cpus_state);
}
/*! Round Robin scheduling algorithm */
void rr(std::vector<proc_data>& proc_list, std::vector<int>& cpus_state, unsigned int rr_time)
{
for(auto cpu_state: cpus_state)
{
if(cpu_state == -1) break;
auto proc_it = proc_list.begin();
/* move iterator to executing process */
while(cpu_state != proc_it->id && proc_it != proc_list.end()) proc_it++;
if (proc_it == proc_list.end()) continue;
/* check if executing process needs to be pushed to the end of process list (if RR time slice has ended) */
unsigned int proc_executed_time = proc_it->exec_time - proc_it->remaining_time;
if( proc_executed_time > 0 && proc_executed_time % rr_time == 0)
{
/* push process to the end of process list */
proc_data pd = *proc_it;
proc_list.erase(proc_it);
proc_list.push_back(pd);
}
}
update_cpus_state(proc_list, cpus_state);
}
/*! Priority with preemption scheduling algorithm, same priorities are scheduled using FCFS algorithm */
void prio_fcfs(std::vector<proc_data>& proc_list, std::vector<int>& cpus_state)
{
/* sort processes in terms of priority, same priorities are already sorted */
std::stable_sort (proc_list.begin(), proc_list.end(), proc_data::compare_priority);
update_cpus_state(proc_list, cpus_state);
}
/*! Priority with preemption scheduling algorithm, same priorities are scheduled using SRTF algorithm */
void prio_srtf(std::vector<proc_data>& proc_list, std::vector<int>& cpus_state)
{
/* sort processes in terms of remaining execution time (same priority) */
std::stable_sort (proc_list.begin(), proc_list.end(), proc_data::compare_remaining_time);
/* sort processes in terms of priority */
std::stable_sort (proc_list.begin(), proc_list.end(), proc_data::compare_priority);
update_cpus_state(proc_list, cpus_state);
}
/*! Priority without preemption scheduling algorithm, same priorities are scheduled using FCFS algorithm */
void prio_fcfs_no_preemption(std::vector<proc_data>& proc_list, std::vector<int>& cpus_state)
{
/* prevent preemption by moving iterator after executing processes */
auto proc_it = proc_list.begin();
for(auto cpu_state: cpus_state)
{
if(proc_it == proc_list.end() || cpu_state == -1) break;
for(auto proc: proc_list)
if(cpu_state == proc.id) proc_it++;
}
/* sort processes in terms of priority, same priorities are already sorted */
std::stable_sort (proc_it, proc_list.end(), proc_data::compare_priority);
update_cpus_state(proc_list, cpus_state);
}
/*! checks if all CPUS are sleeping (==-1) */
bool all_cpus_sleeping(std::vector<int>& cpus_state)
{
if(std::any_of(cpus_state.begin(), cpus_state.end(), [](int i){return i != -1;}))
return false;
return true;
}
int main(int argc, char* argv[])
{
unsigned int method; // scheduling method (arg1)
unsigned int cpu_count = 1; // number of CPUS (arg2), default 1
unsigned int rr_time = 1; // Round Robin slice time (arg3), default 1
// read first argument (schedule method)
if(argc < 2) throw std::invalid_argument("arg1 not given (schedule method)");
else method = static_cast<unsigned int>(std::strtol(argv[1], nullptr, 0));
// check for second argument (CPU count)
if(argc >= 3) cpu_count = static_cast<unsigned int>(std::strtol(argv[2], nullptr, 0));
// check for third argument (round robin time step)
if(argc >= 4) rr_time = static_cast<unsigned int>(std::strtol(argv[3], nullptr, 0));
std::vector<proc_data> proc_list; // processes execution list
std::vector<int> cpus_state(cpu_count); // CPU states list
unsigned int time = 0; // simulation time
bool read = true; // flag for reading input
while(read || !all_cpus_sleeping(cpus_state)) // run until there is no input and all CPUS are sleeping
{
// read input
if(read)
{
std::string line;
std::getline(std::cin, line);
std::istringstream ss(line);
if (ss.rdbuf()->in_avail() != 0)
{
ss >> time;
while (ss.rdbuf()->in_avail() / 2 >= 3)
{
proc_data pd{};
ss >> pd;
proc_list.push_back(pd);
}
}
else read = false;
}
// run given method
switch (method)
{
case 0: // FCFS
{
fcfs(proc_list, cpus_state);
break;
}
case 1: // SJF
{
sjf(proc_list, cpus_state);
break;
}
case 2: // SRTF
{
srtf(proc_list, cpus_state);
break;
}
case 3: // RR
{
rr(proc_list, cpus_state, rr_time);
break;
}
case 4: // Priority_FCFS
{
prio_fcfs(proc_list, cpus_state);
break;
}
case 5: // Priority_SRTF
{
prio_srtf(proc_list, cpus_state);
break;
}
case 6: // Priority without preemption (FCFS)
{
prio_fcfs_no_preemption(proc_list, cpus_state);
break;
}
default: // Wrong method, raises error
throw std::invalid_argument("invalid schedule method");
}
// update proc_list
for(auto id: cpus_state)
{
auto it_proc = proc_list.begin();
if(id == -1) continue;
while(it_proc->id != id) ++it_proc;
// pop an executed process
if(--(it_proc->remaining_time) == 0)
proc_list.erase(it_proc);
}
// print output
std::cout << time++;
for(auto & cpu_state: cpus_state)
std::cout << " " << cpu_state;
std::cout << "\n";
}
return 0;
}
| 38.362007 | 127 | 0.622442 | KacperSynator |
37e270fc5a91c1ef49e228ad39aba802b4cee2f1 | 1,696 | cpp | C++ | design_patterns/structural_bridge/bridge_dynamic.cpp | anstellaire/photon-i3-colors | 3f3e44a5b9bdfbdc35e00bd2116acb7211ef6f54 | [
"MIT"
] | 1 | 2021-06-23T09:08:55.000Z | 2021-06-23T09:08:55.000Z | design_patterns/structural_bridge/bridge_dynamic.cpp | anstellaire/sweets | 3f3e44a5b9bdfbdc35e00bd2116acb7211ef6f54 | [
"MIT"
] | null | null | null | design_patterns/structural_bridge/bridge_dynamic.cpp | anstellaire/sweets | 3f3e44a5b9bdfbdc35e00bd2116acb7211ef6f54 | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
// -----------------------------------------------------------------------------
// PATTERN (dynamic polymorphism)
// -----------------------------------------------------------------------------
struct weapon_slot {
virtual char const* use() = 0;
virtual ~weapon_slot() {}
};
struct missle_weapon : weapon_slot {
char const* use() { return "missle launch"; }
};
struct dummy_weapon : weapon_slot {
char const* use() { return "click-click"; }
};
struct spaceship {
std::unique_ptr<weapon_slot> slot;
spaceship(std::unique_ptr<weapon_slot> s) : slot(std::move(s)) {}
void set_slot(std::unique_ptr<weapon_slot> s) { slot = std::move(s); }
virtual void attack() = 0;
virtual ~spaceship() {}
};
struct destroyer : spaceship {
destroyer(std::unique_ptr<weapon_slot> slot) : spaceship(std::move(slot)) {}
void attack() {
std::cout << "Destroyer attacks: " << slot->use() << std::endl;
}
};
struct cruiser : spaceship {
cruiser(std::unique_ptr<weapon_slot> slot) : spaceship(std::move(slot)) {}
void attack() {
std::cout << "Cruiser attacks: " << slot->use() << std::endl;
}
};
// -----------------------------------------------------------------------------
// USAGE
// -----------------------------------------------------------------------------
void unit_attack(spaceship& ship) {
ship.attack();
}
int main() {
std::unique_ptr<spaceship> ship{new cruiser{
std::unique_ptr<weapon_slot>{new missle_weapon{}}
}};
unit_attack(*ship);
ship->set_slot(
std::unique_ptr<weapon_slot>{new dummy_weapon{}}
);
unit_attack(*ship);
}
| 24.941176 | 80 | 0.504127 | anstellaire |
37e75c8ec953bc5ccea781d3ba6900291606e451 | 3,832 | cpp | C++ | src/treemodel.cpp | RazrFalcon/ttf-explorer | ff6eab3616824a54c466ab28da43464a8a2540f3 | [
"MIT"
] | 18 | 2020-03-12T16:03:04.000Z | 2022-01-22T16:07:32.000Z | src/treemodel.cpp | RazrFalcon/ttf-explorer | ff6eab3616824a54c466ab28da43464a8a2540f3 | [
"MIT"
] | null | null | null | src/treemodel.cpp | RazrFalcon/ttf-explorer | ff6eab3616824a54c466ab28da43464a8a2540f3 | [
"MIT"
] | null | null | null | #include <QFont>
#include "utils.h"
#include "treemodel.h"
TreeItem::TreeItem(TreeItem *parent)
: m_parent(parent)
{
}
TreeItem::~TreeItem()
{
qDeleteAll(m_children);
}
TreeItem* TreeItem::child(int number)
{
return m_children.value(number);
}
int TreeItem::childCount() const
{
return m_children.count();
}
int TreeItem::childIndex() const
{
if (m_parent) {
return m_parent->m_children.indexOf(const_cast<TreeItem*>(this));
}
return 0;
}
void TreeItem::reserveChildren(const qsizetype n)
{
m_children.reserve(n);
}
QVariant TreeItem::data(int column) const
{
switch (column) {
case Column::Title: return title;
case Column::Value: return value;
case Column::Type: return type;
case Column::Size: return size;
default: return QVariant();
}
}
void TreeItem::addChild(TreeItem *item)
{
m_children.append(item);
}
TreeItem* TreeItem::parent()
{
return m_parent;
}
TreeModel::TreeModel(QObject *parent)
: QAbstractItemModel(parent)
, m_rootItem(new TreeItem(nullptr))
{
}
TreeModel::~TreeModel()
{
delete m_rootItem;
}
QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const
{
if (parent.isValid() && parent.column() != 0) {
return QModelIndex();
}
const auto parentItem = itemByIndex(parent);
const auto childItem = parentItem->child(row);
if (childItem) {
return createIndex(row, column, childItem);
} else {
return QModelIndex();
}
}
QModelIndex TreeModel::parent(const QModelIndex &index) const
{
if (!index.isValid()) {
return QModelIndex();
}
const auto childItem = itemByIndex(index);
const auto parentItem = childItem->parent();
if (parentItem == m_rootItem) {
return QModelIndex();
}
return createIndex(parentItem->childIndex(), 0, parentItem);
}
int TreeModel::rowCount(const QModelIndex &parent) const
{
if (parent.column() > 0) {
return 0;
}
TreeItem *parentItem = nullptr;
if (!parent.isValid()) {
parentItem = m_rootItem;
} else {
parentItem = itemByIndex(parent);
}
return parentItem->childCount();
}
int TreeModel::columnCount(const QModelIndex &/* parent */) const
{
return (int)Column::LastColumn;
}
Qt::ItemFlags TreeModel::flags(const QModelIndex &/*index*/) const
{
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
QVariant TreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
const auto item = itemByIndex(index);
if (role == Qt::FontRole && index.column() >= Column::Value) {
return QVariant(QFont(Utils::monospacedFont()));
}
if (role == Qt::ToolTipRole && index.column() == Column::Value) {
return item->data(index.column());
}
if (role == Qt::TextAlignmentRole && index.column() == Column::Size) {
return Qt::AlignRight;
}
if (role != Qt::DisplayRole) {
return QVariant();
}
return item->data(index.column());
}
QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch (section) {
case Column::Title: return QLatin1String("Title");
case Column::Value: return QLatin1String("Value");
case Column::Type: return QLatin1String("Type");
case Column::Size: return QLatin1String("Size");
}
}
return QVariant();
}
TreeItem* TreeModel::itemByIndex(const QModelIndex &index) const
{
if (index.isValid()) {
TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
if (item) {
return item;
}
}
return m_rootItem;
}
| 21.054945 | 88 | 0.629958 | RazrFalcon |
37e95a08ec1c6d85092eba530c33bf32f30ee6b3 | 1,737 | hpp | C++ | cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/util.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/util.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/util.hpp | yizhang-cae/torsten | dc82080ca032325040844cbabe81c9a2b5e046f9 | [
"BSD-3-Clause"
] | null | null | null | #ifndef TEST_UNIT_MATH_REV_SCAL_FUN_UTIL_HPP
#define TEST_UNIT_MATH_REV_SCAL_FUN_UTIL_HPP
#include <stan/math/rev/scal.hpp>
#include <test/unit/math/rev/scal/util.hpp>
typedef stan::math::var AVAR;
typedef std::vector<AVAR> AVEC;
typedef std::vector<double> VEC;
AVEC createAVEC(AVAR x) {
AVEC v;
v.push_back(x);
return v;
}
AVEC createAVEC(AVAR x1, AVAR x2) {
AVEC v;
v.push_back(x1);
v.push_back(x2);
return v;
}
AVEC createAVEC(AVAR x1, AVAR x2, AVAR x3) {
AVEC v;
v.push_back(x1);
v.push_back(x2);
v.push_back(x3);
return v;
}
AVEC createAVEC(AVAR x1, AVAR x2, AVAR x3, AVAR x4) {
AVEC v = createAVEC(x1,x2,x3);
v.push_back(x4);
return v;
}
AVEC createAVEC(AVAR x1, AVAR x2, AVAR x3, AVAR x4, AVAR x5) {
AVEC v = createAVEC(x1,x2,x3,x4);
v.push_back(x5);
return v;
}
AVEC createAVEC(AVAR x1, AVAR x2, AVAR x3, AVAR x4, AVAR x5, AVAR x6) {
AVEC v = createAVEC(x1,x2,x3,x4,x5);
v.push_back(x6);
return v;
}
AVEC createAVEC(AVAR x1, AVAR x2, AVAR x3, AVAR x4, AVAR x5, AVAR x6, AVAR x7) {
AVEC v = createAVEC(x1,x2,x3,x4,x5,x6);
v.push_back(x7);
return v;
}
AVEC createAVEC(AVAR x1, AVAR x2, AVAR x3, AVAR x4, AVAR x5, AVAR x6, AVAR x7, AVAR x8) {
AVEC v = createAVEC(x1,x2,x3,x4,x5,x6,x7);
v.push_back(x8);
return v;
}
VEC cgrad(AVAR f, AVAR x1) {
AVEC x = createAVEC(x1);
VEC g;
f.grad(x,g);
return g;
}
VEC cgrad(AVAR f, AVAR x1, AVAR x2) {
AVEC x = createAVEC(x1,x2);
VEC g;
f.grad(x,g);
return g;
}
VEC cgrad(AVAR f, AVAR x1, AVAR x2, AVAR x3) {
AVEC x = createAVEC(x1,x2,x3);
VEC g;
f.grad(x,g);
return g;
}
VEC cgrad(AVAR f, AVAR x1, AVAR x2, AVAR x3, AVAR x4) {
AVEC x = createAVEC(x1,x2,x3,x4);
VEC g;
f.grad(x,g);
return g;
}
#endif
| 20.927711 | 89 | 0.654001 | yizhang-cae |
37fa5dbcab513c7755df2b2137f41afd6ad207a0 | 1,331 | cpp | C++ | test/entity_tests.cpp | ShelbyZ/BattleSystem | 475b6e1024267d429c1e0946b7e9ddd05316fb49 | [
"MIT"
] | null | null | null | test/entity_tests.cpp | ShelbyZ/BattleSystem | 475b6e1024267d429c1e0946b7e9ddd05316fb49 | [
"MIT"
] | 2 | 2018-05-29T06:31:12.000Z | 2018-06-01T05:44:44.000Z | test/entity_tests.cpp | ShelbyZ/BattleSystem | 475b6e1024267d429c1e0946b7e9ddd05316fb49 | [
"MIT"
] | null | null | null | #include <string>
#include "gtest/gtest.h"
#include "../battle_system/entity.h"
TEST(Reference, Constructor)
{
std::string name = "shelby";
auto entity = CEntity(name);
ASSERT_EQ("shelby", entity.getName());
ASSERT_EQ("", name);
}
TEST(Reference_EmptyName, Constructor)
{
ASSERT_THROW({
std::string name = "";
auto entity = CEntity(name);
}, std::logic_error);
}
TEST(AutoReference, Constructor)
{
auto name = "shelby";
auto entity = CEntity(name);
ASSERT_EQ(name, entity.getName());
}
TEST(AutoReference_EmptyName, Constructor)
{
ASSERT_THROW({
auto name = "";
auto entity = CEntity(name);
}, std::logic_error);
}
TEST(RValueReference, Constructor)
{
auto entity = CEntity("shelby");
ASSERT_EQ("shelby", entity.getName());
}
TEST(RValueReference_EmptyName, Constructor)
{
ASSERT_THROW({
auto entity = CEntity("");
}, std::logic_error);
}
TEST(LhsEqualsRhs, operatorEquals)
{
auto name = "shelby";
auto entity = CEntity(name);
auto result = (entity == entity);
ASSERT_EQ(true, result);
}
TEST(LhsNotEqualsRhs, operatorEquals)
{
auto name = "shelby";
auto entity = CEntity(name);
auto entity2 = CEntity("NotShelby");
auto result = (entity == entity2);
ASSERT_EQ(false, result);
} | 18.232877 | 44 | 0.636364 | ShelbyZ |
37fda60166636d21210077343121767f5fb066be | 528 | hpp | C++ | include/snd/ramp_gen.hpp | colugomusic/snd | 3ecb87581870b14e62893610d027516aea48ff3c | [
"MIT"
] | 18 | 2020-08-26T11:33:50.000Z | 2021-04-13T15:57:28.000Z | include/snd/ramp_gen.hpp | colugomusic/snd | 3ecb87581870b14e62893610d027516aea48ff3c | [
"MIT"
] | 1 | 2021-05-16T17:11:57.000Z | 2021-05-16T17:25:17.000Z | include/snd/ramp_gen.hpp | colugomusic/snd | 3ecb87581870b14e62893610d027516aea48ff3c | [
"MIT"
] | null | null | null | #pragma once
#pragma warning(push, 0)
#include <DSP/MLDSPOps.h>
#pragma warning(pop)
namespace ml {
class RampGen
{
public:
RampGen(int p = kFloatsPerDSPVector) : mCounter(p), mPeriod(p) {}
~RampGen() {}
inline void setPeriod(int p) { mPeriod = p; }
inline DSPVectorInt operator()()
{
DSPVectorInt vy;
for (int i = 0; i < kFloatsPerDSPVector; ++i)
{
float fy = 0;
if (++mCounter >= mPeriod)
{
mCounter = 0;
fy = 1;
}
vy[i] = mCounter;
}
return vy;
}
int mCounter;
int mPeriod;
};
} | 14.666667 | 66 | 0.611742 | colugomusic |
5301078cd20e7b2f699cde88f558226e8d6f5047 | 1,544 | cpp | C++ | Codeforces/1240C/dp_tree.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2018-02-14T01:59:31.000Z | 2018-03-28T03:30:45.000Z | Codeforces/1240C/dp_tree.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | Codeforces/1240C/dp_tree.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <bits/stdc++.h>
using namespace std;
#define SIZE 500010
class Edge {
public:
int to, next, len;
};
Edge edges[SIZE << 1];
int head[SIZE], edgesPt;
int vertexNum, lim; long long int dp[SIZE][2];
void addEdge(int from, int to, int len) {
edges[edgesPt] = {to, head[from], len};
head[from] = edgesPt++;
}
void dfs(int cntPt, int fatherPt) {
dp[cntPt][0] = 0; dp[cntPt][1] = 0;
vector<long long int> vec;
for (int i = head[cntPt]; i != -1; i = edges[i].next) {
int nextPt = edges[i].to;
if (nextPt == fatherPt)
continue;
dfs(nextPt, cntPt);
dp[cntPt][0] += dp[nextPt][0]; dp[cntPt][1] += dp[nextPt][0];
vec.push_back(-dp[nextPt][0] + dp[nextPt][1] + edges[i].len);
}
sort(vec.begin(), vec.end(), greater<long long int>());
int siz = vec.size();
for (int i = 0; i < min(siz, lim - 1) && vec[i] > 0; i++)
dp[cntPt][0] += vec[i], dp[cntPt][1] += vec[i];
for (int i = lim - 1; i < min(siz, lim) && vec[i] > 0; i++)
dp[cntPt][0] += vec[i];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int caseNum; cin >> caseNum;
while (caseNum--) {
cin >> vertexNum >> lim;
fill(head + 0, head + vertexNum, -1); edgesPt = 0;
for (int i = 1; i < vertexNum; i++) {
int from, to, len; cin >> from >> to >> len;
from--; to--; addEdge(from, to, len); addEdge(to, from, len);
}
dfs(0, -1); cout << dp[0][0] << '\n';
}
return 0;
} | 27.087719 | 73 | 0.513601 | codgician |
530417011596662d07fd809484395dd78444c354 | 1,006 | hpp | C++ | ModSource/breakingpoint_infected/CfgBody.hpp | nrailuj/breakingpointmod | e102e106b849ca78deb3cb299f3ae18c91c3bfe9 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 70 | 2017-06-23T21:25:05.000Z | 2022-03-27T02:39:33.000Z | ModSource/breakingpoint_infected/CfgBody.hpp | nrailuj/breakingpointmod | e102e106b849ca78deb3cb299f3ae18c91c3bfe9 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 84 | 2017-08-26T22:06:28.000Z | 2021-09-09T15:32:56.000Z | ModSource/breakingpoint_infected/CfgBody.hpp | nrailuj/breakingpointmod | e102e106b849ca78deb3cb299f3ae18c91c3bfe9 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 71 | 2017-06-24T01:10:42.000Z | 2022-03-18T23:02:00.000Z | /*
Breaking Point Mod for Arma 3
Released under Arma Public Share Like Licence (APL-SA)
https://www.bistudio.com/community/licenses/arma-public-license-share-alike
Alderon Games Pty Ltd
*/
class CfgBody {
class head_hit {
memoryPoint = "pilot";
variation = 0.08;
};
class body {
memoryPoint = "aimPoint";
variation = 0.15;
};
class Spine2 : body {};
class LeftArm {
memoryPoint = "lelbow";
variation = 0.1;
};
class RightArm {
memoryPoint = "relbow";
variation = 0.04;
};
class LeftForeArm {
memoryPoint = "lwrist";
variation = 0.04;
};
class RightForeArm {
memoryPoint = "rwrist";
variation = 0.04;
};
class LeftHand {
memoryPoint = "LeftHandMiddle1";
variation = 0.04;
};
class RightHand {
memoryPoint = "RightHandMiddle1";
variation = 0.04;
};
class legs {
memoryPoint = "pelvis";
variation = 0.15;
};
class LeftLeg : legs {};
class LeftUpLeg : legs {};
class RightLeg : legs {};
class RightUpLeg : legs {};
};
| 15.242424 | 76 | 0.638171 | nrailuj |
5305301f280d86529dc2ead504eed0e339c3b6cd | 16,353 | hpp | C++ | engine/ItemType.hpp | rigertd/LegacyMUD | cf351cca466158f0682f6c877b88d5c2eb59e240 | [
"BSD-3-Clause"
] | 1 | 2021-04-24T06:01:57.000Z | 2021-04-24T06:01:57.000Z | engine/ItemType.hpp | rigertd/LegacyMUD | cf351cca466158f0682f6c877b88d5c2eb59e240 | [
"BSD-3-Clause"
] | null | null | null | engine/ItemType.hpp | rigertd/LegacyMUD | cf351cca466158f0682f6c877b88d5c2eb59e240 | [
"BSD-3-Clause"
] | null | null | null | /*********************************************************************//**
* \author Rachel Weissman-Hohler
* \created 02/01/2017
* \modified 03/08/2017
* \course CS467, Winter 2017
* \file ItemType.hpp
*
* \details Header file for ItemType class. Defines the members and
* functions that apply to all item types. Item types
* define in-game item types that an item may use as its
* type. Item types allow the world builder to define a type
* once and then create many items of that type.
************************************************************************/
#ifndef ITEM_TYPE_HPP
#define ITEM_TYPE_HPP
#include <string>
#include <atomic>
#include <mutex>
#include <vector>
#include "InteractiveNoun.hpp"
#include "EquipmentSlot.hpp"
#include "ItemRarity.hpp"
#include "DataType.hpp"
#include "ObjectType.hpp"
#include "DamageType.hpp"
#include "AreaSize.hpp"
#include "EffectType.hpp"
namespace legacymud { namespace engine {
/*!
* \details This class defines in-game item types that an item may use as
* its type. Item types allow the world builder to define a type
* once and then create many items of that type.
*/
class ItemType: public InteractiveNoun {
public:
ItemType();
ItemType(int weight, ItemRarity rarity, std::string description, std::string name, int cost, EquipmentSlot slotType);
ItemType(int weight, ItemRarity rarity, std::string description, std::string name, int cost, EquipmentSlot slotType, int anID);
/*!
* \brief Gets the weight of this item type.
*
* \return Returns an int with the weight of this item type.
*/
int getWeight() const;
/*!
* \brief Gets the rarity of this item type.
*
* \return Returns an ItemRarity with the rarity of this item type.
*/
ItemRarity getRarity() const;
/*!
* \brief Gets the description of this item type.
*
* \return Returns a std::string with the description of this item type.
*/
std::string getDescription() const;
/*!
* \brief Gets the name of this item type.
*
* \return Returns a std::string with the name of this item type.
*/
std::string getName() const;
/*!
* \brief Gets the cost of this item type.
*
* \return Returns an int with the cost of this item type.
*/
int getCost() const;
/*!
* \brief Gets the slot type of this item type.
*
* \return Returns an EquipmentSlot with the slot type of this item type.
*/
EquipmentSlot getSlotType() const;
/*!
* \brief Sets the weight of this item type.
*
* \param[in] weight Specifies the weight of this item type.
*
* \return Returns a bool indicating whether or not setting the
* weight was successful.
*/
bool setWeight(int weight);
/*!
* \brief Sets the rarity of this item type.
*
* \param[in] rarity Specifies the rarity of this item type.
*
* \return Returns a bool indicating whether or not setting the
* rarity was successful.
*/
bool setRarity(ItemRarity rarity);
/*!
* \brief Sets the description of this item type.
*
* \param[in] description Specifies the description of this item type.
*
* \return Returns a bool indicating whether or not setting the
* description was successful.
*/
bool setDescription(std::string description);
/*!
* \brief Sets the name of this item type.
*
* \param[in] name Specifies the name of this item type.
*
* \return Returns a bool indicating whether or not setting the
* name was successful.
*/
bool setName(std::string name);
/*!
* \brief Sets the cost of this item type.
*
* \param[in] cost Specifies the cost of this item type.
*
* \return Returns a bool indicating whether or not setting the
* cost was successful.
*/
bool setCost(int cost);
/*!
* \brief Sets the slot type of this item type.
*
* \param[in] slotType Specifies the slot type of this item type.
*
* \return Returns a bool indicating whether or not setting the
* slot type was successful.
*/
bool setSlotType(EquipmentSlot slotType);
/*!
* \brief Gets the armor bonus if this item type has an armor bonus.
*
* \return Returns an int with the armor bonus for this item type.
*/
virtual int getArmorBonus() const;
/*!
* \brief Gets the damage type this item type is resistant to.
*
* \return Returns a DamageType with the damage type this item type is
* resistant to.
*/
virtual DamageType getResistantTo() const;
/*!
* \brief Gets the damage if this item type has a damage.
*
* \return Returns an int with the damage for this item type.
*/
virtual int getDamage() const;
/*!
* \brief Gets the damage type if this item type has a damage type.
*
* \return Returns a DamageType with the damage type for this item type.
*/
virtual DamageType getDamageType() const;
/*!
* \brief Gets the range if this item type has a range.
*
* \return Returns an AreaSize with the range for this item type.
*/
virtual AreaSize getRange() const;
/*!
* \brief Gets the crit multiplier if this item type has an crit multiplier.
*
* \return Returns an int with the crit multiplier for this item type.
*/
virtual int getCritMultiplier() const;
/*!
* \brief Sets the damage if this item type has a damage.
*
* \param[in] damage Specifies the damage.
*
* \return Returns a bool indicating whether or not setting the damage was
* sucessful.
*/
virtual bool setDamage(int damage);
/*!
* \brief Sets the damage type if this item type has a damage type.
*
* \param[in] type Specifies the damage type.
*
* \return Returns a bool indicating whether or not setting the damage type was
* sucessful.
*/
virtual bool setDamageType(DamageType type);
/*!
* \brief Sets the range if this item type has a range.
*
* \param[in] range Specifies the range.
*
* \return Returns a bool indicating whether or not setting the range was
* sucessful.
*/
virtual bool setRange(AreaSize range);
/*!
* \brief Sets the crit multiplier if this item type has a crit multiplier.
*
* \param[in] multiplier Specifies the crit multiplier.
*
* \return Returns a bool indicating whether or not setting the crit multiplier
* was sucessful.
*/
virtual bool setCritMultiplier(int multiplier);
/*!
* \brief Sets the armor bonus for this item type, if it has an armor bonus.
*
* \param[in] bonus Specifes the armor bonus for this item type.
*
* \return Returns a bool indicating whether or not setting the
* armor bonus was successful.
*/
virtual bool setArmorBonus(int bonus);
/*!
* \brief Sets the damage type that this item type is resistant to.
*
* \param[in] resistance Specifies the damage type this item type
* is resistant to.
*
* \return Returns a bool indicating whether or not setting the
* resistance was successful.
*/
virtual bool setResistantTo(DamageType resistance);
/*!
* \brief Gets the object type.
*
* \return Returns an ObjectType indicating the actual class the object
* belongs to.
*/
virtual ObjectType getObjectType() const;
/*!
* \brief Serializes this object for writing to file.
*
* \return Returns a std::string with the serialized data.
*/
virtual std::string serialize();
/*!
* \brief Deserializes and creates an object of this type from the
* specified string of serialized data.
*
* \param[in] string Holds the data to be deserialized.
*
* \return Returns an InteractiveNoun* with the newly created object.
*/
static ItemType* deserialize(std::string);
/*!
* \brief Gets the response of this object to the command move.
*
* \param[in] aPlayer Specifies the player that is moving the object.
* \param[out] effects Specifies the effects of the action.
*
* \note May cause an effect on the player.
*
* \return Returns a std::string with the response to the command
* move.
*/
virtual std::string move(Player *aPlayer, std::vector<EffectType> *effects);
/*!
* \brief Gets the response of this object to the command read.
*
* \param[in] aPlayer Specifies the player that is reading the object.
* \param[out] effects Specifies the effects of the action.
*
* \note May cause an effect on the player.
*
* \return Returns a std::string with the response to the command
* read.
*/
virtual std::string read(Player *aPlayer, std::vector<EffectType> *effects);
/*!
* \brief Gets the response of this object to the command break.
*
* \param[in] aPlayer Specifies the player that is breaking the object.
* \param[out] effects Specifies the effects of the action.
*
* \note May cause an effect on the player.
*
* \return Returns a std::string with the response to the command
* break.
*/
virtual std::string breakIt(Player *aPlayer, std::vector<EffectType> *effects);
/*!
* \brief Gets the response of this object to the command climb.
*
* \param[in] aPlayer Specifies the player that is climbing the object.
* \param[out] effects Specifies the effects of the action.
*
* \note May cause an effect on the player.
*
* \return Returns a std::string with the response to the command
* climb.
*/
virtual std::string climb(Player *aPlayer, std::vector<EffectType> *effects);
/*!
* \brief Gets the response of this object to the command turn.
*
* \param[in] aPlayer Specifies the player that is turning the object.
* \param[out] effects Specifies the effects of the action.
*
* \note May cause an effect on the player.
*
* \return Returns a std::string with the response to the command
* turn.
*/
virtual std::string turn(Player *aPlayer, std::vector<EffectType> *effects);
/*!
* \brief Gets the response of this object to the command push.
*
* \param[in] aPlayer Specifies the player that is pushing the object.
* \param[out] effects Specifies the effects of the action.
*
* \note May cause an effect on the player.
*
* \return Returns a std::string with the response to the command
* push.
*/
virtual std::string push(Player *aPlayer, std::vector<EffectType> *effects);
/*!
* \brief Gets the response of this object to the command pull.
*
* \param[in] aPlayer Specifies the player that is pulling the object.
* \param[out] effects Specifies the effects of the action.
*
* \note May cause an effect on the player.
*
* \return Returns a std::string with the response to the command
* pull.
*/
virtual std::string pull(Player *aPlayer, std::vector<EffectType> *effects);
/*!
* \brief Gets the response of this object to the command eat.
*
* \param[in] aPlayer Specifies the player that is eating the object.
* \param[out] effects Specifies the effects of the action.
*
* \note May cause an effect on the player.
*
* \return Returns a std::string with the response to the command
* eat.
*/
virtual std::string eat(Player *aPlayer, std::vector<EffectType> *effects);
/*!
* \brief Gets the response of this object to the command drink.
*
* \param[in] aPlayer Specifies the player that is drinking the object.
* \param[out] effects Specifies the effects of the action.
*
* \note May cause an effect on the player.
*
* \return Returns a std::string with the response to the command
* drink.
*/
virtual std::string drink(Player *aPlayer, std::vector<EffectType> *effects);
/*!
* \brief Creates a copy of this object.
*
* This function creates a new object with the same attributes as this
* object and returns a pointer to the new object.
*
* \return Returns a pointer to the newly created object or nullptr if
* the copy was unsuccessful.
*/
virtual InteractiveNoun* copy();
/*!
* \brief Edits an attribute of this object.
*
* This function edits the specified attribute of this object. It asks
* the user for the new value and then sets it to that.
*
* \param[in] aPlayer Specifies the player that is doing the editing.
* \param[in] attribute Specifies the attribute to edit.
*
* \return Returns bool indicating whether or not editing the attribute
* was successful.
*/
//virtual bool editAttribute(Player *aPlayer, std::string attribute);
/*!
* \brief Edits this object.
*
* This function edits this object. It interacts with the user to determine
* which attributes to update and what the new values should be and then
* makes those changes.
*
* \param[in] aPlayer Specifies the player that is doing the editing.
*
* \return Returns bool indicating whether or not editing this object
* was successful.
*/
virtual bool editWizard(Player *aPlayer);
/*!
* \brief Gets the attribute signature of the class.
*
* This function returns a map of string to DataType with the
* attributes required by the Action class to instantiate a new
* action.
*
* \return Returns a map of std::string to DataType indicating
* the required attributes.
*/
static std::map<std::string, DataType> getAttributeSignature();
private:
std::atomic<int> weight;
std::atomic<ItemRarity> rarity;
std::string description;
mutable std::mutex descriptionMutex;
std::string name;
mutable std::mutex nameMutex;
std::atomic<int> cost;
std::atomic<EquipmentSlot> slotType;
};
}}
#endif | 35.940659 | 135 | 0.554333 | rigertd |
530c162bdcea1cd5099808ad4ecffd8bc904549b | 9,463 | hpp | C++ | kv/complex.hpp | soonho-tri/kv | 4963be6560d8600cdc9ff22d004b2b965ae7b1df | [
"MIT"
] | 67 | 2017-01-04T15:30:54.000Z | 2022-03-31T05:45:02.000Z | src/interval/kv/complex.hpp | takafumihoriuchi/HyLaGI | 26b9f32a84611ee62d9cbbd903773d224088c959 | [
"BSL-1.0"
] | 4 | 2017-02-10T02:59:45.000Z | 2019-10-10T14:17:08.000Z | src/interval/kv/complex.hpp | takafumihoriuchi/HyLaGI | 26b9f32a84611ee62d9cbbd903773d224088c959 | [
"BSL-1.0"
] | 5 | 2021-09-29T02:27:46.000Z | 2022-03-31T05:45:04.000Z | /*
* Copyright (c) 2013-2016 Masahide Kashiwagi ([email protected])
*/
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <iostream>
#include <cmath>
#include <kv/convert.hpp>
namespace kv {
template <class T> class complex;
template <class C, class T> struct convertible<C, complex<T> > {
static const bool value = convertible<C, T>::value || boost::is_same<C, complex<T> >::value;
};
template <class C, class T> struct acceptable_n<C, complex<T> > {
static const bool value = convertible<C, T>::value;
};
template <class T> class complex {
T re;
T im;
public:
typedef T base_type;
complex() {
re = 0.;
im = 0.;
}
template <class C> explicit complex(const C& x, typename boost::enable_if_c< acceptable_n<C, complex>::value >::type* =0) {
re = x;
im = 0.;
}
template <class C> explicit complex(const complex<C>& x, typename boost::enable_if_c< acceptable_n<C, complex>::value >::type* =0) {
re = x.real();
im = x.imag();
}
template <class C1, class C2> complex(const C1& x, const C2& y, typename boost::enable_if_c< acceptable_n<C1, complex>::value && acceptable_n<C2, complex>::value >::type* =0) {
re = x;
im = y;
}
template <class C> typename boost::enable_if_c< acceptable_n<C, complex>::value, complex& >::type operator=(const C& x) {
re = x;
im = 0.;
return *this;
}
template <class C> typename boost::enable_if_c< acceptable_n<C, complex>::value, complex& >::type operator=(const complex<C>& x) {
re = x.real();
im = x.imag();
return *this;
}
friend complex operator+(const complex& x, const complex& y) {
complex r;
r.re = x.re + y.re;
r.im = x.im + y.im;
return r;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex >::type operator+(const complex& x, const C& y) {
complex r;
r.re = x.re + y;
r.im = x.im;
return r;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex >::type operator+(const C& x, const complex& y) {
complex r;
r.re = x + y.re;
r.im = y.im;
return r;
}
friend complex& operator+=(complex& x, const complex& y) {
x = x + y;
return x;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex& >::type operator+=(complex& x, const C& y) {
x.re += y;
return x;
}
friend complex operator-(const complex& x, const complex& y) {
complex r;
r.re = x.re - y.re;
r.im = x.im - y.im;
return r;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex >::type operator-(const complex& x, const C& y) {
complex r;
r.re = x.re - y;
r.im = x.im;
return r;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex >::type operator-(const C& x, const complex& y) {
complex r;
r.re = x - y.re;
r.im = - y.im;
return r;
}
friend complex& operator-=(complex& x, const complex& y) {
x = x - y;
return x;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex& >::type operator-=(complex& x, const C& y) {
x.re -= y;
return x;
}
friend complex operator-(const complex& x) {
complex r;
r.re = - x.re;
r.im = - x.im;
return r;
}
friend complex operator*(const complex& x, const complex& y) {
complex r;
r.re = x.re * y.re - x.im * y.im;
r.im = x.re * y.im + x.im * y.re;
return r;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex >::type operator*(const complex& x, const C& y) {
complex r;
r.re = x.re * y;
r.im = x.im * y;
return r;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex >::type operator*(const C& x, const complex& y) {
complex r;
r.re = x * y.re;
r.im = x * y.im;
return r;
}
friend complex& operator*=(complex& x, const complex& y) {
x = x * y;
return x;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex& >::type operator*=(complex& x, const C& y) {
x.re *= y;
x.im *= y;
return x;
}
friend complex operator/(const complex& x, const complex& y) {
complex r;
T tmp, tmp2;
tmp = y.re * y.re + y.im * y.im;
r.re = (y.re * x.re + y.im * x.im) / tmp;
r.im = (y.re * x.im - x.re * y.im) / tmp;
#if 0
using std::abs;
if (abs(y.re) > abs(y.im)) {
tmp2 = y.im / y.re;
tmp = y.re + y.im * tmp2;
r.re = (x.re + tmp2 * x.im) / tmp;
r.im = (x.im - x.re * tmp2) / tmp;
} else {
tmp2 = y.re / y.im;
tmp = y.re * tmp2 + y.im;
r.re = (tmp2 * x.re + x.im) / tmp;
r.im = (tmp2 * x.im - x.re) / tmp;
}
#endif
return r;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex >::type operator/(const complex& x, const C& y) {
complex r;
r.re = x.re / y;
r.im = x.im / y;
return r;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex >::type operator/(const C& x, const complex& y) {
complex r;
T tmp;
tmp = y.re * y.re + y.im * y.im;
r.re = (y.re * x) / tmp;
r.im = (- x * y.im) / tmp;
#if 0
T tmp2;
using std::abs;
if (abs(y.re) > abs(y.im)) {
tmp2 = y.im / y.re;
tmp = y.re + y.im * tmp2;
r.re = x / tmp;
r.im = (- x * tmp2) / tmp;
} else {
tmp2 = y.re / y.im;
tmp = y.re * tmp2 + y.im;
r.re = (tmp2 * x) / tmp;
r.im = (- x) / tmp;
}
#endif
return r;
}
friend complex& operator/=(complex& x, const complex& y) {
x = x / y;
return x;
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex& >::type operator/=(complex& x, const C& y) {
x.re /= y;
x.im /= y;
return x;
}
friend std::ostream& operator<<(std::ostream& s, const complex& x) {
s << '(' << x.re << ")+(" << x.im << ")i";
return s;
}
const T& real() const {
return re;
}
const T& imag() const {
return im;
}
T& real() {
return re;
}
T& imag() {
return im;
}
static complex i() {
return complex(T(0.), T(1.));
}
friend T abs(const complex& x) {
using std::sqrt;
using std::pow;
return sqrt(pow(x.re, 2) + pow(x.im, 2));
}
friend T arg(const complex& x) {
using std::atan2;
return atan2(x.im, x.re);
}
friend complex conj(const complex& x) {
return complex(x.re, -x.im);
}
friend complex sqrt(const complex& x) {
T a, r;
using std::sqrt;
r = sqrt(abs(x));
a = arg(x) * 0.5;
using std::cos;
using std::sin;
return complex(r * cos(a), r * sin(a));
}
friend complex pow(const complex& x, int y) {
complex r, xp;
int tmp;
if (y == 0) return complex(1.);
tmp = (y >= 0) ? y : -y;
r = 1.;
xp = x;
while (tmp != 0) {
if (tmp % 2 != 0) {
r *= xp;
}
tmp /= 2;
xp = xp * xp;
}
if (y < 0) {
r = 1. / r;
}
return r;
}
friend complex pow(const complex& x, const complex& y) {
return exp(y * log(x));
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value && ! boost::is_integral<C>::value, complex >::type pow(const complex& x, const C& y) {
return pow(x, complex(y));
}
template <class C> friend typename boost::enable_if_c< acceptable_n<C, complex>::value, complex >::type pow(const C& x, const complex& y) {
return pow(complex(x), y);
}
friend complex exp(const complex& x) {
T tmp;
using std::exp;
using std::cos;
using std::sin;
tmp = exp(x.re);
return complex(tmp * cos(x.im), tmp * sin(x.im));
}
friend complex log(const complex& x) {
using std::log;
return complex(log(abs(x)), arg(x));
}
friend complex sin(const complex& x) {
using std::sin;
using std::cos;
using std::cosh;
using std::sinh;
return complex(sin(x.re) * cosh(x.im), cos(x.re) * sinh(x.im));
}
friend complex cos(const complex& x) {
using std::sin;
using std::cos;
using std::cosh;
using std::sinh;
return complex(cos(x.re) * cosh(x.im), - sin(x.re) * sinh(x.im));
}
friend complex tan(const complex& x) {
T tx, ty, tmp;
tx = 2. * x.re;
ty = 2. * x.im;
using std::sin;
using std::cos;
using std::cosh;
using std::sinh;
tmp = cos(tx) + cosh(ty);
return complex(sin(tx) / tmp, sinh(ty) / tmp);
}
friend complex asin(const complex& x) {
return -i() * log(i() * x + sqrt(1. - x * x));
}
friend complex acos(const complex& x) {
return -i() * log(x + i() * sqrt(1. - x * x));
}
friend complex atan(const complex& x) {
return i() * 0.5 * log((i() + x) / (i() - x));
}
friend complex sinh(const complex& x) {
using std::sin;
using std::cos;
using std::cosh;
using std::sinh;
return complex(sinh(x.re) * cos(x.im), cosh(x.re) * sin(x.im));
}
friend complex cosh(const complex& x) {
using std::sin;
using std::cos;
using std::cosh;
using std::sinh;
return complex(cosh(x.re) * cos(x.im), sinh(x.re) * sin(x.im));
}
friend complex tanh(const complex& x) {
T tx, ty, tmp;
tx = 2. * x.re;
ty = 2. * x.im;
using std::sin;
using std::cos;
using std::cosh;
using std::sinh;
tmp = cosh(tx) + cos(ty);
return complex(sinh(tx) / tmp, sin(ty) / tmp);
}
friend complex asinh(const complex& x) {
return log(x + sqrt(x * x + 1.));
}
friend complex acosh(const complex& x) {
return log(x + sqrt(x * x - 1.));
}
friend complex atanh(const complex& x) {
return 0.5 * log((1. + x) / (1. - x));
}
};
} // namespace kv
#endif // COMPLEX_HPP
| 21.265169 | 177 | 0.590933 | soonho-tri |
530c4b2b94372f67ff4688139ea8d9b08d386bdf | 7,496 | cpp | C++ | Source/HeliumRain/UI/Menus/FlareCompanyMenu.cpp | fdsalbj/HeliumRain | a429db86e59e3c8d71c306a20c7abd2899a36464 | [
"BSD-3-Clause"
] | 2 | 2016-09-20T18:48:21.000Z | 2021-03-30T02:42:59.000Z | Source/HeliumRain/UI/Menus/FlareCompanyMenu.cpp | fdsalbj/HeliumRain | a429db86e59e3c8d71c306a20c7abd2899a36464 | [
"BSD-3-Clause"
] | null | null | null | Source/HeliumRain/UI/Menus/FlareCompanyMenu.cpp | fdsalbj/HeliumRain | a429db86e59e3c8d71c306a20c7abd2899a36464 | [
"BSD-3-Clause"
] | null | null | null |
#include "../../Flare.h"
#include "FlareCompanyMenu.h"
#include "../Components/FlarePartInfo.h"
#include "../Components/FlareCompanyInfo.h"
#include "../../Game/FlareGame.h"
#include "../../Game/FlareCompany.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlareMenuPawn.h"
#include "../../Player/FlarePlayerController.h"
#define LOCTEXT_NAMESPACE "FlareCompanyMenu"
/*----------------------------------------------------
Construct
----------------------------------------------------*/
void SFlareCompanyMenu::Construct(const FArguments& InArgs)
{
// Data
Company = NULL;
MenuManager = InArgs._MenuManager;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
AFlarePlayerController* PC = MenuManager->GetPC();
// Build structure
ChildSlot
.HAlign(HAlign_Fill)
.VAlign(VAlign_Fill)
.Padding(FMargin(0, AFlareMenuManager::GetMainOverlayHeight(), 0, 0))
[
SNew(SVerticalBox)
// Content block
+ SVerticalBox::Slot()
[
SNew(SScrollBox)
.Style(&Theme.ScrollBoxStyle)
.ScrollBarStyle(&Theme.ScrollBarStyle)
+ SScrollBox::Slot()
[
SNew(SVerticalBox)
// Company name
+ SVerticalBox::Slot()
.Padding(Theme.TitlePadding)
.AutoHeight()
[
SNew(STextBlock)
.Text(this, &SFlareCompanyMenu::GetCompanyName)
.TextStyle(&Theme.SubTitleFont)
]
// Company info
+ SVerticalBox::Slot()
.Padding(Theme.ContentPadding)
.AutoHeight()
[
SAssignNew(CompanyInfo, SFlareCompanyInfo)
.Player(PC)
]
// Title
+ SVerticalBox::Slot()
.Padding(Theme.TitlePadding)
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("Colors", "Colors"))
.TextStyle(&Theme.SubTitleFont)
]
// Color picker
+ SVerticalBox::Slot()
.Padding(Theme.ContentPadding)
.AutoHeight()
[
SAssignNew(ColorBox, SFlareColorPanel)
.MenuManager(MenuManager)
]
// Trade routes Title
+ SVerticalBox::Slot()
.Padding(Theme.TitlePadding)
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("Trade routes", "Trade routes"))
.TextStyle(&Theme.SubTitleFont)
.Visibility(this, &SFlareCompanyMenu::GetTradeRouteVisibility)
]
// New trade route button
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(Theme.ContentPadding)
.HAlign(HAlign_Left)
[
SNew(SFlareButton)
.Width(6)
.Text(LOCTEXT("NewTradeRouteButton", "Add new trade route"))
.HelpText(LOCTEXT("NewTradeRouteInfo", "Create a new trade route and edit it"))
.Icon(FFlareStyleSet::GetIcon("New"))
.OnClicked(this, &SFlareCompanyMenu::OnNewTradeRouteClicked)
.Visibility(this, &SFlareCompanyMenu::GetTradeRouteVisibility)
]
// Trade route list
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Left)
[
SAssignNew(TradeRouteList, SVerticalBox)
]
// Object list
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Left)
[
SAssignNew(ShipList, SFlareShipList)
.MenuManager(MenuManager)
.Title(LOCTEXT("Property", "Property"))
]
]
]
];
}
/*----------------------------------------------------
Interaction
----------------------------------------------------*/
void SFlareCompanyMenu::Setup()
{
SetEnabled(false);
SetVisibility(EVisibility::Collapsed);
}
void SFlareCompanyMenu::Enter(UFlareCompany* Target)
{
FLOG("SFlareCompanyMenu::Enter");
SetEnabled(true);
// Company data
Company = Target;
SetVisibility(EVisibility::Visible);
CompanyInfo->SetCompany(Company);
AFlarePlayerController* PC = MenuManager->GetPC();
if (PC && Target)
{
// Colors
FFlarePlayerSave Data;
FFlareCompanyDescription Unused;
PC->Save(Data, Unused);
ColorBox->Setup(Data);
// Menu
PC->GetMenuPawn()->SetCameraOffset(FVector2D(100, -30));
if (PC->GetPlayerShip())
{
PC->GetMenuPawn()->ShowShip(PC->GetPlayerShip());
}
else
{
const FFlareSpacecraftComponentDescription* PartDesc = PC->GetGame()->GetShipPartsCatalog()->Get("object-safe");
PC->GetMenuPawn()->ShowPart(PartDesc);
}
// Station list
TArray<UFlareSimulatedSpacecraft*>& CompanyStations = Target->GetCompanyStations();
for (int32 i = 0; i < CompanyStations.Num(); i++)
{
if (CompanyStations[i]->GetDamageSystem()->IsAlive())
{
ShipList->AddShip(CompanyStations[i]);
}
}
// Ship list
TArray<UFlareSimulatedSpacecraft*>& CompanyShips = Target->GetCompanyShips();
for (int32 i = 0; i < CompanyShips.Num(); i++)
{
if (CompanyShips[i]->GetDamageSystem()->IsAlive())
{
ShipList->AddShip(CompanyShips[i]);
}
}
}
ShipList->RefreshList();
ShipList->SetVisibility(EVisibility::Visible);
UpdateTradeRouteList();
}
void SFlareCompanyMenu::Exit()
{
SetEnabled(false);
ShipList->Reset();
ShipList->SetVisibility(EVisibility::Collapsed);
TradeRouteList->ClearChildren();
Company = NULL;
SetVisibility(EVisibility::Collapsed);
}
void SFlareCompanyMenu::UpdateTradeRouteList()
{
if (Company)
{
TradeRouteList->ClearChildren();
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
TArray<UFlareTradeRoute*>& TradeRoutes = Company->GetCompanyTradeRoutes();
for (int RouteIndex = 0; RouteIndex < TradeRoutes.Num(); RouteIndex++)
{
UFlareTradeRoute* TradeRoute = TradeRoutes[RouteIndex];
// Add line
TradeRouteList->AddSlot()
.AutoHeight()
.HAlign(HAlign_Right)
.Padding(Theme.ContentPadding)
[
SNew(SHorizontalBox)
// Inspect
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SFlareButton)
.Width(6)
.Text(TradeRoute->GetTradeRouteName())
.HelpText(FText(LOCTEXT("InspectHelp", "Edit this trade route")))
.OnClicked(this, &SFlareCompanyMenu::OnInspectTradeRouteClicked, TradeRoute)
]
// Remove
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SFlareButton)
.Transparent(true)
.Text(FText())
.HelpText(LOCTEXT("RemoveTradeRouteHelp", "Remove this trade route"))
.Icon(FFlareStyleSet::GetIcon("Stop"))
.OnClicked(this, &SFlareCompanyMenu::OnDeleteTradeRoute, TradeRoute)
.Width(1)
]
];
}
}
}
/*----------------------------------------------------
Callbacks
----------------------------------------------------*/
FText SFlareCompanyMenu::GetCompanyName() const
{
FText Result;
if (Company)
{
Result = FText::Format(LOCTEXT("Company", "Company : {0}"), Company->GetCompanyName());
}
return Result;
}
void SFlareCompanyMenu::OnNewTradeRouteClicked()
{
UFlareTradeRoute* TradeRoute = Company->CreateTradeRoute(LOCTEXT("UntitledRoute", "Untitled Route"));
check(TradeRoute);
FFlareMenuParameterData Data;
Data.Route = TradeRoute;
MenuManager->OpenMenu(EFlareMenu::MENU_TradeRoute, Data);
}
void SFlareCompanyMenu::OnInspectTradeRouteClicked(UFlareTradeRoute* TradeRoute)
{
FFlareMenuParameterData Data;
Data.Route = TradeRoute;
MenuManager->OpenMenu(EFlareMenu::MENU_TradeRoute, Data);
}
void SFlareCompanyMenu::OnDeleteTradeRoute(UFlareTradeRoute* TradeRoute)
{
check(TradeRoute);
TradeRoute->Dissolve();
UpdateTradeRouteList();
}
EVisibility SFlareCompanyMenu::GetTradeRouteVisibility() const
{
if (Company)
{
return MenuManager->GetPC()->GetCompany()->GetVisitedSectors().Num() >= 2 ? EVisibility::Visible : EVisibility::Collapsed;
}
else
{
return EVisibility::Collapsed;
}
}
#undef LOCTEXT_NAMESPACE
| 23.796825 | 130 | 0.651147 | fdsalbj |
53127eaa0c23b10c46391f8b88f95e066d5df024 | 181 | cpp | C++ | chapters/1/1-10.cpp | Raymain1944/CPPLv1 | 96e5fd5347a336870fc868206ebfe44f88ce69eb | [
"Apache-2.0"
] | null | null | null | chapters/1/1-10.cpp | Raymain1944/CPPLv1 | 96e5fd5347a336870fc868206ebfe44f88ce69eb | [
"Apache-2.0"
] | null | null | null | chapters/1/1-10.cpp | Raymain1944/CPPLv1 | 96e5fd5347a336870fc868206ebfe44f88ce69eb | [
"Apache-2.0"
] | null | null | null | #include <iostream>
/*
* 使用递减运算符打印10到0之间的整数
*/
int main()
{
int base = 10;
while(base >= 0){
std::cout << base << std::endl;
--base;
}
return 0;
}
| 12.928571 | 39 | 0.486188 | Raymain1944 |
531421e1ca3b40383e7cb57725b02c17f7238ee8 | 215 | cpp | C++ | ares/sfc/coprocessor/dip/dip.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | ares/sfc/coprocessor/dip/dip.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | ares/sfc/coprocessor/dip/dip.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | //DIP switch
//used for Nintendo Super System emulation
DIP dip;
#include "serialization.cpp"
auto DIP::power() -> void {
}
auto DIP::read(n24, n8) -> n8 {
return value;
}
auto DIP::write(n24, n8) -> void {
}
| 13.4375 | 42 | 0.646512 | CasualPokePlayer |
531507ccae44b4d0653aa8c98c677bbb806d7f9f | 13,857 | cpp | C++ | src/spy/Spy.cpp | VincentPT/spy | f3b4dd87d00cf12886f52b4ee30ee15430317acd | [
"MIT"
] | 1 | 2022-02-14T12:42:26.000Z | 2022-02-14T12:42:26.000Z | src/spy/Spy.cpp | VincentPT/spy | f3b4dd87d00cf12886f52b4ee30ee15430317acd | [
"MIT"
] | null | null | null | src/spy/Spy.cpp | VincentPT/spy | f3b4dd87d00cf12886f52b4ee30ee15430317acd | [
"MIT"
] | null | null | null | #include "Spy.h"
#include <Shlwapi.h>
#include <Windows.h>
#include <iostream>
#include <vector>
#include <list>
#include "CustomCommandInvoker.h"
#include "CustomCommandManager.h"
#include "spy_interfaces.h"
// internal command function handlers
int freeBufferCommand(FreeBufferCmdData* commandData);
int loadPredifnedFunctions(LoadPredefinedCmdData* param);
int invokeCustomCommand(CustomCommandCmdData* commandData);
int LoadCustomFunctions(LoadCustomFunctionsCmdData* commandData);
int unloadModule(UnloadModuleCmdData* commandData);
int getFunctionPtr(GetFunctionPtrCmdData* commandData);
int getModule(GetModuleCmdData* commandData);
int getModulePath(GetModulePathCmdData* commandData);
// using namespaces
using namespace std;
// extern variables declaration
extern int _runner_count;
// global variables
CustomFunctionManager customFunctionManager;
// macro definition
#define GetPredefinedFunctionCountName "getPredefinedFunctionCount"
#define LoadPredefinedFunctionsName "loadPredefinedFunctions"
// internal structures
struct SetPredefinedCommandContext {
ModuleInfo* moduleInfo;
CustomCommandId commandBase;
unsigned short loadedFunctionCount;
};
extern "C" {
SPY_API DWORD spyRoot(BaseCmdData* param) {
switch (param->commandId)
{
case CommandId::CUSTOM_COMMAND:
return invokeCustomCommand((CustomCommandCmdData*)param);
case CommandId::FREE_BUFFER:
return freeBufferCommand((FreeBufferCmdData*)param);
case CommandId::LOAD_PREDEFINED_FUNCTIONS:
return loadPredifnedFunctions((LoadPredefinedCmdData*)param);
case CommandId::LOAD_CUSTOM_FUNCTIONS:
return LoadCustomFunctions((LoadCustomFunctionsCmdData*)param);
case CommandId::UNLOAD_MODULE:
return unloadModule((UnloadModuleCmdData*)param);
case CommandId::GET_CUSTOM_FUNCTION_PTR:
return getFunctionPtr((GetFunctionPtrCmdData*)param);
case CommandId::GET_MODULE:
return getModule((GetModuleCmdData*)param);
case CommandId::GET_MODULE_PATH:
return getModulePath((GetModulePathCmdData*)param);
default:
break;
}
return -1;
}
}
int freeBufferCommand(FreeBufferCmdData* commandData) {
if (commandData->commandSize != sizeof(FreeBufferCmdData)) {
cout << "Invalid free buffer command" << std::endl;
return -1;
}
cout << "deallocated buffer:" << commandData->buffer << std::endl;
free(commandData->buffer);
//VirtualFree(commandData->buffer, commandData->bufferSize, MEM_RELEASE);
return 0;
}
inline CustomCommandId addCustomFunction(void* pFunc, const char* sFunctionName) {
return customFunctionManager.addCustomFunction(pFunc, sFunctionName);
}
int setCustomFunction(SetPredefinedCommandContext* context, CustomCommandId cmdId, void* pFunc) {
if (context == nullptr) {
cout << "setCustomFunction must be call with suppiled context of function " LoadPredefinedFunctionsName << std::endl;
return -1;
}
ModuleInfo* moduleInfo = context->moduleInfo;
cmdId = cmdId + context->commandBase;
if (!customFunctionManager.setCustomFunction(cmdId, pFunc, "predefined function")) {
return -1;
}
moduleInfo->commandListRef->push_back(cmdId);
cout << "Command " << cmdId << " loaded!" << std::endl;
context->loadedFunctionCount++;
return 0;
}
inline void* getCustomFunction(CustomCommandId cmdId) {
return customFunctionManager.getFunctionAddress(cmdId);
}
// load custom functions function
// all custom functions must be set here
int loadPredifnedFunctions(LoadPredefinedCmdData* param) {
if (param->commandSize < sizeof(LoadPredefinedCmdData)) {
cout << "Invalid custom command:" << (unsigned short)param->commandId << std::endl;
return -1;
}
ReturnData& returnData = param->returnData;
returnData.customData = nullptr;
returnData.sizeOfCustomData = 0;
char* dllFile = param->dllName;
// first try load the dll file as it is, dll file can be an absolute path or a relative path
HMODULE hModule = LoadLibrary(dllFile);
// if dll cannot be load...
if (hModule == NULL) {
// if the dll file is a relative path, we find it in location of root dll
HMODULE hModuleRoot = GetModuleHandle(SPY_ROOT_DLL_NAME);
if (hModuleRoot == nullptr) {
cout << "Name of spy root dll is changed." << std::endl;
return -1;
}
char path[MAX_PATH];
int pathLen;
if (!(pathLen = GetModuleFileName(hModuleRoot, path, MAX_PATH))) {
cout << "Cannot find location of root dll path" << std::endl;
return -1;
}
// remove root dll name to get the directory
path[pathLen - strlen(SPY_ROOT_DLL_NAME)] = 0;
string moduleFullPath(path);
moduleFullPath.append(dllFile);
hModule = LoadLibrary(moduleFullPath.c_str());
if (hModule == nullptr) {
cout << "Cannot find location of spy lib dll (" << dllFile << ")" << std::endl;
return -1;
}
}
auto GetPredefinedFunctionCount = (FGetPredefinedFunctionCount)GetProcAddress(hModule, GetPredefinedFunctionCountName);
if (GetPredefinedFunctionCount == nullptr) {
FreeLibrary(hModule);
cout << dllFile << " does not contain function " GetPredefinedFunctionCountName << std::endl;
return -1;
}
auto LoadPredefinedFunctions = (FLoadPredefinedFunctions)GetProcAddress(hModule, LoadPredefinedFunctionsName);
if (LoadPredefinedFunctions == nullptr) {
FreeLibrary(hModule);
cout << dllFile << " does not contain function " LoadPredefinedFunctionsName << std::endl;
return -1;
}
auto moduleInfo = customFunctionManager.createModuleContainer(hModule, dllFile);
returnData.sizeOfCustomData = sizeof(LoadPredefinedReturnData);
auto pLoadPredefinedReturnData = (LoadPredefinedReturnData*)malloc(returnData.sizeOfCustomData);
returnData.customData = (char*)pLoadPredefinedReturnData;
pLoadPredefinedReturnData->hModule = hModule;
pLoadPredefinedReturnData->moduleId = moduleInfo->moduleId;
int iNumberOfPredefinedFunction = GetPredefinedFunctionCount();
// check if there is no predefined functions need to be loaded
if (iNumberOfPredefinedFunction <= 0) {
return MAKE_RESULT_OF_LOAD_PREDEFINED_FUNC(0, CUSTOM_COMMAND_END);
}
SetPredefinedCommandContext context;
context.moduleInfo = moduleInfo;
context.commandBase = (CustomCommandId)customFunctionManager.getCommandCount();
context.loadedFunctionCount = 0;
// add space to store predefined functions
customFunctionManager.addFunctionSpace(iNumberOfPredefinedFunction);
// call the funcion the load the predefined function to the engine
int iRes = LoadPredefinedFunctions(&context, (FSetPredefinedFunction)setCustomFunction, context.commandBase);
if (iRes != 0) {
// unload all loadded function of the module
customFunctionManager.unloadModule(moduleInfo->moduleId);
cout << LoadPredefinedFunctionsName " return a cancelled value(" << iRes << "the loading result will be discard" << std::endl;
return MAKE_RESULT_OF_LOAD_PREDEFINED_FUNC(0, CUSTOM_COMMAND_END);
}
return MAKE_RESULT_OF_LOAD_PREDEFINED_FUNC(context.loadedFunctionCount, context.commandBase);
}
// this function use to invoke the corresponding custom function with the custom data
int invokeCustomCommand(CustomCommandCmdData* commandData) {
if (commandData->commandSize != sizeof(CustomCommandCmdData) + (commandData->paramCount - 1) * sizeof(void*)) {
cout << "Invalid custom command:" << commandData->commandSize << std::endl;
return -1;
}
// get function pointer
void* fx = getCustomFunction(commandData->customCommandId);
if (fx == nullptr) {
cout << "custom command '" << (unsigned short)commandData->customCommandId << "' has been not set" << std::endl;
return -1;
}
if (_runner_count <= commandData->paramCount) {
cout << "custom command " << commandData->paramCount << " parameters has been not supported" << std::endl;
return -1;
}
CustomCommandInvoker invoker(fx, commandData->paramCount);
commandData->returnData = invoker.invoke(commandData->params);
return 0;
}
int LoadCustomFunctions(LoadCustomFunctionsCmdData* commandData) {
if (commandData->commandSize < sizeof(LoadCustomFunctionsCmdData)) {
cout << "Invalid load custom command" << std::endl;
return -1;
}
int bufferSize = commandData->commandSize - sizeof(LoadCustomFunctionsCmdData) + sizeof(LoadCustomFunctionsCmdData::fNames);
if (commandData->fNames[bufferSize - 1] != 0) {
cout << "Invalid load custom command" << std::endl;
return -1;
}
char* dllFile = commandData->fNames;
char* endBuffer = dllFile + bufferSize;
auto c = dllFile + strlen(dllFile) + 1;
// first try load the dll file as it is, dll file can be an absolute path or a relative path
HMODULE hModule = LoadLibrary(dllFile);
vector<CustomCommandId> commandIds;
commandData->returnData.sizeOfCustomData = 0;
commandData->returnData.customData = nullptr;
// if dll cannot be load...
if (hModule == NULL) {
// if the dll file is not a relative path, we don't process more
if (!PathIsRelative(dllFile)) {
return 0;
}
// if the dll file is a relative path, we find it in location of root dll
HMODULE hModuleRoot = GetModuleHandle(SPY_ROOT_DLL_NAME);
if (hModuleRoot == nullptr) {
cout << "Name of spy root dll is changed." << std::endl;
return -1;
}
char path[MAX_PATH];
int pathLen;
if (!(pathLen = GetModuleFileName(hModuleRoot, path, MAX_PATH))) {
cout << "Cannot find location of root dll path" << std::endl;
return -1;
}
// remove root dll name to get the directory
path[pathLen - strlen(SPY_ROOT_DLL_NAME)] = 0;
string moduleFullPath(path);
moduleFullPath.append(dllFile);
hModule = LoadLibrary(moduleFullPath.c_str());
if (hModule == nullptr) {
cout << "Cannot find location of " << dllFile << std::endl;
return 0;
}
}
auto moduleInfo = customFunctionManager.createModuleContainer(hModule, dllFile);
// load procs address from the loaded dll file
void* pFunc;
CustomCommandId customCommandId;
while (c < endBuffer)
{
while (c < endBuffer && (*c == ' ' || *c == '\t') || *c == 0) {
c++;
}
if (c >= endBuffer) {
break;
}
pFunc = GetProcAddress(hModule, c);
if (pFunc) {
customCommandId = addCustomFunction(pFunc, c);
if (customCommandId != CUSTOM_COMMAND_END && moduleInfo) {
moduleInfo->commandListRef->push_back(customCommandId);
cout << "Command " << c << " <--> " << customCommandId << " loaded!" << std::endl;
}
}
else {
customCommandId = CUSTOM_COMMAND_END;
}
commandIds.push_back(customCommandId);
c += strlen(c) + 1;
}
ReturnData& returnData = commandData->returnData;
returnData.sizeOfCustomData = (int)(sizeof(LoadCustomFunctionsReturnData) - sizeof(LoadCustomFunctionsReturnData::cmdIds) + commandIds.size() * sizeof(CustomCommandId));
// allocate memory for return data, spy client should be responsible to free the memory after using
LoadCustomFunctionsReturnData* pCustomFunctionsReturnData = (LoadCustomFunctionsReturnData*)malloc(returnData.sizeOfCustomData);
returnData.customData = (char*)pCustomFunctionsReturnData;
pCustomFunctionsReturnData->hModule = hModule;
pCustomFunctionsReturnData->moduleId = moduleInfo->moduleId;
memcpy_s(&pCustomFunctionsReturnData->cmdIds[0], commandIds.size() * sizeof(CustomCommandId), commandIds.data(), commandIds.size() * sizeof(CustomCommandId));
return 0;
}
int unloadModule(UnloadModuleCmdData* commandData) {
if (commandData->commandSize != sizeof(UnloadModuleCmdData)) {
cout << "Invalid load custom command" << std::endl;
return -1;
}
return customFunctionManager.unloadModule(commandData->moduleId) ? 0 : 1;
}
int getFunctionPtr(GetFunctionPtrCmdData* commandData) {
if (commandData->commandSize != sizeof(GetFunctionPtrCmdData)) {
cout << "Invalid load custom command" << std::endl;
return -1;
}
commandData->ptr = customFunctionManager.getFunctionAddress(commandData->customCommandId);
return 0;
}
int getModule(GetModuleCmdData* commandData) {
if (commandData->commandSize != sizeof(GetModuleCmdData)) {
cout << "Invalid load custom command" << std::endl;
return -1;
}
auto& returnData = commandData->returnData;
returnData.customData = nullptr;
returnData.sizeOfCustomData = 0;
returnData.returnCode = 0;
auto moduleInfo = customFunctionManager.getModuleContainer(commandData->moduleId);
int cmdCount = 0;
int rawDataSize = sizeof(ModuleData) - sizeof(ModuleData::cmdIds);
if (moduleInfo != nullptr) {
auto commandListRef = moduleInfo->commandListRef;
ModuleData* pModuleData;
if (commandListRef) {
cmdCount = (int)moduleInfo->commandListRef->size();
rawDataSize += cmdCount * sizeof(CustomCommandId);
pModuleData = (ModuleData*)malloc(rawDataSize);
auto pCmdId = pModuleData->cmdIds;
for (auto it = commandListRef->begin(); it != commandListRef->end(); it++) {
*pCmdId++ = *it;
}
}
else {
pModuleData = (ModuleData*)malloc(rawDataSize);
}
pModuleData->hModule = moduleInfo->hModule;
pModuleData->commandCount = cmdCount;
returnData.customData = (char*)pModuleData;
returnData.sizeOfCustomData = rawDataSize;
}
return 0;
}
int getModulePath(GetModulePathCmdData* commandData) {
if (commandData->commandSize != sizeof(GetModulePathCmdData)) {
cout << "Invalid load custom command" << std::endl;
return -1;
}
auto& returnData = commandData->returnData;
returnData.customData = nullptr;
returnData.sizeOfCustomData = 0;
returnData.returnCode = 0;
auto moduleInfo = customFunctionManager.getModuleContainer(commandData->moduleId);
int cmdCount = 0;
if (moduleInfo != nullptr) {
HMODULE hModule = moduleInfo->hModule;
int bufferSize = MAX_PATH;
int rawDataSize = sizeof(ModulePathData) - sizeof(ModulePathData::path) + bufferSize;
ModulePathData* pModuleData;
pModuleData = (ModulePathData*)malloc(rawDataSize);
pModuleData->hModule = moduleInfo->hModule;
pModuleData->bufferSize = bufferSize;
GetModuleFileNameA(hModule, pModuleData->path, bufferSize);
returnData.customData = (char*)pModuleData;
returnData.sizeOfCustomData = rawDataSize;
}
return 0;
} | 33.633495 | 170 | 0.748358 | VincentPT |
531b53c42ec6d2d4364908c747ef96121e018a25 | 1,121 | cc | C++ | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/duration/literals/range.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/duration/literals/range.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/duration/literals/range.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | // { dg-do compile { target c++14 } }
// Copyright (C) 2014-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <chrono>
void
test01()
{
using namespace std::literals::chrono_literals;
// std::numeric_limits<int64_t>::max() == 9223372036854775807;
auto h = 9223372036854775808h;
// { dg-error "cannot be represented" "" { target *-*-* } 893 }
}
// { dg-prune-output "in constexpr expansion" } // needed for -O0
| 35.03125 | 74 | 0.714541 | best08618 |
531e78bfa2c8716a6cf77d286ea5767c4ecf7ab4 | 1,260 | cpp | C++ | CTCI/Chapter3/3-4.cpp | EdwaRen/Competitve-Programming | e8bffeb457936d28c75ecfefb5a1f316c15a9b6c | [
"MIT"
] | 1 | 2021-05-03T21:48:25.000Z | 2021-05-03T21:48:25.000Z | CTCI/Chapter3/3-4.cpp | EdwaRen/Competitve_Programming | e8bffeb457936d28c75ecfefb5a1f316c15a9b6c | [
"MIT"
] | null | null | null | CTCI/Chapter3/3-4.cpp | EdwaRen/Competitve_Programming | e8bffeb457936d28c75ecfefb5a1f316c15a9b6c | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
const int MAX_SIZE = 100;
class Stack {
private:
int cur;
int *buf;
int capacity;
public:
Stack(int capa = MAX_SIZE) {
capacity = capa;
cur = -1;
buf = new int[capa];
}
void updateQueue() {
// if (bufFilled) {
for (int i = 0; i < cur; i++) {
queue[i] = buf[cur-i];
bufFilled = !bufFilled;
}
// } else {
// for (int i = 0; i < cur; i++) {
// buf[i] = queue[cur-i];
// bufFilled = !bufFilled;
// }
// }
}
void push(int value) {
cur++;
buf[cur] = value;
}
void pop() {
cur--;
}
int peak() {
return buf[cur];
}
int size() {
return cur;
}
bool isEmpty() {
return (cur == -1);
}
}
class MyQueue {
private:
Stack stackNew;
Stack stackOld;
public:
MyQueue(int capa) {
stackNew = Stack(capa);
stackOld = Stack(capa)
}
void add(int value) {
stackNew.push(value);
}
void shiftStacks() {
if (stackOld.isEmpty) {
while (!stackNew.isEmpty()) {
stackOld.push(stackNew.peak());
stackNew.pop();
}
}
}
int peek() {
shiftStacks();
return(stackOld.peak())
}
void remove() {
shiftStacks();
stackOld.pop();
}
}
| 14.651163 | 40 | 0.512698 | EdwaRen |
5321f099bf6f9ded7e3b350abe66a8c9345c54b7 | 1,472 | cpp | C++ | lib/lane/src/Utils/FilesystemWindows.cpp | calhewitt/LANE | 412c3d465e6a459714f7a4a7ca4de30e571e0220 | [
"BSD-2-Clause"
] | null | null | null | lib/lane/src/Utils/FilesystemWindows.cpp | calhewitt/LANE | 412c3d465e6a459714f7a4a7ca4de30e571e0220 | [
"BSD-2-Clause"
] | null | null | null | lib/lane/src/Utils/FilesystemWindows.cpp | calhewitt/LANE | 412c3d465e6a459714f7a4a7ca4de30e571e0220 | [
"BSD-2-Clause"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
/// \file FilesystemWindows.cpp
/// \author Hector Stalker <[email protected]>
/// \version 0.1
///
/// \brief Cross-platform filesystem handling code - Windows specific
///
/// \copyright Copyright (c) 2014, Hector Stalker. All rights reserved.
/// This file is under the Simplified (2-clause) BSD license
/// For conditions of distribution and use, see:
/// http://opensource.org/licenses/BSD-2-Clause
/// or read the 'LICENSE.md' file distributed with this code
#include <vector>
#include <string>
#include <windows.h>
#include <tchar.h>
#include "Utils/Filesystem.hpp"
namespace lane {
namespace utils {
std::vector<std::string> getDirectoryContents(
const std::string& directory
) noexcept {
std::vector<std::string> fileList;
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
// Find the first file in the directory.
hFind = FindFirstFile((TCHAR*)(directory + "/*").c_str(), &ffd);
// Loop over the rest of the files
if (hFind != INVALID_HANDLE_VALUE) {
do {
std::string path = ffd.cFileName;
// Don't add current directory marker and previous directory marker
if (path != "." && path != "..") {
fileList.push_back(path);
}
} while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
}
return fileList;
}
} // utils
} // lane
| 28.862745 | 79 | 0.601902 | calhewitt |
5322a7ecf129c7d181d3f747bcab653342de468d | 12,344 | cc | C++ | src/applications/dns/DNSServerBase.cc | saenridanra/inet-dns-extension | 1fa452792f954297f2dc7ede3b699e73ca17c0c1 | [
"MIT"
] | 1 | 2015-04-03T15:18:52.000Z | 2015-04-03T15:18:52.000Z | src/applications/dns/DNSServerBase.cc | saenridanra/inet-dns-extension | 1fa452792f954297f2dc7ede3b699e73ca17c0c1 | [
"MIT"
] | null | null | null | src/applications/dns/DNSServerBase.cc | saenridanra/inet-dns-extension | 1fa452792f954297f2dc7ede3b699e73ca17c0c1 | [
"MIT"
] | null | null | null | /* Copyright (c) 2014-2015 Andreas Rain
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "DNSServerBase.h"
Define_Module(DNSServerBase);
void DNSServerBase::initialize(int stage)
{
if (stage == inet::INITSTAGE_LOCAL)
{
cSimpleModule::initialize(stage);
// Initialize gates
out.setOutputGate(gate("udpOut"));
out.bind(DNS_PORT);
receivedQueries = 0;
}
else if (stage == inet::INITSTAGE_LAST)
{
rootServers = inet::L3AddressResolver().resolve(cStringTokenizer(par("root_servers")).asVector());
}
}
void DNSServerBase::handleMessage(cMessage *msg)
{
int isDNS = 0;
int isQR = 0;
std::shared_ptr<INETDNS::Query> query;
DNSPacket* response;
// Check if we received a query
if (msg->arrivedOn("udpIn"))
{
if ((isDNS = INETDNS::isDNSpacket((cPacket*) msg)))
{
if ((isQR = INETDNS::isQueryOrResponse((cPacket*) msg)) == 0)
{
query = INETDNS::resolveQuery((cPacket*) msg);
receivedQueries++;
cPacket *pk = check_and_cast<cPacket *>(msg);
inet::UDPDataIndication *ctrl = check_and_cast<inet::UDPDataIndication *>(pk->getControlInfo());
inet::L3Address srcAddress = ctrl->getSrcAddr();
query->src_address = srcAddress.str();
response = handleQuery(query);
if (response == NULL)
{ // only happens if recursive resolving was initiated
delete msg;
return;
}
// and send the response to the source address
sendResponse(response, srcAddress);
}
else
{
// Just got a response, lets see if its an answer fitting one of
// the queries we need to resolved.
response = handleRecursion((DNSPacket*) msg);
if (response != NULL)
{
// this was the final answer, i.e.
// get the original packet and the src addr
int id = ((DNSPacket*) msg)->getId();
std::shared_ptr<INETDNS::CachedQuery> cq = get_query_from_cache(id);
inet::L3Address addr = inet::L3AddressResolver().resolve(cq->query->src_address.c_str());
// free cached query data
remove_query_from_cache(id, cq);
// we're not an authority, set it here.
sendResponse(response, addr);
}
}
}
}
delete msg;
}
DNSPacket* DNSServerBase::handleRecursion(DNSPacket* packet)
{
// first check if we have a query id that belongs to this packet
// and the answer relates to the query
DNSPacket* response;
if (!queryCache.count(packet->getId()))
{
return NULL; // we do not have a query that belongs to this key
}
std::shared_ptr<INETDNS::CachedQuery> cq = queryCache[packet->getId()];
std::shared_ptr<INETDNS::Query> original_query = cq->query;
// first check, see if there are actually answers
if (DNS_HEADER_AA(packet->getOptions()) && packet->getAncount() > 0)
{
// we have what we looked for, return
std::string msg_name = std::string("dns_response#") + std::to_string(original_query->id);
response = INETDNS::createResponse(msg_name, 1, packet->getAncount(), packet->getNscount(),
packet->getArcount(), original_query->id, DNS_HEADER_OPCODE(original_query->options), 0,
DNS_HEADER_RD(original_query->options), 1, 0);
short i;
for (i = 0; i < cq->query->qdcount; i++)
{
INETDNS::appendQuestion(response, INETDNS::copyDnsQuestion(&cq->query->questions[i]), i);
}
std::string bubble_popup = "";
for (i = 0; i < packet->getAncount(); i++)
{
// store the response in the cache
if (responseCache)
{
// check if the record is not an A or AAAA record
if (packet->getAnswers(i).rtype != DNS_TYPE_VALUE_A
&& packet->getAnswers(i).rtype != DNS_TYPE_VALUE_AAAA)
{
//create a copy and put it into the cache
std::shared_ptr<INETDNS::DNSRecord> r = INETDNS::copyDnsRecord(&(packet->getAnswers(i)));
#ifdef DEBUG_ENABLED
// put the record into the cache
bubble_popup.append("New cache entry:\n");
bubble_popup.append(r->rname.c_str());
bubble_popup.append(":");
bubble_popup.append(INETDNS::getTypeStringForValue(r->rtype));
bubble_popup.append(":");
bubble_popup.append(INETDNS::getClassStringForValue(r->rclass));
bubble_popup.append("\nData: ");
bubble_popup.append(r->strdata.c_str());
bubble_popup.append("\n---------\n");
#endif
responseCache->put_into_cache(r);
}
}
INETDNS::appendAnswer(response, INETDNS::copyDnsRecord(&packet->getAnswers(i)), i);
}
#ifdef DEBUG_ENABLED
if (bubble_popup != "")
{
EV << bubble_popup.c_str();
this->getParentModule()->bubble(bubble_popup.c_str());
}
#endif
if (responseCache && original_query->questions[0].qname == packet->getQuestions(0).qname)
{
// we have a mismatch in the queries, this means we followed a CNAME chain
// and used the end of chain to query the server, hence we need to append
// the CNAME chain
std::string cnhash = original_query->questions[0].qname + ":" + DNS_TYPE_STR_CNAME + ":" +
DNS_CLASS_STR_IN;
std::list<std::string> hashes = responseCache->get_matching_hashes(cnhash);
int num_hashes = hashes.size();
// reset size of answers to ancount + hashes length
response->setNumAnswers(response->getAncount() + num_hashes);
response->setAncount(response->getAncount() + num_hashes);
int pos = packet->getAncount();
for(auto it = hashes.begin(); it != hashes.end(); it++)
{
// use the hash to get the corresponding entry
std::string tmp = (std::string) *it;
std::list<std::shared_ptr<DNSRecord>> records = responseCache->get_from_cache(tmp);
if (!records.empty())
break;
// list should not be greater one otherwise there is a collision
if (records.size() > 1)
{
responseCache->remove_from_cache(tmp);
break;
}
// only one record, extract data into tmp
if ((*(records.begin()))->rtype == DNS_TYPE_VALUE_CNAME)
{
// append record to the section
INETDNS::appendAnswer(response, INETDNS::copyDnsRecord(*(records.begin())),
pos);
pos++;
}
}
}
for (i = 0; i < packet->getNscount(); i++)
{
INETDNS::appendAuthority(response, INETDNS::copyDnsRecord(&packet->getAuthorities(i)), i);
}
for (i = 0; i < packet->getArcount(); i++)
{
INETDNS::appendAdditional(response, INETDNS::copyDnsRecord(&packet->getAdditional(i)), i);
}
return response;
}
else if (DNS_HEADER_AA(packet->getOptions()) && packet->getAncount() == 0)
{
// return the entry not found response
std::string msg_name = "dns_response#" + std::to_string(original_query->id);
response = INETDNS::createResponse(msg_name, 1, 0, 0, 0, original_query->id,
DNS_HEADER_OPCODE(original_query->options), 1, DNS_HEADER_RD(original_query->options), 1, 3);
for (int i = 0; i < cq->query->qdcount; i++)
{
INETDNS::appendQuestion(response, INETDNS::copyDnsQuestion(&cq->query->questions[i]), i);
}
return response; // return the response with no entry found..
}
else if (packet->getNscount() > 0 && packet->getArcount() > 0 && !DNS_HEADER_AA(packet->getOptions()))
{
// we have an answer for a query
// pick one at random and delegate the question
int p = intrand(packet->getNscount());
std::shared_ptr<DNSRecord> r = INETDNS::copyDnsRecord(&packet->getAdditional(p));
// query the name server for our original query
std::string msg_name = "dns_query#" + std::to_string(cq->internal_id) + std::string("--recursive");
DNSPacket *query = INETDNS::createQuery(msg_name, packet->getQuestions(0).qname, DNS_CLASS_IN,
packet->getQuestions(0).qtype, cq->internal_id, 1);
// Resolve the ip address for the record
inet::L3Address address = inet::L3AddressResolver().resolve(r->strdata.c_str());
if (!address.isUnspecified())
sendResponse(query, address);
return NULL; // since this packet is fine we pass it upwards
}
else if (packet->getNscount() > 0 && !DNS_HEADER_AA(packet->getOptions()))
{
// TODO: no ar record, we need to start at the beginning with this reference..
return NULL;
}
else
{
// something went wrong, return a server failure query
std::string msg_name = "dns_response#" + std::to_string(original_query->id);
response = INETDNS::createResponse(msg_name, 1, 0, 0, 0, original_query->id,
DNS_HEADER_OPCODE(original_query->options), 0, DNS_HEADER_RD(original_query->options), 1, 2);
return response; // return the response with no entry found..
}
return NULL;
}
int DNSServerBase::remove_query_from_cache(int id, std::shared_ptr<INETDNS::CachedQuery> cq)
{
queryCache.erase(queryCache.find(id));
return 1;
}
std::shared_ptr<INETDNS::CachedQuery> DNSServerBase::get_query_from_cache(int id)
{
std::shared_ptr<INETDNS::CachedQuery> q = queryCache[id];
return q;
}
int DNSServerBase::store_in_query_cache(int id, std::shared_ptr<INETDNS::Query> query)
{
// store the query in the cache...
std::shared_ptr<INETDNS::CachedQuery> q(new INETDNS::CachedQuery());
q->internal_id = id;
q->query = query;
queryCache[id] = q;
return 1;
}
DNSPacket* DNSServerBase::handleQuery(std::shared_ptr<INETDNS::Query> query)
{
return NULL;
}
void DNSServerBase::sendResponse(DNSPacket *response, inet::L3Address returnAddress)
{
if (!returnAddress.isUnspecified())
{
if (response == NULL)
{
std::cout << "Bad response\n" << std::endl;
return;
}
response->setByteLength(INETDNS::estimateDnsPacketSize(response));
out.sendTo(response, returnAddress, DNS_PORT);
}
else
std::cout << "Missing return address\n" << std::endl;
}
DNSPacket* DNSServerBase::unsupportedOperation(std::shared_ptr<INETDNS::Query> q)
{
// TODO: return unsupported packet.
return NULL;
}
| 36.412979 | 112 | 0.590327 | saenridanra |
5325af0d311e39200f5fb2cea8688113ecadfdb6 | 1,094 | cpp | C++ | search_engine/process_queries.cpp | oleg-nazarov/cpp-yandex-praktikum | a09781c198b0aff469c4d1175c91d72800909bf2 | [
"MIT"
] | 1 | 2022-03-15T19:01:03.000Z | 2022-03-15T19:01:03.000Z | search_engine/process_queries.cpp | oleg-nazarov/cpp-yandex-praktikum | a09781c198b0aff469c4d1175c91d72800909bf2 | [
"MIT"
] | 1 | 2022-03-15T19:11:59.000Z | 2022-03-15T19:11:59.000Z | search_engine/process_queries.cpp | oleg-nazarov/cpp-yandex-praktikum | a09781c198b0aff469c4d1175c91d72800909bf2 | [
"MIT"
] | null | null | null | #include "process_queries.h"
#include <algorithm>
#include <execution>
#include <iterator>
#include <string>
#include <vector>
#include "document.h"
#include "search_server.h"
std::vector<std::vector<Document>> ProcessQueries(const SearchServer& search_server, const std::vector<std::string>& queries) {
std::vector<std::vector<Document>> documents(queries.size());
std::transform(
std::execution::par,
queries.begin(), queries.end(),
documents.begin(),
[&search_server](const std::string& query) {
return search_server.FindTopDocuments(query);
});
return documents;
}
std::vector<Document> ProcessQueriesJoined(const SearchServer& search_server, const std::vector<std::string>& queries) {
auto documents = ProcessQueries(search_server, queries);
std::vector<Document> joined_documents;
for (auto& doc : documents) {
joined_documents.insert(
joined_documents.end(),
std::make_move_iterator(doc.begin()), std::make_move_iterator(doc.end()));
}
return joined_documents;
}
| 28.789474 | 127 | 0.680073 | oleg-nazarov |
5328d7fc5df06a60f6df800f03b5e2d992ad864a | 30,734 | cpp | C++ | src/fs/Formats/FAT/FAT32/FATPartition.cpp | Unified-Projects/Unified-OS | 89912adc1ed9ec35753fe0f4fa35f03d30ec66a2 | [
"BSD-2-Clause"
] | null | null | null | src/fs/Formats/FAT/FAT32/FATPartition.cpp | Unified-Projects/Unified-OS | 89912adc1ed9ec35753fe0f4fa35f03d30ec66a2 | [
"BSD-2-Clause"
] | null | null | null | src/fs/Formats/FAT/FAT32/FATPartition.cpp | Unified-Projects/Unified-OS | 89912adc1ed9ec35753fe0f4fa35f03d30ec66a2 | [
"BSD-2-Clause"
] | null | null | null | #include <fs/Formats/FAT/FAT32/FATPartition.h>
#include <fs/Formats/FAT/FAT32/Directory.h>
#include <fs/Formats/FAT/FAT32/FAT.h>
using namespace UnifiedOS;
using namespace UnifiedOS::FileSystem;
using namespace UnifiedOS::FileSystem::FAT32;
#include <common/cstring.h> //Needed for path interaction
Fat32Partition::Fat32Partition(GPT::GPTPartitonEntry Partition, DiskDevice* disk, void* BootSector)
: PartitionDevice(Partition.StartLBA, Partition.EndLBA, Partition.TypeGUID, Partition.PartitionGUID, disk),
MBR(rMBR)
{
//Save the boot sector
rMBR = *((MBR::FAT32_MBR*)BootSector);
//Read the flags for the drive
rFlags.ReadOnly = (Partition.Flags >> 60 == 1);
rFlags.Hidden = (Partition.Flags >> 62 == 1);
rFlags.AutoMount = !(Partition.Flags >> 63 == 1);
//Set the format
rFormat = PARTITION_FAT_32;
//Read Root Directory to get the volume name
FATClusterEntries* RootClusters = ScanForEntries(this, 0);
//Disk read check
if(RootClusters){
DirectoryEntryListing* RootDirectory = ReadDirectoryEntries(this, RootClusters);
if(RootDirectory){
//If LongFileName
if(RootDirectory->Directories.get_at(0)->LFNE.size()){
}
else{//Normal file name
//Setup name location
PartitionName = new char[11];
//Load data
Memory::memcpy(PartitionName, &(RootDirectory->Directories.get_at(0)->RDE.FileName), 11);
}
delete RootDirectory;
}
delete RootClusters;
}
}
GeneralFile Fat32Partition::ResolveFile(const char* Path){
//Create the file
GeneralFile File = {};
//Check if the set Mount is correct
if(Path[0] == Mount + 0x41){
//Find out the length of the path
size_t Length = strlen(Path);
//Subdirectories
uint64_t Subdirectories = 0;
Vector<uint64_t> SectionSpacing = {};
uint64_t CurrentSpacing = 0;
//Calculate how many subdirectories are in the path
for(int i = 0; i < Length; i++){
if(Path[i] == '/' || Path[i] == '\\'){
Subdirectories++;
//Add spacing
SectionSpacing.add_back(CurrentSpacing);
CurrentSpacing = 0;
}
else{
CurrentSpacing++;
}
}
//Add spacing
SectionSpacing.add_back(CurrentSpacing);
CurrentSpacing = 0;
//Remove first entry because its not a part of the filepath
SectionSpacing.erase(0);
//Remove RootDirectory as a subdir
Subdirectories -= 1;
//For memory comparison
uint64_t OffsetIntoPath = 3; //Default to 3 for "A:/"
//if it is a directory we want to store the new cluster
uint32_t NewClusterPosition = 0;
//First iterate over root directory
//Read Root Directory to get the volume name
FATClusterEntries* RootClusters = ScanForEntries(this, NewClusterPosition);
//Disk read check
if(RootClusters){
DirectoryEntryListing* RootDirectory = ReadDirectoryEntries(this, RootClusters);
if(RootDirectory){
//Look over entries
for(int i = 0; i < RootDirectory->Directories.size(); i++){
//To Save time compare if it should be a directory OR NOT
if((Subdirectories > 0 && CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false) && !CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_System_FileM, false)) ||
(Subdirectories == 0 && !CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false) && !CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_System_FileM, false))){
//Because the same process for creaing the file is here so I will make a bool for both to use
bool CorrectEntry = false;
//File name
char* EntryName = nullptr;
if(RootDirectory->Directories.get_at(i)->LFNE.size() > 0){//Compare as a long file name entry
//Creation of Long File Name From Entries
//Name Size
uint64_t NameSize = 0;
//Skipping character
bool Skip = false;
//Loop over LFNE entries and get the length of the s
for(int e = RootDirectory->Directories.get_at(i)->LFNE.size() - 1; e >= 0; e--){
for(int x = 0; x < 10; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
for(int x = 0; x < 12; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
for(int x = 0; x < 4; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
}
//Reset Skip
Skip = false;
//Check lengths
if(NameSize == SectionSpacing.get_at(0)){ //Run further comparsions
EntryName = new char[NameSize];
uint8_t PosInName = 0;
//For File Extentions
bool CountedExtention = 0;
//Read the data into EntryName
for(int e = RootDirectory->Directories.get_at(i)->LFNE.size() - 1; e >= 0; e--){
for(int x = 0; x < 10; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0xFF){
EntryName[PosInName++] = RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x];
}
Skip = !Skip;
}
for(int x = 0; x < 12; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0xFF){
EntryName[PosInName++] = RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x];
}
Skip = !Skip;
}
for(int x = 0; x < 4; x++){
if(!Skip && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0x00 && RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0xFF){
EntryName[PosInName++] = RootDirectory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x];
}
Skip = !Skip;
}
}
//Comparison Time
if(Memory::memcmp(EntryName, ((uint8_t*)Path)+OffsetIntoPath, NameSize)){
CorrectEntry = true;
}
}
}
else{//Root Directory Entry
//For size comparison
uint8_t EntrySize = 0;
//Extention dot
if(!CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false)){
EntrySize += 1;
}
//Load the filename
for(int e = 0; e < 11; e++){
if(RootDirectory->Directories.get_at(i)->RDE.FileName[e] != 0x20){
EntrySize++;
}
}
//Check lengths
if(EntrySize == SectionSpacing.get_at(0)){ //Run further comparsions
EntryName = new char[EntrySize];
uint8_t PosInName = 0;
//For File Extentions
bool CountedExtention = 0;
//Read the data
for(int e = 0; e < 11 && PosInName < EntrySize; e++){
if(RootDirectory->Directories.get_at(i)->RDE.FileName[e] != 0x20){
if(RootDirectory->Directories.get_at(i)->RDE.FileName[e] >= 0x41 && RootDirectory->Directories.get_at(i)->RDE.FileName[e] <= 0x5A)
EntryName[PosInName++] = RootDirectory->Directories.get_at(i)->RDE.FileName[e]+ 0x20;
else{
EntryName[PosInName++] = RootDirectory->Directories.get_at(i)->RDE.FileName[e];
}
}
else if(!CountedExtention && !CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false)){
CountedExtention = true;
//Add the decimal place
EntryName[PosInName++] = '.';
}
}
//Comparison Time
if(Memory::memcmp(EntryName, ((uint8_t*)Path)+OffsetIntoPath, EntrySize)){
CorrectEntry = true;
}
}
}
//File creation
if(CorrectEntry){
//Cluster
NewClusterPosition = ((RootDirectory->Directories.get_at(i)->RDE.High2BytesOfAddressOfFirstCluster << 16) & 0xFF00) |
RootDirectory->Directories.get_at(i)->RDE.Low2BytesOfAddressOfFirstCluster;
//Only entry needed (File is found)
if(Subdirectories == 0){
//Sort out the name
uint16_t ExtentionPos = 0;
//Find the position of the start of the Extention
for(int x = SectionSpacing.get_at(0) - 1; x >= 0; x--){
if(EntryName[x] == '.'){
ExtentionPos = x;
break;
}
}
if(ExtentionPos){
//Copy the name data
File.Name = new uint8_t[ExtentionPos];
Memory::memcpy(File.Name, ((uint8_t*)EntryName), ExtentionPos);
//Copy the extention
File.Extention = new uint8_t[SectionSpacing.get_at(0) - ExtentionPos - 1];
Memory::memcpy(File.Extention, ((uint8_t*)EntryName) + ExtentionPos + 1, SectionSpacing.get_at(0) - ExtentionPos - 1);
}
else{
File.Name = new uint8_t[SectionSpacing.get_at(0)];
Memory::memcpy(File.Name, ((uint8_t*)EntryName), SectionSpacing.get_at(0));
}
//Path Setup
File.FullPath = new uint8_t[strlen(Path)];
Memory::memcpy(File.FullPath, Path, strlen(Path));
//Basic file info
File.FileSize = RootDirectory->Directories.get_at(i)->RDE.FileSize;
//Entries
FATClusterEntries* FatEntries = ScanForEntries(this, NewClusterPosition);
//Setup the secotrs
File.Sectors = new uint64_t[FatEntries->Entries.size()*MBR.SectorsPerCluster];
File.SectorCount = FatEntries->Entries.size()*MBR.SectorsPerCluster;
//Copy the sectors
for(int e = 0; e < FatEntries->Entries.size(); e++){
for(int s = 0; s < MBR.SectorsPerCluster; s++){
File.Sectors[(e * MBR.SectorsPerCluster) + s] = FatEntries->Entries.get_at(e) * MBR.SectorsPerCluster + s;
}
}
//Disk Setup
File.Disk = this;
//Attributes
File.Attributes.Hidden = CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_HiddenM, false);
File.Attributes.Directory = CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false);
File.Attributes.ReadOnly = CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_Read_OnlyM, false);
File.Attributes.Archive = CheckForAttribute(RootDirectory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_ArchiveM, false);
//Validation
File.Found = true;
//End
delete FatEntries;
delete RootDirectory;
delete RootClusters;
return File;
}
}
//Memory Freeing
if(EntryName)
delete EntryName;
}
}
delete RootDirectory;
}
else{ //Fail Prevention
delete RootClusters;
return File;
}
delete RootClusters;
}
else{ //Fail Prevention
return File;
}
//Now move onto any subdirectories
for(int d = 0; d < Subdirectories; d++){
//Offset the PathOffset
OffsetIntoPath += SectionSpacing.get_at(d) + 1;
//Read Directory to get the volume name
FATClusterEntries* DirectoryClusters = ScanForEntries(this, NewClusterPosition);
//Disk read check
if(DirectoryClusters){
DirectoryEntryListing* Directory = ReadDirectoryEntries(this, DirectoryClusters);
if(Directory){
//Look over entries
for(int i = 0; i < Directory->Directories.size(); i++){
//To Save time compare if it should be a directory OR NOT
if((Subdirectories > d + 1 && CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false) && !CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_System_FileM, false)) ||
(Subdirectories == d + 1 && !CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false) && !CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_System_FileM, false))){
//Because the same process for creaing the file is here so I will make a bool for both to use
bool CorrectEntry = false;
//File name
char* EntryName = nullptr;
if(Directory->Directories.get_at(i)->LFNE.size() > 0){//Compare as a long file name entry
//Creation of Long File Name From Entries
//Name Size
uint64_t NameSize = 0;
//Skipping character
bool Skip = false;
//Loop over LFNE entries and get the length of the s
for(int e = Directory->Directories.get_at(i)->LFNE.size() - 1; e >= 0; e--){
for(int x = 0; x < 10; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
for(int x = 0; x < 12; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
for(int x = 0; x < 4; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0xFF){
NameSize++;
}
Skip = !Skip;
}
}
//Reset Skip
Skip = false;
//Check lengths
if(NameSize == SectionSpacing.get_at(d+1)){ //Run further comparsions
EntryName = new char[NameSize];
uint8_t PosInName = 0;
//For File Extentions
bool CountedExtention = 0;
//Read the data into EntryName
for(int e = Directory->Directories.get_at(i)->LFNE.size() - 1; e >= 0; e--){
for(int x = 0; x < 10; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x] != 0xFF){
EntryName[PosInName++] = Directory->Directories.get_at(i)->LFNE.get_at(e).FileName1[x];
}
Skip = !Skip;
}
for(int x = 0; x < 12; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x] != 0xFF){
EntryName[PosInName++] = Directory->Directories.get_at(i)->LFNE.get_at(e).FileName2[x];
}
Skip = !Skip;
}
for(int x = 0; x < 4; x++){
if(!Skip && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0x00 && Directory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x] != 0xFF){
EntryName[PosInName++] = Directory->Directories.get_at(i)->LFNE.get_at(e).FileName3[x];
}
Skip = !Skip;
}
}
//Comparison Time
if(Memory::memcmp(EntryName, ((uint8_t*)Path)+OffsetIntoPath, NameSize)){
CorrectEntry = true;
}
}
}
else{//Root Directory Entry
//For size comparison
uint8_t EntrySize = 0;
//Extention dot
if(!CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false)){
EntrySize += 1;
}
//Load the filename
for(int e = 0; e < 11; e++){
if(Directory->Directories.get_at(i)->RDE.FileName[e] != 0x20){
EntrySize++;
}
}
//Check lengths
if(EntrySize == SectionSpacing.get_at(d + 1)){ //Run further comparsions
EntryName = new char[EntrySize];
uint8_t PosInName = 0;
//For File Extentions
bool CountedExtention = 0;
//Read the data
for(int e = 0; e < 11 && PosInName < EntrySize; e++){
if(Directory->Directories.get_at(i)->RDE.FileName[e] != 0x20){
if(Directory->Directories.get_at(i)->RDE.FileName[e] >= 0x41 && Directory->Directories.get_at(i)->RDE.FileName[e] <= 0x5A)
EntryName[PosInName++] = Directory->Directories.get_at(i)->RDE.FileName[e]+ 0x20;
else{
EntryName[PosInName++] = Directory->Directories.get_at(i)->RDE.FileName[e];
}
}
else if(!CountedExtention && !CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false)){
CountedExtention = true;
//Add the decimal place
EntryName[PosInName++] = '.';
}
}
//Comparison Time
if(Memory::memcmp(EntryName, ((uint8_t*)Path)+OffsetIntoPath, EntrySize)){
CorrectEntry = true;
}
}
}
//File creation
if(CorrectEntry){
//Cluster
NewClusterPosition = ((Directory->Directories.get_at(i)->RDE.High2BytesOfAddressOfFirstCluster << 16) & 0xFF00) |
Directory->Directories.get_at(i)->RDE.Low2BytesOfAddressOfFirstCluster;
//Only entry needed (File is found)
if(Subdirectories == d+1){
//Sort out the name
uint16_t ExtentionPos = 0;
//Find the position of the start of the Extention
for(int x = SectionSpacing.get_at(d+1) - 1; x >= 0; x--){
if(EntryName[x] == '.'){
ExtentionPos = x;
break;
}
}
if(ExtentionPos){
//Copy the name data
File.Name = new uint8_t[ExtentionPos];
Memory::memcpy(File.Name, ((uint8_t*)EntryName), ExtentionPos);
//Copy the extention
File.Extention = new uint8_t[SectionSpacing.get_at(d+1) - ExtentionPos - 1];
Memory::memcpy(File.Extention, ((uint8_t*)EntryName) + ExtentionPos + 1, SectionSpacing.get_at(d+1) - ExtentionPos - 1);
}
else{
File.Name = new uint8_t[SectionSpacing.get_at(d+1)];
Memory::memcpy(File.Name, ((uint8_t*)EntryName), SectionSpacing.get_at(d+1));
}
//Path Setup
File.FullPath = new uint8_t[strlen(Path)];
Memory::memcpy(File.FullPath, Path, strlen(Path));
//Basic file info
File.FileSize = Directory->Directories.get_at(i)->RDE.FileSize;
//Entries
FATClusterEntries* FatEntries = ScanForEntries(this, NewClusterPosition);
//Setup the secotrs
File.Sectors = new uint64_t[FatEntries->Entries.size()*MBR.SectorsPerCluster];
File.SectorCount = FatEntries->Entries.size()*MBR.SectorsPerCluster;
//Copy the sectors
for(int e = 0; e < FatEntries->Entries.size(); e++){
for(int s = 0; s < MBR.SectorsPerCluster; s++){
File.Sectors[(e * MBR.SectorsPerCluster) + s] = FatEntries->Entries.get_at(e) * MBR.SectorsPerCluster + s;
}
}
//Disk Setup
File.Disk = this;
//Attributes
File.Attributes.Hidden = CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_HiddenM, false);
File.Attributes.Directory = CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_DirectoryM, false);
File.Attributes.ReadOnly = CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_Read_OnlyM, false);
File.Attributes.Archive = CheckForAttribute(Directory->Directories.get_at(i)->RDE.FileAttributes, FAT32DirEntry_ArchiveM, false);
//Validation
File.Found = true;
//End
// delete FatEntries;
delete Directory;
delete DirectoryClusters;
return File;
}
}
//Memory Freeing
if(EntryName)
delete EntryName;
}
}
delete Directory;
}
else{ //Fail Prevention
delete DirectoryClusters;
return File;
}
delete DirectoryClusters;
}
else{ //Fail Prevention
return File;
}
}
}
//return
return File;
}
GeneralDirectory Fat32Partition::ResolveDir(const char* Path){
//Create the directory
GeneralDirectory Directory = {};
//return
return Directory;
} | 52.179966 | 276 | 0.413874 | Unified-Projects |
53298cf97e74554425a7e2d3be0f025f32ae6125 | 1,608 | cpp | C++ | src/shared/variable.cpp | FoFabien/SF2DEngine | 3d10964cbdae439584c10ab427ade394d720713f | [
"Zlib"
] | null | null | null | src/shared/variable.cpp | FoFabien/SF2DEngine | 3d10964cbdae439584c10ab427ade394d720713f | [
"Zlib"
] | null | null | null | src/shared/variable.cpp | FoFabien/SF2DEngine | 3d10964cbdae439584c10ab427ade394d720713f | [
"Zlib"
] | null | null | null | #include "variable.hpp"
// globale variable
int32_t gVar[VARIABLE_COUNT];
int32_t sysVar[SYSTEM_VARIABLE_COUNT];
void initGlobaleVariable()
{
for(int32_t i = 0; i < VARIABLE_COUNT; ++i) gVar[i] = 0;
for(int32_t i = 0; i < SYSTEM_VARIABLE_COUNT; ++i) sysVar[i] = 0;
}
void resetGlobaleVariableAndString()
{
for(int32_t i = 0; i < VARIABLE_COUNT; ++i) gVar[i] = 0;
for(int32_t i = 0; i < STRING_COUNT; ++i) gStr[i].clear();
}
void storeFloat(const float &f, int32_t &v)
{
v = *((int32_t*)(&f));
}
float loadFloat(const int32_t &v)
{
return *((float*)(&v));
}
// globale string
std::string gStr[STRING_COUNT];
void updateGlobaleString(int32_t id)
{
if(id < 0)
{
for(int32_t i = 0; i < STRING_COUNT; ++i) updateGlobaleString(i);
return;
}
if(id > STRING_COUNT) return;
switch(id)
{
default: return;
}
}
std::string sysStr[SYSTEM_STRING_COUNT];
void updateSystemString(int32_t id)
{
if(id < 0)
{
for(int32_t i = 0; i < SYSTEM_STRING_COUNT; ++i) updateSystemString(i);
return;
}
if(id > SYSTEM_STRING_COUNT) return;
switch(id)
{
default: return;
}
}
// debug
#ifdef DEBUG_BUILD
int32_t dVar[10];
std::string dStr[10];
#endif
// ---------------------------------
// add specific global variable here
// ---------------------------------
// dungeon data
std::vector<std::vector<int8_t> > fov;
std::vector<int8_t> tile_grid;
void initDungeonData()
{
fov.clear();
while(fov.size() < DUNGEON_MAX_COUNT) fov.push_back(std::vector<int8_t>());
tile_grid.clear();
}
| 20.615385 | 79 | 0.600746 | FoFabien |
532be93864c9a79d5616e6dd14585049baf732c0 | 31,561 | cpp | C++ | src/vehicles/Plane.cpp | gameblabla/reeee3 | 1b6d0f742b1b6fb681756de702ed618e90361139 | [
"Unlicense"
] | 2 | 2021-03-24T22:11:27.000Z | 2021-05-07T06:51:04.000Z | src/vehicles/Plane.cpp | gameblabla/reeee3 | 1b6d0f742b1b6fb681756de702ed618e90361139 | [
"Unlicense"
] | null | null | null | src/vehicles/Plane.cpp | gameblabla/reeee3 | 1b6d0f742b1b6fb681756de702ed618e90361139 | [
"Unlicense"
] | null | null | null | #include "common.h"
#include "main.h"
#include "General.h"
#include "ModelIndices.h"
#include "FileMgr.h"
#include "Streaming.h"
#include "Replay.h"
#include "Camera.h"
#include "DMAudio.h"
#include "Wanted.h"
#include "Coronas.h"
#include "Particle.h"
#include "Explosion.h"
#include "World.h"
#include "HandlingMgr.h"
#include "Plane.h"
#include "MemoryHeap.h"
CPlaneNode *pPathNodes;
CPlaneNode *pPath2Nodes;
CPlaneNode *pPath3Nodes;
CPlaneNode *pPath4Nodes;
int32 NumPathNodes;
int32 NumPath2Nodes;
int32 NumPath3Nodes;
int32 NumPath4Nodes;
float TotalLengthOfFlightPath;
float TotalLengthOfFlightPath2;
float TotalLengthOfFlightPath3;
float TotalLengthOfFlightPath4;
float TotalDurationOfFlightPath;
float TotalDurationOfFlightPath2;
float TotalDurationOfFlightPath3;
float TotalDurationOfFlightPath4;
float LandingPoint;
float TakeOffPoint;
CPlaneInterpolationLine aPlaneLineBits[6];
float PlanePathPosition[3];
float OldPlanePathPosition[3];
float PlanePathSpeed[3];
float PlanePath2Position[3];
float PlanePath3Position;
float PlanePath4Position;
float PlanePath2Speed[3];
float PlanePath3Speed;
float PlanePath4Speed;
enum
{
CESNA_STATUS_NONE, // doesn't even exist
CESNA_STATUS_FLYING,
CESNA_STATUS_DESTROYED,
CESNA_STATUS_LANDED,
};
int32 CesnaMissionStatus;
int32 CesnaMissionStartTime;
CPlane *pDrugRunCesna;
int32 DropOffCesnaMissionStatus;
int32 DropOffCesnaMissionStartTime;
CPlane *pDropOffCesna;
CPlane::CPlane(int32 id, uint8 CreatedBy)
: CVehicle(CreatedBy)
{
CVehicleModelInfo *mi = (CVehicleModelInfo*)CModelInfo::GetModelInfo(id);
m_vehType = VEHICLE_TYPE_PLANE;
pHandling = mod_HandlingManager.GetHandlingData((tVehicleType)mi->m_handlingId);
SetModelIndex(id);
m_fMass = 100000000.0f;
m_fTurnMass = 100000000.0f;
m_fAirResistance = 0.9994f;
m_fElasticity = 0.05f;
bUsesCollision = false;
m_bHasBeenHit = false;
m_bIsDrugRunCesna = false;
m_bIsDropOffCesna = false;
SetStatus(STATUS_PLANE);
bIsBIGBuilding = true;
m_level = LEVEL_GENERIC;
#ifdef FIX_BUGS
m_isFarAway = false;
#endif
}
CPlane::~CPlane()
{
DeleteRwObject();
}
void
CPlane::SetModelIndex(uint32 id)
{
CVehicle::SetModelIndex(id);
}
void
CPlane::DeleteRwObject(void)
{
if(m_rwObject && RwObjectGetType(m_rwObject) == rpATOMIC){
m_matrix.Detach();
if(RwObjectGetType(m_rwObject) == rpATOMIC){ // useless check
RwFrame *f = RpAtomicGetFrame((RpAtomic*)m_rwObject);
RpAtomicDestroy((RpAtomic*)m_rwObject);
RwFrameDestroy(f);
}
m_rwObject = nil;
}
CEntity::DeleteRwObject();
}
// There's a LOT of copy and paste in here. Maybe this could be refactored somehow
void
CPlane::ProcessControl(void)
{
int i;
CVector pos;
// Explosion
if(m_bHasBeenHit){
// BUG: since this is all based on frames, you can skip the explosion processing when you go into the menu
if(GetModelIndex() == MI_AIRTRAIN){
int frm = CTimer::GetFrameCounter() - m_nFrameWhenHit;
if(frm == 20){
static int nFrameGen;
CRGBA colors[8];
CExplosion::AddExplosion(nil, FindPlayerPed(), EXPLOSION_HELI, GetMatrix() * CVector(0.0f, 0.0f, 0.0f), 0);
colors[0] = CRGBA(0, 0, 0, 255);
colors[1] = CRGBA(224, 230, 238, 255);
colors[2] = CRGBA(224, 230, 238, 255);
colors[3] = CRGBA(0, 0, 0, 255);
colors[4] = CRGBA(224, 230, 238, 255);
colors[5] = CRGBA(0, 0, 0, 255);
colors[6] = CRGBA(0, 0, 0, 255);
colors[7] = CRGBA(224, 230, 238, 255);
CVector dir;
for(i = 0; i < 40; i++){
dir.x = CGeneral::GetRandomNumberInRange(-2.0f, 2.0f);
dir.y = CGeneral::GetRandomNumberInRange(-2.0f, 2.0f);
dir.z = CGeneral::GetRandomNumberInRange(0.0f, 2.0f);
int rotSpeed = CGeneral::GetRandomNumberInRange(10, 30);
if(CGeneral::GetRandomNumber() & 1)
rotSpeed = -rotSpeed;
int f = ++nFrameGen & 3;
CParticle::AddParticle(PARTICLE_HELI_DEBRIS, GetMatrix() * CVector(0.0f, 0.0f, 0.0f), dir,
nil, CGeneral::GetRandomNumberInRange(0.1f, 1.0f),
colors[nFrameGen&7], rotSpeed, 0, f, 0);
}
}
if(frm >= 40 && frm <= 80 && frm & 1){
if(frm & 1){
pos.x = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.2f;
pos.z = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.2f;
pos.y = frm - 40;
pos = GetMatrix() * pos;
}else{
pos.x = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.2f;
pos.z = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.2f;
pos.y = 40 - frm;
pos = GetMatrix() * pos;
}
CExplosion::AddExplosion(nil, FindPlayerPed(), EXPLOSION_HELI, pos, 0);
}
if(frm == 60)
bRenderScorched = true;
if(frm == 82){
TheCamera.SetFadeColour(255, 255, 255);
TheCamera.Fade(0.0f, FADE_OUT);
TheCamera.ProcessFade();
TheCamera.Fade(1.0f, FADE_IN);
FlagToDestroyWhenNextProcessed();
}
}else{
int frm = CTimer::GetFrameCounter() - m_nFrameWhenHit;
if(frm == 20){
static int nFrameGen;
CRGBA colors[8];
CExplosion::AddExplosion(nil, FindPlayerPed(), EXPLOSION_HELI, GetMatrix() * CVector(0.0f, 0.0f, 0.0f), 0);
colors[0] = CRGBA(0, 0, 0, 255);
colors[1] = CRGBA(224, 230, 238, 255);
colors[2] = CRGBA(224, 230, 238, 255);
colors[3] = CRGBA(0, 0, 0, 255);
colors[4] = CRGBA(252, 66, 66, 255);
colors[5] = CRGBA(0, 0, 0, 255);
colors[6] = CRGBA(0, 0, 0, 255);
colors[7] = CRGBA(252, 66, 66, 255);
CVector dir;
for(i = 0; i < 40; i++){
dir.x = CGeneral::GetRandomNumberInRange(-2.0f, 2.0f);
dir.y = CGeneral::GetRandomNumberInRange(-2.0f, 2.0f);
dir.z = CGeneral::GetRandomNumberInRange(0.0f, 2.0f);
int rotSpeed = CGeneral::GetRandomNumberInRange(30.0f, 20.0f);
if(CGeneral::GetRandomNumber() & 1)
rotSpeed = -rotSpeed;
int f = ++nFrameGen & 3;
CParticle::AddParticle(PARTICLE_HELI_DEBRIS, GetMatrix() * CVector(0.0f, 0.0f, 0.0f), dir,
nil, CGeneral::GetRandomNumberInRange(0.1f, 1.0f),
colors[nFrameGen&7], rotSpeed, 0, f, 0);
}
}
if(frm >= 40 && frm <= 60 && frm & 1){
if(frm & 1){
pos.x = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.1f;
pos.z = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.1f;
pos.y = (frm - 40)*0.3f;
pos = GetMatrix() * pos;
}else{
pos.x = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.1f;
pos.z = ((CGeneral::GetRandomNumber() & 0x3F) - 32) * 0.1f;
pos.y = (40 - frm)*0.3f;
pos = GetMatrix() * pos;
}
CExplosion::AddExplosion(nil, FindPlayerPed(), EXPLOSION_HELI, pos, 0);
}
if(frm == 30)
bRenderScorched = true;
if(frm == 62){
TheCamera.SetFadeColour(200, 200, 200);
TheCamera.Fade(0.0f, FADE_OUT);
TheCamera.ProcessFade();
TheCamera.Fade(1.0f, FADE_IN);
if(m_bIsDrugRunCesna){
CesnaMissionStatus = CESNA_STATUS_DESTROYED;
pDrugRunCesna = nil;
}
if(m_bIsDropOffCesna){
DropOffCesnaMissionStatus = CESNA_STATUS_DESTROYED;
pDropOffCesna = nil;
}
FlagToDestroyWhenNextProcessed();
}
}
}
// Update plane position and speed
if(GetModelIndex() == MI_AIRTRAIN || !m_isFarAway || ((CTimer::GetFrameCounter() + m_randomSeed) & 7) == 0){
if(GetModelIndex() == MI_AIRTRAIN){
float pathPositionRear = PlanePathPosition[m_nPlaneId] - 30.0f;
if(pathPositionRear < 0.0f)
pathPositionRear += TotalLengthOfFlightPath;
float pathPosition = pathPositionRear + 30.0f;
float pitch = 0.0f;
float distSinceTakeOff = pathPosition - TakeOffPoint;
if(distSinceTakeOff <= 0.0f && distSinceTakeOff > -70.0f){
// shortly before take off
pitch = 1.0f - distSinceTakeOff/-70.0f;
}else if(distSinceTakeOff >= 0.0f && distSinceTakeOff < 100.0f){
// shortly after take off
pitch = 1.0f - distSinceTakeOff/100.0f;
}
float distSinceLanding = pathPosition - LandingPoint;
if(distSinceLanding <= 0.0f && distSinceLanding > -200.0f){
// shortly before landing
pitch = 1.0f - distSinceLanding/-200.0f;
}else if(distSinceLanding >= 0.0f && distSinceLanding < 70.0f){
// shortly after landing
pitch = 1.0f - distSinceLanding/70.0f;
}
// Advance current node to appropriate position
float pos1, pos2;
int nextTrackNode = m_nCurPathNode + 1;
pos1 = pPathNodes[m_nCurPathNode].t;
if(nextTrackNode < NumPathNodes)
pos2 = pPathNodes[nextTrackNode].t;
else{
nextTrackNode = 0;
pos2 = TotalLengthOfFlightPath;
}
while(pathPositionRear < pos1 || pathPositionRear > pos2){
m_nCurPathNode = (m_nCurPathNode+1) % NumPathNodes;
nextTrackNode = m_nCurPathNode + 1;
pos1 = pPathNodes[m_nCurPathNode].t;
if(nextTrackNode < NumPathNodes)
pos2 = pPathNodes[nextTrackNode].t;
else{
nextTrackNode = 0;
pos2 = TotalLengthOfFlightPath;
}
}
bool bothOnGround = pPathNodes[m_nCurPathNode].bOnGround && pPathNodes[nextTrackNode].bOnGround;
if(PlanePathPosition[m_nPlaneId] >= LandingPoint && OldPlanePathPosition[m_nPlaneId] < LandingPoint)
DMAudio.PlayOneShot(m_audioEntityId, SOUND_PLANE_ON_GROUND, 0.0f);
float dist = pPathNodes[nextTrackNode].t - pPathNodes[m_nCurPathNode].t;
if(dist < 0.0f)
dist += TotalLengthOfFlightPath;
float f = (pathPositionRear - pPathNodes[m_nCurPathNode].t)/dist;
CVector posRear = (1.0f - f)*pPathNodes[m_nCurPathNode].p + f*pPathNodes[nextTrackNode].p;
// Same for the front
float pathPositionFront = pathPositionRear + 60.0f;
if(pathPositionFront > TotalLengthOfFlightPath)
pathPositionFront -= TotalLengthOfFlightPath;
int curPathNodeFront = m_nCurPathNode;
int nextPathNodeFront = curPathNodeFront + 1;
pos1 = pPathNodes[curPathNodeFront].t;
if(nextPathNodeFront < NumPathNodes)
pos2 = pPathNodes[nextPathNodeFront].t;
else{
nextPathNodeFront = 0;
pos2 = TotalLengthOfFlightPath;
}
while(pathPositionFront < pos1 || pathPositionFront > pos2){
curPathNodeFront = (curPathNodeFront+1) % NumPathNodes;
nextPathNodeFront = curPathNodeFront + 1;
pos1 = pPathNodes[curPathNodeFront].t;
if(nextPathNodeFront < NumPathNodes)
pos2 = pPathNodes[nextPathNodeFront].t;
else{
nextPathNodeFront = 0;
pos2 = TotalLengthOfFlightPath;
}
}
dist = pPathNodes[nextPathNodeFront].t - pPathNodes[curPathNodeFront].t;
if(dist < 0.0f)
dist += TotalLengthOfFlightPath;
f = (pathPositionFront - pPathNodes[curPathNodeFront].t)/dist;
CVector posFront = (1.0f - f)*pPathNodes[curPathNodeFront].p + f*pPathNodes[nextPathNodeFront].p;
// And for another point 60 units in front of the plane, used to calculate roll
float pathPositionFront2 = pathPositionFront + 60.0f;
if(pathPositionFront2 > TotalLengthOfFlightPath)
pathPositionFront2 -= TotalLengthOfFlightPath;
int curPathNodeFront2 = m_nCurPathNode;
int nextPathNodeFront2 = curPathNodeFront2 + 1;
pos1 = pPathNodes[curPathNodeFront2].t;
if(nextPathNodeFront2 < NumPathNodes)
pos2 = pPathNodes[nextPathNodeFront2].t;
else{
nextPathNodeFront2 = 0;
pos2 = TotalLengthOfFlightPath;
}
while(pathPositionFront2 < pos1 || pathPositionFront2 > pos2){
curPathNodeFront2 = (curPathNodeFront2+1) % NumPathNodes;
nextPathNodeFront2 = curPathNodeFront2 + 1;
pos1 = pPathNodes[curPathNodeFront2].t;
if(nextPathNodeFront2 < NumPathNodes)
pos2 = pPathNodes[nextPathNodeFront2].t;
else{
nextPathNodeFront2 = 0;
pos2 = TotalLengthOfFlightPath;
}
}
dist = pPathNodes[nextPathNodeFront2].t - pPathNodes[curPathNodeFront2].t;
if(dist < 0.0f)
dist += TotalLengthOfFlightPath;
f = (pathPositionFront2 - pPathNodes[curPathNodeFront2].t)/dist;
CVector posFront2 = (1.0f - f)*pPathNodes[curPathNodeFront2].p + f*pPathNodes[nextPathNodeFront2].p;
// Now set matrix
GetMatrix().SetTranslateOnly((posRear + posFront) / 2.0f);
GetMatrix().GetPosition().z += 4.3f;
CVector fwd = posFront - posRear;
fwd.Normalise();
if(pitch != 0.0f){
fwd.z += 0.4f*pitch;
fwd.Normalise();
}
CVector fwd2 = posFront2 - posRear;
fwd2.Normalise();
CVector roll = CrossProduct(fwd, fwd2);
CVector right = CrossProduct(fwd, CVector(0.0f, 0.0f, 1.0f));
if(!bothOnGround)
right.z += 3.0f*roll.z;
right.Normalise();
CVector up = CrossProduct(right, fwd);
GetMatrix().GetRight() = right;
GetMatrix().GetUp() = up;
GetMatrix().GetForward() = fwd;
// Set speed
m_vecMoveSpeed = fwd*PlanePathSpeed[m_nPlaneId]/60.0f;
m_fSpeed = PlanePathSpeed[m_nPlaneId]/60.0f;
m_vecTurnSpeed = CVector(0.0f, 0.0f, 0.0f);
m_isFarAway = !((posFront - TheCamera.GetPosition()).MagnitudeSqr2D() < sq(300.0f));
}else{
float planePathPosition;
float totalLengthOfFlightPath;
CPlaneNode *pathNodes;
float planePathSpeed;
int numPathNodes;
if(m_bIsDrugRunCesna){
planePathPosition = PlanePath3Position;
totalLengthOfFlightPath = TotalLengthOfFlightPath3;
pathNodes = pPath3Nodes;
planePathSpeed = PlanePath3Speed;
numPathNodes = NumPath3Nodes;
if(CesnaMissionStatus == CESNA_STATUS_LANDED){
pDrugRunCesna = nil;
FlagToDestroyWhenNextProcessed();
}
}else if(m_bIsDropOffCesna){
planePathPosition = PlanePath4Position;
totalLengthOfFlightPath = TotalLengthOfFlightPath4;
pathNodes = pPath4Nodes;
planePathSpeed = PlanePath4Speed;
numPathNodes = NumPath4Nodes;
if(DropOffCesnaMissionStatus == CESNA_STATUS_LANDED){
pDropOffCesna = nil;
FlagToDestroyWhenNextProcessed();
}
}else{
planePathPosition = PlanePath2Position[m_nPlaneId];
totalLengthOfFlightPath = TotalLengthOfFlightPath2;
pathNodes = pPath2Nodes;
planePathSpeed = PlanePath2Speed[m_nPlaneId];
numPathNodes = NumPath2Nodes;
}
// Advance current node to appropriate position
float pathPositionRear = planePathPosition - 10.0f;
if(pathPositionRear < 0.0f)
pathPositionRear += totalLengthOfFlightPath;
float pos1, pos2;
int nextTrackNode = m_nCurPathNode + 1;
pos1 = pathNodes[m_nCurPathNode].t;
if(nextTrackNode < numPathNodes)
pos2 = pathNodes[nextTrackNode].t;
else{
nextTrackNode = 0;
pos2 = totalLengthOfFlightPath;
}
while(pathPositionRear < pos1 || pathPositionRear > pos2){
m_nCurPathNode = (m_nCurPathNode+1) % numPathNodes;
nextTrackNode = m_nCurPathNode + 1;
pos1 = pathNodes[m_nCurPathNode].t;
if(nextTrackNode < numPathNodes)
pos2 = pathNodes[nextTrackNode].t;
else{
nextTrackNode = 0;
pos2 = totalLengthOfFlightPath;
}
}
float dist = pathNodes[nextTrackNode].t - pathNodes[m_nCurPathNode].t;
if(dist < 0.0f)
dist += totalLengthOfFlightPath;
float f = (pathPositionRear - pathNodes[m_nCurPathNode].t)/dist;
CVector posRear = (1.0f - f)*pathNodes[m_nCurPathNode].p + f*pathNodes[nextTrackNode].p;
// Same for the front
float pathPositionFront = pathPositionRear + 20.0f;
if(pathPositionFront > totalLengthOfFlightPath)
pathPositionFront -= totalLengthOfFlightPath;
int curPathNodeFront = m_nCurPathNode;
int nextPathNodeFront = curPathNodeFront + 1;
pos1 = pathNodes[curPathNodeFront].t;
if(nextPathNodeFront < numPathNodes)
pos2 = pathNodes[nextPathNodeFront].t;
else{
nextPathNodeFront = 0;
pos2 = totalLengthOfFlightPath;
}
while(pathPositionFront < pos1 || pathPositionFront > pos2){
curPathNodeFront = (curPathNodeFront+1) % numPathNodes;
nextPathNodeFront = curPathNodeFront + 1;
pos1 = pathNodes[curPathNodeFront].t;
if(nextPathNodeFront < numPathNodes)
pos2 = pathNodes[nextPathNodeFront].t;
else{
nextPathNodeFront = 0;
pos2 = totalLengthOfFlightPath;
}
}
dist = pathNodes[nextPathNodeFront].t - pathNodes[curPathNodeFront].t;
if(dist < 0.0f)
dist += totalLengthOfFlightPath;
f = (pathPositionFront - pathNodes[curPathNodeFront].t)/dist;
CVector posFront = (1.0f - f)*pathNodes[curPathNodeFront].p + f*pathNodes[nextPathNodeFront].p;
// And for another point 30 units in front of the plane, used to calculate roll
float pathPositionFront2 = pathPositionFront + 30.0f;
if(pathPositionFront2 > totalLengthOfFlightPath)
pathPositionFront2 -= totalLengthOfFlightPath;
int curPathNodeFront2 = m_nCurPathNode;
int nextPathNodeFront2 = curPathNodeFront2 + 1;
pos1 = pathNodes[curPathNodeFront2].t;
if(nextPathNodeFront2 < numPathNodes)
pos2 = pathNodes[nextPathNodeFront2].t;
else{
nextPathNodeFront2 = 0;
pos2 = totalLengthOfFlightPath;
}
while(pathPositionFront2 < pos1 || pathPositionFront2 > pos2){
curPathNodeFront2 = (curPathNodeFront2+1) % numPathNodes;
nextPathNodeFront2 = curPathNodeFront2 + 1;
pos1 = pathNodes[curPathNodeFront2].t;
if(nextPathNodeFront2 < numPathNodes)
pos2 = pathNodes[nextPathNodeFront2].t;
else{
nextPathNodeFront2 = 0;
pos2 = totalLengthOfFlightPath;
}
}
dist = pathNodes[nextPathNodeFront2].t - pathNodes[curPathNodeFront2].t;
if(dist < 0.0f)
dist += totalLengthOfFlightPath;
f = (pathPositionFront2 - pathNodes[curPathNodeFront2].t)/dist;
CVector posFront2 = (1.0f - f)*pathNodes[curPathNodeFront2].p + f*pathNodes[nextPathNodeFront2].p;
// Now set matrix
GetMatrix().SetTranslateOnly((posRear + posFront) / 2.0f);
GetMatrix().GetPosition().z += 1.0f;
CVector fwd = posFront - posRear;
fwd.Normalise();
CVector fwd2 = posFront2 - posRear;
fwd2.Normalise();
CVector roll = CrossProduct(fwd, fwd2);
CVector right = CrossProduct(fwd, CVector(0.0f, 0.0f, 1.0f));
right.z += 3.0f*roll.z;
right.Normalise();
CVector up = CrossProduct(right, fwd);
GetMatrix().GetRight() = right;
GetMatrix().GetUp() = up;
GetMatrix().GetForward() = fwd;
// Set speed
m_vecMoveSpeed = fwd*planePathSpeed/60.0f;
m_fSpeed = planePathSpeed/60.0f;
m_vecTurnSpeed = CVector(0.0f, 0.0f, 0.0f);
m_isFarAway = !((posFront - TheCamera.GetPosition()).MagnitudeSqr2D() < sq(300.0f));
}
}
bIsInSafePosition = true;
GetMatrix().UpdateRW();
UpdateRwFrame();
// Handle streaming and such
CVehicleModelInfo *mi = (CVehicleModelInfo*)CModelInfo::GetModelInfo(GetModelIndex());
if(m_isFarAway){
// Switch to LOD model
if(m_rwObject && RwObjectGetType(m_rwObject) == rpCLUMP){
DeleteRwObject();
if(mi->m_planeLodId != -1){
PUSH_MEMID(MEMID_WORLD);
m_rwObject = CModelInfo::GetModelInfo(mi->m_planeLodId)->CreateInstance();
POP_MEMID();
if(m_rwObject)
m_matrix.AttachRW(RwFrameGetMatrix(RpAtomicGetFrame((RpAtomic*)m_rwObject)));
}
}
}else if(CStreaming::HasModelLoaded(GetModelIndex())){
if(m_rwObject && RwObjectGetType(m_rwObject) == rpATOMIC){
// Get rid of LOD model
m_matrix.Detach();
if(m_rwObject){ // useless check
if(RwObjectGetType(m_rwObject) == rpATOMIC){ // useless check
RwFrame *f = RpAtomicGetFrame((RpAtomic*)m_rwObject);
RpAtomicDestroy((RpAtomic*)m_rwObject);
RwFrameDestroy(f);
}
m_rwObject = nil;
}
}
// Set high detail model
if(m_rwObject == nil){
int id = GetModelIndex();
m_modelIndex = -1;
SetModelIndex(id);
}
}else{
CStreaming::RequestModel(GetModelIndex(), STREAMFLAGS_DEPENDENCY);
}
}
void
CPlane::PreRender(void)
{
CVehicleModelInfo *mi = (CVehicleModelInfo*)CModelInfo::GetModelInfo(GetModelIndex());
CVector lookVector = GetPosition() - TheCamera.GetPosition();
float camDist = lookVector.Magnitude();
if(camDist != 0.0f)
lookVector *= 1.0f/camDist;
else
lookVector = CVector(1.0f, 0.0f, 0.0f);
float behindness = DotProduct(lookVector, GetForward());
// Wing lights
if(behindness < 0.0f){
// in front of plane
CVector lightPos = mi->m_positions[PLANE_POS_LIGHT_RIGHT];
CVector lightR = GetMatrix() * lightPos;
CVector lightL = lightR;
lightL -= GetRight()*2.0f*lightPos.x;
float intensity = -0.6f*behindness + 0.4f;
float size = 1.0f - behindness;
if(behindness < -0.9f && camDist < 50.0f){
// directly in front
CCoronas::RegisterCorona((uintptr)this + 10, 255*intensity, 255*intensity, 255*intensity, 255,
lightL, size, 240.0f,
CCoronas::TYPE_NORMAL, CCoronas::FLARE_HEADLIGHTS, CCoronas::REFLECTION_ON,
CCoronas::LOSCHECK_OFF, CCoronas::STREAK_ON, 0.0f);
CCoronas::RegisterCorona((uintptr)this + 11, 255*intensity, 255*intensity, 255*intensity, 255,
lightR, size, 240.0f,
CCoronas::TYPE_NORMAL, CCoronas::FLARE_HEADLIGHTS, CCoronas::REFLECTION_ON,
CCoronas::LOSCHECK_OFF, CCoronas::STREAK_ON, 0.0f);
}else{
CCoronas::RegisterCorona((uintptr)this + 10, 255*intensity, 255*intensity, 255*intensity, 255,
lightL, size, 240.0f,
CCoronas::TYPE_NORMAL, CCoronas::FLARE_NONE, CCoronas::REFLECTION_ON,
CCoronas::LOSCHECK_OFF, CCoronas::STREAK_ON, 0.0f);
CCoronas::RegisterCorona((uintptr)this + 11, 255*intensity, 255*intensity, 255*intensity, 255,
lightR, size, 240.0f,
CCoronas::TYPE_NORMAL, CCoronas::FLARE_NONE, CCoronas::REFLECTION_ON,
CCoronas::LOSCHECK_OFF, CCoronas::STREAK_ON, 0.0f);
}
}
// Tail light
if(CTimer::GetTimeInMilliseconds() & 0x200){
CVector pos = GetMatrix() * mi->m_positions[PLANE_POS_LIGHT_TAIL];
CCoronas::RegisterCorona((uintptr)this + 12, 255, 0, 0, 255,
pos, 1.0f, 120.0f,
CCoronas::TYPE_NORMAL, CCoronas::FLARE_NONE, CCoronas::REFLECTION_ON,
CCoronas::LOSCHECK_OFF, CCoronas::STREAK_ON, 0.0f);
}
}
void
CPlane::Render(void)
{
CEntity::Render();
}
#define CRUISE_SPEED (50.0f)
#define TAXI_SPEED (5.0f)
void
CPlane::InitPlanes(void)
{
int i;
CesnaMissionStatus = CESNA_STATUS_NONE;
// Jumbo
if(pPathNodes == nil){
pPathNodes = LoadPath("data\\paths\\flight.dat", NumPathNodes, TotalLengthOfFlightPath, true);
// Figure out which nodes are on ground
CColPoint colpoint;
CEntity *entity;
for(i = 0; i < NumPathNodes; i++){
if(CWorld::ProcessVerticalLine(pPathNodes[i].p, 1000.0f, colpoint, entity, true, false, false, false, true, false, nil)){
pPathNodes[i].p.z = colpoint.point.z;
pPathNodes[i].bOnGround = true;
}else
pPathNodes[i].bOnGround = false;
}
// Find lading and takeoff points
LandingPoint = -1.0f;
TakeOffPoint = -1.0f;
bool lastOnGround = pPathNodes[NumPathNodes-1].bOnGround;
for(i = 0; i < NumPathNodes; i++){
if(pPathNodes[i].bOnGround && !lastOnGround)
LandingPoint = pPathNodes[i].t;
else if(!pPathNodes[i].bOnGround && lastOnGround)
TakeOffPoint = pPathNodes[i].t;
lastOnGround = pPathNodes[i].bOnGround;
}
// Animation
float time = 0.0f;
float position = 0.0f;
// Start on ground with slow speed
aPlaneLineBits[0].type = 1;
aPlaneLineBits[0].time = time;
aPlaneLineBits[0].position = position;
aPlaneLineBits[0].speed = TAXI_SPEED;
aPlaneLineBits[0].acceleration = 0.0f;
float dist = (TakeOffPoint-600.0f) - position;
time += dist/TAXI_SPEED;
position += dist;
// Accelerate to take off
aPlaneLineBits[1].type = 2;
aPlaneLineBits[1].time = time;
aPlaneLineBits[1].position = position;
aPlaneLineBits[1].speed = TAXI_SPEED;
aPlaneLineBits[1].acceleration = 618.75f/600.0f;
time += 600.0f/((CRUISE_SPEED+TAXI_SPEED)/2.0f);
position += 600.0f;
// Fly at cruise speed
aPlaneLineBits[2].type = 1;
aPlaneLineBits[2].time = time;
aPlaneLineBits[2].position = position;
aPlaneLineBits[2].speed = CRUISE_SPEED;
aPlaneLineBits[2].acceleration = 0.0f;
dist = LandingPoint - TakeOffPoint;
time += dist/CRUISE_SPEED;
position += dist;
// Brake after landing
aPlaneLineBits[3].type = 2;
aPlaneLineBits[3].time = time;
aPlaneLineBits[3].position = position;
aPlaneLineBits[3].speed = CRUISE_SPEED;
aPlaneLineBits[3].acceleration = -618.75f/600.0f;
time += 600.0f/((CRUISE_SPEED+TAXI_SPEED)/2.0f);
position += 600.0f;
// Taxi
aPlaneLineBits[4].type = 1;
aPlaneLineBits[4].time = time;
aPlaneLineBits[4].position = position;
aPlaneLineBits[4].speed = TAXI_SPEED;
aPlaneLineBits[4].acceleration = 0.0f;
time += (TotalLengthOfFlightPath - position)/TAXI_SPEED;
// end
aPlaneLineBits[5].time = time;
TotalDurationOfFlightPath = time;
}
// Dodo
if(pPath2Nodes == nil){
pPath2Nodes = LoadPath("data\\paths\\flight2.dat", NumPath2Nodes, TotalLengthOfFlightPath2, true);
TotalDurationOfFlightPath2 = TotalLengthOfFlightPath2/CRUISE_SPEED;
}
// Mission Cesna
if(pPath3Nodes == nil){
pPath3Nodes = LoadPath("data\\paths\\flight3.dat", NumPath3Nodes, TotalLengthOfFlightPath3, false);
TotalDurationOfFlightPath3 = TotalLengthOfFlightPath3/CRUISE_SPEED;
}
// Mission Cesna
if(pPath4Nodes == nil){
pPath4Nodes = LoadPath("data\\paths\\flight4.dat", NumPath4Nodes, TotalLengthOfFlightPath4, false);
TotalDurationOfFlightPath4 = TotalLengthOfFlightPath4/CRUISE_SPEED;
}
CStreaming::LoadAllRequestedModels(false);
CStreaming::RequestModel(MI_AIRTRAIN, 0);
CStreaming::LoadAllRequestedModels(false);
for(i = 0; i < 3; i++){
CPlane *plane = new CPlane(MI_AIRTRAIN, PERMANENT_VEHICLE);
plane->GetMatrix().SetTranslate(0.0f, 0.0f, 0.0f);
plane->SetStatus(STATUS_ABANDONED);
plane->bIsLocked = true;
plane->m_nPlaneId = i;
plane->m_nCurPathNode = 0;
CWorld::Add(plane);
}
CStreaming::RequestModel(MI_DEADDODO, 0);
CStreaming::LoadAllRequestedModels(false);
for(i = 0; i < 3; i++){
CPlane *plane = new CPlane(MI_DEADDODO, PERMANENT_VEHICLE);
plane->GetMatrix().SetTranslate(0.0f, 0.0f, 0.0f);
plane->SetStatus(STATUS_ABANDONED);
plane->bIsLocked = true;
plane->m_nPlaneId = i;
plane->m_nCurPathNode = 0;
CWorld::Add(plane);
}
}
void
CPlane::Shutdown(void)
{
delete[] pPathNodes;
delete[] pPath2Nodes;
delete[] pPath3Nodes;
delete[] pPath4Nodes;
pPathNodes = nil;
pPath2Nodes = nil;
pPath3Nodes = nil;
pPath4Nodes = nil;
}
CPlaneNode*
CPlane::LoadPath(char const *filename, int32 &numNodes, float &totalLength, bool loop)
{
int bp, lp;
int i;
CFileMgr::LoadFile(filename, work_buff, sizeof(work_buff), "r");
*gString = '\0';
for(bp = 0, lp = 0; work_buff[bp] != '\n'; bp++, lp++)
gString[lp] = work_buff[bp];
bp++;
gString[lp] = '\0';
sscanf(gString, "%d", &numNodes);
CPlaneNode *nodes = new CPlaneNode[numNodes];
for(i = 0; i < numNodes; i++){
*gString = '\0';
for(lp = 0; work_buff[bp] != '\n'; bp++, lp++)
gString[lp] = work_buff[bp];
bp++;
// BUG: game doesn't terminate string
gString[lp] = '\0';
sscanf(gString, "%f %f %f", &nodes[i].p.x, &nodes[i].p.y, &nodes[i].p.z);
}
// Calculate length of segments and path
totalLength = 0.0f;
for(i = 0; i < numNodes; i++){
nodes[i].t = totalLength;
float l = (nodes[(i+1) % numNodes].p - nodes[i].p).Magnitude2D();
if(!loop && i == numNodes-1)
l = 0.0f;
totalLength += l;
}
return nodes;
}
void
CPlane::UpdatePlanes(void)
{
int i, j;
uint32 time;
float t, deltaT;
if(CReplay::IsPlayingBack())
return;
// Jumbo jets
time = CTimer::GetTimeInMilliseconds();
for(i = 0; i < 3; i++){
t = TotalDurationOfFlightPath * (float)(time & 0x7FFFF)/0x80000;
// find current frame
for(j = 0; t > aPlaneLineBits[j+1].time; j++);
OldPlanePathPosition[i] = PlanePathPosition[i];
deltaT = t - aPlaneLineBits[j].time;
switch(aPlaneLineBits[j].type){
case 0: // standing still
PlanePathPosition[i] = aPlaneLineBits[j].position;
PlanePathSpeed[i] = 0.0f;
break;
case 1: // moving with constant speed
PlanePathPosition[i] = aPlaneLineBits[j].position + aPlaneLineBits[j].speed*deltaT;
PlanePathSpeed[i] = (TotalDurationOfFlightPath*1000.0f/0x80000) * aPlaneLineBits[j].speed;
break;
case 2: // accelerating/braking
PlanePathPosition[i] = aPlaneLineBits[j].position + (aPlaneLineBits[j].speed + aPlaneLineBits[j].acceleration*deltaT)*deltaT;
PlanePathSpeed[i] = (TotalDurationOfFlightPath*1000.0f/0x80000)*aPlaneLineBits[j].speed + 2.0f*aPlaneLineBits[j].acceleration*deltaT;
break;
}
// time offset for each plane
time += 0x80000/3;
}
time = CTimer::GetTimeInMilliseconds();
t = TotalDurationOfFlightPath2/0x80000;
PlanePath2Position[0] = CRUISE_SPEED * (time & 0x7FFFF)*t;
PlanePath2Position[1] = CRUISE_SPEED * ((time + 0x80000/3) & 0x7FFFF)*t;
PlanePath2Position[2] = CRUISE_SPEED * ((time + 0x80000/3*2) & 0x7FFFF)*t;
PlanePath2Speed[0] = CRUISE_SPEED*t;
PlanePath2Speed[1] = CRUISE_SPEED*t;
PlanePath2Speed[2] = CRUISE_SPEED*t;
if(CesnaMissionStatus == CESNA_STATUS_FLYING){
PlanePath3Speed = CRUISE_SPEED*TotalDurationOfFlightPath3/0x20000;
PlanePath3Position = PlanePath3Speed * ((time - CesnaMissionStartTime) & 0x1FFFF);
if(time - CesnaMissionStartTime >= 128072)
CesnaMissionStatus = CESNA_STATUS_LANDED;
}
if(DropOffCesnaMissionStatus == CESNA_STATUS_FLYING){
PlanePath4Speed = CRUISE_SPEED*TotalDurationOfFlightPath4/0x80000;
PlanePath4Position = PlanePath4Speed * ((time - DropOffCesnaMissionStartTime) & 0x7FFFF);
if(time - DropOffCesnaMissionStartTime >= 521288)
DropOffCesnaMissionStatus = CESNA_STATUS_LANDED;
}
}
bool
CPlane::TestRocketCollision(CVector *rocketPos)
{
int i;
i = CPools::GetVehiclePool()->GetSize();
while(--i >= 0){
CPlane *plane = (CPlane*)CPools::GetVehiclePool()->GetSlot(i);
if(plane &&
#ifdef EXPLODING_AIRTRAIN
(plane->GetModelIndex() == MI_AIRTRAIN || plane->GetModelIndex() == MI_DEADDODO) &&
#else
plane->GetModelIndex() != MI_AIRTRAIN && plane->GetModelIndex() == MI_DEADDODO && // strange check
#endif
!plane->m_bHasBeenHit && (*rocketPos - plane->GetPosition()).Magnitude() < 25.0f){
plane->m_nFrameWhenHit = CTimer::GetFrameCounter();
plane->m_bHasBeenHit = true;
CWorld::Players[CWorld::PlayerInFocus].m_pPed->m_pWanted->RegisterCrime_Immediately(CRIME_DESTROYED_CESSNA,
plane->GetPosition(), i+1983, false);
return true;
}
}
return false;
}
// BUG: not in CPlane in the game
void
CPlane::CreateIncomingCesna(void)
{
if(CesnaMissionStatus == CESNA_STATUS_FLYING){
CWorld::Remove(pDrugRunCesna);
delete pDrugRunCesna;
pDrugRunCesna = nil;
}
pDrugRunCesna = new CPlane(MI_DEADDODO, PERMANENT_VEHICLE);
pDrugRunCesna->GetMatrix().SetTranslate(0.0f, 0.0f, 0.0f);
pDrugRunCesna->SetStatus(STATUS_ABANDONED);
pDrugRunCesna->bIsLocked = true;
pDrugRunCesna->m_nPlaneId = 0;
pDrugRunCesna->m_nCurPathNode = 0;
pDrugRunCesna->m_bIsDrugRunCesna = true;
CWorld::Add(pDrugRunCesna);
CesnaMissionStatus = CESNA_STATUS_FLYING;
CesnaMissionStartTime = CTimer::GetTimeInMilliseconds();
printf("CPlane::CreateIncomingCesna(void)\n");
}
void
CPlane::CreateDropOffCesna(void)
{
if(DropOffCesnaMissionStatus == CESNA_STATUS_FLYING){
CWorld::Remove(pDropOffCesna);
delete pDropOffCesna;
pDropOffCesna = nil;
}
pDropOffCesna = new CPlane(MI_DEADDODO, PERMANENT_VEHICLE);
pDropOffCesna->GetMatrix().SetTranslate(0.0f, 0.0f, 0.0f);
pDropOffCesna->SetStatus(STATUS_ABANDONED);
pDropOffCesna->bIsLocked = true;
pDropOffCesna->m_nPlaneId = 0;
pDropOffCesna->m_nCurPathNode = 0;
pDropOffCesna->m_bIsDropOffCesna = true;
CWorld::Add(pDropOffCesna);
DropOffCesnaMissionStatus = CESNA_STATUS_FLYING;
DropOffCesnaMissionStartTime = CTimer::GetTimeInMilliseconds();
printf("CPlane::CreateDropOffCesna(void)\n");
}
const CVector CPlane::FindDrugPlaneCoordinates(void) { return pDrugRunCesna->GetPosition(); }
const CVector CPlane::FindDropOffCesnaCoordinates(void) { return pDropOffCesna->GetPosition(); }
bool CPlane::HasCesnaLanded(void) { return CesnaMissionStatus == CESNA_STATUS_LANDED; }
bool CPlane::HasCesnaBeenDestroyed(void) { return CesnaMissionStatus == CESNA_STATUS_DESTROYED; }
bool CPlane::HasDropOffCesnaBeenShotDown(void) { return DropOffCesnaMissionStatus == CESNA_STATUS_DESTROYED; }
| 32.33709 | 136 | 0.701784 | gameblabla |
532cd22b5c3fc5703751081b99b23a3b37cd742d | 503 | cpp | C++ | src/MageFramework/Vulkan/RendererBackend/vAccelerationStructure.cpp | AmanSachan1/ShaderPlayGround | aba8293404bcba7ecad2a97c86c8aea7d0693945 | [
"MIT"
] | 2 | 2019-12-04T17:06:44.000Z | 2019-12-24T16:33:37.000Z | src/MageFramework/Vulkan/RendererBackend/vAccelerationStructure.cpp | AmanSachan1/GraphicsPlayground | aba8293404bcba7ecad2a97c86c8aea7d0693945 | [
"MIT"
] | null | null | null | src/MageFramework/Vulkan/RendererBackend/vAccelerationStructure.cpp | AmanSachan1/GraphicsPlayground | aba8293404bcba7ecad2a97c86c8aea7d0693945 | [
"MIT"
] | null | null | null | #include "Vulkan/RendererBackend/vAccelerationStructure.h"
#include <Vulkan/Utilities/vAccelerationStructureUtil.h>
void vBLAS::generateBLAS(VkCommandBuffer commandBuffer,
mageVKBuffer& scratchBuffer, VkDeviceSize scratchOffset,
bool updateOnly) const
{
const VkAccelerationStructureNV previousStructure = updateOnly ? m_accelerationStructure : nullptr;
}
void vTLAS::generateTLAS(VkCommandBuffer commandBuffer,
mageVKBuffer& scratchBuffer, VkDeviceSize scratchOffset,
bool updateOnly) const
{
} | 31.4375 | 100 | 0.840954 | AmanSachan1 |
532d377395f6bef19fc6b88303fa8d4b7daa55ee | 116 | cpp | C++ | src/cpu/tms9900/tms9995.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 145 | 2018-04-10T17:24:39.000Z | 2022-03-27T17:39:03.000Z | src/cpu/tms9900/tms9995.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 779 | 2018-04-09T21:30:15.000Z | 2022-03-31T06:38:07.000Z | src/cpu/tms9900/tms9995.cpp | gameblabla/mame_nspire | 83dfe1606aba906bd28608f2cb8f0754492ac3da | [
"Unlicense"
] | 152 | 2018-04-10T10:52:18.000Z | 2022-03-09T08:24:16.000Z | /*
generate the tms9995 emulator
*/
#include "tms9900.h"
#define TMS99XX_MODEL TMS9995_ID
#include "99xxcore.h"
| 11.6 | 32 | 0.741379 | gameblabla |
53327b456447c6c5ff086262ab9c12fb0d5f14f9 | 1,965 | cpp | C++ | src/test/test_utils.cpp | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | 3 | 2021-09-08T07:28:13.000Z | 2022-03-02T21:12:40.000Z | src/test/test_utils.cpp | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | 1 | 2021-09-21T14:40:55.000Z | 2021-09-26T01:19:38.000Z | src/test/test_utils.cpp | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | null | null | null | //
// Created by James Noeckel on 4/7/20.
//
#include <iostream>
#include "utils/top_k_indices.hpp"
#include "utils/sorted_data_structures.hpp"
int main(int argc, char **argv) {
bool passed = true;
{
std::vector<int> sorted_vec;
sorted_insert(sorted_vec, 0);
sorted_insert(sorted_vec, 0);
sorted_insert(sorted_vec, 0);
sorted_insert(sorted_vec, 99);
sorted_insert(sorted_vec, 99);
sorted_insert(sorted_vec, 0);
sorted_insert(sorted_vec, 3);
passed = passed && sorted_vec.size() == 3 && sorted_vec[0] == 0 && sorted_vec[1] == 3 && sorted_vec[2] == 99
&& &(*sorted_find(sorted_vec, 99)) == &sorted_vec[2] && sorted_contains(sorted_vec, 3);
}
{
std::vector<std::pair<int, int>> sorted_map;
sorted_insert(sorted_map, 0, 9);
sorted_insert(sorted_map, 4, 99);
sorted_insert(sorted_map, 86, 999);
sorted_insert(sorted_map, 4, 98);
sorted_get(sorted_map, 86) = 998;
for (const auto &pair : sorted_map) {
std::cout << '(' << pair.first << ", " << pair.second << ") ";
}
std::cout << std::endl;
passed = passed && sorted_map.size() == 3 && sorted_get(sorted_map, 4) == 99 &&
sorted_get(sorted_map, 0) == 9 &&
sorted_get(sorted_map, 86) == 998 &&
sorted_find(sorted_map, 666) == sorted_map.end() &&
sorted_find(sorted_map, 0)->second == 9;
}
{
std::vector<int> values = {-1, 8, 4, 99};
std::vector<size_t> indices = top_k_indices(values.begin(), values.end(), 3);
passed = passed && indices.size() == 3 && indices[0] == 3 && indices[1] == 1 && indices[2] == 2;
std::vector<size_t> indices2 = top_k_indices(values.begin(), values.end(), 2, std::greater<>());
passed = passed && indices2.size() == 2 && indices2[0] == 0 && indices2[1] == 2;
}
return !passed;
} | 40.9375 | 116 | 0.561832 | ShnitzelKiller |
5335fbf56bc6ff0746bf13c3f4f09f653da58c71 | 347 | cc | C++ | dreal/util/precision_guard.cc | soonho-tri/dreal4 | e774d1496001e826c82dccee45094dd694089bee | [
"Apache-2.0"
] | null | null | null | dreal/util/precision_guard.cc | soonho-tri/dreal4 | e774d1496001e826c82dccee45094dd694089bee | [
"Apache-2.0"
] | 1 | 2018-01-19T16:11:44.000Z | 2018-01-19T16:11:44.000Z | dreal/util/precision_guard.cc | soonho-tri/dreal4 | e774d1496001e826c82dccee45094dd694089bee | [
"Apache-2.0"
] | null | null | null | #include "dreal/util/precision_guard.h"
namespace dreal {
PrecisionGuard::PrecisionGuard(std::ostream* os,
const std::streamsize precision)
: os_{os}, old_precision_(os->precision()) {
os_->precision(precision);
}
PrecisionGuard::~PrecisionGuard() { os_->precision(old_precision_); }
} // namespace dreal
| 24.785714 | 69 | 0.668588 | soonho-tri |
533c9c4ecdbdc99bc55d94df5c363119491a63bc | 7,874 | cc | C++ | code/Samples/ResourceStress/ResourceStress.cc | infancy/oryol | 06b580116cc2e929b9e1a85920a74fb32d76493c | [
"MIT"
] | 1,707 | 2015-01-01T14:56:08.000Z | 2022-03-28T06:44:09.000Z | code/Samples/ResourceStress/ResourceStress.cc | infancy/oryol | 06b580116cc2e929b9e1a85920a74fb32d76493c | [
"MIT"
] | 256 | 2015-01-03T14:55:53.000Z | 2020-09-09T10:43:46.000Z | code/Samples/ResourceStress/ResourceStress.cc | infancy/oryol | 06b580116cc2e929b9e1a85920a74fb32d76493c | [
"MIT"
] | 222 | 2015-01-05T00:20:54.000Z | 2022-02-06T01:41:37.000Z | //------------------------------------------------------------------------------
// ResourceStress.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/Main.h"
#include "IO/IO.h"
#include "Gfx/Gfx.h"
#include "Dbg/Dbg.h"
#include "HttpFS/HTTPFileSystem.h"
#include "Assets/Gfx/ShapeBuilder.h"
#include "Assets/Gfx/TextureLoader.h"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/random.hpp"
#include "shaders.h"
using namespace Oryol;
class ResourceStressApp : public App {
public:
AppState::Code OnInit();
AppState::Code OnRunning();
AppState::Code OnCleanup();
void createObjects();
void updateObjects();
void showInfo();
struct Object {
DrawState drawState;
ResourceLabel label;
glm::mat4 modelTransform;
};
glm::mat4 computeMVP(const Object& obj);
static const int MaxNumObjects = 1024;
uint32_t frameCount = 0;
Id shader;
Array<Object> objects;
glm::mat4 view;
glm::mat4 proj;
TextureSetup texBlueprint;
};
OryolMain(ResourceStressApp);
//------------------------------------------------------------------------------
AppState::Code
ResourceStressApp::OnInit() {
// setup IO system
IOSetup ioSetup;
ioSetup.FileSystems.Add("http", HTTPFileSystem::Creator());
ioSetup.Assigns.Add("tex:", ORYOL_SAMPLE_URL);
IO::Setup(ioSetup);
// setup Gfx system
auto gfxSetup = GfxSetup::Window(600, 400, "Oryol Resource Stress Test");
gfxSetup.DefaultPassAction = PassAction::Clear(glm::vec4(0.5f, 0.5f, 0.5f, 1.0f));
gfxSetup.ResourcePoolSize[GfxResourceType::Mesh] = MaxNumObjects + 32;
gfxSetup.ResourcePoolSize[GfxResourceType::Texture] = MaxNumObjects + 32;
gfxSetup.ResourcePoolSize[GfxResourceType::Pipeline] = MaxNumObjects + 32;
gfxSetup.ResourcePoolSize[GfxResourceType::Shader] = 4;
Gfx::Setup(gfxSetup);
// setup debug text rendering
Dbg::Setup();
// setup the shader that is used by all objects
this->shader = Gfx::CreateResource(Shader::Setup());
// setup matrices
const float fbWidth = (const float) Gfx::DisplayAttrs().FramebufferWidth;
const float fbHeight = (const float) Gfx::DisplayAttrs().FramebufferHeight;
this->proj = glm::perspectiveFov(glm::radians(45.0f), fbWidth, fbHeight, 0.01f, 100.0f);
this->view = glm::mat4();
this->texBlueprint.Sampler.MinFilter = TextureFilterMode::LinearMipmapLinear;
this->texBlueprint.Sampler.MagFilter = TextureFilterMode::Linear;
this->texBlueprint.Sampler.WrapU = TextureWrapMode::ClampToEdge;
this->texBlueprint.Sampler.WrapV = TextureWrapMode::ClampToEdge;
return App::OnInit();
}
//------------------------------------------------------------------------------
AppState::Code
ResourceStressApp::OnRunning() {
// delete and create objects
this->frameCount++;
this->updateObjects();
this->createObjects();
this->showInfo();
Gfx::BeginPass();
for (const auto& obj : this->objects) {
// only render objects that have successfully loaded
const Id& tex = obj.drawState.FSTexture[Shader::tex];
if (Gfx::QueryResourceInfo(tex).State == ResourceState::Valid) {
Gfx::ApplyDrawState(obj.drawState);
Shader::vsParams vsParams;
vsParams.mvp = this->proj * this->view * obj.modelTransform;
Gfx::ApplyUniformBlock(vsParams);
Gfx::Draw();
}
}
Dbg::DrawTextBuffer();
Gfx::EndPass();
Gfx::CommitFrame();
// quit or keep running?
return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}
//------------------------------------------------------------------------------
AppState::Code
ResourceStressApp::OnCleanup() {
Dbg::Discard();
Gfx::Discard();
IO::Discard();
return App::OnCleanup();
}
//------------------------------------------------------------------------------
void
ResourceStressApp::createObjects() {
if (this->objects.Size() >= MaxNumObjects) {
return;
}
if (Gfx::QueryFreeResourceSlots(GfxResourceType::Mesh) == 0) {
return;
}
if (Gfx::QueryFreeResourceSlots(GfxResourceType::Texture) == 0) {
return;
}
// create a cube object
// NOTE: we're deliberatly not sharing resources to actually
// put some stress on the resource system
Object obj;
obj.label = Gfx::PushResourceLabel();
ShapeBuilder shapeBuilder;
shapeBuilder.Layout = {
{ VertexAttr::Position, VertexFormat::Float3 },
{ VertexAttr::TexCoord0, VertexFormat::Float2 }
};
shapeBuilder.Box(0.1f, 0.1f, 0.1f, 1);
obj.drawState.Mesh[0] = Gfx::CreateResource(shapeBuilder.Build());
auto ps = PipelineSetup::FromLayoutAndShader(shapeBuilder.Layout, this->shader);
obj.drawState.Pipeline = Gfx::CreateResource(ps);
obj.drawState.FSTexture[Shader::tex] = Gfx::LoadResource(TextureLoader::Create(
TextureSetup::FromFile(Locator::NonShared("tex:lok_dxt1.dds"), this->texBlueprint)));
glm::vec3 pos = glm::ballRand(2.0f) + glm::vec3(0.0f, 0.0f, -6.0f);
obj.modelTransform = glm::translate(glm::mat4(), pos);
this->objects.Add(obj);
Gfx::PopResourceLabel();
}
//------------------------------------------------------------------------------
void
ResourceStressApp::updateObjects() {
for (int i = this->objects.Size() - 1; i >= 0; i--) {
Object& obj = this->objects[i];
// check if object should be destroyed (it will be
// destroyed after the texture object had been valid for
// at least 3 seconds, or if it failed to load)
const Id& tex = obj.drawState.FSTexture[Shader::tex];
const auto info = Gfx::QueryResourceInfo(tex);
if ((info.State == ResourceState::Failed) ||
((info.State == ResourceState::Valid) && (info.StateAge > (20 * 60)))) {
Gfx::DestroyResources(obj.label);
this->objects.Erase(i);
}
}
}
//------------------------------------------------------------------------------
void
ResourceStressApp::showInfo() {
ResourcePoolInfo texPoolInfo = Gfx::QueryResourcePoolInfo(GfxResourceType::Texture);
ResourcePoolInfo mshPoolInfo = Gfx::QueryResourcePoolInfo(GfxResourceType::Mesh);
Dbg::PrintF("texture pool\r\n"
" num slots: %d, free: %d, used: %d\r\n"
" by state:\r\n"
" initial: %d\r\n"
" setup: %d\r\n"
" pending: %d\r\n"
" valid: %d\r\n"
" failed: %d\r\n\n",
texPoolInfo.NumSlots, texPoolInfo.NumFreeSlots, texPoolInfo.NumUsedSlots,
texPoolInfo.NumSlotsByState[ResourceState::Initial],
texPoolInfo.NumSlotsByState[ResourceState::Setup],
texPoolInfo.NumSlotsByState[ResourceState::Pending],
texPoolInfo.NumSlotsByState[ResourceState::Valid],
texPoolInfo.NumSlotsByState[ResourceState::Failed]);
Dbg::PrintF("mesh pool\r\n"
" num slots: %d, free: %d, used: %d\r\n"
" by state:\r\n"
" initial: %d\r\n"
" setup: %d\r\n"
" pending: %d\r\n"
" valid: %d\r\n"
" failed: %d",
mshPoolInfo.NumSlots, mshPoolInfo.NumFreeSlots, mshPoolInfo.NumUsedSlots,
mshPoolInfo.NumSlotsByState[ResourceState::Initial],
mshPoolInfo.NumSlotsByState[ResourceState::Setup],
mshPoolInfo.NumSlotsByState[ResourceState::Pending],
mshPoolInfo.NumSlotsByState[ResourceState::Valid],
mshPoolInfo.NumSlotsByState[ResourceState::Failed]);
}
| 36.623256 | 93 | 0.578613 | infancy |
5340412ccab57648a683999611fdee489474ea5c | 21,781 | cpp | C++ | cpp/src/datacentric/dc/platform/data_source/mongo/temporal_mongo_data_source.cpp | datacentricorg/datacentric-cpp | 252f642b1a81c2475050d48e9564eec0a561907e | [
"Apache-2.0"
] | 2 | 2019-08-08T01:29:02.000Z | 2019-08-18T19:19:00.000Z | cpp/src/datacentric/dc/platform/data_source/mongo/temporal_mongo_data_source.cpp | datacentricorg/datacentric-cpp | 252f642b1a81c2475050d48e9564eec0a561907e | [
"Apache-2.0"
] | null | null | null | cpp/src/datacentric/dc/platform/data_source/mongo/temporal_mongo_data_source.cpp | datacentricorg/datacentric-cpp | 252f642b1a81c2475050d48e9564eec0a561907e | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2013-present The DataCentric Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <dc/precompiled.hpp>
#include <dc/implement.hpp>
#include <dc/platform/data_source/mongo/temporal_mongo_data_source.hpp>
#include <dc/platform/context/context_base.hpp>
#include <dc/types/record/deleted_record.hpp>
#include <dc/types/record/data_type_info.hpp>
#include <dc/attributes/class/index_elements_attribute.hpp>
#include <dot/mongo/mongo_db/mongo/collection.hpp>
#include <dc/platform/data_source/mongo/temporal_mongo_query.hpp>
namespace dc
{
Record TemporalMongoDataSourceImpl::load_or_null(TemporalId id, dot::Type data_type)
{
if (cutoff_time != nullptr)
{
// If revision_time_constraint is not null, return null for any
// id that is not strictly before the constraint TemporalId
if (id >= cutoff_time.value()) return nullptr;
}
dot::Query query = dot::make_query(get_or_create_collection(data_type), data_type);
dot::ObjectCursorWrapperBase cursor = query->where(new dot::OperatorWrapperImpl("_id", "$eq", id))
->limit(1)
->get_cursor();
if (cursor->begin() != cursor->end())
{
dot::Object obj = *(cursor->begin());
if (!obj.is<DeletedRecord>())
{
Record rec = obj.as<Record>();
if (!data_type->is_assignable_from(rec->get_type()))
{
// If cast result is null, the record was found but it is an instance
// of class that is not derived from TRecord, in this case the API
// requires error message, not returning null
throw dot::Exception(dot::String::format(
"Stored Type {0} for TemporalId={1} and "
"Key={2} is not an instance of the requested Type {3}.", rec->get_type()->name(),
id.to_string(), rec->get_key(), data_type->name()
));
}
// Now we use get_cutoff_time() for the full check
dot::Nullable<TemporalId> cutoff_time = get_cutoff_time(rec->data_set);
if (cutoff_time != nullptr)
{
// Return null for any record that has TemporalId
// that is greater than or equal to cutoff_time.
if (id >= cutoff_time.value()) return nullptr;
}
rec->init(context);
return rec;
}
}
return nullptr;
}
Record TemporalMongoDataSourceImpl::load_or_null(Key key, TemporalId load_from)
{
// dot::String key in semicolon delimited format used in the lookup
dot::String key_value = key->to_string();
dot::Type record_type = dot::typeof<Record>();
dot::Query base_query = dot::make_query(get_or_create_collection(key->get_type()), key->get_type())
->where(new dot::OperatorWrapperImpl("_key", "$eq", key_value))
;
dot::Query query_with_final_constraints = apply_final_constraints(base_query, load_from);
dot::ObjectCursorWrapperBase cursor = query_with_final_constraints
->sort_by_descending(record_type->get_field("_dataset"))
->then_by_descending(record_type->get_field("_id"))
->limit(1)
->get_cursor();
if (cursor->begin() != cursor->end())
{
dot::Object obj = *(cursor->begin());
if (!obj.is<DeletedRecord>())
{
Record rec = obj.as<Record>();
rec->init(context);
return rec;
}
}
return nullptr;
}
void TemporalMongoDataSourceImpl::save_many(dot::List<Record> records, TemporalId save_to)
{
check_not_read_only(save_to);
auto collection = get_or_create_collection(records[0]->get_type());
// Iterate over list elements to populate fields
for(Record rec : records)
{
// This method guarantees that TemporalIds will be in strictly increasing
// order for this instance of the data source class always, and across
// all processes and machine if they are not created within the same
// second.
TemporalId object_id = create_ordered_object_id();
// TemporalId of the record must be strictly later
// than TemporalId of the dataset where it is stored
if (object_id <= save_to)
throw dot::Exception(dot::String::format(
"Attempting to save a record with TemporalId={0} that is later "
"than TemporalId={1} of the dataset where it is being saved.", object_id.to_string(), save_to.to_string()));
// Assign ID and DataSet, and only then initialize, because
// initialization code may use record.ID and record.DataSet
rec->id = object_id;
rec->data_set = save_to;
rec->init(context);
}
collection->insert_many(records);
}
TemporalMongoQuery TemporalMongoDataSourceImpl::get_query(TemporalId data_set, dot::Type type)
{
return make_temporal_mongo_query(get_or_create_collection(type), type, this, data_set);
}
void TemporalMongoDataSourceImpl::delete_record(Key key, TemporalId delete_in)
{
check_not_read_only(delete_in);
dot::Collection collection = get_or_create_collection(key->get_type());
DeletedRecord record = make_deleted_record(key);
TemporalId object_id = create_ordered_object_id();
// TemporalId of the record must be strictly later
// than TemporalId of the dataset where it is stored
if (object_id <= delete_in)
throw dot::Exception(dot::String::format(
"Attempting to save a record with TemporalId={0} that is later "
"than TemporalId={1} of the dataset where it is being saved.", object_id.to_string(), delete_in.to_string()));
// Assign id and data_set, and only then initialize, because
// initialization code may use record.id and record.data_set
record->id = object_id;
record->data_set = delete_in;
collection->insert_one(record);
}
dot::Query TemporalMongoDataSourceImpl::apply_final_constraints(dot::Query query, TemporalId load_from)
{
// Get lookup list by expanding the list of imports to arbitrary
// depth with duplicates and cyclic references removed.
//
// The list will not include datasets that are after the value of
// CutoffTime if specified, or their imports (including
// even those imports that are earlier than the constraint).
dot::HashSet<TemporalId> lookup_set = get_data_set_lookup_list(load_from);
dot::List<TemporalId> lookup_list = dot::make_list<TemporalId>(std::vector<TemporalId>(lookup_set->begin(), lookup_set->end()));
// Apply constraint that the value is _dataset is
// one of the elements of dataSetLookupList_
dot::Query result = query->where(new dot::OperatorWrapperImpl("_dataset", "$in", lookup_list));
// Apply revision time constraint. By making this constraint the
// last among the constraints, we optimize the use of the index.
//
// The property savedBy_ is set using either CutoffTime element.
// Only one of these two elements can be set at a given time.
dot::Nullable<TemporalId> cutoff_time = get_cutoff_time(load_from);
if (cutoff_time != nullptr)
{
result = result->where(new dot::OperatorWrapperImpl("_id", "$lt", cutoff_time.value()));
}
return result;
}
dot::Nullable<TemporalId> TemporalMongoDataSourceImpl::get_data_set_or_empty(dot::String data_set_name, TemporalId load_from)
{
TemporalId result;
if (data_set_dict_->try_get_value(data_set_name, result))
{
// Check if already cached, return if found
return result;
}
else
{
// Otherwise load from storage (this also updates the dictionaries)
DataSetKey data_set_key = make_data_set_key();
data_set_key->data_set_name = data_set_name;
DataSet data_set_data = (dc::DataSet)load_or_null(data_set_key, load_from);
// If not found, return TemporalId.Empty
if (data_set_data == nullptr) return nullptr;
// Get or create dataset detail record
DataSetDetailKey data_set_detail_key = make_data_set_detail_key();
data_set_detail_key->data_set_id = data_set_data->id;
DataSetDetail data_set_detail_data = (dc::DataSetDetail)load_or_null(data_set_detail_key, load_from);
if (data_set_detail_data == nullptr)
{
data_set_detail_data = make_data_set_detail_data();
data_set_detail_key->data_set_id = data_set_data->id;
context.lock()->save_one(data_set_detail_data, load_from);
}
// Cache TemporalId for the dataset and its parent
data_set_dict_[data_set_name] = data_set_data->id;
data_set_owners_dict_[data_set_data->id] = data_set_data->data_set;
dot::HashSet<TemporalId> import_set;
// Build and cache dataset lookup list if not found
if (!data_set_parent_dict_->try_get_value(data_set_data->id, import_set))
{
import_set = build_data_set_lookup_list(data_set_data);
data_set_parent_dict_->add(data_set_data->id, import_set);
}
return data_set_data->id;
}
}
void TemporalMongoDataSourceImpl::save_data_set(DataSet data_set_data, TemporalId save_to)
{
// Save dataset to storage. This updates its Id
// to the new TemporalId created during save
context.lock()->save_one(data_set_data, save_to);
// Cache TemporalId for the dataset and its parent
data_set_dict_[data_set_data->get_key()] = data_set_data->id;
data_set_owners_dict_[data_set_data->id] = data_set_data->data_set;
// Update lookup list dictionary
dot::HashSet<TemporalId> lookup_list = build_data_set_lookup_list(data_set_data);
data_set_parent_dict_->add(data_set_data->id, lookup_list);
}
dot::HashSet<TemporalId> TemporalMongoDataSourceImpl::get_data_set_lookup_list(TemporalId load_from)
{
dot::HashSet<TemporalId> result;
// Root dataset has no imports (there is not even a record
// where these imports can be specified).
//
// Return list containing only the root dataset (TemporalId.Empty) and exit
if (load_from == TemporalId::empty)
{
result = dot::make_hash_set<TemporalId>();
result->add(TemporalId::empty);
return result;
}
if (data_set_parent_dict_->try_get_value(load_from, result))
{
// Check if the lookup list is already cached, return if yes
return result;
}
else
{
// Otherwise load from storage (returns null if not found)
DataSet data_set_data = (dc::DataSet)load_or_null(load_from, dot::typeof<dc::DataSet>());
if (data_set_data == nullptr) throw dot::Exception(dot::String::format("Dataset with TemporalId={0} is not found.", load_from.to_string()));
if (data_set_data->data_set != TemporalId::empty) throw dot::Exception(dot::String::format("Dataset with TemporalId={0} is not stored in root dataset.", load_from.to_string()));
// Build the lookup list
result = build_data_set_lookup_list(data_set_data);
// Add to dictionary and return
data_set_parent_dict_->add(load_from, result);
return result;
}
}
DataSetDetail TemporalMongoDataSourceImpl::get_data_set_detail_or_empty(TemporalId detail_for)
{
DataSetDetail result;
if (detail_for == TemporalId::empty)
{
// Root dataset does not have details
// as it has no parent where the details
// would be stored, and storing details
// in the dataset itself would subject
// them to their own settings.
//
// Accordingly, return null.
return nullptr;
}
else if (data_set_detail_dict_->try_get_value(detail_for, result))
{
// Check if already cached, return if found
return result;
}
else
{
// Get dataset parent from the dictionary.
// We should not get here unless the value
// is already cached.
TemporalId parent_id = data_set_owners_dict_[detail_for];
// Otherwise try loading from storage (this also updates the dictionaries)
DataSetDetailKey data_set_detail_key = make_data_set_detail_key();
data_set_detail_key->data_set_id = detail_for;
result = (DataSetDetail)load_or_null(data_set_detail_key, parent_id);
// Cache in dictionary even if null
data_set_detail_dict_[detail_for] = result;
return result;
}
}
dot::Nullable<TemporalId> TemporalMongoDataSourceImpl::get_cutoff_time(TemporalId data_set_id)
{
// Get imports cutoff time for the dataset detail record.
// If the record is not found, consider its CutoffTime null.
DataSetDetail data_set_detail_data = get_data_set_detail_or_empty(data_set_id);
dot::Nullable<TemporalId> data_set_cutoff_time = data_set_detail_data != nullptr ? data_set_detail_data->cutoff_time : nullptr;
// If CutoffTime is set for both data source and dataset,
// this method returns the earlier of the two values.
dot::Nullable<TemporalId> result = TemporalId::min(cutoff_time, data_set_cutoff_time);
return result;
}
dot::Nullable<TemporalId> TemporalMongoDataSourceImpl::get_imports_cutoff_time(TemporalId data_set_id)
{
// Get dataset detail record
DataSetDetail data_set_detail_data = get_data_set_detail_or_empty(data_set_id);
// Return null if the record is not found
if (data_set_detail_data != nullptr) return data_set_detail_data->imports_cutoff_time;
else return nullptr;
}
dot::Collection TemporalMongoDataSourceImpl::get_or_create_collection(dot::Type data_type)
{
// Check if collection Object has already been cached
// for this type and return cached result if found
dot::Object collection_obj;
if (collection_dict_->try_get_value(data_type, collection_obj))
{
dot::Collection cached_result = collection_obj.as<dot::Collection>();
return cached_result;
}
// Collection name is root class name of the record without prefix
dot::String collection_name = DataTypeInfoImpl::get_or_create(data_type)->get_collection_name();
// Get interfaces to base and typed collections for the same name
dot::Collection typed_collection = db_->get_collection(collection_name);
//--- Load standard index types
// Each data type has an index for optimized loading by key.
// This index consists of Key in ascending order, followed by
// DataSet and ID in descending order.
dot::List<std::tuple<dot::String, int>> load_index_keys = dot::make_list<std::tuple<dot::String, int>>();
load_index_keys->add({ "_key", 1 }); // .key
load_index_keys->add({ "_dataset", -1 }); // .data_set
load_index_keys->add({ "_id", -1 }); // .id
// Use index definition convention to specify the index name
dot::String load_index_name = "Key-DataSet-Id";
dot::IndexOptions load_index_options = dot::make_index_options();
load_index_options->name = load_index_name;
typed_collection->create_index(load_index_keys, load_index_options);
//--- Load custom index types
// Additional indices are provided using IndexAttribute for the class.
// Get a sorted dictionary of (definition, name) pairs
// for the inheritance chain of the specified type.
dot::Dictionary<dot::String, dot::String> index_dict = IndexElementsAttributeImpl::get_attributes_dict(data_type);
// Iterate over the dictionary to define the index
for (auto index_info : index_dict)
{
dot::String index_definition = index_info.first;
dot::String index_name = index_info.second;
// Parse index definition to get a list of (ElementName,SortOrder) tuples
dot::List<std::tuple<dot::String, int>> index_tokens = IndexElementsAttributeImpl::parse_definition(index_definition, data_type);
if (index_name == nullptr) throw dot::Exception("Index name cannot be null.");
// Add to indexes for the collection
dot::IndexOptions index_opt = dot::make_index_options();
index_opt->name = index_name;
typed_collection->create_index(index_tokens, index_opt);
}
// Add the result to the collection dictionary and return
collection_dict_->add(data_type, typed_collection);
return typed_collection;
}
dot::HashSet<TemporalId> TemporalMongoDataSourceImpl::build_data_set_lookup_list(DataSet data_set_data)
{
// Delegate to the second overload
dot::HashSet<TemporalId> result = dot::make_hash_set<TemporalId>();
build_data_set_lookup_list(data_set_data, result);
return result;
}
void TemporalMongoDataSourceImpl::build_data_set_lookup_list(DataSet data_set_data, dot::HashSet<TemporalId> result)
{
// Return if the dataset is null or has no imports
if (data_set_data == nullptr) return;
// Error message if dataset has no Id or Key set
if (data_set_data->id.is_empty())
throw dot::Exception("Required TemporalId value is not set.");
if (data_set_data->get_key().is_empty())
throw dot::Exception("Required String value is not set.");
dot::Nullable<TemporalId> cutoff_time = get_cutoff_time(data_set_data->data_set);
if (cutoff_time != nullptr && data_set_data->id >= cutoff_time.value())
{
// Do not add if revision time constraint is set and is before this dataset.
// In this case the import datasets should not be added either, even if they
// do not fail the revision time constraint
return;
}
// Add self to the result
result->add(data_set_data->id);
// Add imports to the result
if (data_set_data->imports != nullptr)
{
for (TemporalId data_set_id : data_set_data->imports)
{
// Dataset cannot include itself as its import
if (data_set_data->id == data_set_id)
throw dot::Exception(dot::String::format(
"Dataset {0} with TemporalId={1} includes itself in the list of its imports."
, data_set_data->get_key(), data_set_data->id.to_string()));
if (!result->contains(data_set_id))
{
result->add(data_set_id);
// Add recursively if not already present in the hashset
dot::HashSet<TemporalId> cached_import_list = get_data_set_lookup_list(data_set_id);
for (TemporalId import_id : cached_import_list)
{
result->add(import_id);
}
}
}
}
}
void TemporalMongoDataSourceImpl::check_not_read_only(TemporalId data_set_id)
{
if (read_only)
throw dot::Exception(dot::String::format(
"Attempting write operation for data source {0} where ReadOnly flag is set.", data_source_name));
DataSetDetail data_set_detail_data = get_data_set_detail_or_empty(data_set_id);
if (data_set_detail_data != nullptr && data_set_detail_data->read_only.has_value() && data_set_detail_data->read_only.value())
throw dot::Exception(dot::String::format(
"Attempting write operation for dataset {0} where ReadOnly flag is set.", data_set_id.to_string()));
if (cutoff_time != nullptr)
throw dot::Exception(dot::String::format(
"Attempting write operation for data source {0} where "
"cutoff_time is set. Historical view of the data cannot be written to.", data_source_name));
if (data_set_detail_data != nullptr && data_set_detail_data->cutoff_time != nullptr)
throw dot::Exception(dot::String::format(
"Attempting write operation for the dataset {0} where "
"CutoffTime is set. Historical view of the data cannot be written to.", data_set_id.to_string()));
}
}
| 43.130693 | 189 | 0.635003 | datacentricorg |
c7282262fd465904e45bed337de6db02e61c8422 | 2,754 | cpp | C++ | BAI_12.cpp | anhtuanptit97/anhtuan | 5b1d49cb21368079a8cdd4139d0e6522d054700b | [
"Unlicense"
] | null | null | null | BAI_12.cpp | anhtuanptit97/anhtuan | 5b1d49cb21368079a8cdd4139d0e6522d054700b | [
"Unlicense"
] | null | null | null | BAI_12.cpp | anhtuanptit97/anhtuan | 5b1d49cb21368079a8cdd4139d0e6522d054700b | [
"Unlicense"
] | null | null | null | #include<iostream>
#include<cmath>
using namespace std;
class fraction{
private:
int num;
int den;
public:
fraction(int ,int );
fraction();
void lowterms();
void dislay();
void set_num(int tnum){
this->num=tnum;
}
void set_den(int tden){
this->den=tden;
}
void sum(fraction,fraction);
void sub(fraction,fraction);
void mul(fraction,fraction);
void div(fraction,fraction);
};
fraction::fraction(int tnum, int tden){
if(tden==0){
cout<<"Illegal fraction: division by 0"<<endl;
exit(1);
}
this->num=tnum;
this->den=tden;
}
fraction::fraction(){
this->num=1;
this->den=1;
}
void fraction::lowterms(){
long tnum, tden, temp, gcd;
tnum = labs(num);
tden = labs(den);
if(tden==0){
cout<< "Illegal fraction: division by 0"<<endl;
exit(1);
}
else if( tnum==0 ) {
num=0; den = 1;
return;
}
while(tnum != 0){
if(tnum < tden){
temp=tnum; tnum=tden; tden=temp;
}
tnum = tnum - tden;
}
gcd = tden;
num = num / gcd;
den = den / gcd;
}
void fraction::sum(fraction one,fraction two){
this->num=two.den*one.num+two.num*one.den;
this->den=one.den*two.den;
this->lowterms();
}
void fraction::sub(fraction one,fraction two){
this->num=two.den*one.num-two.num*one.den;
this->den=one.den*two.den;
this->lowterms();
}
void fraction::mul(fraction one,fraction two){
this->num=two.num*one.num;
this->den=one.den*two.den;
this->lowterms();
}
void fraction::div(fraction one,fraction two){
this->num=one.num*one.den;
this->den=one.den*two.num;
this->lowterms();
}
void fraction::dislay(){
cout << this->num<<"/"<<this->den;
}
class dislaytable{
private:
int num;
public:
dislaytable(int);
void add();
void dislay();
};
dislaytable::dislaytable(int tnum){
this->num=tnum;
}
void dislaytable::add(){
int tnum;
do{
cout<<"Input number: ";
cin >> tnum;
if(tnum!=0){
this->num=tnum;
break;
}
cout<< "Illegal fraction: division by 0"<<endl;
}while(1);
}
void dislaytable::dislay(){
fraction temp1(1,this->num);
fraction temp2(1,this->num);
cout<<"\t";
for(int i=1; i <this->num;i++){
temp1.set_num(i);
temp1.set_den(this->num);
temp1.lowterms();
temp1.dislay();
cout<<"\t";
}
cout<<endl<<"---------------------------------------------"<<endl;
for(int i=1; i <this->num;i++){
temp1.set_num(i);
temp1.set_den(this->num);
temp1.lowterms();
temp1.dislay();
cout<<"\t";
for(int j=1;j <this->num;j++){
temp1.set_num(i);
temp2.set_num(j);
temp1.set_den(this->num);
temp2.set_den(this->num);
temp1.mul(temp1,temp2);
temp1.dislay();
cout<<"\t";
}
cout<<endl;
}
}
| 19.258741 | 68 | 0.582426 | anhtuanptit97 |
c72d04c7dcb638babe4a2cc935be8bf799e0caa8 | 652 | cpp | C++ | transpose of matrices.cpp | mohsin5432/CPP-basic | 453c82cdc1b3412ee0a063cd9053c7556c80bd7a | [
"MIT"
] | null | null | null | transpose of matrices.cpp | mohsin5432/CPP-basic | 453c82cdc1b3412ee0a063cd9053c7556c80bd7a | [
"MIT"
] | null | null | null | transpose of matrices.cpp | mohsin5432/CPP-basic | 453c82cdc1b3412ee0a063cd9053c7556c80bd7a | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
main()
{
int r,c;
cout<<"ENTER THE ROWS OF MATRICES= ";
cin>>r;
cout<<"ENTER THE COLUMN OF MATRICES= ";
cin>>c;
int a[r][c];
for(int i=0;i<r;i++)
{
for (int j=0;j<c;j++)
{
cout<<"Enter no= ";
cin>>a[i][j];
}
}
cout<<"\t\t\tOrignal Matrice:"<<endl;
for(int i=0;i<r;i++)
{
cout<<"\t\t\t\t";
for (int j=0;j<c;j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
cout<<"\n\n";
cout<<"\t\t\ttranspose of a matrices:"<<endl;
for(int i=0;i<r;i++)
{
cout<<"\t\t\t\t";
for (int j=0;j<c;j++)
{
cout<<a[j][i]<<" ";
}
cout<<"\n";
}
}
| 15.52381 | 47 | 0.45092 | mohsin5432 |
c732658bd36524425c901e678fe7257825e8df94 | 14,860 | cpp | C++ | source/scene/logic/scene.cpp | imstar15/breeze | 8793493c1245670a66e1a098a0d010c51e7b4783 | [
"Apache-2.0"
] | 454 | 2015-01-06T00:28:13.000Z | 2022-03-17T04:24:39.000Z | source/scene/logic/scene.cpp | 63890390/breeze | e9ce9fae7a3f9dc5f3f1c911a98d75707a50e6b0 | [
"Apache-2.0"
] | 8 | 2016-06-08T21:06:03.000Z | 2021-06-10T11:20:06.000Z | source/scene/logic/scene.cpp | 63890390/breeze | e9ce9fae7a3f9dc5f3f1c911a98d75707a50e6b0 | [
"Apache-2.0"
] | 214 | 2015-01-06T11:06:46.000Z | 2022-03-13T14:29:52.000Z | #include "scene.h"
#include "sceneMgr.h"
#include <aoe/aoe.h>
Scene::Scene(SceneID sceneID)
{
_sceneID = sceneID;
_sceneType = SCENE_NONE;
_sceneStatus = SCENE_STATE_NONE;
}
Scene::~Scene()
{
}
GroupID Scene::getGroupID(ServiceID avatarID)
{
auto entity = getEntityByAvatarID(avatarID);
if (entity)
{
return entity->_state.groupID;
}
return InvalidGroupID;
}
void Scene::getSceneSection(SceneSection & ss)
{
ss.sceneID = _sceneID;
ss.sceneType = _sceneType;
ss.sceneState = _sceneStatus;
ss.sceneStartTime = _startTime;
ss.sceneEndTime = _endTime;
ss.serverTime = getFloatSteadyNowTime();
}
bool Scene::cleanScene()
{
//放入free列表要先clean, 减小内存占用
_sceneType = SCENE_NONE;
_sceneStatus = SCENE_STATE_NONE;
_lastEID = ServerConfig::getRef().getSceneConfig()._lineID * 1000 + 1000;
_entitys.clear();
_players.clear();
while (!_asyncs.empty()) _asyncs.pop();
_move.reset();
_skill.reset();
_ai.reset();
_script.reset();
return true;
}
bool Scene::initScene(SCENE_TYPE sceneType, MapID mapID)
{
if (_sceneStatus != SCENE_STATE_NONE)
{
LOGE("Scene::loadScene scene status error");
return false;
}
double now = getFloatNowTime();
_sceneType = sceneType;
_mapID = mapID;
_sceneStatus = SCENE_STATE_ACTIVE;
_lastEID = ServerConfig::getRef().getSceneConfig()._lineID * 1000 + 1000;
_startTime = getFloatSteadyNowTime();
_endTime = getFloatSteadyNowTime() + 600;
_move = std::make_shared<MoveSync>();
_move->init(shared_from_this());
_skill = std::make_shared<Skill>();
_skill->init(shared_from_this());
_ai = std::make_shared<AI>();
_ai->init(shared_from_this());
_script = std::make_shared<Script>();
_script->init(shared_from_this());
//load map
//load entitys
onSceneInit();
LOGD("initScene success. used time=" << getFloatNowTime() - now);
return true;
}
EntityPtr Scene::getEntity(EntityID eID)
{
auto founder = _entitys.find(eID);
if (founder == _entitys.end())
{
return nullptr;
}
return founder->second;
}
EntityPtr Scene::getEntityByAvatarID(ServiceID avatarID)
{
auto founder = _players.find(avatarID);
if (founder == _players.end())
{
return nullptr;
}
return founder->second;
}
EntityPtr Scene::makeEntity(ui64 modelID, ui64 avatarID, std::string avatarName, DictArrayKey equips,GroupID groupID)
{
EntityPtr entity = std::make_shared<Entity>();
entity->_props = DictProp();
entity->_state.curHP = entity->_props.hp;
entity->_state.eid = ++_lastEID;
entity->_state.avatarID = avatarID;
entity->_state.avatarName = avatarName;
entity->_state.modelID = modelID;
entity->_state.groupID = groupID;
entity->_state.camp = ENTITY_CAMP_NONE;
entity->_state.etype = avatarID == InvalidAvatarID ? ENTITY_AI : ENTITY_PLAYER;
entity->_state.state = ENTITY_STATE_ACTIVE;
entity->_state.master = InvalidEntityID;
entity->_state.foe = InvalidEntityID;
entity->_control.spawnpoint = { 0.0 - 30 + realRandF()*30 ,60 -30 + realRandF()*30 };
entity->_control.eid = entity->_state.eid;
entity->_control.agentNo = RVO::RVO_ERROR;
entity->_control.stateChageTime = getFloatSteadyNowTime();
entity->_move.eid = entity->_state.eid;
entity->_move.position = entity->_control.spawnpoint;
entity->_move.follow = InvalidEntityID;
entity->_move.waypoints.clear();
entity->_move.action = MOVE_ACTION_IDLE;
entity->_report.eid = entity->_state.eid;
entity->_skillSys.eid = entity->_state.eid;
return entity;
}
void Scene::addEntity(EntityPtr entity)
{
entity->_control.agentNo = _move->addAgent(entity->_move.position, entity->_control.collision);
_entitys.insert(std::make_pair(entity->_state.eid, entity));
if (entity->_state.avatarID != InvalidServiceID && entity->_state.etype == ENTITY_PLAYER)
{
_players[entity->_state.avatarID] = entity;
}
LOGD("Scene::addEntity. eid[" << entity->_state.eid << "] aid[" << entity->_state.avatarID << "][" << entity->_state.avatarName
<< "] modleID=" << entity->_state.modelID << ", camp=" << entity->_state.camp << ", etype=" << entity->_state.etype << ", state=" << entity->_state.state
<< ", agentNo=" << entity->_control.agentNo << ", hp=[" << entity->_state.curHP << "/" << entity->_state.maxHP
<< "], spawnpoint" << entity->_control.spawnpoint<< ", position=" << entity->_move.position);
AddEntityNotice notice;
notice.syncs.push_back(entity->getClientSyncData());
broadcast(notice, entity->_state.avatarID);
EntityScriptNotice sn;
sn.controls.push_back(entity->_control);
sn.skills.push_back(entity->_skillSys);
broadcast(notice, entity->_state.avatarID);
onAddEntity(entity);
}
bool Scene::removePlayer(AvatarID avatarID)
{
auto entity = getEntityByAvatarID(avatarID);
if (entity)
{
return removeEntity(entity->_state.eid);
}
return false;
}
bool Scene::removePlayerByGroupID(GroupID groupID)
{
std::set<EntityID> removes;
for (auto entity : _entitys)
{
if (entity.second->_state.etype == ENTITY_PLAYER && entity.second->_state.groupID == groupID)
{
removes.insert(entity.second->_state.eid);
}
}
for (auto eid : removes)
{
removeEntity(eid);
}
return true;
}
bool Scene::removeEntity(EntityID eid)
{
auto entity = getEntity(eid);
if (!entity)
{
LOGE("");
return false;
}
if(_move->isValidAgent(entity->_control.agentNo))
{
_move->delAgent(entity->_control.agentNo);
entity->_control.agentNo = RVO::RVO_ERROR;
}
if (entity->_state.etype == ENTITY_PLAYER)
{
_players.erase(entity->_state.avatarID);
SceneMgr::getRef().sendToWorld(SceneServerGroupStateFeedback(getSceneID(), entity->_state.groupID, SCENE_NONE));
}
_entitys.erase(eid);
RemoveEntityNotice notice;
notice.eids.push_back(eid);
broadcast(notice);
onRemoveEntity(entity);
return true;
}
bool Scene::playerAttach(ServiceID avatarID, SessionID sID)
{
EntityPtr entity = getEntityByAvatarID(avatarID);
if (!entity)
{
return false;
}
entity->_clientSessionID = sID;
LOGI("Scene::playerAttach avatarName=" << entity->_state.avatarName << " sessionID=" << sID << ", entityID=" << entity->_state.eid);
SceneSectionNotice section;
getSceneSection(section.section);
sendToClient(avatarID, section);
AddEntityNotice notice;
for (auto & e : _entitys)
{
notice.syncs.push_back(e.second->getClientSyncData());
}
if (!notice.syncs.empty())
{
sendToClient(avatarID, notice);
}
onPlayerAttach(entity);
return true;
}
bool Scene::playerDettach(ServiceID avatarID, SessionID sID)
{
auto entity = getEntityByAvatarID(avatarID);
if (entity && entity->_clientSessionID == sID)
{
LOGI("Scene::playerDettach avatarName=" << entity->_state.avatarName << " sessionID=" << sID << ", entityID=" << entity->_state.eid);
entity->_clientSessionID = InvalidSessionID;
onPlayerDettach(entity);
}
return true;
}
bool Scene::onUpdate()
{
if (getFloatSteadyNowTime() > _endTime || _players.empty())
{
return false;
}
_move->update();
_skill->update();
_ai->update();
SceneRefreshNotice notice;
EntityScriptNotice scripts;
for (auto &kv : _entitys)
{
if (kv.second->_isStateDirty)
{
notice.entityStates.push_back(kv.second->_state);
kv.second->_isStateDirty = false;
}
if (kv.second->_isMoveDirty)
{
notice.entityMoves.push_back(kv.second->_move);
kv.second->_isMoveDirty = false;
}
scripts.controls.push_back(kv.second->_control);
scripts.skills.push_back(kv.second->_skillSys);
}
if (!notice.entityStates.empty() || !notice.entityMoves.empty())
{
broadcast(notice);
}
_script->protoSync(scripts);
//after flush data
_script->update();
while (!_asyncs.empty())
{
auto func = _asyncs.front();
_asyncs.pop();
func();
}
return true;
}
void Scene::pushAsync(std::function<void()> && func)
{
_asyncs.push(std::move(func));
}
void Scene::onPlayerInstruction(ServiceID avatarID, ReadStream & rs)
{
if (avatarID == InvalidAvatarID)
{
return;
}
if (rs.getProtoID() == MoveReq::getProtoID())
{
MoveReq req;
rs >> req;
LOGD("MoveReq avatarID[" << avatarID << "] req=" << req);
auto entity = getEntity(req.eid);
if (!entity || entity->_state.avatarID != avatarID || entity->_state.etype != ENTITY_PLAYER
|| (req.action != MOVE_ACTION_IDLE && req.action == MOVE_ACTION_FOLLOW && req.action == MOVE_ACTION_PATH)
|| entity->_state.state != ENTITY_STATE_ACTIVE
)
{
sendToClient(avatarID, MoveResp(EC_ERROR, req.eid, req.action));
return;
}
if (!_move->doMove(req.eid, (MOVE_ACTION)req.action, entity->getSpeed(), req.follow, req.waypoints))
{
sendToClient(avatarID, MoveResp(EC_ERROR, req.eid, req.action));
return;
}
if (entity->_skillSys.combating)
{
entity->_skillSys.combating = false;
}
}
else if (rs.getProtoID() == UseSkillReq::getProtoID())
{
UseSkillReq req;
rs >> req;
auto entity = getEntity(req.eid);
if (!entity || entity->_state.avatarID != avatarID || entity->_state.etype != ENTITY_PLAYER || entity->_state.state != ENTITY_STATE_ACTIVE
|| ! _skill->doSkill(shared_from_this(), req.eid, req.skillID, req.dst)
)
{
sendToClient(avatarID, UseSkillResp(EC_ERROR, req.eid, req.skillID, req.dst, req.foeFirst));
}
}
else if (rs.getProtoID() == ClientCustomReq::getProtoID())
{
ClientCustomReq req;
rs >> req;
auto entity = getEntity(req.eid);
if (entity && entity->_state.avatarID == avatarID)
{
broadcast(ClientCustomNotice(req.eid, req.customID, req.fValue,req.uValue, req.sValue));
}
else
{
sendToClient(avatarID, ClientCustomResp(EC_ERROR, req.eid, req.customID));
}
}
else if (rs.getProtoID() == ClientPingTestReq::getProtoID())
{
ClientPingTestReq req;
rs >> req;
sendToClient(avatarID, ClientPingTestResp(EC_ERROR, req.seqID, req.clientTime));
}
}
std::vector<std::pair<EntityPtr, double>> Scene::searchTarget(EntityPtr caster, EPosition org, EPosition vt, ui64 searchID)
{
auto search = DBDict::getRef().getOneKeyAOESearch(searchID);
if (!search.first)
{
LOGE("Scene::searchTarget not found search config. searchID=" << searchID);
return std::vector<std::pair<EntityPtr, double>>();
}
return searchTarget(caster, org, vt, search.second);
}
bool Scene::searchMatched(const EntityPtr & master, const EntityPtr & caster, const EntityPtr & dst, const AOESearch & search)
{
if (getBitFlag(search.filter, FILTER_SELF) && master && master->_state.eid == dst->_state.eid)
{
return true;
}
if (search.etype != ENTITY_NONE && search.etype != dst->_state.etype)
{
return false;
}
if (getBitFlag(search.filter, FILTER_OTHER_FRIEND) && caster->_state.camp == dst->_state.camp)
{
if (master && master->_state.eid == dst->_state.eid)
{
return false;
}
return true;
}
if (getBitFlag(search.filter, FILTER_ENEMY_CAMP) && caster->_state.camp != dst->_state.camp && dst->_state.camp < ENTITY_CAMP_NEUTRAL)
{
return true;
}
if (getBitFlag(search.filter, FILTER_NEUTRAL_CAMP) && dst->_state.camp >= ENTITY_CAMP_NEUTRAL)
{
return true;
}
return false;
}
std::vector<std::pair<EntityPtr, double>> Scene::searchTarget(EntityPtr caster, EPosition org, EPosition vt, const AOESearch & search)
{
EntityPtr master = caster;
if (caster->_state.etype == ENTITY_FLIGHT)
{
if (caster->_state.master != InvalidEntityID)
{
master = getEntity(caster->_state.master);
}
else
{
master = nullptr;
}
}
auto ret = searchTarget(org, vt, search.isRect,
search.value1, search.value2, search.value3, search.compensate, search.clip);
if (getBitFlag(search.filter, FILTER_SELF) && master)
{
if (std::find_if(ret.begin(), ret.end(), [&master](const std::pair<EntityPtr, double> & pr) {return pr.first->_state.eid == master->_state.eid; })
== ret.end())
{
ret.push_back(std::make_pair(master, 0));
}
}
auto beginIter = std::remove_if(ret.begin(), ret.end(), [this, &search, &master, &caster](const std::pair<EntityPtr, double> & e)
{
if (searchMatched(master, caster, e.first, search))
{
return false;
}
return true;
});
ret.erase(beginIter, ret.end());
if (ret.size()> search.limitEntitys)
{
ret.resize(search.limitEntitys);
}
return ret;
}
std::vector<std::pair<EntityPtr, double>> Scene::searchTarget(EPosition org, EPosition vt, ui16 isRect, double value1, double value2, double value3, double compensate, double clip)
{
std::vector<std::pair<EntityPtr, double>> ret;
vt = normalize(vt);
org = org + vt*compensate;
value1 = value1 - compensate;
AOECheck ac;
ac.init(toTuple(org), toTuple(vt), isRect != 0, value1, value2, value3, clip);
for (auto kv : _entitys)
{
EPosition pos = kv.second->_move.position;
if (kv.second->_state.etype != ENTITY_PLAYER && kv.second->_state.etype != ENTITY_AI)
{
continue;
}
if (kv.second->_state.state != ENTITY_STATE_ACTIVE)
{
continue;
}
auto cRet = ac.check(toTuple(pos), kv.second->_control.collision);
if (std::get<0>(cRet))
{
ret.push_back(std::make_pair(kv.second, std::get<1>(cRet)));
}
}
std::sort(ret.begin(), ret.end(), [org](const std::pair<EntityPtr, double> & e1, const std::pair<EntityPtr, double> & e2){return e1.second < e2.second; });
return ret;
}
void Scene::onSceneInit()
{
}
void Scene::onAddEntity(EntityPtr entity)
{
}
void Scene::onRemoveEntity(EntityPtr entity)
{
}
void Scene::onPlayerAttach(EntityPtr entity)
{
}
void Scene::onPlayerDettach(EntityPtr entity)
{
}
| 27.166362 | 181 | 0.622813 | imstar15 |
c738b91713fb49991d53ba916a740c2084e6d15c | 4,044 | hxx | C++ | src/elle/reactor/Generator.hxx | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 521 | 2016-02-14T00:39:01.000Z | 2022-03-01T22:39:25.000Z | src/elle/reactor/Generator.hxx | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 8 | 2017-02-21T11:47:33.000Z | 2018-11-01T09:37:14.000Z | src/elle/reactor/Generator.hxx | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 48 | 2017-02-21T10:18:13.000Z | 2022-03-25T02:35:20.000Z | #include <type_traits>
namespace elle
{
namespace reactor
{
/*----.
| End |
`----*/
template <typename T>
Generator<T>::End::End(Generator<T> const& g)
: elle::Error(elle::sprintf("%s exhausted", g))
{}
/*-------------.
| Construction |
`-------------*/
template <typename T>
template <typename Driver>
Generator<T>::Generator(Driver driver)
{
using Signature = std::function<auto (yielder const&) -> void>;
static_assert(std::is_constructible<Signature, Driver>::value, "");
ELLE_LOG_COMPONENT("elle.reactor.Generator");
auto yield = [this] (T elt) { this->_results.put(std::move(elt)); };
this->_thread.reset(
new Thread("generator",
[this, driver, yield]
{
try
{
driver(yield);
}
catch (...)
{
ELLE_TRACE("%s: handle exception: %s",
this, elle::exception_string());
this->_exception = std::current_exception();
}
this->_results.put({});
}));
}
template <typename T>
Generator<T>::Generator(Generator<T>&& generator)
: _results(std::move(generator._results))
, _thread(std::move(generator._thread))
{}
template <typename T>
Generator<T>::~Generator()
{
ELLE_LOG_COMPONENT("elle.reactor.Generator");
ELLE_TRACE("%s: destruct", this);
}
/*--------.
| Content |
`--------*/
template <typename T>
T
Generator<T>::iterator::operator *() const
{
assert(!this->_fetch);
return std::move(this->_value.get());
}
/*---------.
| Iterator |
`---------*/
template <typename T>
Generator<T>::iterator::iterator()
: _generator(nullptr)
, _fetch(true)
{}
template <typename T>
Generator<T>::iterator::iterator(Generator<T>& generator)
: _generator(&generator)
, _fetch(true)
{}
template <typename T>
bool
Generator<T>::iterator::operator !=(iterator const& other) const
{
assert(other._generator == nullptr);
if (this->_fetch)
{
this->_value = this->_generator->_results.get();
this->_fetch = false;
}
if (this->_value)
return true;
else if (this->_generator->_exception)
std::rethrow_exception(this->_generator->_exception);
else
return false;
}
template <typename T>
bool
Generator<T>::iterator::operator ==(iterator const& other) const
{
return !(*this != other);
}
template <typename T>
typename Generator<T>::iterator&
Generator<T>::iterator::operator ++()
{
this->_fetch = true;
this->_value.reset();
return *this;
}
template <typename T>
void
Generator<T>::iterator::operator ++(int)
{
++*this;
}
template <typename T>
T
Generator<T>::next()
{
if (auto res = this->_results.get())
return *res;
else
throw End(*this);
}
template <typename T>
Generator<T>
generator(std::function<void (yielder<T> const&)> const& driver)
{
return Generator<T>(driver);
}
template <typename T>
typename Generator<T>::iterator
Generator<T>::begin()
{
return typename Generator<T>::iterator(*this);
}
template <typename T>
typename Generator<T>::iterator
Generator<T>::end()
{
return typename Generator<T>::iterator();
}
template <typename T>
typename Generator<T>::const_iterator
Generator<T>::begin() const
{
return typename Generator<T>::iterator(elle::unconst(*this));
}
template <typename T>
typename Generator<T>::const_iterator
Generator<T>::end() const
{
return typename Generator<T>::iterator();
}
}
}
| 22.977273 | 74 | 0.526954 | infinitio |
c73cb9c65a54973505931ffed10a564f468f2d31 | 13,219 | cpp | C++ | main/IotDataMqtt.cpp | nkskjames/wifi_bbq_temp | 28e9d46d64de0a83e5e0a04a6112c1f564421af6 | [
"Apache-2.0"
] | null | null | null | main/IotDataMqtt.cpp | nkskjames/wifi_bbq_temp | 28e9d46d64de0a83e5e0a04a6112c1f564421af6 | [
"Apache-2.0"
] | null | null | null | main/IotDataMqtt.cpp | nkskjames/wifi_bbq_temp | 28e9d46d64de0a83e5e0a04a6112c1f564421af6 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_event_loop.h"
#include <nvs.h>
#include <nvs_flash.h>
#include "aws_iot_config.h"
#include "aws_iot_log.h"
#include "aws_iot_version.h"
#include "aws_iot_mqtt_client_interface.h"
#include "aws_iot_shadow_interface.h"
#include "IotData.hpp"
#include "IotDataMqtt.hpp"
using namespace std;
extern const uint8_t aws_root_ca_pem_start[] asm("_binary_aws_root_ca_pem_start");
extern const uint8_t aws_root_ca_pem_end[] asm("_binary_aws_root_ca_pem_end");
extern const uint8_t certificate_pem_crt_start[] asm("_binary_certificate_pem_crt_start");
extern const uint8_t certificate_pem_crt_end[] asm("_binary_certificate_pem_crt_end");
extern const uint8_t private_pem_key_start[] asm("_binary_private_pem_key_start");
extern const uint8_t private_pem_key_end[] asm("_binary_private_pem_key_end");
extern const uint8_t certificate_and_ca_pem_crt_start[] asm("_binary_certificate_and_ca_pem_crt_start");
extern const uint8_t certificate_and_ca_pem_crt_end[] asm("_binary_certificate_and_ca_pem_crt_end");
#define MQTT_NAMESPACE "mqtt" // Namespace in NVS
#define KEY_REGISTER "registered"
#define KEY_S_VERSION "version"
#define tag "mqtt"
uint32_t s_version = 0x0100;
/**
* Save signup status
*/
static void saveRegisterStatus(bool registered) {
nvs_handle handle;
ESP_ERROR_CHECK(nvs_open(MQTT_NAMESPACE, NVS_READWRITE, &handle));
ESP_ERROR_CHECK(nvs_set_u8(handle, KEY_REGISTER, registered));
ESP_ERROR_CHECK(nvs_set_u32(handle, KEY_S_VERSION, s_version));
ESP_ERROR_CHECK(nvs_commit(handle));
ESP_LOGI(tag, "Registration saved");
nvs_close(handle);
}
bool isRegistered() {
nvs_handle handle;
uint8_t registered = false;
esp_err_t err;
uint32_t version;
err = nvs_open(MQTT_NAMESPACE, NVS_READWRITE, &handle);
if (err != 0) {
ESP_LOGE(tag, "nvs_open: %x", err);
return false;
}
// Get the version that the data was saved against.
err = nvs_get_u32(handle, KEY_S_VERSION, &version);
if (err != ESP_OK) {
ESP_LOGD(tag, "No version record found (%d).", err);
nvs_close(handle);
return false;
}
// Check the versions match
if ((version & 0xff00) != (s_version & 0xff00)) {
ESP_LOGD(tag, "Incompatible versions ... current is %x, found is %x", version, s_version);
nvs_close(handle);
return false;
}
err = nvs_get_u8(handle, KEY_REGISTER, ®istered);
if (err != ESP_OK) {
ESP_LOGD(tag, "No signup record found (%d).", err);
nvs_close(handle);
return false;
}
if (err != ESP_OK) {
ESP_LOGE(tag, "nvs_open: %x", err);
nvs_close(handle);
return -false;
}
// Cleanup
nvs_close(handle);
ESP_LOGI(tag, "Found registration");
return registered;
}
static void disconnectCallbackHandler(AWS_IoT_Client *pClient, void *data) {
static const char* TAG = "shadow_disconnect";
ESP_LOGW(TAG, "MQTT Disconnect");
IoT_Error_t rc = FAILURE;
if(NULL == pClient) {
return;
}
if(aws_iot_is_autoreconnect_enabled(pClient)) {
ESP_LOGI(TAG, "Auto Reconnect is enabled, Reconnecting attempt will start now");
} else {
ESP_LOGW(TAG, "Auto Reconnect not enabled. Starting manual reconnect...");
rc = aws_iot_mqtt_attempt_reconnect(pClient);
if(NETWORK_RECONNECTED == rc) {
ESP_LOGW(TAG, "Manual Reconnect Successful");
} else {
ESP_LOGW(TAG, "Manual Reconnect Failed - %d", rc);
}
}
}
static bool shadowUpdateInProgress;
static void ShadowUpdateStatusCallback(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status,
const char *pReceivedJsonDocument, void *pContextData) {
IOT_UNUSED(pThingName);
IOT_UNUSED(action);
IOT_UNUSED(pReceivedJsonDocument);
IOT_UNUSED(pContextData);
shadowUpdateInProgress = false;
static const char* TAG = "shadow_callback";
if(SHADOW_ACK_TIMEOUT == status) {
ESP_LOGE(TAG, "Update timed out");
} else if(SHADOW_ACK_REJECTED == status) {
ESP_LOGE(TAG, "Update rejected");
} else if(SHADOW_ACK_ACCEPTED == status) {
ESP_LOGI(TAG, "Update accepted");
}
}
int IotDataMqtt::signup(char* thingId,char* username) {
if (isRegistered()) { return 0; }
char cPayload[100];
//int32_t i = 0;
IoT_Error_t rc = FAILURE;
AWS_IoT_Client client;
IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault;
IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault;
IoT_Publish_Message_Params paramsQOS0;
ESP_LOGI(TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);
mqttInitParams.enableAutoReconnect = false; // We enable this later below
mqttInitParams.pHostURL = (char*)IotDataMqtt::HOST;
mqttInitParams.port = IotDataMqtt::PORT;
mqttInitParams.pDeviceCertLocation = (const char *)certificate_and_ca_pem_crt_start;
//mqttInitParams.pDeviceCertLocation = (const char *)certificate_pem_crt_start;
mqttInitParams.pDevicePrivateKeyLocation = (const char *)private_pem_key_start;
mqttInitParams.pRootCALocation = (const char *)aws_root_ca_pem_start;
mqttInitParams.mqttCommandTimeout_ms = 20000;
mqttInitParams.tlsHandshakeTimeout_ms = 5000;
mqttInitParams.isSSLHostnameVerify = true;
mqttInitParams.disconnectHandler = disconnectCallbackHandler;
mqttInitParams.disconnectHandlerData = NULL;
rc = aws_iot_mqtt_init(&client, &mqttInitParams);
if(SUCCESS != rc) {
ESP_LOGE(TAG, "aws_iot_mqtt_init returned error : %d ", rc);
abort();
}
connectParams.keepAliveIntervalInSec = 10;
connectParams.isCleanSession = true;
connectParams.MQTTVersion = MQTT_3_1_1;
connectParams.pClientID = thingId;
connectParams.clientIDLen = (uint16_t) strlen(thingId);
connectParams.isWillMsgPresent = false;
ESP_LOGI(TAG, "Connecting to AWS...");
do {
rc = aws_iot_mqtt_connect(&client, &connectParams);
if(SUCCESS != rc) {
ESP_LOGE(TAG, "Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port);
vTaskDelay(1000 / portTICK_RATE_MS);
}
} while(SUCCESS != rc);
/*
* Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
* #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
* #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
*/
rc = aws_iot_mqtt_autoreconnect_set_status(&client, true);
if(SUCCESS != rc) {
ESP_LOGE(TAG, "Unable to set Auto Reconnect to true - %d", rc);
abort();
}
const char *TOPIC = "topic/iot_signup";
const int TOPIC_LEN = strlen(TOPIC);
paramsQOS0.qos = QOS0;
paramsQOS0.payload = (void *) cPayload;
paramsQOS0.isRetained = 0;
rc = aws_iot_mqtt_yield(&client, 100);
sprintf(cPayload, "{\"username\" : \"%s\"}",username);
paramsQOS0.payloadLen = strlen(cPayload);
rc = aws_iot_mqtt_publish(&client, TOPIC, TOPIC_LEN, ¶msQOS0);
if (rc == MQTT_REQUEST_TIMEOUT_ERROR) {
ESP_LOGW(TAG, "QOS1 publish ack not received.");
} else {
ESP_LOGI(TAG, "Signup publish successful.");
//TODO: fix race issue
this->init(thingId);
char JsonDocumentBuffer[400];
sprintf(JsonDocumentBuffer,
"{\"state\": {\"reported\": {\"thingname\":\"%s\",\"username\":\"%s\", \"td\": [\"Temp 1\",\"Temp 2\",\"Temp 3\"], \"t\": [0,0,0], \"tl\": [0,0,0], \"tu\": [100,100,100]}}, \"clientToken\":\"%s-100\"}",
thingId,username,thingId);
this->sendraw(JsonDocumentBuffer);
this->close();
saveRegisterStatus(true);
}
return 0;
}
int IotDataMqtt::init(char* thingName) {
IoT_Error_t rc = FAILURE;
strcpy(this->thingName,thingName);
strcpy(this->thingId,thingName);
ESP_LOGI(IotDataMqtt::TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);
ShadowInitParameters_t sp = ShadowInitParametersDefault;
sp.pHost = (char*)IotDataMqtt::HOST;
sp.port = IotDataMqtt::PORT;
sp.pClientCRT = (const char *)certificate_and_ca_pem_crt_start;
//sp.pClientCRT = (const char *)certificate_pem_crt_start;
sp.pClientKey = (const char *)private_pem_key_start;
sp.pRootCA = (const char *)aws_root_ca_pem_start;
sp.enableAutoReconnect = false;
sp.disconnectHandler = disconnectCallbackHandler;
ESP_LOGI(TAG, "Shadow Init");
rc = aws_iot_shadow_init(&mqttClient, &sp);
if(SUCCESS != rc) {
ESP_LOGE(TAG, "aws_iot_shadow_init returned error %d, aborting...", rc);
abort();
}
ShadowConnectParameters_t scp = ShadowConnectParametersDefault;
//AWS recommends setting thing name equal to client id
scp.pMyThingName = this->thingName;
scp.pMqttClientId = this->thingName;
scp.mqttClientIdLen = (uint16_t) strlen(this->thingName);
ESP_LOGI(IotDataMqtt::TAG, "Shadow Connect");
rc = aws_iot_shadow_connect(&mqttClient, &scp);
if(SUCCESS != rc) {
ESP_LOGE(IotDataMqtt::TAG, "aws_iot_shadow_connect returned error %d, aborting...", rc);
abort();
}
/*
* Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
* #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
* #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
*/
rc = aws_iot_shadow_set_autoreconnect_status(&mqttClient, true);
if(SUCCESS != rc) {
ESP_LOGE(IotDataMqtt::TAG, "Unable to set Auto Reconnect to true - %d, aborting...", rc);
}
if(SUCCESS != rc) {
ESP_LOGE(IotDataMqtt::TAG, "Shadow Register Delta Error");
}
return rc;
}
int IotDataMqtt::send(char* JsonDocumentBuffer, size_t sizeOfJsonDocumentBuffer, jsonStruct_t* data, int sizeData) {
IoT_Error_t rc = SUCCESS;
bool sent = false;
while(NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) {
rc = aws_iot_shadow_yield(&mqttClient, 200);
if(NETWORK_ATTEMPTING_RECONNECT == rc || shadowUpdateInProgress) {
rc = aws_iot_shadow_yield(&mqttClient, 1000);
// If the client is attempting to reconnect, or already waiting on a shadow update,
// we will skip the rest of the loop.
continue;
}
if (sent) {
break;
}
ESP_LOGI(IotDataMqtt::TAG, "init_json");
rc = aws_iot_shadow_init_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer);
if(SUCCESS == rc) {
ESP_LOGI(IotDataMqtt::TAG, "add_array");
rc = aws_iot_shadow_add_array_reported(JsonDocumentBuffer, sizeOfJsonDocumentBuffer, sizeData, data);
if(SUCCESS == rc) {
ESP_LOGI(IotDataMqtt::TAG, "finalize");
rc = aws_iot_finalize_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer);
if(SUCCESS == rc) {
ESP_LOGI(IotDataMqtt::TAG, "Update Shadow: %s", JsonDocumentBuffer);
rc = aws_iot_shadow_update(&mqttClient, thingName, JsonDocumentBuffer,
ShadowUpdateStatusCallback, NULL, 4, true);
shadowUpdateInProgress = true;
sent = true;
}
}
}
ESP_LOGI(TAG, "*****************************************************************************************");
}
if(SUCCESS != rc) {
ESP_LOGE(TAG, "An error occurred in the loop %d", rc);
}
return rc;
}
int IotDataMqtt::sendraw(char* JsonDocumentBuffer) {
IoT_Error_t rc = SUCCESS;
bool sent = false;
while(NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) {
ESP_LOGI(TAG, "yield");
rc = aws_iot_shadow_yield(&mqttClient, 100);
if(NETWORK_ATTEMPTING_RECONNECT == rc || shadowUpdateInProgress) {
ESP_LOGI(TAG, "yield2");
rc = aws_iot_shadow_yield(&mqttClient, 100);
// If the client is attempting to reconnect, or already waiting on a shadow update,
// we will skip the rest of the loop.
continue;
}
if (sent) {
break;
}
ESP_LOGI(IotDataMqtt::TAG, "Update Shadow: %s", JsonDocumentBuffer);
rc = aws_iot_shadow_update(&mqttClient, thingName, JsonDocumentBuffer,
ShadowUpdateStatusCallback, NULL, 4, true);
ESP_LOGI(TAG, "update: %d",rc);
shadowUpdateInProgress = true;
sent = true;
vTaskDelay(2000 / portTICK_RATE_MS);
ESP_LOGI(TAG, "*****************************************************************************************");
}
if(SUCCESS != rc) {
ESP_LOGE(TAG, "An error occurred in the loop %d", rc);
}
return rc;
}
int IotDataMqtt::close() {
IoT_Error_t rc = SUCCESS;
ESP_LOGI(TAG, "Disconnecting");
rc = aws_iot_shadow_disconnect(&mqttClient);
if(SUCCESS != rc) {
ESP_LOGE(IotDataMqtt::TAG, "Disconnect error %d", rc);
}
return rc;
}
/*
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
return ESP_OK;
}
*/
| 34.069588 | 205 | 0.667827 | nkskjames |
c73faa6d771bdc30f574843285dbb285760bc25a | 15,360 | cpp | C++ | onut/src/onut.cpp | Daivuk/ggj16 | 0ba896f3b6ece32ed3a6e190825e53e88f666d5e | [
"MIT"
] | null | null | null | onut/src/onut.cpp | Daivuk/ggj16 | 0ba896f3b6ece32ed3a6e190825e53e88f666d5e | [
"MIT"
] | null | null | null | onut/src/onut.cpp | Daivuk/ggj16 | 0ba896f3b6ece32ed3a6e190825e53e88f666d5e | [
"MIT"
] | 1 | 2019-10-19T04:49:33.000Z | 2019-10-19T04:49:33.000Z | #include <cassert>
#include <mutex>
#include <sstream>
#include "Audio.h"
#include "InputDevice.h"
#include "onut.h"
#include "Window.h"
using namespace DirectX;
// Our engine services
onut::Window* OWindow = nullptr;
onut::Renderer* ORenderer = nullptr;
onut::Settings* OSettings = new onut::Settings();
onut::SpriteBatch* OSpriteBatch = nullptr;
onut::PrimitiveBatch* OPrimitiveBatch = nullptr;
onut::GamePad* g_gamePads[4] = {nullptr};
onut::EventManager* OEvent = nullptr;
onut::ContentManager* OContentManager = nullptr;
AudioEngine* g_pAudioEngine = nullptr;
onut::TimeInfo<> g_timeInfo;
onut::Synchronous<onut::Pool<>> g_mainSync;
onut::ParticleSystemManager<>* OParticles = nullptr;
Vector2 OMousePos;
onut::InputDevice* g_inputDevice = nullptr;
onut::Input* OInput = nullptr;
onut::UIContext* OUIContext = nullptr;
onut::UIControl* OUI = nullptr;
onut::Music* OMusic = nullptr;
// So commonly used stuff
float ODT = 0.f;
namespace onut
{
void createUI()
{
OUIContext = new UIContext(sUIVector2(OScreenWf, OScreenHf));
OUI = new UIControl();
OUI->retain();
OUI->widthType = eUIDimType::DIM_RELATIVE;
OUI->heightType = eUIDimType::DIM_RELATIVE;
OUIContext->onClipping = [](bool enabled, const onut::sUIRect& rect)
{
OSB->end();
ORenderer->setScissor(enabled, onut::UI2Onut(rect));
OSB->begin();
};
auto getTextureForState = [](onut::UIControl *pControl, const std::string &filename)
{
static std::string stateFilename;
stateFilename = filename;
OTexture *pTexture;
switch (pControl->getState(*OUIContext))
{
case onut::eUIState::NORMAL:
pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::DISABLED:
stateFilename.insert(filename.size() - 4, "_disabled");
pTexture = OGetTexture(stateFilename.c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::HOVER:
stateFilename.insert(filename.size() - 4, "_hover");
pTexture = OGetTexture(stateFilename.c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::DOWN:
stateFilename.insert(filename.size() - 4, "_down");
pTexture = OGetTexture(stateFilename.c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
}
return pTexture;
};
OUIContext->drawRect = [=](onut::UIControl *pControl, const onut::sUIRect &rect, const onut::sUIColor &color)
{
OSB->drawRect(nullptr, onut::UI2Onut(rect), onut::UI2Onut(color));
};
OUIContext->drawTexturedRect = [=](onut::UIControl *pControl, const onut::sUIRect &rect, const onut::sUIImageComponent &image)
{
OSB->drawRect(getTextureForState(pControl, image.filename),
onut::UI2Onut(rect),
onut::UI2Onut(image.color));
};
OUIContext->drawScale9Rect = [=](onut::UIControl* pControl, const onut::sUIRect& rect, const onut::sUIScale9Component& scale9)
{
const std::string &filename = scale9.image.filename;
OTexture *pTexture;
switch (pControl->getState(*OUIContext))
{
case onut::eUIState::NORMAL:
pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::DISABLED:
pTexture = OGetTexture((filename + "_disabled").c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::HOVER:
pTexture = OGetTexture((filename + "_hover").c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
case onut::eUIState::DOWN:
pTexture = OGetTexture((filename + "_down").c_str());
if (!pTexture) pTexture = OGetTexture(filename.c_str());
break;
}
if (scale9.isRepeat)
{
OSB->drawRectScaled9RepeatCenters(getTextureForState(pControl, scale9.image.filename),
onut::UI2Onut(rect),
onut::UI2Onut(scale9.padding),
onut::UI2Onut(scale9.image.color));
}
else
{
OSB->drawRectScaled9(getTextureForState(pControl, scale9.image.filename),
onut::UI2Onut(rect),
onut::UI2Onut(scale9.padding),
onut::UI2Onut(scale9.image.color));
}
};
OUIContext->drawText = [=](onut::UIControl* pControl, const onut::sUIRect& rect, const onut::sUITextComponent& text)
{
if (text.text.empty()) return;
auto align = onut::UI2Onut(text.font.align);
auto oRect = onut::UI2Onut(rect);
auto pFont = OGetBMFont(text.font.typeFace.c_str());
auto oColor = onut::UI2Onut(text.font.color);
if (pControl->getState(*OUIContext) == onut::eUIState::DISABLED)
{
oColor = {.4f, .4f, .4f, 1};
}
oColor.Premultiply();
if (pFont)
{
if (pControl->getStyleName() == "password")
{
std::string pwd;
pwd.resize(text.text.size(), '*');
if (pControl->hasFocus(*OUIContext) && ((onut::UITextBox*)pControl)->isCursorVisible())
{
pwd.back() = '_';
}
pFont->draw<>(pwd, ORectAlign<>(oRect, align), oColor, OSB, align);
}
else
{
pFont->draw<>(text.text, ORectAlign<>(oRect, align), oColor, OSB, align);
}
}
};
OUIContext->addTextCaretSolver<onut::UITextBox>("", [=](const onut::UITextBox* pTextBox, const onut::sUIVector2& localPos) -> decltype(std::string().size())
{
auto pFont = OGetBMFont(pTextBox->textComponent.font.typeFace.c_str());
if (!pFont) return 0;
auto& text = pTextBox->textComponent.text;
return pFont->caretPos(text, localPos.x - 4);
});
OWindow->onWrite = [](char c)
{
OUIContext->write(c);
};
OWindow->onKey = [](uintptr_t key)
{
OUIContext->keyDown(key);
};
OUIContext->addStyle<onut::UIPanel>("blur", [](const onut::UIPanel* pPanel, const onut::sUIRect& rect)
{
OSB->end();
ORenderer->getRenderTarget()->blur();
OSB->begin();
OSB->drawRect(nullptr, onut::UI2Onut(rect), Color(0, 0, 0, .5f));
});
}
void createServices()
{
// Random
randomizeSeed();
// Events
OEvent = new EventManager();
// Window
OWindow = new Window(OSettings->getResolution(), OSettings->getIsResizableWindow());
// DirectX
ORenderer = new Renderer(*OWindow);
// SpriteBatch
OSB = new SpriteBatch();
OPB = new PrimitiveBatch();
// Content
OContentManager = new ContentManager();
OContentManager->addDefaultSearchPaths();
// Mouse/Keyboard
g_inputDevice = new InputDevice(OWindow);
OInput = new onut::Input(OINPUT_MOUSEZ + 1);
// Gamepads
for (int i = 0; i < 4; ++i)
{
g_gamePads[i] = new GamePad(i);
g_gamePads[i]->update();
}
// Audio
#ifdef WIN32
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
#endif
AUDIO_ENGINE_FLAGS eflags = AudioEngine_Default;
#ifdef _DEBUG
eflags = eflags | AudioEngine_Debug;
#endif
try
{
g_pAudioEngine = new AudioEngine(eflags);
}
catch (std::exception e)
{
}
// Particles
OParticles = new ParticleSystemManager<>();
// Register a bunch of default events
OEvent->addEvent("NavigateLeft", []
{
return OJustPressed(OLeftBtn) || OJustPressed(OLLeftBtn);
});
OEvent->addEvent("NavigateRight", []
{
return OJustPressed(ORightBtn) || OJustPressed(OLRightBtn);
});
OEvent->addEvent("NavigateUp", []
{
return OJustPressed(OUpBtn) || OJustPressed(OLUpBtn);
});
OEvent->addEvent("NavigateDown", []
{
return OJustPressed(ODownBtn) || OJustPressed(OLDownBtn);
});
OEvent->addEvent("Accept", []
{
return OJustPressed(OABtn) || OJustPressed(OStartBtn);
});
OEvent->addEvent("Cancel", []
{
return OJustPressed(OBBtn);
});
OEvent->addEvent("Start", []
{
return OJustPressed(OStartBtn);
});
OEvent->addEvent("Back", []
{
return OJustPressed(OBackBtn) || OJustPressed(OBBtn);
});
// UI Context
createUI();
// Music
OMusic = new onut::Music();
}
void cleanup()
{
delete OMusic;
delete OUIContext;
delete OParticles;
delete g_pAudioEngine;
for (int i = 0; i < 4; ++i)
{
delete g_gamePads[i];
}
delete OInput;
delete g_inputDevice;
delete OContentManager;
delete OPB;
delete OSB;
delete ORenderer;
delete OWindow;
delete OEvent;
}
// Start the engine
void run(std::function<void()> initCallback, std::function<void()> updateCallback, std::function<void()> renderCallback)
{
// Make sure we run just once
static bool alreadyRan = false;
assert(!alreadyRan);
alreadyRan = true;
createServices();
// Call the user defined init
if (initCallback)
{
initCallback();
}
// Main loop
MSG msg = {0};
while (true)
{
if (OSettings->getIsEditorMode())
{
if (GetMessage(&msg, 0, 0, 0) >= 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
{
break;
}
}
}
else
{
if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
{
break;
}
}
}
// Sync to main callbacks
g_mainSync.processQueue();
// Update
if (g_pAudioEngine) g_pAudioEngine->Update();
auto framesToUpdate = g_timeInfo.update(OSettings->getIsFixedStep());
ODT = onut::getTimeInfo().getDeltaTime<float>();
while (framesToUpdate--)
{
g_inputDevice->update();
OInput->update();
POINT cur;
GetCursorPos(&cur);
ScreenToClient(OWindow->getHandle(), &cur);
OInput->mousePos.x = cur.x;
OInput->mousePos.y = cur.y;
OInput->mousePosf.x = static_cast<float>(cur.x);
OInput->mousePosf.y = static_cast<float>(cur.y);
OMousePos = OInput->mousePosf;
for (auto& gamePad : g_gamePads)
{
gamePad->update();
}
if (OUIContext->useNavigation)
{
OUI->update(*OUIContext, sUIVector2(OInput->mousePosf.x, OInput->mousePosf.y), OGamePadPressed(OABtn), false, false,
OGamePadJustPressed(OLeftBtn) || OGamePadJustPressed(OLLeftBtn),
OGamePadJustPressed(ORightBtn) || OGamePadJustPressed(OLRightBtn),
OGamePadJustPressed(OUpBtn) || OGamePadJustPressed(OLUpBtn),
OGamePadJustPressed(ODownBtn) || OGamePadJustPressed(OLDownBtn),
0.f);
}
else
{
OUI->update(*OUIContext, sUIVector2(OInput->mousePosf.x, OInput->mousePosf.y), OPressed(OINPUT_MOUSEB1), OPressed(OINPUT_MOUSEB2), OPressed(OINPUT_MOUSEB3),
false, false, false, false,
OPressed(OINPUT_LCONTROL), OInput->getStateValue(OINPUT_MOUSEZ));
}
AnimManager::getGlobalManager()->update();
OEvent->processEvents();
OParticles->update();
if (updateCallback)
{
updateCallback();
}
}
// Render
g_timeInfo.render();
ORenderer->beginFrame();
if (renderCallback)
{
renderCallback();
}
OParticles->render();
OSB->begin();
OSB->changeFiltering(onut::SpriteBatch::eFiltering::Nearest);
OUI->render(*OUIContext);
OSB->end();
ORenderer->endFrame();
}
cleanup();
}
GamePad* getGamePad(int index)
{
assert(index >= 0 && index <= 3);
return g_gamePads[index];
}
const TimeInfo<>& getTimeInfo()
{
return g_timeInfo;
}
void drawPal(const OPal& pal, OFont* pFont)
{
static const float H = 32.f;
float i = 0;
OSB->begin();
for (auto& color : pal)
{
OSB->drawRect(nullptr, {0, i, H * GOLDEN_RATIO, H}, color);
i += H;
}
if (pFont)
{
i = 0;
int index = 0;
for (auto& color : pal)
{
std::stringstream ss;
ss << index;
pFont->draw<OCenter>(ss.str(), Rect{0, i, H * GOLDEN_RATIO, H}.Center(), Color::Black);
i += H;
++index;
}
}
OSB->end();
}
}
| 33.982301 | 176 | 0.484375 | Daivuk |
c7415ed8fe10f663b4035c93700c36926c2e33a4 | 1,482 | cpp | C++ | tools/Container/Containerlogger.cpp | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | 8 | 2015-01-23T05:41:46.000Z | 2019-11-20T05:10:27.000Z | tools/Container/Containerlogger.cpp | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | null | null | null | tools/Container/Containerlogger.cpp | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | 4 | 2015-05-05T05:15:43.000Z | 2020-03-07T11:10:56.000Z | /*********************************************************************************************************
* Containerlogger.cpp
* Note: Phoenix Container
* Date: @2015.03
* E-mail:<[email protected]>
* Copyright (C) 2015 The ForceStudio All Rights Reserved.
**********************************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>
#include "ContainerAPI.h"
static FILE *logfp=nullptr;
static bool SetDefaultLogger()
{
wchar_t temp[4096]={0};
if(GetTempPathW(256,temp)==0)
return false;/// This Function invoke failed.
#if defined(_MSC_VER)&& _MSC_VER>=1400
wcscat_s(temp,4096,L"/Phoenix.tools.Container.defualt.v1.log");
if(_wfopen_s(&logfp,temp,L"a+")!=0)
return false;
#else
wcscat(temp,L"/Phoenix.tools.Container.defualt.v1.log");
if((logfp=wfopen(temp,L"a+"))==nullptr)
return false;
#endif
return true;
}
bool InitializeLogger()
{
return SetDefaultLogger();
}
void LoggerDestory()
{
if(logfp)
fclose(logfp);
}
void TRACEWithFile(FILE *fp,const wchar_t* format,...)
{
if(fp!=nullptr)
{
int ret;
va_list ap;
va_start(ap, format);
ret = vfwprintf_s(fp, format, ap);
va_end(ap);
}
}
void TRACE(const wchar_t* format,...)
{
if(logfp!=nullptr)
{
int ret;
va_list ap;
va_start(ap, format);
ret = vfwprintf_s(logfp, format, ap);
va_end(ap);
}
}
| 22.119403 | 107 | 0.556005 | fstudio |
c7449a6d1a4cda9ce40b45a470791de89486a982 | 2,630 | cpp | C++ | RegisterCodeGenerator/RegisterCodeGenerator.cpp | kevinwu1024/ExtremeCopy | de9ba1aef769d555d10916169ccf2570c69a8d01 | [
"Apache-2.0"
] | 67 | 2020-11-12T11:51:37.000Z | 2022-03-01T13:44:43.000Z | RegisterCodeGenerator/RegisterCodeGenerator.cpp | kevinwu1024/ExtremeCopy | de9ba1aef769d555d10916169ccf2570c69a8d01 | [
"Apache-2.0"
] | 4 | 2021-04-09T08:22:06.000Z | 2021-06-07T13:43:13.000Z | RegisterCodeGenerator/RegisterCodeGenerator.cpp | kevinwu1024/ExtremeCopy | de9ba1aef769d555d10916169ccf2570c69a8d01 | [
"Apache-2.0"
] | 12 | 2020-11-12T11:51:42.000Z | 2022-02-11T08:07:37.000Z | /****************************************************************************
Copyright (c) 2008-2020 Kevin Wu (Wu Feng)
github: https://github.com/kevinwu1024/ExtremeCopy
site: http://www.easersoft.com
Licensed under the Apache License, Version 2.0 License (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
https://opensource.org/licenses/Apache-2.0
****************************************************************************/
#include "stdafx.h"
#include "RegisterCodeGenerator.h"
#include "RegisterCodeGeneratorDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CRegisterCodeGeneratorApp
BEGIN_MESSAGE_MAP(CRegisterCodeGeneratorApp, CWinAppEx)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CRegisterCodeGeneratorApp construction
CRegisterCodeGeneratorApp::CRegisterCodeGeneratorApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CRegisterCodeGeneratorApp object
CRegisterCodeGeneratorApp theApp;
// CRegisterCodeGeneratorApp initialization
BOOL CRegisterCodeGeneratorApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinAppEx::InitInstance();
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
//SetRegistryKey(_T("Local AppWizard-Generated Applications"));
CRegisterCodeGeneratorDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| 29.222222 | 104 | 0.725095 | kevinwu1024 |
c7483cb6f45312806af90fa08caae046cdbee30b | 274 | cpp | C++ | source/scene/entity.cpp | Kostu96/k2d-engine | 8150230034cf4afc862fcc1a3c262c27d544feed | [
"MIT"
] | null | null | null | source/scene/entity.cpp | Kostu96/k2d-engine | 8150230034cf4afc862fcc1a3c262c27d544feed | [
"MIT"
] | null | null | null | source/scene/entity.cpp | Kostu96/k2d-engine | 8150230034cf4afc862fcc1a3c262c27d544feed | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2021-2022 Konstanty Misiak
*
* SPDX-License-Identifier: MIT
*/
#include "scene/entity.hpp"
namespace k2d {
Entity::Entity(entt::entity handle, Scene& scene) :
m_handle(handle),
m_sceneRef(scene)
{
}
} // namespace k2d
| 14.421053 | 55 | 0.616788 | Kostu96 |
c74a50bad375c1f42e1c7bb3d7ac8674ae8754a4 | 4,786 | cpp | C++ | AcrosyncSwift/rsync/block/t_block_out.cpp | aaronvegh/AcrosyncSwift | 469201f6d8ca407334d515260e47526c6965d008 | [
"Unlicense"
] | null | null | null | AcrosyncSwift/rsync/block/t_block_out.cpp | aaronvegh/AcrosyncSwift | 469201f6d8ca407334d515260e47526c6965d008 | [
"Unlicense"
] | null | null | null | AcrosyncSwift/rsync/block/t_block_out.cpp | aaronvegh/AcrosyncSwift | 469201f6d8ca407334d515260e47526c6965d008 | [
"Unlicense"
] | null | null | null | #include "block_out.h"
#include <stdio.h>
struct UserType1
{
int d_i;
double d_d;
};
class UserType2
{
int d_i;
double d_d;
public:
UserType2() {}
~UserType2() {}
};
class Source
{
public:
block::out<void()> out0;
block::out<void(const char*)> out1;
block::out<void(const char*, int)> out2;
block::out<void(const char*, int, char)> out3;
block::out<void(const char*, int, char, float)> out4;
block::out<void(const char*, int, char, float, double)> out5;
block::out<void(const char*, int, char, float, double, void *)> out6;
block::out<void(const char*, int, char, float, double, void *, UserType1)> out7;
block::out<void(const char*, int, char, float, double, void *, UserType1, UserType2)> out8;
// not connected
block::out<void(int, double)> out100;
block::out<void(const int &, double)> out101;
block::out<void(int, const double&)> out102;
block::out<int(int, double)> out103;
block::out<void(int&, double)> out104;
block::out<void(int, double&)> out105;
// connected to mulitple inports
block::out<void(int, double)> out200;
block::out<void(const int &, double)> out201;
block::out<void(int, const double&)> out202;
block::out<int(int, double)> out203;
block::out<void(int&, double)> out204;
block::out<void(int, double&)> out205;
void Run()
{
out0();
out1("Hello World");
out2("Hello World", 1);
out3("Hello World", 1, '2');
out4("Hello World", 1, '2', 3.0f);
out5("Hello World", 1, '2', 3.0f, 4.0);
out6("Hello World", 1, '2', 3.0f, 4.0, 0);
out7("Hello World", 1, '2', 3.0f, 4.0, 0, UserType1());
out8("Hello World", 1, '2', 3.0f, 4.0, 0, UserType1(), UserType2());
int i = 1;
double d = 2.0;
out100(1, 2.0);
out101(1, 2.0);
out102(1, 2.0);
//out103(1, 2.0);
out104(i, d);
out105(i, d);
out200(1, 2.0);
out201(1, 2.0);
out202(1, 2.0);
out203(1, 2.0);
out204(i, d);
out205(i, d);
}
};
struct Dummy
{
int d_i;
int d_double;
};
class Sink : public Dummy
{
private:
mutable int d_numCalls;
public:
Sink()
: d_numCalls(0)
{
}
int numCalls() const { return d_numCalls; }
void in0()
{
++d_numCalls;
}
void in1(const char*) const
{
++d_numCalls;
}
void in2(const char*, int)
{
++d_numCalls;
}
void in3(const char*, int, char) const
{
++d_numCalls;
}
void in4(const char*, int, char, float)
{
++d_numCalls;
}
void in5(const char*, int, char, float, double) const
{
++d_numCalls;
}
void in6(const char*, int, char, float, double, void *)
{
++d_numCalls;
}
void in7(const char*, int, char, float, double, void *, UserType1) const
{
++d_numCalls;
}
void in8(const char*, int, char, float, double, void *, UserType1, UserType2)
{
++d_numCalls;
}
void in200(int, double)
{
++d_numCalls;
}
void in201(const int&, double)
{
++d_numCalls;
}
void in202(int, const double&)
{
++d_numCalls;
}
int in203(int, double)
{
++d_numCalls;
return d_numCalls;
}
void in204(int&, double)
{
++d_numCalls;
}
void in205(int, double&)
{
++d_numCalls;
}
};
int main(int argc, char *argv[])
{
{
Source source;
Sink sink;
source.out0.connect(&sink, &Sink::in0);
source.out1.connect(&sink, &Sink::in1);
source.out2.connect(&sink, &Sink::in2);
source.out3.connect(&sink, &Sink::in3);
source.out4.connect(&sink, &Sink::in4);
source.out5.connect(&sink, &Sink::in5);
source.out6.connect(&sink, &Sink::in6);
source.out7.connect(&sink, &Sink::in7);
source.out8.connect(&sink, &Sink::in8);
source.out200.connect(&sink, &Sink::in200);
source.out200.connect(&sink, &Sink::in200);
source.out201.connect(&sink, &Sink::in201);
source.out201.connect(&sink, &Sink::in201);
source.out202.connect(&sink, &Sink::in202);
source.out202.connect(&sink, &Sink::in202);
source.out203.connect(&sink, &Sink::in203);
source.out203.connect(&sink, &Sink::in203);
source.out204.connect(&sink, &Sink::in204);
source.out204.connect(&sink, &Sink::in204);
source.out205.connect(&sink, &Sink::in205);
source.out205.connect(&sink, &Sink::in205);
source.Run();
printf("Member functions of Sink have been called %d times\n", sink.numCalls());
}
return 0;
}
| 23.93 | 95 | 0.547221 | aaronvegh |
c75b9297fc5af22e94dd59a6431d3def2205444e | 14,738 | cpp | C++ | jack/common/JackAudioAdapterInterface.cpp | KimJeongYeon/jack2_android | 4a8787be4306558cb52e5379466c0ed4cc67e788 | [
"BSD-3-Clause-No-Nuclear-Warranty"
] | 47 | 2015-01-04T21:47:07.000Z | 2022-03-23T16:27:16.000Z | vendor/samsung/external/jack/common/JackAudioAdapterInterface.cpp | cesarmo759/android_kernel_samsung_msm8916 | f19717ef6c984b64a75ea600a735dc937b127c25 | [
"Apache-2.0"
] | 3 | 2015-02-04T21:40:11.000Z | 2019-09-16T19:53:51.000Z | jack/common/JackAudioAdapterInterface.cpp | KimJeongYeon/jack2_android | 4a8787be4306558cb52e5379466c0ed4cc67e788 | [
"BSD-3-Clause-No-Nuclear-Warranty"
] | 7 | 2015-05-17T08:22:52.000Z | 2021-08-07T22:36:17.000Z | /*
Copyright (C) 2008 Grame
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifdef __APPLE__
#include <TargetConditionals.h>
#endif
#include "JackAudioAdapter.h"
#ifndef MY_TARGET_OS_IPHONE
#include "JackLibSampleRateResampler.h"
#endif
#include "JackTime.h"
#include "JackError.h"
#include <stdio.h>
namespace Jack
{
#ifdef JACK_MONITOR
void MeasureTable::Write(int time1, int time2, float r1, float r2, int pos1, int pos2)
{
int pos = (++fCount) % TABLE_MAX;
fTable[pos].time1 = time1;
fTable[pos].time2 = time2;
fTable[pos].r1 = r1;
fTable[pos].r2 = r2;
fTable[pos].pos1 = pos1;
fTable[pos].pos2 = pos2;
}
void MeasureTable::Save(unsigned int fHostBufferSize, unsigned int fHostSampleRate, unsigned int fAdaptedSampleRate, unsigned int fAdaptedBufferSize)
{
FILE* file = fopen("JackAudioAdapter.log", "w");
int max = (fCount) % TABLE_MAX - 1;
for (int i = 1; i < max; i++) {
fprintf(file, "%d \t %d \t %d \t %f \t %f \t %d \t %d \n",
fTable[i].delta, fTable[i].time1, fTable[i].time2,
fTable[i].r1, fTable[i].r2, fTable[i].pos1, fTable[i].pos2);
}
fclose(file);
// No used for now
// Adapter timing 1
file = fopen("AdapterTiming1.plot", "w");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"frames\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 2 title \"Ringbuffer error\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 3 title \"Ringbuffer error with timing correction\" with lines");
fprintf(file, "\n unset multiplot\n");
fprintf(file, "set output 'AdapterTiming1.svg\n");
fprintf(file, "set terminal svg\n");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"frames\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 2 title \"Consumer interrupt period\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 3 title \"Producer interrupt period\" with lines\n");
fprintf(file, "unset multiplot\n");
fprintf(file, "unset output\n");
fclose(file);
// Adapter timing 2
file = fopen("AdapterTiming2.plot", "w");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"resampling ratio\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 4 title \"Ratio 1\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 5 title \"Ratio 2\" with lines");
fprintf(file, "\n unset multiplot\n");
fprintf(file, "set output 'AdapterTiming2.svg\n");
fprintf(file, "set terminal svg\n");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"resampling ratio\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 4 title \"Ratio 1\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 5 title \"Ratio 2\" with lines\n");
fprintf(file, "unset multiplot\n");
fprintf(file, "unset output\n");
fclose(file);
// Adapter timing 3
file = fopen("AdapterTiming3.plot", "w");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"frames\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 6 title \"Frames position in consumer ringbuffer\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 7 title \"Frames position in producer ringbuffer\" with lines");
fprintf(file, "\n unset multiplot\n");
fprintf(file, "set output 'AdapterTiming3.svg\n");
fprintf(file, "set terminal svg\n");
fprintf(file, "set multiplot\n");
fprintf(file, "set grid\n");
fprintf(file, "set title \"Audio adapter timing: host [rate = %.1f kHz buffer = %d frames] adapter [rate = %.1f kHz buffer = %d frames] \"\n"
,float(fHostSampleRate)/1000.f, fHostBufferSize, float(fAdaptedSampleRate)/1000.f, fAdaptedBufferSize);
fprintf(file, "set xlabel \"audio cycles\"\n");
fprintf(file, "set ylabel \"frames\"\n");
fprintf(file, "plot ");
fprintf(file, "\"JackAudioAdapter.log\" using 6 title \"Frames position in consumer ringbuffer\" with lines,");
fprintf(file, "\"JackAudioAdapter.log\" using 7 title \"Frames position in producer ringbuffer\" with lines\n");
fprintf(file, "unset multiplot\n");
fprintf(file, "unset output\n");
fclose(file);
}
#endif
void JackAudioAdapterInterface::GrowRingBufferSize()
{
fRingbufferCurSize *= 2;
}
void JackAudioAdapterInterface::AdaptRingBufferSize()
{
if (fHostBufferSize > fAdaptedBufferSize) {
fRingbufferCurSize = 4 * fHostBufferSize;
} else {
fRingbufferCurSize = 4 * fAdaptedBufferSize;
}
}
void JackAudioAdapterInterface::ResetRingBuffers()
{
if (fRingbufferCurSize > DEFAULT_RB_SIZE) {
fRingbufferCurSize = DEFAULT_RB_SIZE;
}
for (int i = 0; i < fCaptureChannels; i++) {
fCaptureRingBuffer[i]->Reset(fRingbufferCurSize);
}
for (int i = 0; i < fPlaybackChannels; i++) {
fPlaybackRingBuffer[i]->Reset(fRingbufferCurSize);
}
}
void JackAudioAdapterInterface::Reset()
{
ResetRingBuffers();
fRunning = false;
}
#ifdef MY_TARGET_OS_IPHONE
void JackAudioAdapterInterface::Create()
{}
#else
void JackAudioAdapterInterface::Create()
{
//ringbuffers
fCaptureRingBuffer = new JackResampler*[fCaptureChannels];
fPlaybackRingBuffer = new JackResampler*[fPlaybackChannels];
if (fAdaptative) {
AdaptRingBufferSize();
jack_info("Ringbuffer automatic adaptative mode size = %d frames", fRingbufferCurSize);
} else {
if (fRingbufferCurSize > DEFAULT_RB_SIZE) {
fRingbufferCurSize = DEFAULT_RB_SIZE;
}
jack_info("Fixed ringbuffer size = %d frames", fRingbufferCurSize);
}
for (int i = 0; i < fCaptureChannels; i++ ) {
fCaptureRingBuffer[i] = new JackLibSampleRateResampler(fQuality);
fCaptureRingBuffer[i]->Reset(fRingbufferCurSize);
}
for (int i = 0; i < fPlaybackChannels; i++ ) {
fPlaybackRingBuffer[i] = new JackLibSampleRateResampler(fQuality);
fPlaybackRingBuffer[i]->Reset(fRingbufferCurSize);
}
if (fCaptureChannels > 0) {
jack_log("ReadSpace = %ld", fCaptureRingBuffer[0]->ReadSpace());
}
if (fPlaybackChannels > 0) {
jack_log("WriteSpace = %ld", fPlaybackRingBuffer[0]->WriteSpace());
}
}
#endif
void JackAudioAdapterInterface::Destroy()
{
for (int i = 0; i < fCaptureChannels; i++) {
delete(fCaptureRingBuffer[i]);
}
for (int i = 0; i < fPlaybackChannels; i++) {
delete (fPlaybackRingBuffer[i]);
}
delete[] fCaptureRingBuffer;
delete[] fPlaybackRingBuffer;
}
int JackAudioAdapterInterface::PushAndPull(float** inputBuffer, float** outputBuffer, unsigned int frames)
{
bool failure = false;
fRunning = true;
// Finer estimation of the position in the ringbuffer
int delta_frames = (fPullAndPushTime > 0) ? (int)((float(long(GetMicroSeconds() - fPullAndPushTime)) * float(fAdaptedSampleRate)) / 1000000.f) : 0;
double ratio = 1;
// TODO : done like this just to avoid crash when input only or output only...
if (fCaptureChannels > 0) {
ratio = fPIControler.GetRatio(fCaptureRingBuffer[0]->GetError() - delta_frames);
} else if (fPlaybackChannels > 0) {
ratio = fPIControler.GetRatio(fPlaybackRingBuffer[0]->GetError() - delta_frames);
}
#ifdef JACK_MONITOR
if (fCaptureRingBuffer && fCaptureRingBuffer[0] != NULL)
fTable.Write(fCaptureRingBuffer[0]->GetError(), fCaptureRingBuffer[0]->GetError() - delta_frames, ratio, 1/ratio, fCaptureRingBuffer[0]->ReadSpace(), fCaptureRingBuffer[0]->ReadSpace());
#endif
// Push/pull from ringbuffer
for (int i = 0; i < fCaptureChannels; i++) {
fCaptureRingBuffer[i]->SetRatio(ratio);
if (inputBuffer[i]) {
if (fCaptureRingBuffer[i]->WriteResample(inputBuffer[i], frames) < frames) {
failure = true;
}
}
}
for (int i = 0; i < fPlaybackChannels; i++) {
fPlaybackRingBuffer[i]->SetRatio(1/ratio);
if (outputBuffer[i]) {
if (fPlaybackRingBuffer[i]->ReadResample(outputBuffer[i], frames) < frames) {
failure = true;
}
}
}
// Reset all ringbuffers in case of failure
if (failure) {
jack_error("JackAudioAdapterInterface::PushAndPull ringbuffer failure... reset");
if (fAdaptative) {
GrowRingBufferSize();
jack_info("Ringbuffer size = %d frames", fRingbufferCurSize);
}
ResetRingBuffers();
return -1;
} else {
return 0;
}
}
int JackAudioAdapterInterface::PullAndPush(float** inputBuffer, float** outputBuffer, unsigned int frames)
{
fPullAndPushTime = GetMicroSeconds();
if (!fRunning)
return 0;
int res = 0;
// Push/pull from ringbuffer
for (int i = 0; i < fCaptureChannels; i++) {
if (inputBuffer[i]) {
if (fCaptureRingBuffer[i]->Read(inputBuffer[i], frames) < frames) {
res = -1;
}
}
}
for (int i = 0; i < fPlaybackChannels; i++) {
if (outputBuffer[i]) {
if (fPlaybackRingBuffer[i]->Write(outputBuffer[i], frames) < frames) {
res = -1;
}
}
}
return res;
}
int JackAudioAdapterInterface::SetHostBufferSize(jack_nframes_t buffer_size)
{
fHostBufferSize = buffer_size;
if (fAdaptative) {
AdaptRingBufferSize();
}
return 0;
}
int JackAudioAdapterInterface::SetAdaptedBufferSize(jack_nframes_t buffer_size)
{
fAdaptedBufferSize = buffer_size;
if (fAdaptative) {
AdaptRingBufferSize();
}
return 0;
}
int JackAudioAdapterInterface::SetBufferSize(jack_nframes_t buffer_size)
{
SetHostBufferSize(buffer_size);
SetAdaptedBufferSize(buffer_size);
return 0;
}
int JackAudioAdapterInterface::SetHostSampleRate(jack_nframes_t sample_rate)
{
fHostSampleRate = sample_rate;
fPIControler.Init(double(fHostSampleRate) / double(fAdaptedSampleRate));
return 0;
}
int JackAudioAdapterInterface::SetAdaptedSampleRate(jack_nframes_t sample_rate)
{
fAdaptedSampleRate = sample_rate;
fPIControler.Init(double(fHostSampleRate) / double(fAdaptedSampleRate));
return 0;
}
int JackAudioAdapterInterface::SetSampleRate(jack_nframes_t sample_rate)
{
SetHostSampleRate(sample_rate);
SetAdaptedSampleRate(sample_rate);
return 0;
}
void JackAudioAdapterInterface::SetInputs(int inputs)
{
jack_log("JackAudioAdapterInterface::SetInputs %d", inputs);
fCaptureChannels = inputs;
}
void JackAudioAdapterInterface::SetOutputs(int outputs)
{
jack_log("JackAudioAdapterInterface::SetOutputs %d", outputs);
fPlaybackChannels = outputs;
}
int JackAudioAdapterInterface::GetInputs()
{
//jack_log("JackAudioAdapterInterface::GetInputs %d", fCaptureChannels);
return fCaptureChannels;
}
int JackAudioAdapterInterface::GetOutputs()
{
//jack_log ("JackAudioAdapterInterface::GetOutputs %d", fPlaybackChannels);
return fPlaybackChannels;
}
} // namespace
| 37.501272 | 198 | 0.612838 | KimJeongYeon |
c75f385c1ed02bf476e70989d760aa477b4e43f7 | 3,025 | cpp | C++ | src/Main.cpp | innatewonder/onyx | fffb16ab068871fe3d948fa64eff81ce1dc31524 | [
"MIT"
] | null | null | null | src/Main.cpp | innatewonder/onyx | fffb16ab068871fe3d948fa64eff81ce1dc31524 | [
"MIT"
] | null | null | null | src/Main.cpp | innatewonder/onyx | fffb16ab068871fe3d948fa64eff81ce1dc31524 | [
"MIT"
] | null | null | null | #include "CommonPrecompiled.h"
#include "NetworkEngine.h"
#include "OnyxTransfer.h"
#include "HTTP.h"
#include "UDPBase.h"
#include "TCPBase.h"
#include "ByteArray.h"
//handle closing connections
//handle timeouts
//handle sending queue
//handle arbitrary connect requests
int main(int argc, char** argv)
{
ArgParser args(argc, argv);
args.AddCommand("-p", "-port", true);
args.AddCommand("-s", "-serv");
args.AddCommand("-sa", "-serverAddr", false, true);
args.AddCommand("-sp", "-serverPort", false, true);
args.AddCommand("-f", "-folder", false, true);
args.AddCommand("-tcp", "-tcp");
args.AddCommand("-w", "-http");
args.Parse();
auto array = Networking::ByteWriter();
array.WriteS16(-5);
array.WriteU32(7052);
array.WriteU16(89);
array.WriteS32(-8787);
array.WriteF32(56.329864f);
auto buff = array.GetData();
auto buffSize = array.GetSize();
LOG("buffsize " << buffSize)
auto readArray = Networking::ByteReader(buff, buffSize);
s16 v1 = readArray.ReadS16();
u32 v2 = readArray.ReadU32();
u16 v3 = readArray.ReadU16();
s32 v4 = readArray.ReadS32();
f32 v5 = readArray.ReadF32();
LOG(v1 << " " << v2 << " " << v3 << " " << v4 << " " << v5);
return 0;
int port = 0;
if(args.Has("-p"))
{
port = args.Get("-port")->val.iVal;
}
auto engine = new Networking::NetworkEngine();
engine->Initialize(args);
auto serverAddr = Networking::Address("localhost", "10294");
if(args.Has("-sa") && args.Has("-sp"))
{
LOG("Got server from command line");
serverAddr.SetAddress(args.Get("-sa")->val.sVal, args.Get("-sp")->val.sVal);
}
if(args.Has("-folder"))
{
LOG("Adding onyx reader with given folder");
String folder = args.Get("-folder")->val.sVal;
auto reader = new Filesystem::FilesystemReader();
reader->OpenFolder(folder, true);
reader->OpenFile("10294.onyx");
if(args.Has("-serv"))
{
engine->AddProtocol(
new Networking::OnyxServer()
);
while(1)
{
engine->Update(0.016f);
SLEEP_MILLI(5);
}
}
else
{
engine->AddProtocol(
new Networking::OnyxClient(serverAddr, reader->GetFolder(folder))
);
engine->Update(0.f);
}
}
else if(args.Has("-w"))
{
LOG("serving web on " << port);
engine->AddProtocol(
new Networking::HTTP(port)
);
}
else if(args.Has("-serv"))
{
LOG("serving on port " << port);
if(args.Has("-tcp"))
{
LOG("TCP");
engine->AddProtocol(
new Networking::TCPBase(port)
);
}
else
{
engine->AddProtocol(
new Networking::UDPBase(port)
);
}
}
else
{
LOG("Connecting to server at: " << serverAddr)
if(args.Has("-tcp"))
{
LOG("TCP");
engine->AddProtocol(
new Networking::TCPBase(serverAddr, port)
);
}
else
{
engine->AddProtocol(
new Networking::UDPBase(serverAddr, port)
);
}
}
delete engine;
return 0;
}
| 21.453901 | 80 | 0.584793 | innatewonder |
c75fe3c2eaa69eaa41aaa26580ad41719fc37422 | 4,546 | cpp | C++ | day12/day12-tests/day12-tests.cpp | MattHarrington/advent-of-code-2019 | 8733d2692c4d619d1db3b82645032eebca934334 | [
"MIT"
] | null | null | null | day12/day12-tests/day12-tests.cpp | MattHarrington/advent-of-code-2019 | 8733d2692c4d619d1db3b82645032eebca934334 | [
"MIT"
] | null | null | null | day12/day12-tests/day12-tests.cpp | MattHarrington/advent-of-code-2019 | 8733d2692c4d619d1db3b82645032eebca934334 | [
"MIT"
] | null | null | null | // https://adventofcode.com/2019/day/12
#include <catch.hpp>
#include <numeric>
#include "day12-lib.h"
TEST_CASE("sample after 1 timestep should be correct", "[part_one]") {
const std::vector<Moon> sample_moons{
Moon{{-1,0,2}, {0,0,0}},
Moon{{2,-10,-7}, {0,0,0}},
Moon{{4,-8,8}, {0,0,0}},
Moon{{3,5,-1}, {0,0,0}}
};
const std::vector<Moon> moons_after_one_timestep{
Moon{{2,-1,1}, {3,-1,-1}},
Moon{{3,-7,-4}, {1,3,3}},
Moon{{1,-7,5}, {-3,1,-3}},
Moon{{2,2,0}, {-1,-3,1}}
};
REQUIRE(timestep(sample_moons) == moons_after_one_timestep);
}
TEST_CASE("sample after 10 timesteps should be correct", "[part_one]") {
std::vector<Moon> sample_moons{
Moon{{-1,0,2}, {0,0,0}},
Moon{{2,-10,-7}, {0,0,0}},
Moon{{4,-8,8}, {0,0,0}},
Moon{{3,5,-1}, {0,0,0}}
};
const std::vector<Moon> moons_after_10_timesteps{
Moon{{2,1,-3}, {-3,-2,1}},
Moon{{1,-8,0}, {-1,1,3}},
Moon{{3,-6,1}, {3,2,-3}},
Moon{{2,0,4}, {1,-1,-1}}
};
for (int i{ 0 }; i < 10; ++i) {
sample_moons = timestep(sample_moons);
}
REQUIRE(sample_moons == moons_after_10_timesteps);
}
TEST_CASE("energy of sample moon 1 should be 36", "[part_one]") {
const Moon moon{ {2,1,-3}, {-3,-2,1} };
REQUIRE(get_total_energy(moon) == 36);
}
TEST_CASE("energy of sample moon 2 should be 45", "[part_one]") {
const Moon moon{ {1,-8,0}, {-1,1,3} };
REQUIRE(get_total_energy(moon) == 45);
}
TEST_CASE("energy after 10 timesteps should be 179", "[part_one]") {
const std::vector<Moon> moons_after_10_timesteps{
Moon{{2,1,-3}, {-3,-2,1}},
Moon{{1,-8,0}, {-1,1,3}},
Moon{{3,-6,1}, {3,2,-3}},
Moon{{2,0,4}, {1,-1,-1}}
};
const int total_energy{ std::accumulate(begin(moons_after_10_timesteps), end(moons_after_10_timesteps),
0, [](int t, Moon m) noexcept {return t + get_total_energy(m); }) };
REQUIRE(total_energy == 179);
}
TEST_CASE("sample moons should repeat x value at timestep 18", "[part_two]") {
std::vector<Moon> sample_moons{
Moon{{-1,0,2}, {0,0,0}},
Moon{{2,-10,-7}, {0,0,0}},
Moon{{4,-8,8}, {0,0,0}},
Moon{{3,5,-1}, {0,0,0}}
};
int step{ 0 };
do {
sample_moons = timestep(sample_moons);
++step;
} while (sample_moons.at(0).position.x != -1 || sample_moons.at(1).position.x != 2
|| sample_moons.at(2).position.x != 4 || sample_moons.at(3).position.x != 3
|| sample_moons.at(0).velocity.x_velocity == sample_moons.at(1).velocity.x_velocity ==
sample_moons.at(2).velocity.x_velocity == sample_moons.at(3).velocity.x_velocity == 0);
REQUIRE(step == 18);
}
TEST_CASE("sample moons should repeat y value at timestep 28", "[part_two]") {
std::vector<Moon> sample_moons{
Moon{{-1,0,2}, {0,0,0}},
Moon{{2,-10,-7}, {0,0,0}},
Moon{{4,-8,8}, {0,0,0}},
Moon{{3,5,-1}, {0,0,0}}
};
int step{ 0 };
do {
sample_moons = timestep(sample_moons);
++step;
} while (sample_moons.at(0).position.y != 0 || sample_moons.at(1).position.y != -10 ||
sample_moons.at(2).position.y != -8 || sample_moons.at(3).position.y != 5
|| sample_moons.at(0).velocity.y_velocity == sample_moons.at(1).velocity.y_velocity ==
sample_moons.at(2).velocity.y_velocity == sample_moons.at(3).velocity.y_velocity == 0);
REQUIRE(step == 28);
}
TEST_CASE("sample moons should repeat z value at timestep 44", "[part_two]") {
std::vector<Moon> sample_moons{
Moon{{-1,0,2}, {0,0,0}},
Moon{{2,-10,-7}, {0,0,0}},
Moon{{4,-8,8}, {0,0,0}},
Moon{{3,5,-1}, {0,0,0}}
};
int step{ 0 };
do {
sample_moons = timestep(sample_moons);
++step;
} while (sample_moons.at(0).position.z != 2 || sample_moons.at(1).position.z != -7 ||
sample_moons.at(2).position.z != 8 || sample_moons.at(3).position.z != -1
|| sample_moons.at(0).velocity.z_velocity == sample_moons.at(1).velocity.z_velocity ==
sample_moons.at(2).velocity.z_velocity == sample_moons.at(3).velocity.z_velocity == 0);
REQUIRE(step == 44);
}
TEST_CASE("sample moons should repeat state at timestep 2722", "[part_two]") {
// 18, 28, and 44 are results from other TEST_CASEs
constexpr int repeat_timestep_x_y{ std::lcm(18,28) };
constexpr int repeat_timestep_xy_z{ std::lcm(repeat_timestep_x_y, 44) };
REQUIRE(repeat_timestep_xy_z == 2772);
}
| 35.515625 | 107 | 0.568412 | MattHarrington |
c76028d3464e5ff58ddd818e7f2967162a374edd | 1,248 | cpp | C++ | ABC193/d.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | null | null | null | ABC193/d.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | 3 | 2021-03-31T01:39:25.000Z | 2021-05-04T10:02:35.000Z | ABC193/d.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; i < n; i++)
#define REPR(i, n) for (int i = n - 1; i >= 0; i--)
#define FOR(i, m, n) for (int i = m; i <= n; i++)
#define FORR(i, m, n) for (int i = m; i >= n; i--)
#define SORT(v, n) sort(v, v + n)
#define MAX 100000
#define inf 1000000007
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using P = pair<ll, ll>;
using Graph = vector<vector<int>>;
ll score(string s)
{
vector<ll> cnt(10);
// cnt[0] = 0, cnt[1] = 1, ..., cnt[9] = 9
iota(cnt.begin(), cnt.end(), 0);
// 見つかった枚数分だけ*10する
for (char c : s)
cnt[c - '0'] *= 10;
// 配列の合計値を求める
return accumulate(cnt.begin(), cnt.end(), 0);
}
int main()
{
ll k;
string s, t;
cin >> k >> s >> t;
vector<ll> cnt(10, k);
for (char c : s + t)
cnt[c - '0']--;
ll win = 0;
// x, yの組について全探索
FOR(x, 1, 9)
{
FOR(y, 1, 9)
{
s.back() = '0' + x;
t.back() = '0' + y;
if (score(s) <= score(t))
continue;
win += cnt[x] * (cnt[y] - (x == y));
}
}
cout << fixed << setprecision(10) << double(win) / ((9 * k - 8) * (9 * k - 9)) << "\n";
} | 25.469388 | 91 | 0.459936 | KoukiNAGATA |
c760b548acedc9bd42a014357a84a0c6ce7f791a | 1,086 | cpp | C++ | rules/gen/txt_to_cpp.cpp | hleclerc/nsmake | 01c246311cb37d6d85776db87e413c61c692c9dd | [
"Apache-2.0"
] | null | null | null | rules/gen/txt_to_cpp.cpp | hleclerc/nsmake | 01c246311cb37d6d85776db87e413c61c692c9dd | [
"Apache-2.0"
] | null | null | null | rules/gen/txt_to_cpp.cpp | hleclerc/nsmake | 01c246311cb37d6d85776db87e413c61c692c9dd | [
"Apache-2.0"
] | null | null | null | #include "Hpipe/Stream.h"
#include <iostream>
#include <fstream>
using namespace std;
int usage( const char *prg, const char *msg, int res ) {
if ( msg )
std::cerr << msg << std::endl;
std::cerr << "Usage:" << std::endl;
std::cerr << " " << prg << " cpp_var_name input_file" << std::endl;
return res;
}
int main( int argc, char **argv ) {
if ( argc != 3 )
return usage( argv[ 0 ], "nb args", 1 );
// std::ofstream fo( argv[ 1 ] );
std::ifstream fi( argv[ 1 ] );
if ( ! fi ) {
std::cerr << "Impossible to open file '" << argv[ 1 ] << "'" << std::endl;
return 2;
}
std::cout << "char " << argv[ 2 ] << "[] = {";
for( int i = 0; ; ++i ) {
char c = fi.get();
if ( fi.eof() )
c = 0;
if ( i )
std::cout << ", ";
if ( i % 16 == 0 )
std::cout << "\n ";
std::cout << (int)c;
if ( fi.eof() ) {
if ( i )
std::cout << "\n";
break;
}
}
std::cout << "};\n";
return 0;
}
| 23.608696 | 82 | 0.411602 | hleclerc |
c7633337f43003899682b90cd4316ad6daca03c4 | 1,086 | cpp | C++ | 1144/f.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | 1 | 2021-10-24T00:46:37.000Z | 2021-10-24T00:46:37.000Z | 1144/f.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | null | null | null | 1144/f.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <vector>
#include <tuple>
using namespace std;
const int MAXN = 200005;
int color[MAXN];
vector<int> g[MAXN];
vector<pair<int, int>> edges;
void dfs(int v, int p, bool &possible) {
if (!possible) {
return;
}
color[v] = color[p] + 1;
color[v] -= 2 * (color[v] > 2);
for (auto to: g[v]) {
if (to != p) {
if (color[to] == color[v]) {
possible = false;
return;
} else if (!color[to]) {
dfs(to, v, possible);
}
}
}
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
bool possible = true;
for (int i = 0; i < m; ++i) {
int u, v;
scanf("%d %d", &u, &v);
--u; --v;
g[u].push_back(v);
g[v].push_back(u);
edges.push_back({u, v});
}
dfs(0, 0, possible);
if (!possible) {
printf("NO\n");
} else {
printf("YES\n");
for (auto &edge: edges) {
int u, v;
std::tie(u, v) = edge;
if (color[u] < color[v]) {
printf("1");
} else {
printf("0");
}
}
printf("\n");
}
return 0;
}
| 16.208955 | 40 | 0.470534 | vladshablinsky |
c76cff58a164cf3f068a00c8527048a0d819ffd5 | 2,757 | cc | C++ | src/rtc_audio_track_impl.cc | necnecnec/libwebrtc | 220cc87ac678ff0675b16397f46a6a35ecd2ba9c | [
"MIT"
] | null | null | null | src/rtc_audio_track_impl.cc | necnecnec/libwebrtc | 220cc87ac678ff0675b16397f46a6a35ecd2ba9c | [
"MIT"
] | null | null | null | src/rtc_audio_track_impl.cc | necnecnec/libwebrtc | 220cc87ac678ff0675b16397f46a6a35ecd2ba9c | [
"MIT"
] | null | null | null | #include "rtc_audio_track_impl.h"
namespace libwebrtc {
AudioTrackImpl::AudioTrackImpl(
rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track)
: rtc_track_(audio_track),_renderer(nullptr) {
RTC_LOG(INFO) << __FUNCTION__ << ": ctor ";
if(rtc_track_){
strncpy(id_, rtc_track_->id().c_str(), sizeof(id_));
strncpy(kind_, rtc_track_->kind().c_str(), sizeof(kind_));
rtc_track_->AddSink(this);
}
}
AudioTrackImpl::~AudioTrackImpl() {
if(rtc_track_)
rtc_track_->RemoveSink(this);
RTC_LOG(INFO) << __FUNCTION__ << ": dtor ";
}
// AudioTrackSinkInterface implementation.
void AudioTrackImpl:: OnData(const void* audio_data,
int bits_per_sample,
int sample_rate,
size_t number_of_channels,
size_t number_of_frames,
absl::optional<int64_t> absolute_capture_timestamp_ms){
if(_renderer){
_renderer->OnData( audio_data,
static_cast<int>( bits_per_sample),
static_cast<int>(sample_rate),
static_cast<int>(number_of_channels),
static_cast<int>(number_of_frames));
}
}
void AudioTrackImpl::OnRenderData(const void* audio_samples,
const size_t num_samples,
const size_t bytes_per_sample,
const size_t num_channels,
const uint32_t samples_per_sec){
// if(_renderer){
// _renderer->OnData( audio_samples,
// static_cast<int>( bytes_per_sample)*8,
// static_cast<int>(samples_per_sec),
// static_cast<int>(num_channels),
// static_cast<int>(num_samples));
// }
}
void AudioTrackImpl::OnCaptureData(const void* audio_samples,
const size_t nSamples,
const size_t nBytesPerSample,
const size_t nChannels,
const uint32_t samples_per_sec){
if(_renderer){
_renderer->OnData( audio_samples,
static_cast<int>( nSamples)*8,
static_cast<int>(nBytesPerSample),
static_cast<int>(nChannels),
static_cast<int>(samples_per_sec));
}
}
void AudioTrackImpl::AddRenderer(
RTCAudioRenderer* renderer) {
_renderer=renderer;
}
void AudioTrackImpl::RemoveRenderer(
RTCAudioRenderer* renderer) {
_renderer=nullptr;
}
} // namespace libwebrtc
| 34.4625 | 78 | 0.544432 | necnecnec |
c773cab98a04d4ec89cf473d13a51c3c94a504bb | 989 | cpp | C++ | 415.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 415.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 415.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | class Solution {
public:
string addStrings(string num1, string num2) {
int n1 = num1.size(), n2 = num2.size();
string& res = n1 > n2 ? num1 : num2;
int n_res = max(n1, n2);
int d = 1;
int sum, carry = 0;
while (d <= n_res) {
if (n1 - d < 0) {
sum = (int)(num2[n2 - d] - '0') + carry;
carry = sum / 10;
res[n_res - d] = (sum % 10) + '0';
}
else if (n2 - d < 0) {
sum = (int)(num1[n1 - d] - '0') + carry;
carry = sum / 10;
res[n_res - d] = (sum % 10) + '0';
}
else {
sum = (int)(num1[n1 -d] - '0') + (int)(num2[n2 - d] - '0') + carry;
carry = sum / 10;
res[n_res - d] = (sum % 10) + '0';
}
d++;
}
if (carry)
res.insert(res.begin(), (char)(carry + '0'));
return res;
}
};
| 30.90625 | 83 | 0.352882 | Alex-Amber |
c77a2675fd08425e1ec08030da1a2e71a45bbaa0 | 5,264 | cpp | C++ | src/l_Message.cpp | benzap/Kampf | 9cf4fb0d6ec22bc35ade9b476d29df34902c6689 | [
"Zlib"
] | 2 | 2018-05-13T05:27:29.000Z | 2018-05-29T06:35:57.000Z | src/l_Message.cpp | benzap/Kampf | 9cf4fb0d6ec22bc35ade9b476d29df34902c6689 | [
"Zlib"
] | null | null | null | src/l_Message.cpp | benzap/Kampf | 9cf4fb0d6ec22bc35ade9b476d29df34902c6689 | [
"Zlib"
] | null | null | null | #include "l_Message.hpp"
Message* lua_pushmessage(lua_State *L, Message* message) {
if (message == nullptr) {
message = Messenger::getInstance()->appendMessage();
}
Message ** messagePtr = static_cast<Message**>
(lua_newuserdata(L, sizeof(Message*)));
*messagePtr = message;
luaL_getmetatable(L, LUA_USERDATA_MESSAGE);
lua_setmetatable(L, -2);
return message;
}
Message* lua_tomessage(lua_State *L, int index) {
Message* message = *static_cast<Message**>
(luaL_checkudata(L, index, LUA_USERDATA_MESSAGE));
if (message == NULL) {
luaL_error(L, "Provided userdata is not of type 'Message'");
}
return message;
}
boolType lua_ismessage(lua_State* L, int index) {
if (lua_isuserdata(L, index)) {
auto chk = lua_isUserdataType(L, index, LUA_USERDATA_MESSAGE);
return chk;
}
return false;
}
// static int l_Message_Message(lua_State *L) {
// auto message = lua_pushmessage(L);
// return 1;
// }
static int l_Message_isMessage(lua_State *L) {
if (lua_ismessage(L, -1)) {
lua_pushboolean(L, 1);
}
else {
lua_pushboolean(L, 0);
}
return 1;
}
static int l_Message_getID(lua_State *L) {
auto message = lua_tomessage(L, 1);
lua_pushnumber(L, message->getID());
return 1;
}
static int l_Message_getType(lua_State *L) {
auto message = lua_tomessage(L, 1);
enumMessageType messageType = message->getType();
lua_pushstring(L, message->getTypeString().c_str());
return 1;
}
static int l_Message_setType(lua_State *L) {
auto message = lua_tomessage(L, 1);
stringType type = luaL_checkstring(L, 2);
message->setTypeString(type);
return 0;
}
static int l_Message_getFirstEntity(lua_State *L) {
auto message = lua_tomessage(L, 1);
if (message->firstEntity != nullptr) {
lua_pushentity(L, message->firstEntity);
}
else {
lua_pushnil(L);
}
return 1;
}
static int l_Message_setFirstEntity(lua_State *L) {
auto message = lua_tomessage(L, 1);
auto entity = lua_toentity(L, 2);
message->firstEntity = entity;
return 0;
}
static int l_Message_getFirstComponent(lua_State *L) {
auto message = lua_tomessage(L, 1);
if (message->firstComponent != nullptr) {
lua_pushcomponent(L, message->firstComponent);
}
else {
lua_pushnil(L);
}
return 1;
}
static int l_Message_setFirstComponent(lua_State *L) {
auto message = lua_tomessage(L, 1);
auto component = lua_tocomponent(L, 2);
message->firstComponent = component;
return 0;
}
static int l_Message_getSecondEntity(lua_State *L) {
auto message = lua_tomessage(L, 1);
if (message->secondEntity != nullptr) {
lua_pushentity(L, message->secondEntity);
}
else {
lua_pushnil(L);
}
return 1;
}
static int l_Message_setSecondEntity(lua_State *L) {
auto message = lua_tomessage(L, 1);
auto entity = lua_toentity(L, 2);
message->secondEntity = entity;
return 0;
}
static int l_Message_getSecondComponent(lua_State *L) {
auto message = lua_tomessage(L, 1);
if (message->secondComponent != nullptr) {
lua_pushcomponent(L, message->secondComponent);
}
else {
lua_pushnil(L);
}
return 1;
}
static int l_Message_setSecondComponent(lua_State *L) {
auto message = lua_tomessage(L, 1);
auto component = lua_tocomponent(L, 2);
message->secondComponent = component;
return 0;
}
static int l_Message_getCustomAttribute(lua_State *L) {
auto message = lua_tomessage(L, 1);
stringType keyname = luaL_checkstring(L, 2);
//todo, check if attribute exists
auto customAttribute = message->customData[keyname];
lua_pushcustomAttribute(L, new CustomAttribute(customAttribute));
return 1;
}
static int l_Message_setCustomAttribute(lua_State *L) {
auto message = lua_tomessage(L, 1);
stringType keyname = luaL_checkstring(L, 2);
auto customAttribute = lua_tocustomAttribute(L, 3);
message->customData[keyname] = customAttribute;
return 0;
}
static const struct luaL_Reg l_Message_registry [] = {
//{"Message", l_Message_Message},
{"isMessage", l_Message_isMessage},
{NULL, NULL}
};
static const struct luaL_Reg l_Message [] = {
{"getID", l_Message_getID},
{"getType", l_Message_getType},
{"setType", l_Message_setType},
{"getFirstEntity", l_Message_getFirstEntity},
{"setFirstEntity", l_Message_setFirstEntity},
{"getFirstComponent", l_Message_getFirstComponent},
{"setFirstComponent", l_Message_setFirstComponent},
{"getSecondEntity", l_Message_getSecondEntity},
{"setSecondEntity", l_Message_setSecondEntity},
{"getSecondComponent", l_Message_getSecondComponent},
{"setSecondComponent", l_Message_setSecondComponent},
{"getCustomAttribute", l_Message_getCustomAttribute},
{"get", l_Message_getCustomAttribute},
{"setCustomAttribute", l_Message_setCustomAttribute},
{"set", l_Message_setCustomAttribute},
{NULL, NULL}
};
int luaopen_message(lua_State *L) {
luaL_newmetatable(L, LUA_USERDATA_MESSAGE);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, l_Message);
lua_pop(L, 1);
luaL_register(L, KF_LUA_LIBNAME, l_Message_registry);
return 1;
}
| 26.059406 | 69 | 0.68807 | benzap |
c7828544598a63a600ca68615866fd1d4672f91d | 734 | cpp | C++ | Leetcode Solution/HashMap/Medium/1487. Making File Names Unique.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 169 | 2021-05-30T10:02:19.000Z | 2022-03-27T18:09:32.000Z | Leetcode Solution/HashMap/Medium/1487. Making File Names Unique.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 1 | 2021-10-02T14:46:26.000Z | 2021-10-02T14:46:26.000Z | Leetcode Solution/HashMap/Medium/1487. Making File Names Unique.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 44 | 2021-05-30T19:56:29.000Z | 2022-03-17T14:49:00.000Z |
class Solution {
public:
vector<string> getFolderNames(vector<string>& names) {
unordered_map<string,int> mp;
vector<string> ans;
int j;
for(int i=0;i<names.size();i++)
{
j = mp[names[i]];
string temp = names[i];
while(mp[temp]>0)
{
temp = names[i] + '(' + to_string(j++) + ')' ;
mp[names[i]] = j;
}
ans.push_back(temp);
mp[temp]++;
}
return ans;
}
};
| 25.310345 | 82 | 0.30109 | bilwa496 |
c783d231aa59021045a62d029399844437262bc2 | 157 | hpp | C++ | basics/maxdecltypedecay.hpp | hanlulugeren/C-templates | 17181f1e99207430236623e70504b4aecd40afe9 | [
"MIT"
] | null | null | null | basics/maxdecltypedecay.hpp | hanlulugeren/C-templates | 17181f1e99207430236623e70504b4aecd40afe9 | [
"MIT"
] | null | null | null | basics/maxdecltypedecay.hpp | hanlulugeren/C-templates | 17181f1e99207430236623e70504b4aecd40afe9 | [
"MIT"
] | null | null | null | #include<type_traits>
template<typename T1,typename T2>
auto max(T1 a,T2 b) -> typename std::decay< decltype(true ? a:b)>::type
{
return b < a ? a :b;
}
| 22.428571 | 71 | 0.656051 | hanlulugeren |
c788705efdbde2f2cec2993a22c8449d8b0573c9 | 12,737 | cpp | C++ | QuadtreeCollision/main.cpp | kgomathi2910/Quad-Trees | 70059b66a93a9491f435c99d2cd811e0e0df3337 | [
"MIT"
] | null | null | null | QuadtreeCollision/main.cpp | kgomathi2910/Quad-Trees | 70059b66a93a9491f435c99d2cd811e0e0df3337 | [
"MIT"
] | null | null | null | QuadtreeCollision/main.cpp | kgomathi2910/Quad-Trees | 70059b66a93a9491f435c99d2cd811e0e0df3337 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<math.h>
#include<sstream>
#include<string>
#include <SFML/Graphics.hpp>
using namespace std;
using namespace sf;
#define SCREEN_W 600
#define SCREEN_H 600
#define LEVEL_MAX 4
#define CAPACITY 5 //efficiency changes with capacity
#define PI 3.14159265
#define SPEED 0.5f
string intToString(int num)
{
static stringstream toStringConverter;
static string tempString;
toStringConverter.clear();
toStringConverter << num;
toStringConverter >> tempString;
//take num and convert it to string and store in tempString
return tempString;
}
class Rectangle
{
public:
float x;
float y;
float w;
float h;
Rectangle(float x, float y, float w, float h)
{
this->x = x;
this->y = y;
this->w = w;
this->h = h;
}
bool intersects(const Rectangle &other) const
{
return !(x - w > other.x + other.w || x + w < other.x - other.w || y - h > other.y + other.h || y + h < other.y - other.h);
}
void draw(RenderTarget &t)
{
static Vertex vertices[5];
vertices[0] = Vertex(Vector2f(x - w, y - h), Color::Magenta);
vertices[1] = Vertex(Vector2f(x + w, y - h), Color::Magenta);
vertices[2] = Vertex(Vector2f(x - w, y + h), Color::Magenta);
vertices[3] = Vertex(Vector2f(x + w, y + h), Color::Magenta);
vertices[4] = Vertex(Vector2f(x - w, y - h), Color::Magenta);
t.draw(vertices, 5, LineStrip);
}
};
class Entity : public Rectangle
{
public:
bool collides;
float angle;
Entity(float x, float y, float w, float h) : Rectangle(x, y, w, h)
{
collides = false;
angle = 0;
}
void Move()
{
x += cos(angle / 180 * PI) * SPEED;
y += sin(angle / 180 * PI) * SPEED;
if(x < w)
{
x = w;
angle = 180 - angle;
angle += rand() % 21 - 10;
}
else if(x > SCREEN_W - w)
{
x = SCREEN_W - w;
angle = 180 - angle;
angle += rand() % 21 - 10;
}
if(y < h)
{
y = h;
angle = -angle;
angle += rand() % 21 - 10;
}
else if(y > SCREEN_H - h)
{
y = SCREEN_H - h;
angle = -angle;
angle += rand() % 21 - 10;
}
}
};
class QuadTree {
private:
QuadTree *NorthWest;
QuadTree *NorthEast;
QuadTree *SouthWest;
QuadTree *SouthEast;
Rectangle boundaries;
bool divided;
size_t capacity;
size_t level;
vector<Entity*> children;
void subdivide()
{
static Vector2f halfSize;
halfSize.x = boundaries.w / 2.0f;
halfSize.y = boundaries.h / 2.0f;
NorthWest = new QuadTree(Rectangle(boundaries.x - halfSize.x, boundaries.y - halfSize.y, halfSize.x, halfSize.y), capacity, level + 1);
NorthEast = new QuadTree(Rectangle(boundaries.x + halfSize.x, boundaries.y - halfSize.y, halfSize.x, halfSize.y), capacity, level + 1);
SouthWest = new QuadTree(Rectangle(boundaries.x - halfSize.x, boundaries.y + halfSize.y, halfSize.x, halfSize.y), capacity, level + 1);
SouthEast = new QuadTree(Rectangle(boundaries.x + halfSize.x, boundaries.y + halfSize.y, halfSize.x, halfSize.y), capacity, level + 1);
divided = true;
}
public:
QuadTree(const Rectangle &_boundaries, size_t capacity, size_t level) : boundaries(_boundaries)
{
NorthWest = NULL;
NorthEast = NULL;
SouthWest = NULL;
SouthEast = NULL;
divided = false;
this->capacity = capacity;
this->level = level;
if(this->level >= LEVEL_MAX)
{
this->capacity = 0;
}
}
~QuadTree()
{
if(divided)
{
delete NorthWest;
delete NorthEast;
delete SouthWest;
delete SouthEast;
}
}
void query(const Rectangle &area, vector<Entity*> &found) const
{
if(!area.intersects(boundaries))
{
return;
}
if(divided)
{
NorthWest->query(area, found);
NorthEast->query(area, found);
SouthWest->query(area, found);
SouthEast->query(area, found);
}
else
{
for(size_t i = 0; i < children.size(); ++i)
{
if(area.intersects(*children[i]))
{
found.push_back(children[i]);
}
}
}
}
void insert(Entity *e)
{
if(!boundaries.intersects(*e))
{
return;
}
if(!divided)
{
children.push_back(e);
if(children.size() > capacity && capacity != 0 )
{
subdivide();
vector<Entity*>::iterator it = children.begin();
while(it != children.end())
{
NorthWest->insert(*it);
NorthEast->insert(*it);
SouthWest->insert(*it);
SouthEast->insert(*it);
it = children.erase(it);
}
}
}
else
{
NorthWest->insert(e);
NorthEast->insert(e);
SouthWest->insert(e);
SouthEast->insert(e);
}
}
void draw(RenderTarget &t)
{
if(divided)
{
static Vertex vertices[4];
vertices[0] = Vertex(Vector2f(boundaries.x, boundaries.y - boundaries.h), Color::White);
vertices[1] = Vertex(Vector2f(boundaries.x, boundaries.y + boundaries.h), Color::White);
vertices[2] = Vertex(Vector2f(boundaries.x - boundaries.w, boundaries.y), Color::White);
vertices[3] = Vertex(Vector2f(boundaries.x + boundaries.w, boundaries.y), Color::White);
t.draw(vertices, 4, Lines);
NorthWest->draw(t);
NorthEast->draw(t);
SouthWest->draw(t);
SouthEast->draw(t);
}
}
size_t checkCollision()
{
size_t collisionCount = 0;
if(divided)
{
collisionCount += NorthWest->checkCollision();
collisionCount += NorthEast->checkCollision();
collisionCount += SouthWest->checkCollision();
collisionCount += SouthEast->checkCollision();
}
else
{
//check if 2 entities collide
for(vector<Entity*>::iterator i = children.begin(); i != children.end(); ++i)
{
for(vector<Entity*>::iterator j = i; j != children.end(); ++j)
{
if(i != j && (*i)->intersects(**j))
{
(*i)->collides = true;
(*j)->collides = true;
}
++collisionCount;
}
}
}
return collisionCount;
}
};
int main()
{
srand(time(0));
RenderWindow window(sf::VideoMode(SCREEN_W + 200, SCREEN_H), "Collision Plot Using Quad Trees");
QuadTree *tree;
Entity *entity;
vector<Entity*> entities;
vector<Entity*> found;
RectangleShape shape;
shape.setOutlineColor(Color::Blue);
int width = 5, height = 5;
float timeTree, timeBrute;
int countTree, countBrute;
Clock timer; //measures elapsed time
Font font; //loading and manipulating character fonts
font.loadFromFile("AlexBrush-Regular.ttf"); //downloaded AxelBrush
Text text;//for text - we need font
text.setFont(font);
text.setCharacterSize(20);
text.setColor(Color::Yellow);
while(window.isOpen())
{
Event e;
while(window.pollEvent(e))
{
if(e.type == Event::Closed)
{
window.close();
}
else if(e.type == Event::MouseButtonPressed && e.mouseButton.button == Mouse::Left)
{
for(int i = 0; i < 10; ++i)
{
entity = new Entity(Mouse::getPosition(window).x, Mouse::getPosition(window).y, width, height);
entity->angle = rand() % 360; //angle
entities.push_back(entity);
}
}
else if (e.type == Event::MouseWheelScrolled)
{
if(Keyboard::isKeyPressed(Keyboard::LShift))
{
width += e.mouseWheelScroll.delta * 5;
}
else
{
height += e.mouseWheelScroll.delta * 5;
}
}
}
tree = new QuadTree(Rectangle(SCREEN_W / 2, SCREEN_H / 2, SCREEN_W / 2, SCREEN_H / 2), CAPACITY, 0);
timeTree = 0;
for(vector<Entity*>::iterator it = entities.begin(); it != entities.end(); ++it)
{
(*it)->Move();
(*it)->collides = false;
timer.restart();
tree->insert(*it);
timeTree += timer.restart().asMicroseconds();
}
countTree = tree->checkCollision();
timeTree += timer.restart().asMicroseconds();
countBrute = 0;
timer.restart();
for(vector<Entity*>::iterator i = entities.begin(); i != entities.end(); ++i)
{
for(vector<Entity*>::iterator j = i; j != entities.end(); ++j)
{
if(i != j && (*i)->intersects(**j))
{
(*j)->collides = true;
(*j)->collides = true;
}
++countBrute;
}
}
timeBrute = timer.restart().asMicroseconds();
window.clear();
shape.setOutlineThickness(-1);
for(Entity *e : entities)
{
shape.setPosition(e->x, e->y);
shape.setSize(Vector2f(e->w * 2, e->h * 2));
shape.setOrigin(e->w, e->h);
shape.setFillColor(e->collides?Color::Red:Color::Green);
window.draw(shape);
}
tree->draw(window);
shape.setOutlineThickness(0);
shape.setPosition(Mouse::getPosition(window).x, Mouse::getPosition(window).y);
shape.setSize(Vector2f(width * 2, height * 2));
shape.setOrigin(width, height);
shape.setFillColor(Color(255, 255, 0, 50));
window.draw(shape);
text.setString("Tree count: " + intToString(countTree) +
"\nBrute force count: " + intToString(countBrute) +
"\nTree time: " + intToString(timeTree) +
"\nBrute force time:" + intToString(timeBrute) +
"\nTree is " +
intToString(round(timeBrute / timeTree)) + "times faster");
text.setPosition(SCREEN_W + 10, 20);
window.draw(text);
window.display();
}
for(int i = 0; i < entities.size(); ++i)
{
delete entities[i];
}
delete tree;
return 0;
}
| 34.705722 | 151 | 0.437544 | kgomathi2910 |
c78a0d53574181ae16ab39a3b8605730b2426cfa | 4,768 | cpp | C++ | Source/ShooterGame/Weapons/ShooterWeapon_Melee.cpp | ugsgame/ShooterPrototype | 48fbc5401f52bd6d0b7f5b9bda8399c929eab4b9 | [
"Apache-2.0"
] | 1 | 2019-07-16T09:46:54.000Z | 2019-07-16T09:46:54.000Z | Source/ShooterGame/Weapons/ShooterWeapon_Melee.cpp | ugsgame/ShooterPrototype | 48fbc5401f52bd6d0b7f5b9bda8399c929eab4b9 | [
"Apache-2.0"
] | null | null | null | Source/ShooterGame/Weapons/ShooterWeapon_Melee.cpp | ugsgame/ShooterPrototype | 48fbc5401f52bd6d0b7f5b9bda8399c929eab4b9 | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "ShooterGame.h"
#include "ShooterWeapon_Melee.h"
AShooterWeapon_Melee::AShooterWeapon_Melee(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
CollisionComp1P = ObjectInitializer.CreateDefaultSubobject<UCapsuleComponent>(this, "CapsuleComp1P");
CollisionComp1P->InitCapsuleSize(5.0f, 10.0f);
CollisionComp1P->AlwaysLoadOnClient = true;
CollisionComp1P->AlwaysLoadOnServer = true;
CollisionComp1P->bTraceComplexOnMove = true;
CollisionComp1P->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
CollisionComp1P->SetCollisionObjectType(COLLISION_WEAPON);
CollisionComp1P->SetCollisionResponseToAllChannels(ECR_Ignore);
CollisionComp1P->SetCollisionResponseToChannel(ECC_Pawn, ECR_Overlap);
CollisionComp1P->SetupAttachment(GetMesh1P());
CollisionComp1P->OnComponentBeginOverlap.AddDynamic(this, &AShooterWeapon_Melee::OnOverlapBegin);
CollisionComp1P->OnComponentEndOverlap.AddDynamic(this, &AShooterWeapon_Melee::OnOverlapEnd);
CollisionComp3P = ObjectInitializer.CreateDefaultSubobject<UCapsuleComponent>(this, "CapsuleComp3P");
CollisionComp3P->InitCapsuleSize(5.0f, 10.0f);
CollisionComp3P->AlwaysLoadOnClient = true;
CollisionComp3P->AlwaysLoadOnServer = true;
CollisionComp3P->bTraceComplexOnMove = true;
CollisionComp3P->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
CollisionComp3P->SetCollisionObjectType(COLLISION_WEAPON);
CollisionComp3P->SetCollisionResponseToAllChannels(ECR_Ignore);
CollisionComp3P->SetCollisionResponseToChannel(ECC_Pawn, ECR_Overlap);
CollisionComp3P->SetupAttachment(GetMesh3P());
CollisionComp3P->OnComponentBeginOverlap.AddDynamic(this, &AShooterWeapon_Melee::OnOverlapBegin);
CollisionComp3P->OnComponentEndOverlap.AddDynamic(this, &AShooterWeapon_Melee::OnOverlapEnd);
CollisionComp = CollisionComp1P;
bHitWithStartFire = true;
}
void AShooterWeapon_Melee::PostInitializeComponents()
{
Super::PostInitializeComponents();
CollisionComp1P->MoveIgnoreActors.Add(Instigator);
CollisionComp1P->MoveIgnoreActors.Add(this);
CollisionComp3P->MoveIgnoreActors.Add(Instigator);
CollisionComp3P->MoveIgnoreActors.Add(this);
this->ApplyWeaponConfig(MeleeWeaponData);
}
void AShooterWeapon_Melee::ApplyWeaponConfig(FMeleeWeaponData& Data)
{
Data.MeleeClass = AShooterWeapon_Melee::StaticClass();
}
void AShooterWeapon_Melee::OnImpact(const FHitResult& HitResult)
{
//TODO:Spawn effect
}
void AShooterWeapon_Melee::SetHitEnable(bool Enable)
{
if (Enable)
{
CollisionComp->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
}
else
{
CollisionComp->SetCollisionEnabled(ECollisionEnabled::NoCollision);
}
}
void AShooterWeapon_Melee::FireWeapon()
{
}
void AShooterWeapon_Melee::OnStartFire()
{
Super::OnStartFire();
if (bHitWithStartFire)
{
SetHitEnable(true);
}
}
void AShooterWeapon_Melee::OnStopFire()
{
Super::OnStopFire();
if (bHitWithStartFire)
{
SetHitEnable(false);
}
}
void AShooterWeapon_Melee::AttachMeshToPawn()
{
Super::AttachMeshToPawn();
CollisionComp1P->SetCollisionEnabled(ECollisionEnabled::NoCollision);
CollisionComp3P->SetCollisionEnabled(ECollisionEnabled::NoCollision);
if (MyPawn != NULL)
{
MyPawn->IsFirstPerson() ? CollisionComp = CollisionComp1P : CollisionComp = CollisionComp3P;
CollisionComp1P->MoveIgnoreActors.Add(MyPawn);
CollisionComp3P->MoveIgnoreActors.Add(MyPawn);
}
}
bool AShooterWeapon_Melee::ShouldDealDamage(AActor* TestActor) const
{
// if we're an actor on the server, or the actor's role is authoritative, we should register damage
if (TestActor)
{
if (GetNetMode() != NM_Client ||
TestActor->Role == ROLE_Authority ||
TestActor->GetTearOff())
{
return true;
}
}
return false;
}
void AShooterWeapon_Melee::DealDamage(const FHitResult& Impact)
{
FPointDamageEvent PointDmg;
PointDmg.DamageTypeClass = MeleeWeaponData.DamageType;
PointDmg.HitInfo = Impact;
PointDmg.Damage = MeleeWeaponData.MeleeDamage;
if (MyPawn)
{
Impact.GetActor()->TakeDamage(PointDmg.Damage, PointDmg, MyPawn->Controller, this);
this->OnImpact(Impact);
}
}
void AShooterWeapon_Melee::OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
// Other Actor is the actor that triggered the event. Check that is not ourself.
if ((OtherActor != nullptr) && (OtherActor != this) && (OtherComp != nullptr))
{
//TODO:handle damage
if (ShouldDealDamage(OtherActor))
{
DealDamage(SweepResult);
}
}
}
void AShooterWeapon_Melee::OnOverlapEnd(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
} | 28.213018 | 200 | 0.79719 | ugsgame |
c78db1a32fb4d1c35d70ed2abda77ab9e691ed89 | 3,725 | hpp | C++ | src/poutreBase/poutreChronos.hpp | ThomasRetornaz/poutre | 21717ce1da24515dd208f711d6e7c38095ba8ecf | [
"BSL-1.0"
] | null | null | null | src/poutreBase/poutreChronos.hpp | ThomasRetornaz/poutre | 21717ce1da24515dd208f711d6e7c38095ba8ecf | [
"BSL-1.0"
] | null | null | null | src/poutreBase/poutreChronos.hpp | ThomasRetornaz/poutre | 21717ce1da24515dd208f711d6e7c38095ba8ecf | [
"BSL-1.0"
] | null | null | null |
//==============================================================================
// Copyright (c) 2015 - Thomas Retornaz //
// [email protected] //
// Distributed under the Boost Software License, Version 1.0. //
// See accompanying file LICENSE.txt or copy at //
// http://www.boost.org/LICENSE_1_0.txt //
//==============================================================================
#ifndef POUTRE_CHRONOS_HPP__
#define POUTRE_CHRONOS_HPP__
/**
* @file poutreChronos.hpp
* @author Thomas Retornaz
* @brief Define helper objects around std::chrono facilities
*
*
*/
#include <poutreBase/poutreBase.hpp>
#include <chrono>
#include <ctime>
#include <iostream>
#include <sstream>
namespace poutre
{
/**
* @addtogroup timer_group Timing facilities
* @ingroup poutre_base_group
*@{
*/
/**
* @brief Simple Timer class (wrapping std::chronos) with classical
* start,stop interface and serialisation capabilites
* @todo think about multi-threading
*/
class BASE_API Timer // see http://en.cppreference.com/w/cpp/chrono/c/clock
{
public:
using high_resolution_clock = std::chrono::high_resolution_clock;
using double_milliseconds = std::chrono::duration<double, std::milli>; // switch to other duration through
// template<rep,duration> ?
using timerep = double_milliseconds::rep; // todo use
// decltype(auto)
//! ctor
Timer(void);
//! dor
~Timer(void) POUTRE_NOEXCEPT;
//! Start the timing action
void Start() POUTRE_NOEXCEPT;
//! Stop the timing action
void Stop() POUTRE_NOEXCEPT;
//! Grab wall time accumulated in ms
const timerep GetCumulativeTime() const POUTRE_NOEXCEPT;
//! Grab wall mean time of iteration in ms
const timerep GetMeanTime() const POUTRE_NOEXCEPT;
//! Grab cpu time accumulated in ms
const timerep GetCumulativeCPUTime() const POUTRE_NOEXCEPT;
//! Grab wall mean time of iteration in ms
const timerep GetMeanCpuTime() const POUTRE_NOEXCEPT;
//! Grab number off triggered start
const std::size_t NbIter() const POUTRE_NOEXCEPT;
//! String serialization
const std::string to_str() const POUTRE_NOEXCEPT;
//! Reset the chrono
void Reset() POUTRE_NOEXCEPT;
private:
std::chrono::high_resolution_clock::time_point m_start; //! start wall time
timerep m_accu; //! accumulate wall time over all iteration
std::clock_t m_start_cputime; //! start cpu time
std::clock_t m_accu_cputime; //! accumulate cpu time
std::size_t m_nbiter; //! nb iteration
};
//! Timer stream serialization
BASE_API std::ostream &operator<<(std::ostream &os, Timer &timer);
/**
* @brief Scoped (RAII) timer, start and stop of embedded timer are automatically triggered
*
* @todo think about multi-threading
*/
class BASE_API ScopedTimer
{
private:
Timer &m_timer; //! Inner timer
public:
//! ctor
ScopedTimer(Timer &itimer);
//! dtor
~ScopedTimer(void);
};
} // namespace poutre
/**
//! @} doxygroup: timer_group
*/
#endif // POUTRE_CHRONOS_HPP__
| 32.391304 | 113 | 0.54255 | ThomasRetornaz |
c78e71eb1d401394d83cd4dcbfea3a706a3cd27c | 637 | cpp | C++ | engine/core/Concurency/Task.cpp | TristanFish/SuperBongoEngine | 3a6c67c0aa0c6b4f75e353690016b8f91d813717 | [
"MIT"
] | null | null | null | engine/core/Concurency/Task.cpp | TristanFish/SuperBongoEngine | 3a6c67c0aa0c6b4f75e353690016b8f91d813717 | [
"MIT"
] | null | null | null | engine/core/Concurency/Task.cpp | TristanFish/SuperBongoEngine | 3a6c67c0aa0c6b4f75e353690016b8f91d813717 | [
"MIT"
] | null | null | null | #include "Task.h"
#include "Thread.h"
Task::Task(): E_Priority(ETaskPriority::Low), E_TaskType(ETaskType::TT_GENERAL), B_HasBeenCompleted(false)
{
}
Task::Task(ETaskPriority newPriority, ETaskType newType) : E_Priority(newPriority), E_TaskType(newType), B_HasBeenCompleted(false)
{
}
Task::Task(std::shared_ptr<Task> copyTask) : E_Priority(copyTask->E_Priority),E_TaskType(ETaskType::TT_GENERAL), F_Function(copyTask->F_Function), B_HasBeenCompleted(false)
{
}
Task::~Task()
{
}
void Task::RunTask()
{
F_Function();
B_HasBeenCompleted = true;
}
void Task::SetTask(std::function<void()> newFunc)
{
F_Function = newFunc;
}
| 17.216216 | 172 | 0.739403 | TristanFish |
c794ca9c70a0d9ab1f63dc13ebc98459b81b8971 | 40,116 | cpp | C++ | src/plugins/assembly/gstpartassembly.cpp | AIoT-IST/EVA_Show-Case | 14474d97c233b4740c8216ba6564454cd954129c | [
"MIT"
] | 4 | 2021-05-26T07:14:50.000Z | 2022-01-10T00:15:32.000Z | src/plugins/assembly/gstpartassembly.cpp | maxpark/EVA_Show-Case | c21fdf7d81efaaf4b63b071eeaf8911791336058 | [
"MIT"
] | 2 | 2021-06-07T16:00:14.000Z | 2021-07-06T13:35:38.000Z | src/plugins/assembly/gstpartassembly.cpp | maxpark/EVA_Show-Case | c21fdf7d81efaaf4b63b071eeaf8911791336058 | [
"MIT"
] | 3 | 2021-08-19T02:27:59.000Z | 2022-01-10T07:40:22.000Z | #ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gst/gst.h>
#include <gst/video/video.h>
#include <gst/video/gstvideofilter.h>
#include "gstpartassembly.h"
#include <ctime>
#include <iostream>
#include <fstream>
#include <regex>
#include <string>
#include <vector>
#include "gstadmeta.h"
#include "utils.h"
#define NANO_SECOND 1000000000.0
GST_DEBUG_CATEGORY_STATIC (gst_partassembly_debug_category);
#define GST_CAT_DEFAULT gst_partassembly_debug_category
static void gst_partassembly_set_property (GObject * object, guint property_id, const GValue * value, GParamSpec * pspec);
static void gst_partassembly_get_property (GObject * object, guint property_id, GValue * value, GParamSpec * pspec);
static void gst_partassembly_dispose (GObject * object);
static void gst_partassembly_finalize (GObject * object);
static void gst_partassembly_before_transform (GstBaseTransform * trans, GstBuffer * buffer);
static gboolean gst_partassembly_start (GstBaseTransform * trans);
static gboolean gst_partassembly_stop (GstBaseTransform * trans);
static gboolean gst_partassembly_set_info (GstVideoFilter * filter, GstCaps * incaps, GstVideoInfo * in_info, GstCaps * outcaps, GstVideoInfo * out_info);
static GstFlowReturn gst_partassembly_transform_frame_ip (GstVideoFilter * filter, GstVideoFrame * frame);
static void mapGstVideoFrame2OpenCVMat(Gstpartassembly *partassembly, GstVideoFrame *frame, GstMapInfo &info);
static void getDetectedBox(Gstpartassembly *partassembly, GstBuffer* buffer);
static int getPartIndexInBomList(Gstpartassembly *partassembly, const std::string& partName);
static bool twoSidesCheck(Gstpartassembly *partassembly, int partIndex, int eachSideExistNumber);
static void doAlgorithm(Gstpartassembly *partassembly, GstBuffer* buffer);
static void drawObjects(Gstpartassembly *partassembly);
static void drawStatus(Gstpartassembly *partassembly);
std::vector<bool> assemblyActionVector = {
false, // put 1 semi-product in container
false, // put 2 light-guide-cover in semi-finished-products(left and right)
false, // put 2 small-board-side-B in semi-finished-products(left and right)
false, // screw on 4 screws(2 on left, 2 on right)
false, // put wire on
false, // final visual inspection: 2 small-board-side-B with 4 screw-on(each small-board-side-B contains 2 screw-on) and 1 wire
false}; // Complete
std::vector<double> processingTime = {
0, // put 1 semi-product in container
0, // put 2 light-guide-cover in semi-finished-products(left and right)
0, // put 2 small-board-side-B in semi-finished-products(left and right)
0, // screw on 4 screws(2 on left, 2 on right)
0, // put wire on
0, // final visual inspection: 2 small-board-side-B with 4 screw-on(each small-board-side-B contains 2 screw-on) and 1 wire
0}; // Complete
std::vector<float> processingRegularTime = {
10, // put 1 semi-product in container
10, // put 2 light-guide-cover in semi-finished-products(left and right)
6, // put 2 small-board-side-B in semi-finished-products(left and right)
10, // screw on 4 screws(2 on left, 2 on right)
5, // put wire on
5, // final visual inspection: 2 small-board-side-B with 4 screw-on(each small-board-side-B contains 2 screw-on) and 1 wire
5}; // Complete
std::vector<std::string> assemblyActionInfoVector = {
"semi-product in container", // put 1 semi-product in container
"2 light-guide-cover(left and right)", // put 2 light-guide-cover in semi-finished-products(left and right)
"2 small-board-side-B(left and right)", // put 2 small-board-side-B in semi-finished-products(left and right)
"screw on 4 screws(2 on left, 2 on right)", // screw on 4 screws(2 on left, 2 on right)
"put wire on", // put wire on
"final visual inspection", // final visual inspection: 2 small-board-side-B with 4 screw-on(each small-board-side-B contains 2 screw-on) and 1 wire
"completion"}; // Complete
struct _GstpartassemblyPrivate
{
std::vector<std::string> bomList;
std::vector<Material*> bomMaterial;
int indexOfSemiProductContainer;
int indexOfSemiProduct;
int bestIndexObjectOfSemiProduct;
bool partsDisplay;
bool informationDisplay;
bool alert;
gchar* targetType;
gchar* alertType;
int resetSeconds;
};
enum
{
PROP_0,
PROP_TARGET_TYPE,
PROP_ALERT_TYPE,
PROP_PARTS_DISPLAY,
PROP_INFORMATION_DISPLAY,
PROP_RESET
};
#define DEBUG_INIT GST_DEBUG_CATEGORY_INIT(GST_CAT_DEFAULT, "gstpartassembly", 0, "debug category for gstpartassembly element");
G_DEFINE_TYPE_WITH_CODE(Gstpartassembly, gst_partassembly, GST_TYPE_VIDEO_FILTER, G_ADD_PRIVATE(Gstpartassembly) DEBUG_INIT)
/* pad templates */
/* FIXME: add/remove formats you can handle */
#define VIDEO_SRC_CAPS \
GST_VIDEO_CAPS_MAKE("{ BGR }")
/* FIXME: add/remove formats you can handle */
#define VIDEO_SINK_CAPS \
GST_VIDEO_CAPS_MAKE("{ BGR }")
/* class initialization */
static void gst_partassembly_class_init (GstpartassemblyClass * klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
GstBaseTransformClass *base_transform_class = GST_BASE_TRANSFORM_CLASS (klass);
GstVideoFilterClass *video_filter_class = GST_VIDEO_FILTER_CLASS (klass);
/* Setting up pads and setting metadata should be moved to
base_class_init if you intend to subclass this class. */
gst_element_class_add_pad_template (GST_ELEMENT_CLASS(klass),
gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
gst_caps_from_string (VIDEO_SRC_CAPS)));
gst_element_class_add_pad_template (GST_ELEMENT_CLASS(klass),
gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
gst_caps_from_string (VIDEO_SINK_CAPS)));
gst_element_class_set_static_metadata (GST_ELEMENT_CLASS(klass),
"Adlink part assembly video filter", "Filter/Video", "An ADLINK Part-Assembly demo video filter", "Dr. Paul Lin <[email protected]>");
gobject_class->set_property = gst_partassembly_set_property;
gobject_class->get_property = gst_partassembly_get_property;
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_TARGET_TYPE,
g_param_spec_string ("target-type", "Target-Type", "The target type name used in this element for processing.", "NONE"/*DEFAULT_TARGET_TYPE*/, (GParamFlags)(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_ALERT_TYPE,
g_param_spec_string ("alert-type", "Alert-Type", "The alert type name represents the event occurred. Two alert types are offered:\n\t\t\t(1)\"idling\", which means OP is idling;\n\t\t\t(2)\"completed\", which means the assembly is completed.", "idling\0", (GParamFlags)(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PARTS_DISPLAY,
g_param_spec_boolean("parts-display", "Parts-display", "Show detected parts in frame.", TRUE, G_PARAM_READWRITE));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_INFORMATION_DISPLAY,
g_param_spec_boolean("information-display", "Information-display", "Show the assembly process status.", TRUE, G_PARAM_READWRITE));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_RESET,
g_param_spec_int("reset-time", "reset counting duration time", "Reset the counting time every defined seconds when only checking assembly.", 0, 100, 25, G_PARAM_READWRITE));
gobject_class->dispose = gst_partassembly_dispose;
gobject_class->finalize = gst_partassembly_finalize;
base_transform_class->before_transform = GST_DEBUG_FUNCPTR(gst_partassembly_before_transform);
base_transform_class->start = GST_DEBUG_FUNCPTR (gst_partassembly_start);
base_transform_class->stop = GST_DEBUG_FUNCPTR (gst_partassembly_stop);
video_filter_class->set_info = GST_DEBUG_FUNCPTR (gst_partassembly_set_info);
video_filter_class->transform_frame_ip = GST_DEBUG_FUNCPTR (gst_partassembly_transform_frame_ip);
}
static void gst_partassembly_init (Gstpartassembly *partassembly)
{
/*< private >*/
partassembly->priv = (GstpartassemblyPrivate *)gst_partassembly_get_instance_private (partassembly);
// *** define the required parts name, their required number and order to assemble
std::vector<std::string> partNameVector = {
"background",
"container-parts",
"container-semi-finished-products",
"light-guide-cover",
"screw",
"screwed-on",
"semi-finished-products",
"small-board-side-A",
"small-board-side-B",
"wire"};
std::vector<int> partRequiredNumberVector = {0, 0, 1, 2, 0, 4, 1, 0, 2, 1};
std::vector<int> partAssembleOrderVector = {-1, -1, -1, 1, -1, 3, 0, -1, 2, 4}; // -1: omit to check; 0~n: assemble order
partassembly->bom = BASIC_INFORMATION::BOM(partNameVector, partRequiredNumberVector, partAssembleOrderVector);
// ***
// initialize the materials
for(unsigned int i = 0; i < partassembly->bom.NameVector.size(); i++)
{
if(partRequiredNumberVector[i] > 0)
{
partassembly->priv->bomList.push_back(partassembly->bom.NameVector[i]);
partassembly->priv->bomMaterial.push_back(new Material(partassembly->bom.NumberVector[i], partassembly->bom.OrderVector[i]));
}
}
partassembly->priv->partsDisplay = true;
partassembly->priv->informationDisplay = true;
partassembly->priv->alert = false;
partassembly->priv->resetSeconds = 25;
partassembly->targetTypeChecked = false;
partassembly->startTick = 0;
partassembly->alertTick = 0;
partassembly->runningTime = 0;
partassembly->priv->targetType = "NONE\0";//DEFAULT_TARGET_TYPE;
partassembly->priv->alertType = "idling\0";//DEFAULT_ALERT_TYPE;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
{
assemblyActionVector[i] = false;
processingTime[i] = 0;
}
partassembly->lastTotalNumber = 0;
partassembly->partContainerIsEmpty = false;
}
void gst_partassembly_set_property (GObject * object, guint property_id, const GValue * value, GParamSpec * pspec)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (object);
GST_DEBUG_OBJECT (partassembly, "set_property");
switch (property_id)
{
case PROP_TARGET_TYPE:
{
partassembly->priv->targetType = g_value_dup_string(value);
break;
}
case PROP_ALERT_TYPE:
{
partassembly->priv->alertType = g_value_dup_string(value);
break;
}
case PROP_PARTS_DISPLAY:
{
partassembly->priv->partsDisplay = g_value_get_boolean(value);
if(partassembly->priv->partsDisplay)
GST_MESSAGE("Display part objects is enabled!");
break;
}
case PROP_INFORMATION_DISPLAY:
{
partassembly->priv->informationDisplay = g_value_get_boolean(value);
if(partassembly->priv->informationDisplay)
GST_MESSAGE("Display assembly information is enabled!");
break;
}
case PROP_RESET:
{
partassembly->priv->resetSeconds = g_value_get_int(value);
break;
}
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
void gst_partassembly_get_property (GObject * object, guint property_id, GValue * value, GParamSpec * pspec)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (object);
GST_DEBUG_OBJECT (partassembly, "get_property");
switch (property_id)
{
case PROP_TARGET_TYPE:
//g_value_set_string (value, weardetection->priv->targetType.c_str());
g_value_set_string (value, partassembly->priv->targetType);
break;
case PROP_ALERT_TYPE:
//g_value_set_string (value, partassembly->priv->alertType.c_str());
g_value_set_string (value, partassembly->priv->alertType);
break;
case PROP_PARTS_DISPLAY:
g_value_set_boolean(value, partassembly->priv->partsDisplay);
break;
case PROP_INFORMATION_DISPLAY:
g_value_set_boolean(value, partassembly->priv->informationDisplay);
break;
case PROP_RESET:
g_value_set_int(value, partassembly->priv->resetSeconds);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
void gst_partassembly_dispose (GObject * object)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (object);
GST_DEBUG_OBJECT (partassembly, "dispose");
/* clean up as possible. may be called multiple times */
G_OBJECT_CLASS (gst_partassembly_parent_class)->dispose (object);
}
void gst_partassembly_finalize (GObject * object)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY(object);
GST_DEBUG_OBJECT (partassembly, "finalize");
/* clean up object here */
G_OBJECT_CLASS (gst_partassembly_parent_class)->finalize (object);
}
static gboolean gst_partassembly_start (GstBaseTransform * trans)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (trans);
GST_DEBUG_OBJECT (partassembly, "start");
return TRUE;
}
static gboolean gst_partassembly_stop (GstBaseTransform * trans)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (trans);
partassembly->priv->alert = false;
partassembly->targetTypeChecked = false;
partassembly->startTick = 0;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
{
assemblyActionVector[i] = false;
processingTime[i] = 0;
}
partassembly->lastTotalNumber = 0;
partassembly->partContainerIsEmpty = false;
GST_DEBUG_OBJECT (partassembly, "stop");
return TRUE;
}
static gboolean gst_partassembly_set_info (GstVideoFilter * filter, GstCaps * incaps, GstVideoInfo * in_info, GstCaps * outcaps, GstVideoInfo * out_info)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (filter);
GST_DEBUG_OBJECT (partassembly, "set_info");
return TRUE;
}
static void gst_partassembly_before_transform (GstBaseTransform * trans, GstBuffer * buffer)
{
long base_time = (GST_ELEMENT (trans))->base_time;
long current_time = gst_clock_get_time((GST_ELEMENT (trans))->clock);
Gstpartassembly *partassembly = GST_PARTASSEMBLY (trans);
partassembly->runningTime = (current_time - base_time)/NANO_SECOND;
}
static GstFlowReturn gst_partassembly_transform_frame_ip (GstVideoFilter * filter, GstVideoFrame * frame)
{
Gstpartassembly *partassembly = GST_PARTASSEMBLY (filter);
GstMapInfo info;
GST_DEBUG_OBJECT (partassembly, "transform_frame_ip");
gst_buffer_map(frame->buffer, &info, GST_MAP_READ);
// map frame data from stream to partassembly srcMat
mapGstVideoFrame2OpenCVMat(partassembly, frame, info);
// get inference detected persons
getDetectedBox(partassembly, frame->buffer);
// do algorithm
doAlgorithm(partassembly, frame->buffer);
// draw part objects
if(partassembly->priv->partsDisplay)
drawObjects(partassembly);
// draw assembly information
if(partassembly->priv->informationDisplay)
drawStatus(partassembly);
gst_buffer_unmap(frame->buffer, &info);
return GST_FLOW_OK;
}
static void mapGstVideoFrame2OpenCVMat(Gstpartassembly *partassembly, GstVideoFrame *frame, GstMapInfo &info)
{
if(partassembly->srcMat.cols == 0 || partassembly->srcMat.rows == 0)
partassembly->srcMat = cv::Mat(frame->info.height, frame->info.width, CV_8UC3, info.data);
else if((partassembly->srcMat.cols != frame->info.width) || (partassembly->srcMat.rows != frame->info.height))
{
partassembly->srcMat.release();
partassembly->srcMat = cv::Mat(frame->info.height, frame->info.width, CV_8UC3, info.data);
}
else
partassembly->srcMat.data = info.data;
}
static void getDetectedBox(Gstpartassembly *partassembly, GstBuffer* buffer)
{
// reset the status
for (auto& value : partassembly->priv->bomMaterial)
{
value->ClearStatus();
}
partassembly->priv->indexOfSemiProductContainer = -1;
GstAdBatchMeta *meta = gst_buffer_get_ad_batch_meta(buffer);
if (meta == NULL)
GST_MESSAGE("Adlink metadata is not exist!");
else
{
AdBatch &batch = meta->batch;
bool frame_exist = batch.frames.size() > 0 ? true : false;
if(frame_exist)
{
VideoFrameData frame_info = batch.frames[0];
int detectionBoxResultNumber = frame_info.detection_results.size();
int width = partassembly->srcMat.cols;
int height = partassembly->srcMat.rows;
// full iterated all object to find "container-parts" exists alert-type(target-type used in this element)
if(partassembly->targetTypeChecked == false)
{
partassembly->targetTypeChecked = (std::string(partassembly->priv->targetType).compare("NONE"/*DEFAULT_TARGET_TYPE*/) == 0);
if(!partassembly->targetTypeChecked) // target-type was set by user
{
for(unsigned int i = 0 ; i < (uint)detectionBoxResultNumber ; ++i)
{
adlink::ai::DetectionBoxResult detection_result = frame_info.detection_results[i];
// check alert type was set
if(detection_result.meta.find(partassembly->priv->targetType) != std::string::npos)
{
partassembly->targetTypeChecked = true;
break;
}
}
}
}
// if partassembly->targetTypeChecked is true, check whether to reset or not
if(partassembly->targetTypeChecked == true)
{
for(unsigned int i = 0 ; i < (uint)detectionBoxResultNumber ; ++i)
{
adlink::ai::DetectionBoxResult detection_result = frame_info.detection_results[i];
// check alert type was set
if(detection_result.meta.find("empty") != std::string::npos)
{
partassembly->partContainerIsEmpty = true;
}
}
}
for(unsigned int i = 0 ; i < (uint)detectionBoxResultNumber ; ++i)
{
adlink::ai::DetectionBoxResult detection_result = frame_info.detection_results[i];
// check target type is required or set
if(partassembly->targetTypeChecked)
{
int materialIndex = getPartIndexInBomList(partassembly, detection_result.obj_label);
if(materialIndex != -1)
{
int x1 = (int)(width * detection_result.x1);
int y1 = (int)(height * detection_result.y1);
int x2 = (int)(width * detection_result.x2);
int y2 = (int)(height * detection_result.y2);
partassembly->priv->bomMaterial[materialIndex]->Add(x1, y1, x2, y2, detection_result.prob);
// container index
if(detection_result.obj_label.compare("container-semi-finished-products") == 0)
partassembly->priv->indexOfSemiProductContainer = materialIndex;
// semi-product index
if(detection_result.obj_label.compare("semi-finished-products") == 0)
partassembly->priv->indexOfSemiProduct = materialIndex;
}
}
}
}
}
// Check overlap if required in the future
// add the check overlap code here to remove multi-detected objects.
if(partassembly->priv->indexOfSemiProduct > 0) // more than one semi-product
partassembly->priv->bestIndexObjectOfSemiProduct = partassembly->priv->bomMaterial[partassembly->priv->indexOfSemiProduct]->GetBestScoreObjectIndex();
}
static int getPartIndexInBomList(Gstpartassembly *partassembly, const std::string& partName)
{
std::vector<std::string>::iterator it = std::find(partassembly->priv->bomList.begin(), partassembly->priv->bomList.end(), partName);
if(it != partassembly->priv->bomList.end())
return std::distance(partassembly->priv->bomList.begin(), it);
else
return -1;
}
static bool twoSidesCheck(Gstpartassembly *partassembly, int partIndex, int eachSideExistNumber)
{
// get semi-product points vector
std::vector<int> containerPointsVector = partassembly->priv->bomMaterial[partassembly->priv->indexOfSemiProduct]->GetPosition(partassembly->priv->bestIndexObjectOfSemiProduct);
// central vertical line of semi-product
int verticalCenter = (containerPointsVector[0] + containerPointsVector[2]) / 2;
// calculate each side object number
int numLeft = 0;
int numRight = 0;
int objectNumber = partassembly->priv->bomMaterial[partIndex]->GetObjectNumber();
for(int i = 0; i < objectNumber; ++i)
{
std::vector<int> objectPointsVector = partassembly->priv->bomMaterial[partIndex]->GetPosition(i);
if(objectPointsVector[0] < verticalCenter)
numLeft++;
else
numRight++;
}
bool sideCheck = numLeft == eachSideExistNumber && numRight == eachSideExistNumber ? true : false;
return sideCheck;
}
static void doAlgorithm(Gstpartassembly *partassembly, GstBuffer* buffer)
{
// get base time of this element from last startTick
long base_time = (GST_ELEMENT (partassembly))->base_time;
// If metadata does not exist, return directly.
GstAdBatchMeta *meta = gst_buffer_get_ad_batch_meta(buffer);
if (meta == NULL)
{
g_message("Adlink metadata is not exist!");
return;
}
AdBatch &batch = meta->batch;
bool frame_exist = batch.frames.size() > 0 ? true : false;
// if(partassembly->priv->alert == true)
// if((gst_clock_get_time((GST_ELEMENT (partassembly))->clock) - base_time)/NANO_SECOND > 5)
// partassembly->priv->alert = false;
if(partassembly->priv->alert == true)
{
if(partassembly->runningTime - partassembly->alertTick > 5)
{
partassembly->priv->alert = false;
}
}
// Check whether materials are in the container and semi-product
// Get container
int containerId = partassembly->priv->indexOfSemiProductContainer;
if(containerId < 0)
return;
std::vector<int> rectContainerVector;
if(partassembly->priv->bomMaterial[containerId]->GetObjectNumber() > 0)
rectContainerVector = partassembly->priv->bomMaterial[containerId]->GetRectangle(0);
if(rectContainerVector.size() != 4)
{
g_info("No Semi product container detected.");
return;
}
// Container index is containerId in bomMaterial, take the first object one as the container
std::vector<cv::Point> containerPointsVec = partassembly->priv->bomMaterial[containerId]->GetObjectPoints(0);
// Get semi-product
// check semi-product
if(partassembly->priv->bestIndexObjectOfSemiProduct < 0)
{
g_info("No Semi product detected.");
return;
}
int semiProductId = partassembly->priv->indexOfSemiProduct;
int bestIndexObjectOfSemiProduct = partassembly->priv->bestIndexObjectOfSemiProduct;
std::vector<cv::Point> semiProductPointsVec = partassembly->priv->bomMaterial[semiProductId]->GetObjectPoints(bestIndexObjectOfSemiProduct);
//Check each material is in the container and required number
int requiredMaterialNumber = partassembly->priv->bomMaterial.size();
int totalPartsNum = 0;
for(unsigned int materialID = 0; materialID < (uint)requiredMaterialNumber; ++materialID)
{
int totalObjectNumber = partassembly->priv->bomMaterial[materialID]->GetObjectNumber();
std::vector<cv::Point> intersectionPolygon;
int numberInSemiProduct = 0;
for(unsigned int objID = 0; objID < (uint)totalObjectNumber; objID++)
{
std::vector<cv::Point> objectPointsVec = partassembly->priv->bomMaterial[materialID]->GetObjectPoints(objID);
float intersectAreaWithContainer = cv::intersectConvexConvex(containerPointsVec, objectPointsVec, intersectionPolygon, true);
float intersectAreaWithSemiProduct = cv::intersectConvexConvex(semiProductPointsVec, objectPointsVec, intersectionPolygon, true);
if(intersectAreaWithContainer > 0 && intersectAreaWithSemiProduct > 0)
{
numberInSemiProduct++;
totalPartsNum++;
partassembly->priv->bomMaterial[materialID]->SetPartNumber(numberInSemiProduct);
}
}
}
// check is there exist any object in semi-product container.
// if only exist semi-product container, reset all parameters and return
if((totalPartsNum == 2 && partassembly->partContainerIsEmpty == true) // 1 container-semi-finished-products + 1 semi-finished-products
|| (totalPartsNum == 2 && partassembly->priv->alert == true)) // when empty and already alert
{
partassembly->priv->alert = false;
partassembly->targetTypeChecked = false;
partassembly->startTick = 0;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
{
assemblyActionVector[i] = false;
processingTime[i] = 0;
}
partassembly->lastTotalNumber = 0;
partassembly->partContainerIsEmpty = false;
return;
}
// If this is single assembly, check the reset criteria
if (std::string(partassembly->priv->targetType).compare("NONE") == 0)
{
double totalElapsedTime = 0;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
totalElapsedTime += processingTime[i];
if((totalPartsNum == 2 && partassembly->lastTotalNumber > 8) || totalElapsedTime > partassembly->priv->resetSeconds)
{
partassembly->priv->alert = false;
partassembly->targetTypeChecked = false;
partassembly->startTick = 0;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
{
assemblyActionVector[i] = false;
processingTime[i] = 0;
}
partassembly->lastTotalNumber = 0;
partassembly->partContainerIsEmpty = false;
return;
}
}
partassembly->lastTotalNumber = totalPartsNum;
//get check assembly action
int checkAction = -1;
for(unsigned int i = 0; i < assemblyActionVector.size(); ++i)
{
if(!assemblyActionVector[i])
{
checkAction = i;
break;
}
}
switch(checkAction)
{
case 0: // put 1 semi-product in container
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
if(partassembly->priv->bomMaterial[semiProductId]->CheckNumber())
{
partassembly->priv->bomMaterial[semiProductId]->SetIndexInBox(checkAction);
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Put semi-product in container done.");
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 1: // put 2 light-guide-cover in semi-finished-products(left and right)
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
int id = getPartIndexInBomList(partassembly, "light-guide-cover");
if(partassembly->priv->bomMaterial[id]->CheckNumber())
{
partassembly->priv->bomMaterial[id]->SetIndexInBox(checkAction);
if(twoSidesCheck(partassembly, id, 1)) // Simply check each one should be at left and right side.
{
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Put light-guide-cover done.");
}
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 2: // put 2 small-board-side-B in semi-finished-products(left and right)
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
int id = getPartIndexInBomList(partassembly, "small-board-side-B");
if(partassembly->priv->bomMaterial[id]->CheckNumber())
{
partassembly->priv->bomMaterial[id]->SetIndexInBox(checkAction);
if(twoSidesCheck(partassembly, id, 1)) // Simply check each one should be at left and right side.
{
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Put small-board-side-B done.");
}
else
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 3: // screw on 4 screws(2 on left, 2 on right)
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
int id = getPartIndexInBomList(partassembly, "screwed-on");
if(partassembly->priv->bomMaterial[id]->CheckNumber())
{
partassembly->priv->bomMaterial[id]->SetIndexInBox(checkAction);
if(twoSidesCheck(partassembly, id, 2)) // Simply check each two should be at left and right side.
{
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Screw on screws done.");
}
else
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 4: // put wire on
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
int id = getPartIndexInBomList(partassembly, "wire");
if(partassembly->priv->bomMaterial[id]->CheckNumber())
{
partassembly->priv->bomMaterial[id]->SetIndexInBox(checkAction);
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Put wire done.");
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 5: // final visual inspection: 2 small-board-side-B with 4 screw-on(each small-board-side-B contains 2 screw-on) and 1 wire
{
if(processingTime[checkAction] == 0)
partassembly->startTick = partassembly->runningTime;
bool checkFinal = true;
// 2 small-board-side-B
int id = getPartIndexInBomList(partassembly, "small-board-side-B");
checkFinal &= partassembly->priv->bomMaterial[id]->CheckNumber() && twoSidesCheck(partassembly, id, 1);
// 4 screw on
id = getPartIndexInBomList(partassembly, "screwed-on");
checkFinal &= partassembly->priv->bomMaterial[id]->CheckNumber() && twoSidesCheck(partassembly, id, 2);
// 1 wire
id = getPartIndexInBomList(partassembly, "wire");
checkFinal &= partassembly->priv->bomMaterial[id]->CheckNumber();
if(checkFinal)
{
assemblyActionVector[checkAction] = true;
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
partassembly->startTick = 0;
GST_MESSAGE("Visual inspection done.");
}
else
{
processingTime[checkAction] = partassembly->runningTime - partassembly->startTick;
}
break;
}
case 6: // complete
GST_MESSAGE("Assembly completed");
assemblyActionVector[checkAction] = true;
break;
default:
//std::cout << "no action need to check.\n";
break;
}
if(frame_exist && containerId != -1)
{
// Check regular time
for(unsigned int i = 0; i < assemblyActionVector.size() ; ++i)
{
if(processingTime[i] > processingRegularTime[i] && partassembly->priv->alert == false)
{
GST_MESSAGE("put idling alert message.");
partassembly->priv->alert = true;
std::string alertMessage = "," + std::string(partassembly->priv->alertType) + "<" + return_current_time_and_date() + ">";
meta->batch.frames[0].detection_results[containerId].meta += alertMessage;
//partassembly->alertTick = cv::getTickCount();
partassembly->alertTick = partassembly->runningTime;
}
}
// If completed, set alert
if(checkAction == assemblyActionVector.size() - 1)
{
std::string alertMessage = "," + std::string("Completed") + "<" + return_current_time_and_date() + ">";
meta->batch.frames[0].detection_results[containerId].meta += alertMessage;
GST_MESSAGE("put Completed alert message.");
}
}
}
static void drawObjects(Gstpartassembly *partassembly)
{
int width = partassembly->srcMat.cols;
int height = partassembly->srcMat.rows;
float scale = 0.025;
int font = cv::FONT_HERSHEY_COMPLEX;
//double font_scale = 0.5;
double font_scale = std::min(width, height)/(25/scale);
int thickness = 2;
int indexOfContainer = partassembly->priv->indexOfSemiProductContainer;
if(indexOfContainer < 0)
return;
if(partassembly->priv->indexOfSemiProductContainer >= 0)
{
int numOfContainer = partassembly->priv->bomMaterial[indexOfContainer]->GetObjectNumber();
if(numOfContainer <= 0)
return;
}
std::vector<cv::Point> containerPointsVec = partassembly->priv->bomMaterial[indexOfContainer]->GetObjectPoints(0);
std::vector<cv::Point> intersectionPolygon;
for(unsigned int i = 0; i < partassembly->priv->bomMaterial.size(); ++i)
{
int numberOfObjectInMaterial = partassembly->priv->bomMaterial[i]->GetObjectNumber();
for(unsigned int index = 0; index < (uint)numberOfObjectInMaterial; index++)
{
std::vector<int> pointsVector = partassembly->priv->bomMaterial[i]->GetPosition(index);
if(pointsVector.size() > 0)
{
std::vector<cv::Point> objectPointsVec = partassembly->priv->bomMaterial[i]->GetObjectPoints(index);
float intersectArea = cv::intersectConvexConvex(containerPointsVec, objectPointsVec, intersectionPolygon, true);
if(intersectArea > 0)
{
int x1 = pointsVector[0];
int y1 = pointsVector[1];
int x2 = pointsVector[2];
int y2 = pointsVector[3];
// draw rectangle
cv::rectangle(partassembly->srcMat, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0, 255, 0), 2);
// put label name
cv::putText(partassembly->srcMat, partassembly->priv->bomList[i], cv::Point(x1, y1), font, font_scale, cv::Scalar(0, 255, 255), thickness, 8, 0);
}
}
}
}
}
static void drawStatus(Gstpartassembly *partassembly)
{
int width = partassembly->srcMat.cols;
int height = partassembly->srcMat.rows;
float scale = 0.02;
int font = cv::FONT_HERSHEY_COMPLEX;
//double font_scale = 1;
double font_scale = std::min(width, height)/(25/scale);
int thickness = 1;
cv::Scalar contentInfoColor = cv::Scalar(255, 255, 255);
cv::Scalar actionDoneColor = cv::Scalar(0, 255, 0);
cv::Scalar actionProcessColor = cv::Scalar(0, 255, 255);
int startX = width * 0.03;
int startY = height * 0.5;
//int heightShift = 35;
int heightShift = cv::getTextSize("Text", font, font_scale, thickness, 0).height * 1.5;
bool metProcessingAction = false;
double totalElapsedTime = 0;
for(unsigned int i = 0; i < assemblyActionVector.size() - 1 ; ++i)
{
startY += heightShift;
totalElapsedTime += processingTime[i];
std::string timeString = " [" + round2String(processingTime[i], 3) + " s]";
if(!assemblyActionVector[i] && !metProcessingAction)
{
metProcessingAction = true;
cv::putText(partassembly->srcMat, assemblyActionInfoVector[i] + timeString, cv::Point(startX, startY), font, font_scale, actionProcessColor, thickness * 2, 4, 0);
cv::circle (partassembly->srcMat, cv::Point(startX - width * 0.015, startY - heightShift / 4), heightShift / 2.5, actionProcessColor, -1, cv::LINE_8, 0);
}
else if(assemblyActionVector[i])
{
cv::putText(partassembly->srcMat, assemblyActionInfoVector[i] + timeString, cv::Point(startX, startY), font, font_scale, actionDoneColor, thickness, 4, 0);
}
else
{
cv::putText(partassembly->srcMat, assemblyActionInfoVector[i] + timeString, cv::Point(startX, startY), font, font_scale, contentInfoColor, thickness, 4, 0);
}
}
// show total elapsed time
startY += heightShift;
cv::putText(partassembly->srcMat, "total elapsed time = " + round2String(totalElapsedTime, 3) + " s", cv::Point(startX, startY), font, font_scale, cv::Scalar(30, 144, 255), thickness, 4, 0);
// show alert
if(partassembly->priv->alert)
{
startY += 2 * heightShift;
cv::putText(partassembly->srcMat, " idling !!", cv::Point(startX, startY), font, font_scale * 2, cv::Scalar(0, 0, 255), thickness * 2, 4, 0);
}
}
| 41.399381 | 351 | 0.635083 | AIoT-IST |
c7955b06d771c30961059c9dbbdc62196053fa3d | 12,843 | cpp | C++ | src/app_eth.cpp | tsc19/fring | 2418ce1b27892f2f5c256f94ae0c5fc376cfa72c | [
"Apache-2.0"
] | 3 | 2019-11-06T09:05:07.000Z | 2021-04-11T08:46:57.000Z | src/app_eth.cpp | tsc19/fring | 2418ce1b27892f2f5c256f94ae0c5fc376cfa72c | [
"Apache-2.0"
] | null | null | null | src/app_eth.cpp | tsc19/fring | 2418ce1b27892f2f5c256f94ae0c5fc376cfa72c | [
"Apache-2.0"
] | null | null | null | #include "app_eth.h"
// constructors
BaseAppETH::BaseAppETH(std::string ip, unsigned short port, std::string id) {
this->node = std::make_shared<Node>(id, ip, port);
this->node_table = std::make_shared<NodeTableETH>(id);
}
// getters
std::shared_ptr<Node> BaseAppETH::get_node() {
return this->node;
}
std::shared_ptr<NodeTableETH> BaseAppETH::get_node_table() {
return this->node_table;
}
std::shared_ptr<PeerManagerETH> BaseAppETH::get_peer_manager() {
return this->peer_manager;
}
// public functions
void BaseAppETH::form_structure(int num_nodes_in_dist, int num_cnodes_in_dist,
int num_nodes_in_city, int num_cnodes_in_city,
int num_nodes_in_state, int num_cnodes_in_state,
int num_nodes_in_country, int num_cnodes_in_country,
int num_nodes_in_continent, int num_continents,
int num_cnodes_in_continent,
unsigned short starting_port_number) {
// form network topology based ID
std::string id_in_dist = this->node->get_id().substr(ID_SINGLE_START, ID_SINGLE_LEN);
std::string dist_id = this->node->get_id().substr(ID_DISTRICT_START, ID_DISTRICT_LEN);
std::string city_id = this->node->get_id().substr(ID_CITY_START, ID_CITY_LEN);
std::string state_id = this->node->get_id().substr(ID_STATE_START, ID_STATE_LEN);
std::string country_id = this->node->get_id().substr(ID_COUNTRY_START, ID_COUNTRY_LEN);
std::string continent_id = this->node->get_id().substr(ID_CONTINENT_START, ID_CONTINENT_LEN);
int num_dists_in_city, num_cities_in_state, num_states_in_country, num_countries_in_continent;
num_dists_in_city = num_nodes_in_city/num_cnodes_in_dist;
if (num_dists_in_city == 0)
num_dists_in_city = 1;
num_cities_in_state = num_nodes_in_state/num_cnodes_in_city;
if (num_cities_in_state == 0)
num_cities_in_state = 1;
num_states_in_country = num_nodes_in_country/num_cnodes_in_state;
if (num_states_in_country == 0)
num_states_in_country = 1;
num_countries_in_continent = num_nodes_in_continent/num_cnodes_in_country;
if (num_countries_in_continent == 0)
num_countries_in_continent = 1;
int num_nodes_total = num_continents * num_countries_in_continent * num_states_in_country * num_cities_in_state * num_dists_in_city * num_nodes_in_dist;
// set node table
std::vector<std::shared_ptr<Node>> table;
// generate random neighbors to connect
std::unordered_set<int> neighbor_ids;
int self_order = convert_ID_string_to_int(this->node->get_id(),
num_nodes_in_dist, num_cnodes_in_dist,
num_nodes_in_city, num_cnodes_in_city,
num_nodes_in_state, num_cnodes_in_state,
num_nodes_in_country, num_cnodes_in_country,
num_nodes_in_continent);
neighbor_ids.insert((self_order+1) % num_nodes_total);
for (int i = 0; i < TABLE_SIZE_ETH; i++) {
int id = rand() % num_nodes_total;
if (neighbor_ids.find(id) == neighbor_ids.end() && id != self_order) {
neighbor_ids.insert(id);
} else {
i--;
}
}
// int to string
std::stringstream ss;
int counter = 0;
for (int continent_counter = 0; continent_counter < num_continents; continent_counter++) {
ss.str("");
ss.clear();
ss << std::setw(ID_CONTINENT_LEN) << std::setfill('0') << continent_counter;
continent_id = ss.str();
for (int country_counter = 0; country_counter < num_countries_in_continent; country_counter++) {
ss.str("");
ss.clear();
ss << std::setw(ID_COUNTRY_LEN) << std::setfill('0') << country_counter;
country_id = ss.str();
for (int state_counter = 0; state_counter < num_states_in_country; state_counter++) {
ss.str("");
ss.clear();
ss << std::setw(ID_STATE_LEN) << std::setfill('0') << state_counter;
state_id = ss.str();
for (int city_counter = 0; city_counter < num_cities_in_state; city_counter++) {
ss.str("");
ss.clear();
ss << std::setw(ID_CITY_LEN) << std::setfill('0') << city_counter;
city_id = ss.str();
for (int district_counter = 0; district_counter < num_dists_in_city; district_counter++) {
ss.str("");
ss.clear();
ss << std::setw(ID_DISTRICT_LEN) << std::setfill('0') << district_counter;
dist_id = ss.str();
for (int i = 0; i < num_nodes_in_dist; i++) {
ss.str("");
ss.clear();
ss << std::setw(ID_SINGLE_LEN) << std::setfill('0') << i;
id_in_dist = ss.str();
std::string node_id = continent_id + country_id + state_id + city_id + dist_id + id_in_dist;
int order = convert_ID_string_to_int(node_id,
num_nodes_in_dist, num_cnodes_in_dist,
num_nodes_in_city, num_cnodes_in_city,
num_nodes_in_state, num_cnodes_in_state,
num_nodes_in_country, num_cnodes_in_country,
num_nodes_in_continent);
if (neighbor_ids.find(order) != neighbor_ids.end() && node_id != this->node->get_id()) {
unsigned short port = starting_port_number + order;
Node node(node_id, "127.0.0.1", port);
if (order == self_order+1)
table.insert(table.begin(), std::make_shared<Node>(node));
else
table.push_back(std::make_shared<Node>(node));
}
counter++;
}
}
}
}
}
}
this->node_table->set_table(table);
return;
}
void BaseAppETH::start(const std::string &start_time, int num_nodes_in_dist, int num_cnodes_in_dist,
int num_nodes_in_city, int num_cnodes_in_city,
int num_nodes_in_state, int num_cnodes_in_state,
int num_nodes_in_country, int num_cnodes_in_country,
int num_nodes_in_continent, int num_continents,
int num_cnodes_in_continent,
unsigned short starting_port_number) {
std::cout << "Setting up NodeTable for node [ID: " + this->node->get_id() + "] [IP: " + this->node->get_ip() + "] [" + std::to_string(this->node->get_port()) + "]\n";
std::cout << "Establishing structure on node [ID: " + this->node->get_id() + "] [IP: " + this->node->get_ip() + "] [" + std::to_string(this->node->get_port()) + "]\n";
// form the geographical structure
this->form_structure(num_nodes_in_dist, num_cnodes_in_dist,
num_nodes_in_city, num_cnodes_in_city,
num_nodes_in_state, num_cnodes_in_state,
num_nodes_in_country, num_cnodes_in_country,
num_nodes_in_continent, num_continents,
num_cnodes_in_continent,
starting_port_number);
std::cout << "Structure established on node [ID: " + this->node->get_id() + "] [IP: " + this->node->get_ip() + "] [" + std::to_string(this->node->get_port()) + "]\n";
std::cout << "Node Tables on node [ID: " + this->node->get_id() + "] [IP: " + this->node->get_ip() + "] [" + std::to_string(this->node->get_port()) + "]\n";
for (auto peer : this->node_table->get_table()) {
std::cout << "Peer - " + peer->get_id() + " " + peer->get_ip() + ":" + std::to_string(peer->get_port()) << "\n";
}
this->peer_manager = std::make_shared<PeerManagerETH>(node, node_table, start_time);
// set gossip mode
this->peer_manager->set_mode(PeerManagerETH::PUSH); // PUSH version
// this->peer_manager->set_mode(PeerManagerETH::PULL); // PULL version
std::cout << "Starting ETH PeerManager on node [ID: " + this->node->get_id() + "] [IP: " + this->node->get_ip() + "] [" + std::to_string(this->node->get_port()) + "]\n";
this->peer_manager->start();
return;
}
void BaseAppETH::stop() {
this->peer_manager->stop();
return;
}
void BaseAppETH::broadcast(const std::string &data) {
this->peer_manager->broadcast(data, TTL_ETH, "");
return;
}
int main(int argc, char** argv) {
srand(std::atoi(argv[2]) + time(NULL));
if (argc != 17) {
std::cout << "Wrong arguments. Correct usage: "
<< "./app_eth ip_addr port_num id "
<< "num_nodes_in_dist num_cnodes_in_dist "
<< "num_nodes_in_city num_cnodes_in_city "
<< "num_nodes_in_state num_cnodes_in_state "
<< "num_nodes_in_country num_cnodes_in_country "
<< "num_nodes_in_continent num_cnodes_in_continent "
<< "num_continents"
<< "starting_port_num start_time\n";
return 0;
}
std::string ip = argv[1];
unsigned short port = (unsigned short) std::atoi(argv[2]);
std::string id = argv[3];
// information used for network topology establishment (only used for evaluation)
int num_nodes_in_dist = std::atoi(argv[4]);
int num_cnodes_in_dist = std::atoi(argv[5]);
int num_nodes_in_city = std::atoi(argv[6]);
int num_cnodes_in_city = std::atoi(argv[7]);
int num_nodes_in_state = std::atoi(argv[8]);
int num_cnodes_in_state = std::atoi(argv[9]);
int num_nodes_in_country = std::atoi(argv[10]);
int num_cnodes_in_country = std::atoi(argv[11]);
int num_nodes_in_continent = std::atoi(argv[12]);
int num_cnodes_in_continent = std::atoi(argv[13]);
int num_continents = std::atoi(argv[14]);
int starting_port_number = std::atoi(argv[15]);
std::string start_time = argv[16];
// initialize the app
std::cout << "Creating ETH base application on node [ID: " + id + "] [IP: " + ip + "] [" + std::to_string(port) + "]\n";
BaseAppETH app = BaseAppETH(ip, port, id);
// start the app service
std::cout << "Starting ETH base service on node [ID: " + id + "] [IP: " + ip + "] [" + std::to_string(port) + "]\n";
app.start(start_time, num_nodes_in_dist, num_cnodes_in_dist,
num_nodes_in_city, num_cnodes_in_city,
num_nodes_in_state, num_cnodes_in_state,
num_nodes_in_country, num_cnodes_in_country,
num_nodes_in_continent, num_continents,
num_cnodes_in_continent,
starting_port_number);
// message record logging
std::ofstream ofs;
ofs.open("../test/log/" + start_time + "/" + app.get_node()->get_id() + ".csv");
if (ofs.is_open()) {
ofs << Message::csv_header << "\n";
ofs.close();
} else {
std::cout << "Error opening file\n";
}
// broadcast a message
int order = convert_ID_string_to_int(id, num_nodes_in_dist, num_cnodes_in_dist,
num_nodes_in_city, num_cnodes_in_city,
num_nodes_in_state, num_cnodes_in_state,
num_nodes_in_country, num_cnodes_in_country,
num_nodes_in_continent);
if (order == 1) {
//int num_messages_to_broadcast = 2;
//int mean_interval = 10;
//int variance = 2;
int random_sleep_time = 5; // rand() % 180;
std::this_thread::sleep_for (std::chrono::seconds(random_sleep_time));
std::cout << "Slept for " << random_sleep_time << " seconds\n";
std::cout << "Broadcasting message ...\n";
// for (int i = 0; i < num_messages_to_broadcast-1; i++) {
// std::cout << "Broadcast a message of size " << data_of_block_size.length() / 1000 << "kb\n";
// app.broadcast(data_of_block_size);
// std::this_thread::sleep_for (std::chrono::seconds(mean_interval-variance + rand() % variance));
// }
app.broadcast(data_of_block_size);
}
// block
app.stop();
return 0;
}
| 46.032258 | 173 | 0.56926 | tsc19 |
c7961212cb8b85c10114c83869a245f0d7803c16 | 403 | cpp | C++ | CLIHelperTests/group_argument_is.cpp | BitCruncher0/CLIHelper | 9ea8e6b5f14f038c143c4e552fad8e1394556a9d | [
"Apache-2.0"
] | 1 | 2022-01-10T23:47:40.000Z | 2022-01-10T23:47:40.000Z | CLIHelperTests/group_argument_is.cpp | BitCruncher0/CLIHelper | 9ea8e6b5f14f038c143c4e552fad8e1394556a9d | [
"Apache-2.0"
] | null | null | null | CLIHelperTests/group_argument_is.cpp | BitCruncher0/CLIHelper | 9ea8e6b5f14f038c143c4e552fad8e1394556a9d | [
"Apache-2.0"
] | null | null | null | #include "CppUTest/TestHarness.h"
#include "../cli.hpp"
#include <string>
#include <fstream>
#include <vector>
using std::string;
using std::vector;
TEST_GROUP(ArgumentIs)
{
};
TEST(ArgumentIs, Returns_true_if_Nth_argument_is_key)
{
CHECK_EQUAL(false, argumentIs("a", 0, "a b"));
CHECK_EQUAL(true, argumentIs("b", 0, "a b"));
CHECK_EQUAL(true, argumentIs("d", 2, "a b c d"));
}
| 13.433333 | 53 | 0.662531 | BitCruncher0 |
c79b1259fec0b2d76602c19fa77ad7979dd8509f | 1,993 | hpp | C++ | engine/glrenderer/buffers.hpp | tapio/weep | aca40e3ce20eae4ce183a98ab707ac65c4be4e63 | [
"MIT"
] | 33 | 2017-01-13T20:47:21.000Z | 2022-03-21T23:29:17.000Z | engine/glrenderer/buffers.hpp | tapio/weep | aca40e3ce20eae4ce183a98ab707ac65c4be4e63 | [
"MIT"
] | null | null | null | engine/glrenderer/buffers.hpp | tapio/weep | aca40e3ce20eae4ce183a98ab707ac65c4be4e63 | [
"MIT"
] | 4 | 2016-12-10T16:10:42.000Z | 2020-06-28T04:44:11.000Z | #pragma once
#include "common.hpp"
#include "../../data/shaders/uniforms.glsl"
// Generic Buffer Object
struct BufferObjectBase
{
virtual ~BufferObjectBase() { destroy(); }
NONCOPYABLE(BufferObjectBase);
protected:
BufferObjectBase() {}
void create(uint type, uint binding, uint size, const void* data);
void bindBase(uint type, uint binding);
void upload(uint type, uint size, const void* data);
public:
void destroy();
uint id = 0;
};
// Uniform Buffer Object
template<typename T>
struct UBO : public BufferObjectBase
{
UBO() {}
NONCOPYABLE(UBO);
void create() { BufferObjectBase::create(/*GL_UNIFORM_BUFFER*/ 0x8A11, uniforms.binding, sizeof(uniforms), &uniforms); }
void bindBase() { BufferObjectBase::bindBase(/*GL_UNIFORM_BUFFER*/ 0x8A11, uniforms.binding); }
void upload() { BufferObjectBase::upload(/*GL_UNIFORM_BUFFER*/ 0x8A11, sizeof(uniforms), &uniforms); }
T uniforms = T();
};
// Shader Storage Buffer Object
template<typename T>
struct SSBO : public BufferObjectBase
{
SSBO(uint binding, uint size = 0): binding(binding) { buffer.resize(size); }
NONCOPYABLE(SSBO);
void create(bool preserveData = false) {
BufferObjectBase::create(/*GL_SHADER_STORAGE_BUFFER*/ 0x90D2, binding, sizeof(T) * buffer.size(), buffer.data());
if (!preserveData)
releaseCPUMem();
}
void create(uint newSize, bool preserveData = false) {
if (buffer.empty() && !preserveData) {
BufferObjectBase::create(/*GL_SHADER_STORAGE_BUFFER*/ 0x90D2, binding, sizeof(T) * newSize, nullptr);
} else {
buffer.resize(newSize);
create(preserveData);
}
}
void bindBase() { BufferObjectBase::bindBase(/*GL_SHADER_STORAGE_BUFFER*/ 0x90D2, binding); }
void upload(bool preserveData = false) {
BufferObjectBase::upload(/*GL_SHADER_STORAGE_BUFFER*/ 0x90D2, sizeof(T) * buffer.size(), buffer.data());
if (!preserveData)
releaseCPUMem();
}
void releaseCPUMem() {
buffer.clear();
buffer.shrink_to_fit();
}
uint binding = 0;
std::vector<T> buffer;
};
| 24.9125 | 121 | 0.712494 | tapio |
c79bf17c6647e14d45af6d6a9f7eae7520b24632 | 4,519 | cpp | C++ | DataConverter/SegmenterDictionaryFeatureGenerator.cpp | hiroshi-manabe/CRFSegmenter | c8b0544933701f91ff9cfac9301c51b181a4f846 | [
"BSL-1.0"
] | 16 | 2016-07-01T01:40:56.000Z | 2020-05-06T03:29:42.000Z | DataConverter/SegmenterDictionaryFeatureGenerator.cpp | hiroshi-manabe/CRFSegmenter | c8b0544933701f91ff9cfac9301c51b181a4f846 | [
"BSL-1.0"
] | 9 | 2016-07-04T06:44:42.000Z | 2020-05-14T21:23:46.000Z | DataConverter/SegmenterDictionaryFeatureGenerator.cpp | hiroshi-manabe/CRFSegmenter | c8b0544933701f91ff9cfac9301c51b181a4f846 | [
"BSL-1.0"
] | 2 | 2016-07-05T14:50:32.000Z | 2019-10-03T02:35:53.000Z | #include "SegmenterDictionaryFeatureGenerator.h"
#include "../Dictionary/DictionaryClass.h"
#include "../Utility/CharWithSpace.h"
#include <algorithm>
#include <cassert>
#include <unordered_set>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
namespace DataConverter {
using std::make_shared;
using std::move;
using std::string;
using std::unordered_set;
using std::vector;
using Dictionary::DictionaryClass;
using HighOrderCRF::FeatureTemplate;
using Utility::CharWithSpace;
SegmenterDictionaryFeatureGenerator::SegmenterDictionaryFeatureGenerator(const unordered_set<string> &dictionaries, size_t maxLabelLength) {
dictionary = make_shared<DictionaryClass>(dictionaries);
this->maxLabelLength = maxLabelLength;
}
vector<vector<FeatureTemplate>> SegmenterDictionaryFeatureGenerator::generateFeatureTemplates(const vector<CharWithSpace> &observationList) const {
vector<vector<FeatureTemplate>> featureTemplateListList(observationList.size());
// Generates all the templates
// Reconstructs the whole sentence, recording the start positions
string sentence;
vector<size_t> startPosList;
for (const auto uchar : observationList) {
startPosList.emplace_back(sentence.length());
sentence += uchar.toString();
}
startPosList.emplace_back(sentence.length());
vector<size_t> utf8PosToCharPosList(sentence.length() + 1);
for (size_t i = 0; i < startPosList.size(); ++i) {
utf8PosToCharPosList[startPosList[i]] = i;
}
utf8PosToCharPosList[sentence.length()] = startPosList.size();
for (size_t i = 0; i < startPosList.size() - 1; ++i) {
size_t startUtf8Pos = startPosList[i];
auto ch = observationList[i];
// skip the space if there is one
if (ch.hasSpace()) {
++startUtf8Pos;
}
// Looks up the words
auto results = dictionary->commonPrefixSearch(
string(sentence.c_str() + startUtf8Pos, sentence.length() - startUtf8Pos));
for (auto &p : results) {
auto charLength = p.first;
auto &featureListList = p.second;
unordered_set<string> featureSet;
for (auto &featureList : featureListList) {
for (auto &feature : featureList) {
featureSet.emplace(move(feature));
}
}
size_t endCharPos = utf8PosToCharPosList[startUtf8Pos + charLength];
if (endCharPos == 0) { // This cannot happen if everything is in well-formed utf-8
continue;
}
int wordLength = endCharPos - i;
assert(wordLength > 0);
size_t labelLength = wordLength + 1;
if (labelLength > maxLabelLength) {
labelLength = maxLabelLength;
}
bool hasLeftSpace = ch.hasSpace();
bool hasRightSpace = (endCharPos < observationList.size() ? observationList[endCharPos].hasSpace() : true);
string spaceStr;
if (hasLeftSpace) {
spaceStr += "LS";
}
if (hasRightSpace) {
spaceStr += "RS";
}
spaceStr += "-";
// Feature template for the left position
auto &leftTemplateList = featureTemplateListList[i];
for (const auto &featureStr : featureSet) {
leftTemplateList.emplace_back(string("Rw-") + featureStr, 1);
if (hasLeftSpace || hasRightSpace) {
leftTemplateList.emplace_back(string("Rw") + spaceStr + featureStr, 1);
}
}
if (endCharPos >= observationList.size()) {
continue;
}
// Feature templates for the right position
auto &rightTemplateList = featureTemplateListList[endCharPos];
for (const auto &featureStr : featureSet) {
rightTemplateList.emplace_back(string("Lw-") + featureStr, 1);
rightTemplateList.emplace_back(string("LW-") + featureStr, labelLength);
if (hasLeftSpace || hasRightSpace) {
rightTemplateList.emplace_back(string("Lw") + spaceStr + featureStr, 1);
rightTemplateList.emplace_back(string("LW") + spaceStr + featureStr, labelLength);
}
}
}
}
return featureTemplateListList;
}
} // namespace DataConverter
| 36.739837 | 147 | 0.612525 | hiroshi-manabe |
c7a2aafa94bf6965635216afb9ef0f2e0be9aa35 | 154 | hpp | C++ | pythran/pythonic/__builtin__/pythran/kwonly.hpp | AlifeLines/pythran | b793344637173cac8e5f4a79b0ab788951d53899 | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/__builtin__/pythran/kwonly.hpp | AlifeLines/pythran | b793344637173cac8e5f4a79b0ab788951d53899 | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/__builtin__/pythran/kwonly.hpp | AlifeLines/pythran | b793344637173cac8e5f4a79b0ab788951d53899 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_BUILTIN_PYTHRAN_KWONLY_HPP
#define PYTHONIC_BUILTIN_PYTHRAN_KWONLY_HPP
#include "pythonic/include/__builtin__/pythran/kwonly.hpp"
#endif
| 30.8 | 58 | 0.883117 | AlifeLines |
c7a3126de11c19d81ebc972cbf196e7dd7637b43 | 14,537 | cpp | C++ | flite/src/cg/mlsa.cpp | Barath-Kannan/flite | 236f91a9a1e60fd25f1deed6d48022567cd7100f | [
"Apache-2.0"
] | 7 | 2017-12-10T23:02:22.000Z | 2021-08-05T21:12:11.000Z | flite/src/cg/mlsa.cpp | Barath-Kannan/flite | 236f91a9a1e60fd25f1deed6d48022567cd7100f | [
"Apache-2.0"
] | null | null | null | flite/src/cg/mlsa.cpp | Barath-Kannan/flite | 236f91a9a1e60fd25f1deed6d48022567cd7100f | [
"Apache-2.0"
] | 3 | 2018-10-28T03:47:09.000Z | 2020-06-04T08:54:23.000Z | #include "flite/audio/audio.hpp"
#include "flite/synthcommon/track.hpp"
#include "flite/synthcommon/wave.hpp"
#include "flite/utils/alloc.hpp"
#include "flite/utils/math.hpp"
#include "flite/utils/string.hpp"
#ifdef ANDROID
#define SPEED_HACK
#endif
#ifdef UNDER_CE
#define SPEED_HACK
/* This is one of those other things you shouldn't do, but it makes
CG voices in flowm fast enough on my phone */
#define double float
#endif
#include "./mlsa.hpp"
static cst_wave* synthesis_body(const cst_track* params, const cst_track* str, double fs, double framem, cst_cg_db* cg_db, cst_audio_streaming_info* asi, int mlsa_speed_param);
cst_wave* mlsa_resynthesis(const cst_track* params, const cst_track* str, cst_cg_db* cg_db, cst_audio_streaming_info* asi, int mlsa_speed_param)
{
/* Resynthesizes a wave from given track */
cst_wave* wave = 0;
int sr = cg_db->sample_rate;
double shift;
if (params->num_frames > 1)
shift = 1000.0 * (params->times[1] - params->times[0]);
else
shift = 5.0;
wave = synthesis_body(params, str, sr, shift, cg_db, asi, mlsa_speed_param);
return wave;
}
static cst_wave* synthesis_body(const cst_track* params, /* f0 + mcep */
const cst_track* str,
double fs, /* sampling frequency (Hz) */
double framem, /* frame size */
cst_cg_db* cg_db,
cst_audio_streaming_info* asi,
int mlsa_speed_param)
{
long t, pos;
int framel, i;
double f0;
VocoderSetup vs;
cst_wave* wave = 0;
double* mcep;
int stream_mark;
int rc = CST_AUDIO_STREAM_CONT;
int num_mcep;
double ffs = fs;
num_mcep = params->num_channels - 1;
if ((num_mcep > mlsa_speed_param) &&
((num_mcep - mlsa_speed_param) > 4))
/* Basically ignore some of the higher coeffs */
/* It'll sound worse, but it will be faster */
num_mcep -= mlsa_speed_param;
framel = (int)(0.5 + (framem * ffs / 1000.0)); /* 80 for 16KHz */
init_vocoder(ffs, framel, num_mcep, &vs, cg_db);
if (str != NULL)
vs.gauss = MFALSE;
/* synthesize waveforms by MLSA filter */
wave = new_wave();
cst_wave_resize(wave, params->num_frames * framel, 1);
wave->sample_rate = fs;
mcep = cst_alloc(double, num_mcep + 1);
for (t = 0, stream_mark = pos = 0;
(rc == CST_AUDIO_STREAM_CONT) && (t < params->num_frames);
t++) {
f0 = (double)params->frames[t][0];
for (i = 1; i < num_mcep + 1; i++)
mcep[i - 1] = params->frames[t][i];
mcep[i - 1] = 0;
if (str)
vocoder(f0, mcep, str->frames[t], num_mcep, cg_db, &vs, wave, &pos);
else
vocoder(f0, mcep, NULL, num_mcep, cg_db, &vs, wave, &pos);
if (asi && (pos - stream_mark > asi->min_buffsize)) {
rc = (*asi->asc)(wave, stream_mark, pos - stream_mark, 0, asi);
stream_mark = pos;
}
}
wave->num_samples = pos;
if (asi && (rc == CST_AUDIO_STREAM_CONT)) { /* drain the last part of the waveform */
(*asi->asc)(wave, stream_mark, pos - stream_mark, 1, asi);
}
/* memory free */
cst_free(mcep);
free_vocoder(&vs);
if (rc == CST_AUDIO_STREAM_STOP) {
delete_wave(wave);
return NULL;
}
else
return wave;
}
static void init_vocoder(double fs, int framel, int m, VocoderSetup* vs, cst_cg_db* cg_db)
{
/* initialize global parameter */
vs->fprd = framel;
vs->iprd = 1;
vs->seed = 1;
#ifdef SPEED_HACK
/* This makes it about 25% faster and sounds basically the same */
vs->pd = 4;
#else
vs->pd = 5;
#endif
vs->next = 1;
vs->gauss = MTRUE;
/* Pade' approximants */
vs->pade[0] = 1.0;
vs->pade[1] = 1.0;
vs->pade[2] = 0.0;
vs->pade[3] = 1.0;
vs->pade[4] = 0.0;
vs->pade[5] = 0.0;
vs->pade[6] = 1.0;
vs->pade[7] = 0.0;
vs->pade[8] = 0.0;
vs->pade[9] = 0.0;
vs->pade[10] = 1.0;
vs->pade[11] = 0.4999273;
vs->pade[12] = 0.1067005;
vs->pade[13] = 0.01170221;
vs->pade[14] = 0.0005656279;
vs->pade[15] = 1.0;
vs->pade[16] = 0.4999391;
vs->pade[17] = 0.1107098;
vs->pade[18] = 0.01369984;
vs->pade[19] = 0.0009564853;
vs->pade[20] = 0.00003041721;
vs->rate = fs;
vs->c = cst_alloc(double, 3 * (m + 1) + 3 * (vs->pd + 1) + vs->pd * (m + 2));
vs->p1 = -1;
vs->sw = 0;
vs->x = 0x55555555;
/* for postfiltering */
vs->mc = NULL;
vs->o = 0;
vs->d = NULL;
vs->irleng = 64;
/* for MIXED EXCITATION */
vs->ME_order = cg_db->ME_order;
vs->ME_num = cg_db->ME_num;
vs->hpulse = cst_alloc(double, vs->ME_order);
vs->hnoise = cst_alloc(double, vs->ME_order);
vs->xpulsesig = cst_alloc(double, vs->ME_order);
vs->xnoisesig = cst_alloc(double, vs->ME_order);
vs->h = cg_db->me_h;
return;
}
static double plus_or_minus_one()
{
/* Randomly return 1 or -1 */
/* not sure rand() is portable */
if (rand() > RAND_MAX / 2.0)
return 1.0;
else
return -1.0;
}
static void vocoder(double p, double* mc, const float* str, int m, cst_cg_db* cg_db, VocoderSetup* vs, cst_wave* wav, long* pos)
{
double inc, x, e1, e2;
int i, j, k;
double xpulse, xnoise;
double fxpulse, fxnoise;
float gain = 1.0;
if (cg_db->gain != 0.0)
gain = cg_db->gain;
if (str != NULL) /* MIXED-EXCITATION */
{
/* Copy in str's and build hpulse and hnoise for this frame */
for (i = 0; i < vs->ME_order; i++) {
vs->hpulse[i] = vs->hnoise[i] = 0.0;
for (j = 0; j < vs->ME_num; j++) {
vs->hpulse[i] += str[j] * vs->h[j][i];
vs->hnoise[i] += (1 - str[j]) * vs->h[j][i];
}
}
}
if (p != 0.0)
p = vs->rate / p; /* f0 -> pitch */
if (vs->p1 < 0) {
if (vs->gauss & (vs->seed != 1))
vs->next = srnd((unsigned)vs->seed);
vs->p1 = p;
vs->pc = vs->p1;
vs->cc = vs->c + m + 1;
vs->cinc = vs->cc + m + 1;
vs->d1 = vs->cinc + m + 1;
mc2b(mc, vs->c, m, cg_db->mlsa_alpha);
if (cg_db->mlsa_beta > 0.0 && m > 1) {
e1 = b2en(vs->c, m, cg_db->mlsa_alpha, vs);
vs->c[1] -= cg_db->mlsa_beta * cg_db->mlsa_alpha * mc[2];
for (k = 2; k <= m; k++)
vs->c[k] *= (1.0 + cg_db->mlsa_beta);
e2 = b2en(vs->c, m, cg_db->mlsa_alpha, vs);
vs->c[0] += log(e1 / e2) / 2;
}
return;
}
mc2b(mc, vs->cc, m, cg_db->mlsa_alpha);
if (cg_db->mlsa_beta > 0.0 && m > 1) {
e1 = b2en(vs->cc, m, cg_db->mlsa_alpha, vs);
vs->cc[1] -= cg_db->mlsa_beta * cg_db->mlsa_alpha * mc[2];
for (k = 2; k <= m; k++)
vs->cc[k] *= (1.0 + cg_db->mlsa_beta);
e2 = b2en(vs->cc, m, cg_db->mlsa_alpha, vs);
vs->cc[0] += log(e1 / e2) / 2.0;
}
for (k = 0; k <= m; k++)
vs->cinc[k] = (vs->cc[k] - vs->c[k]) *
(double)vs->iprd / (double)vs->fprd;
if (vs->p1 != 0.0 && p != 0.0) {
inc = (p - vs->p1) * (double)vs->iprd / (double)vs->fprd;
}
else {
inc = 0.0;
vs->pc = p;
vs->p1 = 0.0;
}
for (j = vs->fprd, i = (vs->iprd + 1) / 2; j--;) {
if (vs->p1 == 0.0) {
if (vs->gauss)
x = (double)nrandom(vs);
else
x = plus_or_minus_one();
if (str != NULL) /* MIXED EXCITATION */
{
xnoise = x;
xpulse = 0.0;
}
}
else {
if ((vs->pc += 1.0) >= vs->p1) {
x = sqrt(vs->p1);
vs->pc = vs->pc - vs->p1;
}
else
x = 0.0;
if (str != NULL) /* MIXED EXCITATION */
{
xpulse = x;
xnoise = plus_or_minus_one();
}
}
/* MIXED EXCITATION */
/* The real work -- apply shaping filters to pulse and noise */
if (str != NULL) {
fxpulse = fxnoise = 0.0;
for (k = vs->ME_order - 1; k > 0; k--) {
fxpulse += vs->hpulse[k] * vs->xpulsesig[k];
fxnoise += vs->hnoise[k] * vs->xnoisesig[k];
vs->xpulsesig[k] = vs->xpulsesig[k - 1];
vs->xnoisesig[k] = vs->xnoisesig[k - 1];
}
fxpulse += vs->hpulse[0] * xpulse;
fxnoise += vs->hnoise[0] * xnoise;
vs->xpulsesig[0] = xpulse;
vs->xnoisesig[0] = xnoise;
x = fxpulse + fxnoise; /* excitation is pulse plus noise */
}
if (cg_db->sample_rate == 8000)
/* 8KHz voices are too quiet: this is probably not general */
x *= exp(vs->c[0]) * 2.0;
else
x *= exp(vs->c[0]) * gain;
x = mlsadf(x, vs->c, m, cg_db->mlsa_alpha, vs->pd, vs->d1, vs);
wav->samples[*pos] = (short)x;
*pos += 1;
if (!--i) {
vs->p1 += inc;
for (k = 0; k <= m; k++) vs->c[k] += vs->cinc[k];
i = vs->iprd;
}
}
vs->p1 = p;
memmove(vs->c, vs->cc, sizeof(double) * (m + 1));
return;
}
static double mlsadf(double x, double* b, int m, double a, int pd, double* d, VocoderSetup* vs)
{
vs->ppade = &(vs->pade[pd * (pd + 1) / 2]);
x = mlsadf1(x, b, m, a, pd, d, vs);
x = mlsadf2(x, b, m, a, pd, &d[2 * (pd + 1)], vs);
return (x);
}
static double mlsadf1(double x, double* b, int m, double a, int pd, double* d, VocoderSetup* vs)
{
double v, out = 0.0, *pt, aa;
register int i;
aa = 1 - a * a;
pt = &d[pd + 1];
for (i = pd; i >= 1; i--) {
d[i] = aa * pt[i - 1] + a * d[i];
pt[i] = d[i] * b[1];
v = pt[i] * vs->ppade[i];
x += (1 & i) ? v : -v;
out += v;
}
pt[0] = x;
out += x;
return (out);
}
static double mlsadf2(double x, double* b, int m, double a, int pd, double* d, VocoderSetup* vs)
{
double v, out = 0.0, *pt;
register int i;
pt = &d[pd * (m + 2)];
for (i = pd; i >= 1; i--) {
pt[i] = mlsafir(pt[i - 1], b, m, a, &d[(i - 1) * (m + 2)]);
v = pt[i] * vs->ppade[i];
x += (1 & i) ? v : -v;
out += v;
}
pt[0] = x;
out += x;
return (out);
}
static double mlsafir(double x, double* b, int m, double a, double* d)
{
double y = 0.0;
double aa;
register int i;
aa = 1 - a * a;
d[0] = x;
d[1] = aa * d[0] + a * d[1];
for (i = 2; i <= m; i++) {
d[i] = d[i] + a * (d[i + 1] - d[i - 1]);
y += d[i] * b[i];
}
for (i = m + 1; i > 1; i--)
d[i] = d[i - 1];
return (y);
}
static double nrandom(VocoderSetup* vs)
{
if (vs->sw == 0) {
vs->sw = 1;
do {
vs->r1 = 2.0 * rnd(&vs->next) - 1.0;
vs->r2 = 2.0 * rnd(&vs->next) - 1.0;
vs->s = vs->r1 * vs->r1 + vs->r2 * vs->r2;
} while (vs->s > 1 || vs->s == 0);
vs->s = sqrt(-2 * log(vs->s) / vs->s);
return (vs->r1 * vs->s);
}
else {
vs->sw = 0;
return (vs->r2 * vs->s);
}
}
static double rnd(unsigned long* next)
{
double r;
*next = *next * 1103515245L + 12345;
r = (*next / 65536L) % 32768L;
return (r / RANDMAX);
}
static unsigned long srnd(unsigned long seed)
{
return (seed);
}
/* mc2b : transform mel-cepstrum to MLSA digital fillter coefficients */
static void mc2b(double* mc, double* b, int m, double a)
{
b[m] = mc[m];
for (m--; m >= 0; m--)
b[m] = mc[m] - a * b[m + 1];
return;
}
static double b2en(double* b, int m, double a, VocoderSetup* vs)
{
double en;
int k;
if (vs->o < m) {
if (vs->mc != NULL)
cst_free(vs->mc);
vs->mc = cst_alloc(double, (m + 1) + 2 * vs->irleng);
vs->cep = vs->mc + m + 1;
vs->ir = vs->cep + vs->irleng;
}
b2mc(b, vs->mc, m, a);
freqt(vs->mc, m, vs->cep, vs->irleng - 1, -a, vs);
c2ir(vs->cep, vs->irleng, vs->ir, vs->irleng);
en = 0.0;
for (k = 0; k < vs->irleng; k++)
en += vs->ir[k] * vs->ir[k];
return (en);
}
/* b2bc : transform MLSA digital filter coefficients to mel-cepstrum */
static void b2mc(double* b, double* mc, int m, double a)
{
double d, o;
d = mc[m] = b[m];
for (m--; m >= 0; m--) {
o = b[m] + a * d;
d = b[m];
mc[m] = o;
}
return;
}
/* freqt : frequency transformation */
static void freqt(double* c1, int m1, double* c2, int m2, double a, VocoderSetup* vs)
{
register int i, j;
double b;
if (vs->d == NULL) {
vs->size = m2;
vs->d = cst_alloc(double, vs->size + vs->size + 2);
vs->g = vs->d + vs->size + 1;
}
if (m2 > vs->size) {
cst_free(vs->d);
vs->size = m2;
vs->d = cst_alloc(double, vs->size + vs->size + 2);
vs->g = vs->d + vs->size + 1;
}
b = 1 - a * a;
for (i = 0; i < m2 + 1; i++)
vs->g[i] = 0.0;
for (i = -m1; i <= 0; i++) {
if (0 <= m2)
vs->g[0] = c1[-i] + a * (vs->d[0] = vs->g[0]);
if (1 <= m2)
vs->g[1] = b * vs->d[0] + a * (vs->d[1] = vs->g[1]);
for (j = 2; j <= m2; j++)
vs->g[j] = vs->d[j - 1] + a * ((vs->d[j] = vs->g[j]) - vs->g[j - 1]);
}
memmove(c2, vs->g, sizeof(double) * (m2 + 1));
return;
}
/* c2ir : The minimum phase impulse response is evaluated from the minimum phase cepstrum */
static void c2ir(double* c, int nc, double* h, int leng)
{
register int n, k, upl;
double d;
h[0] = exp(c[0]);
for (n = 1; n < leng; n++) {
d = 0;
upl = (n >= nc) ? nc - 1 : n;
for (k = 1; k <= upl; k++)
d += k * c[k] * h[n - k];
h[n] = d / n;
}
return;
}
static void free_vocoder(VocoderSetup* vs)
{
cst_free(vs->c);
cst_free(vs->mc);
cst_free(vs->d);
vs->c = NULL;
vs->mc = NULL;
vs->d = NULL;
vs->ppade = NULL;
vs->cc = NULL;
vs->cinc = NULL;
vs->d1 = NULL;
vs->g = NULL;
vs->cep = NULL;
vs->ir = NULL;
cst_free(vs->hpulse);
cst_free(vs->hnoise);
cst_free(vs->xpulsesig);
cst_free(vs->xnoisesig);
return;
}
| 25.369983 | 176 | 0.475683 | Barath-Kannan |
c7a34f2c452678da6f1895bbabb32ab890ed62bc | 4,118 | cpp | C++ | src/test/cpp/filter/levelmatchfiltertest.cpp | Blaxar/log4cxxNG | 8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae | [
"Apache-2.0"
] | null | null | null | src/test/cpp/filter/levelmatchfiltertest.cpp | Blaxar/log4cxxNG | 8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae | [
"Apache-2.0"
] | null | null | null | src/test/cpp/filter/levelmatchfiltertest.cpp | Blaxar/log4cxxNG | 8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxxNG/filter/levelmatchfilter.h>
#include <log4cxxNG/logger.h>
#include <log4cxxNG/spi/filter.h>
#include <log4cxxNG/spi/loggingevent.h>
#include "../logunit.h"
using namespace log4cxxng;
using namespace log4cxxng::filter;
using namespace log4cxxng::spi;
using namespace log4cxxng::helpers;
/**
* Unit tests for LevelMatchFilter.
*/
LOGUNIT_CLASS(LevelMatchFilterTest)
{
LOGUNIT_TEST_SUITE(LevelMatchFilterTest);
LOGUNIT_TEST(test1);
LOGUNIT_TEST(test2);
LOGUNIT_TEST(test3);
LOGUNIT_TEST(test4);
LOGUNIT_TEST(test5);
LOGUNIT_TEST_SUITE_END();
public:
/**
* Check that LevelMatchFilter.decide() returns Filter.ACCEPT when level matches.
*/
void test1()
{
LoggingEventPtr event(new LoggingEvent(
LOG4CXXNG_STR("org.apache.log4j.filter.LevelMatchFilterTest"),
Level::getInfo(),
LOG4CXXNG_STR("Hello, World"),
LOG4CXXNG_LOCATION));
LevelMatchFilterPtr filter(new LevelMatchFilter());
filter->setLevelToMatch(LOG4CXXNG_STR("info"));
Pool p;
filter->activateOptions(p);
LOGUNIT_ASSERT_EQUAL(Filter::ACCEPT, filter->decide(event));
}
/**
* Check that LevelMatchFilter.decide() returns Filter.DENY
* when level matches and acceptOnMatch = false.
*/
void test2()
{
LoggingEventPtr event(new LoggingEvent(
LOG4CXXNG_STR("org.apache.log4j.filter.LevelMatchFilterTest"),
Level::getInfo(),
LOG4CXXNG_STR("Hello, World"),
LOG4CXXNG_LOCATION));
LevelMatchFilterPtr filter(new LevelMatchFilter());
filter->setLevelToMatch(LOG4CXXNG_STR("info"));
filter->setAcceptOnMatch(false);
Pool p;
filter->activateOptions(p);
LOGUNIT_ASSERT_EQUAL(Filter::DENY, filter->decide(event));
}
/**
* Check that LevelMatchFilter.decide() returns Filter.NEUTRAL
* when levelToMatch is unspecified.
*/
void test3()
{
LoggingEventPtr event(new LoggingEvent(
LOG4CXXNG_STR("org.apache.log4j.filter.LevelMatchFilterTest"),
Level::getInfo(),
LOG4CXXNG_STR("Hello, World"),
LOG4CXXNG_LOCATION));
LevelMatchFilterPtr filter(new LevelMatchFilter());
Pool p;
filter->activateOptions(p);
LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event));
}
/**
* Check that LevelMatchFilter.decide() returns Filter.NEUTRAL
* when event level is higher than level to match.
*/
void test4()
{
LoggingEventPtr event(new LoggingEvent(
LOG4CXXNG_STR("org.apache.log4j.filter.LevelMatchFilterTest"),
Level::getInfo(),
LOG4CXXNG_STR("Hello, World"),
LOG4CXXNG_LOCATION));
LevelMatchFilterPtr filter(new LevelMatchFilter());
filter->setLevelToMatch(LOG4CXXNG_STR("debug"));
Pool p;
filter->activateOptions(p);
LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event));
}
/**
* Check that LevelMatchFilter.decide() returns Filter.NEUTRAL
* when event level is lower than level to match.
*/
void test5()
{
LoggingEventPtr event(new LoggingEvent(
LOG4CXXNG_STR("org.apache.log4j.filter.LevelMatchFilterTest"),
Level::getInfo(),
LOG4CXXNG_STR("Hello, World"),
LOG4CXXNG_LOCATION));
LevelMatchFilterPtr filter(new LevelMatchFilter());
filter->setLevelToMatch(LOG4CXXNG_STR("warn"));
Pool p;
filter->activateOptions(p);
LOGUNIT_ASSERT_EQUAL(Filter::NEUTRAL, filter->decide(event));
}
};
LOGUNIT_TEST_SUITE_REGISTRATION(LevelMatchFilterTest);
| 30.279412 | 82 | 0.741136 | Blaxar |
c7a54ff53495b66fda4b12f683546f16f01ac85f | 1,586 | hpp | C++ | integration/traits.hpp | FMeirinhos/gsl-modules | a638e90bbcfd2573232cb5d398d04a20f4058adb | [
"Unlicense"
] | null | null | null | integration/traits.hpp | FMeirinhos/gsl-modules | a638e90bbcfd2573232cb5d398d04a20f4058adb | [
"Unlicense"
] | null | null | null | integration/traits.hpp | FMeirinhos/gsl-modules | a638e90bbcfd2573232cb5d398d04a20f4058adb | [
"Unlicense"
] | null | null | null | //
// traits.hpp
// gsl-modules
//
// Created by Francisco Meirinhos on 13/01/17.
//
#ifndef traits_hpp
#define traits_hpp
#include <chrono>
#include <tuple>
/*
Stolen from
http://stackoverflow.com/questions/7943525/is-it-possible-to-figure-out-the-parameter-type-and-return-type-of-a-lambda
Traits of lambda functions
*/
namespace util {
template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())> {};
template <typename ReturnType, typename... Args>
struct function_traits<ReturnType (*)(Args...)> {
enum { arity = sizeof...(Args) };
// arity is the number of arguments.
typedef ReturnType result_type;
template <size_t i> struct arg {
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
// the i-th argument is equivalent to the i-th tuple element of a tuple
// composed of those arguments.
};
};
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType (ClassType::*)(Args...) const>
// we specialize for pointers to member function
{
enum { arity = sizeof...(Args) };
// arity is the number of arguments.
typedef ReturnType result_type;
template <size_t i> struct arg {
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
// the i-th argument is equivalent to the i-th tuple element of a tuple
// composed of those arguments.
};
// See: https://stackoverflow.com/questions/36612596/tuple-to-parameter-pack
using argument_t = std::tuple<Args...>;
};
} // namespace util
#endif /* traits_hpp */
| 26 | 118 | 0.704918 | FMeirinhos |
c7a63b24eac32b5cbf21d026b3709e15a3e1021d | 521 | cpp | C++ | src/main.cpp | Andrewkf5011/s4.3 | 32ba306f7f8e8fd48def706977b950a355a183b0 | [
"MIT"
] | null | null | null | src/main.cpp | Andrewkf5011/s4.3 | 32ba306f7f8e8fd48def706977b950a355a183b0 | [
"MIT"
] | null | null | null | src/main.cpp | Andrewkf5011/s4.3 | 32ba306f7f8e8fd48def706977b950a355a183b0 | [
"MIT"
] | null | null | null | #include <mbed.h>
#include <C12832.h>
// Using Arduino pin notation
C12832 lcd(D11, D13, D12, D7, D10);
int main()
{
int j=0;
lcd.cls();
lcd.locate(0,0);
lcd.printf("mbed application shield!");
lcd.locate(0,10);
lcd.printf("char %dx%d : %dx%d pixels",
lcd.columns(), lcd.rows(),
lcd.width(), lcd.height() );
lcd.circle(100, 20, 10, 1);
while(true) {
lcd.locate(0,20);
lcd.printf("Counting : %4d",j);
j++;
wait(1.0);
}
}
| 20.038462 | 43 | 0.512476 | Andrewkf5011 |
c7a7c12ca1d1623c023f8e49b205ce4514378bfe | 18,660 | hpp | C++ | libs/boost_1_72_0/boost/spirit/home/support/detail/endian/endian.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/spirit/home/support/detail/endian/endian.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/spirit/home/support/detail/endian/endian.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | // Boost endian.hpp header file
// -------------------------------------------------------//
// (C) Copyright Darin Adler 2000
// (C) Copyright Beman Dawes 2006, 2009
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
// See library home page at http://www.boost.org/libs/endian
//--------------------------------------------------------------------------------------//
// Original design developed by Darin Adler based on classes developed by Mark
// Borgerding. Four original class templates were combined into a single endian
// class template by Beman Dawes, who also added the unrolled_byte_loops sign
// partial specialization to correctly extend the sign when cover integer size
// differs from endian representation size.
// TODO: When a compiler supporting constexpr becomes available, try possible
// uses.
#ifndef BOOST_SPIRIT_ENDIAN_HPP
#define BOOST_SPIRIT_ENDIAN_HPP
#if defined(_MSC_VER)
#pragma once
#endif
#ifdef BOOST_ENDIAN_LOG
#include <iostream>
#endif
#if defined(__BORLANDC__) || defined(__CODEGEARC__)
#pragma pack(push, 1)
#endif
#include <boost/config.hpp>
#include <boost/predef/other/endian.h>
#ifndef BOOST_MINIMAL_INTEGER_COVER_OPERATORS
#define BOOST_MINIMAL_INTEGER_COVER_OPERATORS
#endif
#ifndef BOOST_NO_IO_COVER_OPERATORS
#define BOOST_NO_IO_COVER_OPERATORS
#endif
#include <boost/spirit/home/support/detail/endian/cover_operators.hpp>
#undef BOOST_NO_IO_COVER_OPERATORS
#undef BOOST_MINIMAL_INTEGER_COVER_OPERATORS
#include <boost/cstdint.hpp>
#include <boost/spirit/home/support/detail/scoped_enum_emulation.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_signed.hpp>
#include <boost/type_traits/make_unsigned.hpp>
#include <climits>
#include <iosfwd>
#if CHAR_BIT != 8
#error Platforms with CHAR_BIT != 8 are not supported
#endif
#define BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT \
{} // C++03
#if defined(BOOST_ENDIAN_NO_CTORS) || defined(BOOST_ENDIAN_FORCE_PODNESS)
#define BOOST_SPIRIT_ENDIAN_NO_CTORS
#endif
namespace boost {
namespace spirit {
namespace detail {
// Unrolled loops for loading and storing streams of bytes.
template <typename T, std::size_t n_bytes,
bool sign = boost::is_signed<T>::value>
struct unrolled_byte_loops {
typedef unrolled_byte_loops<T, n_bytes - 1, sign> next;
static typename boost::make_unsigned<T>::type
load_big(const unsigned char *bytes) {
return *(bytes - 1) | (next::load_big(bytes - 1) << 8);
}
static typename boost::make_unsigned<T>::type
load_little(const unsigned char *bytes) {
return *bytes | (next::load_little(bytes + 1) << 8);
}
static void store_big(char *bytes, T value) {
*(bytes - 1) = static_cast<char>(value);
next::store_big(bytes - 1, value >> 8);
}
static void store_little(char *bytes, T value) {
*bytes = static_cast<char>(value);
next::store_little(bytes + 1, value >> 8);
}
};
template <typename T> struct unrolled_byte_loops<T, 1, false> {
static T load_big(const unsigned char *bytes) { return *(bytes - 1); }
static T load_little(const unsigned char *bytes) { return *bytes; }
static void store_big(char *bytes, T value) {
*(bytes - 1) = static_cast<char>(value);
}
static void store_little(char *bytes, T value) {
*bytes = static_cast<char>(value);
}
};
template <typename T> struct unrolled_byte_loops<T, 1, true> {
static typename boost::make_unsigned<T>::type
load_big(const unsigned char *bytes) {
return *(bytes - 1);
}
static typename boost::make_unsigned<T>::type
load_little(const unsigned char *bytes) {
return *bytes;
}
static void store_big(char *bytes, T value) {
*(bytes - 1) = static_cast<char>(value);
}
static void store_little(char *bytes, T value) {
*bytes = static_cast<char>(value);
}
};
template <typename T, std::size_t n_bytes>
inline T load_big_endian(const void *bytes) {
return static_cast<T>(unrolled_byte_loops<T, n_bytes>::load_big(
static_cast<const unsigned char *>(bytes) + n_bytes));
}
template <> inline float load_big_endian<float, 4>(const void *bytes) {
const unsigned char *b = reinterpret_cast<const unsigned char *>(bytes);
b += 3;
float value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for (std::size_t i = 0; i < 4; ++i) {
*v++ = *b--;
}
return value;
}
template <> inline double load_big_endian<double, 8>(const void *bytes) {
const unsigned char *b = reinterpret_cast<const unsigned char *>(bytes);
b += 7;
double value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for (std::size_t i = 0; i < 8; ++i) {
*v++ = *b--;
}
return value;
}
template <typename T, std::size_t n_bytes>
inline T load_little_endian(const void *bytes) {
return static_cast<T>(unrolled_byte_loops<T, n_bytes>::load_little(
static_cast<const unsigned char *>(bytes)));
}
template <> inline float load_little_endian<float, 4>(const void *bytes) {
const unsigned char *b = reinterpret_cast<const unsigned char *>(bytes);
float value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for (std::size_t i = 0; i < 4; ++i) {
*v++ = *b++;
}
return value;
}
template <> inline double load_little_endian<double, 8>(const void *bytes) {
const unsigned char *b = reinterpret_cast<const unsigned char *>(bytes);
double value;
unsigned char *v = reinterpret_cast<unsigned char *>(&value);
for (std::size_t i = 0; i < 8; ++i) {
*v++ = *b++;
}
return value;
}
template <typename T, std::size_t n_bytes>
inline void store_big_endian(void *bytes, T value) {
unrolled_byte_loops<T, n_bytes>::store_big(
static_cast<char *>(bytes) + n_bytes, value);
}
template <> inline void store_big_endian<float, 4>(void *bytes, float value) {
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
b += 3;
const unsigned char *v = reinterpret_cast<const unsigned char *>(&value);
for (std::size_t i = 0; i < 4; ++i) {
*b-- = *v++;
}
}
template <> inline void store_big_endian<double, 8>(void *bytes, double value) {
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
b += 7;
const unsigned char *v = reinterpret_cast<const unsigned char *>(&value);
for (std::size_t i = 0; i < 8; ++i) {
*b-- = *v++;
}
}
template <typename T, std::size_t n_bytes>
inline void store_little_endian(void *bytes, T value) {
unrolled_byte_loops<T, n_bytes>::store_little(static_cast<char *>(bytes),
value);
}
template <>
inline void store_little_endian<float, 4>(void *bytes, float value) {
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
const unsigned char *v = reinterpret_cast<const unsigned char *>(&value);
for (std::size_t i = 0; i < 4; ++i) {
*b++ = *v++;
}
}
template <>
inline void store_little_endian<double, 8>(void *bytes, double value) {
unsigned char *b = reinterpret_cast<unsigned char *>(bytes);
const unsigned char *v = reinterpret_cast<const unsigned char *>(&value);
for (std::size_t i = 0; i < 8; ++i) {
*b++ = *v++;
}
}
} // namespace detail
namespace endian {
#ifdef BOOST_ENDIAN_LOG
bool endian_log(true);
#endif
// endian class template and specializations
// ---------------------------------------//
BOOST_SCOPED_ENUM_START(endianness){big, little, native};
BOOST_SCOPED_ENUM_END
BOOST_SCOPED_ENUM_START(alignment){unaligned, aligned};
BOOST_SCOPED_ENUM_END
template <BOOST_SCOPED_ENUM(endianness) E, typename T, std::size_t n_bits,
BOOST_SCOPED_ENUM(alignment) A = alignment::unaligned>
class endian;
// Specializations that represent unaligned bytes.
// Taking an integer type as a parameter provides a nice way to pass both
// the size and signedness of the desired integer and get the appropriate
// corresponding integer type for the interface.
// unaligned big endian specialization
template <typename T, std::size_t n_bits>
class endian<endianness::big, T, n_bits, alignment::unaligned>
: cover_operators<endian<endianness::big, T, n_bits>, T> {
BOOST_STATIC_ASSERT((n_bits / 8) * 8 == n_bits);
public:
typedef T value_type;
#ifndef BOOST_SPIRIT_ENDIAN_NO_CTORS
endian() BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT explicit endian(T val) {
#ifdef BOOST_ENDIAN_LOG
if (endian_log)
std::clog << "big, unaligned, " << n_bits << "-bits, construct(" << val
<< ")\n";
#endif
detail::store_big_endian<T, n_bits / 8>(m_value, val);
}
#endif
endian &operator=(T val) {
detail::store_big_endian<T, n_bits / 8>(m_value, val);
return *this;
}
operator T() const {
#ifdef BOOST_ENDIAN_LOG
if (endian_log)
std::clog << "big, unaligned, " << n_bits << "-bits, convert("
<< detail::load_big_endian<T, n_bits / 8>(m_value) << ")\n";
#endif
return detail::load_big_endian<T, n_bits / 8>(m_value);
}
private:
char m_value[n_bits / 8];
};
// unaligned little endian specialization
template <typename T, std::size_t n_bits>
class endian<endianness::little, T, n_bits, alignment::unaligned>
: cover_operators<endian<endianness::little, T, n_bits>, T> {
BOOST_STATIC_ASSERT((n_bits / 8) * 8 == n_bits);
public:
typedef T value_type;
#ifndef BOOST_SPIRIT_ENDIAN_NO_CTORS
endian() BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT explicit endian(T val) {
#ifdef BOOST_ENDIAN_LOG
if (endian_log)
std::clog << "little, unaligned, " << n_bits << "-bits, construct(" << val
<< ")\n";
#endif
detail::store_little_endian<T, n_bits / 8>(m_value, val);
}
#endif
endian &operator=(T val) {
detail::store_little_endian<T, n_bits / 8>(m_value, val);
return *this;
}
operator T() const {
#ifdef BOOST_ENDIAN_LOG
if (endian_log)
std::clog << "little, unaligned, " << n_bits << "-bits, convert("
<< detail::load_little_endian<T, n_bits / 8>(m_value) << ")\n";
#endif
return detail::load_little_endian<T, n_bits / 8>(m_value);
}
private:
char m_value[n_bits / 8];
};
// unaligned native endian specialization
template <typename T, std::size_t n_bits>
class endian<endianness::native, T, n_bits, alignment::unaligned>
: cover_operators<endian<endianness::native, T, n_bits>, T> {
BOOST_STATIC_ASSERT((n_bits / 8) * 8 == n_bits);
public:
typedef T value_type;
#ifndef BOOST_SPIRIT_ENDIAN_NO_CTORS
endian() BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT
#if BOOST_ENDIAN_BIG_BYTE
explicit endian(T val) {
detail::store_big_endian<T, n_bits / 8>(m_value, val);
}
#else
explicit endian(T val) {
detail::store_little_endian<T, n_bits / 8>(m_value, val);
}
#endif
#endif
#if BOOST_ENDIAN_BIG_BYTE
endian &operator=(T val) {
detail::store_big_endian<T, n_bits / 8>(m_value, val);
return *this;
}
operator T() const { return detail::load_big_endian<T, n_bits / 8>(m_value); }
#else
endian &operator=(T val) {
detail::store_little_endian<T, n_bits / 8>(m_value, val);
return *this;
}
operator T() const {
return detail::load_little_endian<T, n_bits / 8>(m_value);
}
#endif
private:
char m_value[n_bits / 8];
};
// Specializations that mimic built-in integer types.
// These typically have the same alignment as the underlying types.
// aligned big endian specialization
template <typename T, std::size_t n_bits>
class endian<endianness::big, T, n_bits, alignment::aligned>
: cover_operators<endian<endianness::big, T, n_bits, alignment::aligned>,
T> {
BOOST_STATIC_ASSERT((n_bits / 8) * 8 == n_bits);
BOOST_STATIC_ASSERT(sizeof(T) == n_bits / 8);
public:
typedef T value_type;
#ifndef BOOST_SPIRIT_ENDIAN_NO_CTORS
endian() BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT
#if BOOST_ENDIAN_BIG_BYTE
endian(T val)
: m_value(val) {
}
#else
explicit endian(T val) {
detail::store_big_endian<T, sizeof(T)>(&m_value, val);
}
#endif
#endif
#if BOOST_ENDIAN_BIG_BYTE
endian &operator=(T val) {
m_value = val;
return *this;
}
operator T() const { return m_value; }
#else
endian &operator=(T val) {
detail::store_big_endian<T, sizeof(T)>(&m_value, val);
return *this;
}
operator T() const { return detail::load_big_endian<T, sizeof(T)>(&m_value); }
#endif
private:
T m_value;
};
// aligned little endian specialization
template <typename T, std::size_t n_bits>
class endian<endianness::little, T, n_bits, alignment::aligned>
: cover_operators<endian<endianness::little, T, n_bits, alignment::aligned>,
T> {
BOOST_STATIC_ASSERT((n_bits / 8) * 8 == n_bits);
BOOST_STATIC_ASSERT(sizeof(T) == n_bits / 8);
public:
typedef T value_type;
#ifndef BOOST_SPIRIT_ENDIAN_NO_CTORS
endian() BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT
#if BOOST_ENDIAN_LITTLE_BYTE
endian(T val)
: m_value(val) {
}
#else
explicit endian(T val) {
detail::store_little_endian<T, sizeof(T)>(&m_value, val);
}
#endif
#endif
#if BOOST_ENDIAN_LITTLE_BYTE
endian &operator=(T val) {
m_value = val;
return *this;
}
operator T() const { return m_value; }
#else
endian &operator=(T val) {
detail::store_little_endian<T, sizeof(T)>(&m_value, val);
return *this;
}
operator T() const {
return detail::load_little_endian<T, sizeof(T)>(&m_value);
}
#endif
private:
T m_value;
};
// naming convention typedefs
// ------------------------------------------------------//
// unaligned big endian signed integer types
typedef endian<endianness::big, int_least8_t, 8> big8_t;
typedef endian<endianness::big, int_least16_t, 16> big16_t;
typedef endian<endianness::big, int_least32_t, 24> big24_t;
typedef endian<endianness::big, int_least32_t, 32> big32_t;
typedef endian<endianness::big, int_least64_t, 40> big40_t;
typedef endian<endianness::big, int_least64_t, 48> big48_t;
typedef endian<endianness::big, int_least64_t, 56> big56_t;
typedef endian<endianness::big, int_least64_t, 64> big64_t;
// unaligned big endian unsigned integer types
typedef endian<endianness::big, uint_least8_t, 8> ubig8_t;
typedef endian<endianness::big, uint_least16_t, 16> ubig16_t;
typedef endian<endianness::big, uint_least32_t, 24> ubig24_t;
typedef endian<endianness::big, uint_least32_t, 32> ubig32_t;
typedef endian<endianness::big, uint_least64_t, 40> ubig40_t;
typedef endian<endianness::big, uint_least64_t, 48> ubig48_t;
typedef endian<endianness::big, uint_least64_t, 56> ubig56_t;
typedef endian<endianness::big, uint_least64_t, 64> ubig64_t;
// unaligned little endian signed integer types
typedef endian<endianness::little, int_least8_t, 8> little8_t;
typedef endian<endianness::little, int_least16_t, 16> little16_t;
typedef endian<endianness::little, int_least32_t, 24> little24_t;
typedef endian<endianness::little, int_least32_t, 32> little32_t;
typedef endian<endianness::little, int_least64_t, 40> little40_t;
typedef endian<endianness::little, int_least64_t, 48> little48_t;
typedef endian<endianness::little, int_least64_t, 56> little56_t;
typedef endian<endianness::little, int_least64_t, 64> little64_t;
// unaligned little endian unsigned integer types
typedef endian<endianness::little, uint_least8_t, 8> ulittle8_t;
typedef endian<endianness::little, uint_least16_t, 16> ulittle16_t;
typedef endian<endianness::little, uint_least32_t, 24> ulittle24_t;
typedef endian<endianness::little, uint_least32_t, 32> ulittle32_t;
typedef endian<endianness::little, uint_least64_t, 40> ulittle40_t;
typedef endian<endianness::little, uint_least64_t, 48> ulittle48_t;
typedef endian<endianness::little, uint_least64_t, 56> ulittle56_t;
typedef endian<endianness::little, uint_least64_t, 64> ulittle64_t;
// unaligned native endian signed integer types
typedef endian<endianness::native, int_least8_t, 8> native8_t;
typedef endian<endianness::native, int_least16_t, 16> native16_t;
typedef endian<endianness::native, int_least32_t, 24> native24_t;
typedef endian<endianness::native, int_least32_t, 32> native32_t;
typedef endian<endianness::native, int_least64_t, 40> native40_t;
typedef endian<endianness::native, int_least64_t, 48> native48_t;
typedef endian<endianness::native, int_least64_t, 56> native56_t;
typedef endian<endianness::native, int_least64_t, 64> native64_t;
// unaligned native endian unsigned integer types
typedef endian<endianness::native, uint_least8_t, 8> unative8_t;
typedef endian<endianness::native, uint_least16_t, 16> unative16_t;
typedef endian<endianness::native, uint_least32_t, 24> unative24_t;
typedef endian<endianness::native, uint_least32_t, 32> unative32_t;
typedef endian<endianness::native, uint_least64_t, 40> unative40_t;
typedef endian<endianness::native, uint_least64_t, 48> unative48_t;
typedef endian<endianness::native, uint_least64_t, 56> unative56_t;
typedef endian<endianness::native, uint_least64_t, 64> unative64_t;
// These types only present if platform has exact size integers:
// aligned big endian signed integer types
// aligned big endian unsigned integer types
// aligned little endian signed integer types
// aligned little endian unsigned integer types
// aligned native endian typedefs are not provided because
// <cstdint> types are superior for this use case
#ifdef INT16_MAX
typedef endian<endianness::big, int16_t, 16, alignment::aligned>
aligned_big16_t;
typedef endian<endianness::big, uint16_t, 16, alignment::aligned>
aligned_ubig16_t;
typedef endian<endianness::little, int16_t, 16, alignment::aligned>
aligned_little16_t;
typedef endian<endianness::little, uint16_t, 16, alignment::aligned>
aligned_ulittle16_t;
#endif
#ifdef INT32_MAX
typedef endian<endianness::big, int32_t, 32, alignment::aligned>
aligned_big32_t;
typedef endian<endianness::big, uint32_t, 32, alignment::aligned>
aligned_ubig32_t;
typedef endian<endianness::little, int32_t, 32, alignment::aligned>
aligned_little32_t;
typedef endian<endianness::little, uint32_t, 32, alignment::aligned>
aligned_ulittle32_t;
#endif
#ifdef INT64_MAX
typedef endian<endianness::big, int64_t, 64, alignment::aligned>
aligned_big64_t;
typedef endian<endianness::big, uint64_t, 64, alignment::aligned>
aligned_ubig64_t;
typedef endian<endianness::little, int64_t, 64, alignment::aligned>
aligned_little64_t;
typedef endian<endianness::little, uint64_t, 64, alignment::aligned>
aligned_ulittle64_t;
#endif
} // namespace endian
} // namespace spirit
} // namespace boost
#undef BOOST_SPIRIT_ENDIAN_DEFAULT_CONSTRUCT
#undef BOOST_SPIRIT_ENDIAN_NO_CTORS
#if defined(__BORLANDC__) || defined(__CODEGEARC__)
#pragma pack(pop)
#endif
#endif // BOOST_SPIRIT_ENDIAN_HPP
| 32.11704 | 90 | 0.710021 | henrywarhurst |
c7aa1aad149753749241a39cced2f20c736c6a8d | 1,839 | cpp | C++ | TESTS/mbed_drivers/timeout/main.cpp | nachocarballeda/mbed-os | fc1836545dcc2fc86f03b01292b62bf2089f67c3 | [
"Apache-2.0"
] | 3 | 2018-03-13T13:42:12.000Z | 2019-05-17T11:48:04.000Z | TESTS/mbed_drivers/timeout/main.cpp | nachocarballeda/mbed-os | fc1836545dcc2fc86f03b01292b62bf2089f67c3 | [
"Apache-2.0"
] | 1 | 2017-02-20T10:48:02.000Z | 2017-02-21T11:34:16.000Z | TESTS/mbed_drivers/timeout/main.cpp | nachocarballeda/mbed-os | fc1836545dcc2fc86f03b01292b62bf2089f67c3 | [
"Apache-2.0"
] | 8 | 2018-01-28T02:23:18.000Z | 2021-02-26T01:15:55.000Z | /*
* Copyright (c) 2013-2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* 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 "mbed.h"
#include "greentea-client/test_env.h"
#include "utest/utest.h"
using namespace utest::v1;
Timeout timeout;
DigitalOut led(LED1);
volatile int ticker_count = 0;
volatile bool print_tick = false;
static const int total_ticks = 10;
const int ONE_SECOND_US = 1000000;
void send_kv_tick() {
if (ticker_count <= total_ticks) {
timeout.attach_us(send_kv_tick, ONE_SECOND_US);
print_tick = true;
}
}
void wait_and_print() {
while(ticker_count <= total_ticks) {
if (print_tick) {
print_tick = false;
greentea_send_kv("tick", ticker_count++);
led = !led;
}
}
}
void test_case_ticker() {
timeout.attach_us(send_kv_tick, ONE_SECOND_US);
wait_and_print();
}
// Test cases
Case cases[] = {
Case("Timers: toggle on/off", test_case_ticker),
};
utest::v1::status_t greentea_test_setup(const size_t number_of_cases) {
GREENTEA_SETUP(total_ticks + 5, "timing_drift_auto");
return greentea_test_setup_handler(number_of_cases);
}
Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler);
int main() {
Harness::run(specification);
}
| 27.044118 | 88 | 0.710169 | nachocarballeda |
c7ab178e0ff3dfece38b430bb52c93b657ef8e5c | 9,378 | cc | C++ | ithwrapper/ith/cli/pipe.cc | wareya/chiitrans | 7a392a304e6315cb4ecf836804512bb972090e8b | [
"Apache-2.0"
] | 71 | 2015-01-06T03:06:25.000Z | 2022-03-02T17:47:28.000Z | ithwrapper/ith/cli/pipe.cc | holemcross/chiitrans | c5e9aba5f555b1f81792d1dd4864b7efeb12f823 | [
"Apache-2.0"
] | 7 | 2015-01-14T15:08:41.000Z | 2018-11-20T18:18:15.000Z | ithwrapper/ith/cli/pipe.cc | holemcross/chiitrans | c5e9aba5f555b1f81792d1dd4864b7efeb12f823 | [
"Apache-2.0"
] | 35 | 2015-05-24T02:16:17.000Z | 2022-03-23T18:52:56.000Z | // pipe.cc
// 8/24/2013 jichi
// Branch: ITH_DLL/pipe.cpp, rev 66
// 8/24/2013 TODO: Clean up this file
#ifdef _MSC_VER
# pragma warning (disable:4100) // C4100: unreference formal parameter
#endif // _MSC_VER
#include "cli_p.h"
#include "ith/common/defs.h"
//#include "ith/common/growl.h"
#include "ith/sys/sys.h"
#include "cc/ccmacro.h"
//#include <ITH\AVL.h>
//#include <ITH\ntdll.h>
WCHAR mutex[] = ITH_GRANTPIPE_MUTEX;
WCHAR exist[] = ITH_PIPEEXISTS_EVENT;
WCHAR detach_mutex[0x20];
//WCHAR write_event[0x20];
//WCHAR engine_event[0x20];
//WCHAR recv_pipe[] = L"\\??\\pipe\\ITH_PIPE";
//WCHAR command[] = L"\\??\\pipe\\ITH_COMMAND";
wchar_t recv_pipe[] = ITH_TEXT_PIPE;
wchar_t command[] = ITH_COMMAND_PIPE;
LARGE_INTEGER wait_time={-100*10000,-1};
LARGE_INTEGER sleep_time={-20*10000,-1};
DWORD engine_type;
DWORD engine_base;
DWORD module_base;
HANDLE hPipe,
hCommand,
hDetach; //,hLose;
IdentifyEngineFun IdentifyEngine;
InsertHookFun InsertHook;
InsertDynamicHookFun InsertDynamicHook;
bool hook_inserted=0;
// jichi 9/28/2013: protect pipe on wine
// Put the definition in this file so that it might be inlined
void CliUnlockPipe()
{
if (IthIsWine())
IthReleaseMutex(::hmMutex);
}
void CliLockPipe()
{
if (IthIsWine()) {
const LONGLONG timeout = -50000000; // in nanoseconds = 5 seconds
NtWaitForSingleObject(hmMutex, 0, (PLARGE_INTEGER)&timeout);
}
}
HANDLE IthOpenPipe(LPWSTR name, ACCESS_MASK direction)
{
UNICODE_STRING us;
RtlInitUnicodeString(&us,name);
SECURITY_DESCRIPTOR sd = {1};
OBJECT_ATTRIBUTES oa = {sizeof(oa), 0, &us, OBJ_CASE_INSENSITIVE, &sd, 0};
HANDLE hFile;
IO_STATUS_BLOCK isb;
if (NT_SUCCESS(NtCreateFile(&hFile, direction, &oa, &isb, 0, 0, FILE_SHARE_READ, FILE_OPEN, 0, 0, 0)))
return hFile;
else
return INVALID_HANDLE_VALUE;
}
DWORD WINAPI WaitForPipe(LPVOID lpThreadParameter) // Dynamically detect ITH main module status.
{
CC_UNUSED(lpThreadParameter);
int i;
TextHook *man;
struct {
DWORD pid;
TextHook *man;
DWORD module;
DWORD engine;
} u;
HANDLE hMutex,
hPipeExist;
//swprintf(engine_event,L"ITH_ENGINE_%d",current_process_id);
swprintf(detach_mutex, ITH_DETACH_MUTEX_ L"%d",current_process_id);
//swprintf(lose_event,L"ITH_LOSEPIPE_%d",current_process_id);
//hEngine=IthCreateEvent(engine_event);
//NtWaitForSingleObject(hEngine,0,0);
//NtClose(hEngine);
while (engine_base == 0)
NtDelayExecution(0, &wait_time);
//LoadEngine(L"ITH_Engine.dll");
u.module = module_base;
u.pid = current_process_id;
u.man = hookman;
u.engine = engine_base;
hPipeExist = IthOpenEvent(exist);
IO_STATUS_BLOCK ios;
//hLose=IthCreateEvent(lose_event,0,0);
if (hPipeExist != INVALID_HANDLE_VALUE)
while (running) {
hPipe = INVALID_HANDLE_VALUE;
hCommand = INVALID_HANDLE_VALUE;
while (NtWaitForSingleObject(hPipeExist,0,&wait_time) == WAIT_TIMEOUT)
if (!running)
goto _release;
hMutex = IthCreateMutex(mutex,0);
NtWaitForSingleObject(hMutex,0,0);
while (hPipe == INVALID_HANDLE_VALUE||
hCommand == INVALID_HANDLE_VALUE) {
NtDelayExecution(0, &sleep_time);
if (hPipe == INVALID_HANDLE_VALUE)
hPipe = IthOpenPipe(recv_pipe, GENERIC_WRITE);
if (hCommand == INVALID_HANDLE_VALUE)
hCommand = IthOpenPipe(command, GENERIC_READ);
}
//NtClearEvent(hLose);
CliLockPipe();
NtWriteFile(hPipe, 0, 0, 0, &ios, &u, 16, 0, 0);
CliUnlockPipe();
live = true;
for (man = hookman, i = 0; i < current_hook; man++)
if (man->RecoverHook()) // jichi 9/27/2013: This is the place where built-in hooks like TextOutA are inserted
i++;
//OutputConsole(dll_name);
//OutputConsole(L"Pipe connected.");
//OutputDWORD(tree->Count());
NtReleaseMutant(hMutex,0);
NtClose(hMutex);
if (!hook_inserted && engine_base) {
hook_inserted = true;
IdentifyEngine();
}
hDetach = IthCreateMutex(detach_mutex,1);
while (running && NtWaitForSingleObject(hPipeExist,0,&sleep_time)==WAIT_OBJECT_0)
NtDelayExecution(0,&sleep_time);
live=false;
for (man = hookman, i = 0; i < current_hook; man++)
if (man->RemoveHook())
i++;
if (!running) {
IthCoolDown(); // jichi 9/28/2013: Use cooldown instead of lock pipe to revent from hanging on exit
//CliLockPipe();
NtWriteFile(hPipe,0,0,0,&ios, man,4,0,0);
//CliUnlockPipe();
IthReleaseMutex(hDetach);
}
NtClose(hDetach);
NtClose(hPipe);
}
_release:
//NtClose(hLose);
NtClose(hPipeExist);
return 0;
}
DWORD WINAPI CommandPipe(LPVOID lpThreadParameter)
{
CC_UNUSED(lpThreadParameter);
DWORD command;
BYTE buff[0x400] = {};
HANDLE hPipeExist;
hPipeExist = IthOpenEvent(exist);
IO_STATUS_BLOCK ios={};
if (hPipeExist!=INVALID_HANDLE_VALUE)
while (running) {
while (!live) {
if (!running)
goto _detach;
NtDelayExecution(0, &sleep_time);
}
// jichi 9/27/2013: Why 0x200 not 0x400? wchar_t?
switch (NtReadFile(hCommand, 0, 0, 0, &ios, buff, 0x200, 0, 0)) {
case STATUS_PIPE_BROKEN:
case STATUS_PIPE_DISCONNECTED:
NtClearEvent(hPipeExist);
continue;
case STATUS_PENDING:
NtWaitForSingleObject(hCommand, 0, 0);
switch (ios.Status) {
case STATUS_PIPE_BROKEN:
case STATUS_PIPE_DISCONNECTED:
NtClearEvent(hPipeExist);
continue;
case 0: break;
default:
if (NtWaitForSingleObject(hDetach, 0, &wait_time) == WAIT_OBJECT_0)
goto _detach;
}
}
if (ios.uInformation && live) {
command = *(DWORD *)buff;
switch(command) {
case IHF_COMMAND_NEW_HOOK:
//IthBreak();
buff[ios.uInformation] = 0;
buff[ios.uInformation + 1] = 0;
NewHook(*(HookParam *)(buff + 4), (LPWSTR)(buff + 4 + sizeof(HookParam)), 0);
break;
case IHF_COMMAND_REMOVE_HOOK:
{
DWORD rm_addr = *(DWORD *)(buff+4);
HANDLE hRemoved = IthOpenEvent(ITH_REMOVEHOOK_EVENT);
TextHook *in = hookman;
for (int i = 0; i < current_hook; in++) {
if (in->Address()) i++;
if (in->Address() == rm_addr) break;
}
if (in->Address())
in->ClearHook();
IthSetEvent(hRemoved);
NtClose(hRemoved);
} break;
case IHF_COMMAND_MODIFY_HOOK:
{
DWORD rm_addr = *(DWORD *)(buff + 4);
HANDLE hModify = IthOpenEvent(ITH_MODIFYHOOK_EVENT);
TextHook *in = hookman;
for (int i = 0; i < current_hook; in++) {
if (in->Address()) i++;
if (in->Address() == rm_addr) break;
}
if (in->Address())
in->ModifyHook(*(HookParam *)(buff + 4));
IthSetEvent(hModify);
NtClose(hModify);
} break;
case IHF_COMMAND_DETACH:
running = false;
live = false;
goto _detach;
default: ;
}
}
}
_detach:
NtClose(hPipeExist);
NtClose(hCommand);
return 0;
}
extern "C" {
DWORD IHFAPI OutputConsole(LPWSTR)
{
// jichi 9/28/2013: I do not need this ><
//if (live)
//if (str) {
// int t, len, sum;
// BYTE buffer[0x80];
// BYTE *buff;
// len = wcslen(str) << 1;
// t = swprintf((LPWSTR)(buffer + 8),L"%d: ",current_process_id) << 1;
// sum = len + t + 8;
// if (sum > 0x80) {
// buff = new BYTE[sum];
// memset(buff, 0, sum); // jichi 9/25/2013: zero memory
// memcpy(buff + 8, buffer + 8, t);
// }
// else
// buff = buffer;
// *(DWORD *)buff = IHF_NOTIFICATION; //cmd
// *(DWORD *)(buff + 4) = IHF_NOTIFICATION_TEXT; //console
// memcpy(buff + t + 8, str, len);
// IO_STATUS_BLOCK ios;
// NtWriteFile(hPipe,0,0,0,&ios,buff,sum,0,0);
// if (buff != buffer)
// delete[] buff;
// return len;
//}
return 0;
}
//DWORD IHFAPI OutputDWORD(DWORD d)
//{
// WCHAR str[0x10];
// swprintf(str,L"%.8X",d);
// OutputConsole(str);
// return 0;
//}
//DWORD IHFAPI OutputRegister(DWORD *base)
//{
// WCHAR str[0x40];
// swprintf(str,L"EAX:%.8X",base[0]);
// OutputConsole(str);
// swprintf(str,L"ECX:%.8X",base[-1]);
// OutputConsole(str);
// swprintf(str,L"EDX:%.8X",base[-2]);
// OutputConsole(str);
// swprintf(str,L"EBX:%.8X",base[-3]);
// OutputConsole(str);
// swprintf(str,L"ESP:%.8X",base[-4]);
// OutputConsole(str);
// swprintf(str,L"EBP:%.8X",base[-5]);
// OutputConsole(str);
// swprintf(str,L"ESI:%.8X",base[-6]);
// OutputConsole(str);
// swprintf(str,L"EDI:%.8X",base[-7]);
// OutputConsole(str);
// return 0;
//}
DWORD IHFAPI RegisterEngineModule(DWORD base, DWORD idEngine, DWORD dnHook)
{
IdentifyEngine = (IdentifyEngineFun)idEngine;
InsertDynamicHook = (InsertDynamicHookFun)dnHook;
engine_base = base;
return 0;
}
DWORD IHFAPI NotifyHookInsert(DWORD addr)
{
if (live) {
BYTE buffer[0x10];
*(DWORD*)buffer=IHF_NOTIFICATION;
*(DWORD*)(buffer+4)=IHF_NOTIFICATION_NEWHOOK;
*(DWORD*)(buffer+8)=addr;
*(DWORD*)(buffer+0xc)=0;
IO_STATUS_BLOCK ios;
CliLockPipe();
NtWriteFile(hPipe,0,0,0,&ios,buffer,0x10,0,0);
CliUnlockPipe();
}
return 0;
}
}
// EOF
| 28.591463 | 115 | 0.621881 | wareya |
c7ac381b26bd3c4eff54f9011e245c0429a1629e | 3,797 | cpp | C++ | android-31/android/renderscript/Matrix4f.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/renderscript/Matrix4f.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/android/renderscript/Matrix4f.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../JFloatArray.hpp"
#include "./Matrix4f.hpp"
namespace android::renderscript
{
// Fields
// QJniObject forward
Matrix4f::Matrix4f(QJniObject obj) : JObject(obj) {}
// Constructors
Matrix4f::Matrix4f()
: JObject(
"android.renderscript.Matrix4f",
"()V"
) {}
Matrix4f::Matrix4f(JFloatArray arg0)
: JObject(
"android.renderscript.Matrix4f",
"([F)V",
arg0.object<jfloatArray>()
) {}
// Methods
jfloat Matrix4f::get(jint arg0, jint arg1) const
{
return callMethod<jfloat>(
"get",
"(II)F",
arg0,
arg1
);
}
JFloatArray Matrix4f::getArray() const
{
return callObjectMethod(
"getArray",
"()[F"
);
}
jboolean Matrix4f::inverse() const
{
return callMethod<jboolean>(
"inverse",
"()Z"
);
}
jboolean Matrix4f::inverseTranspose() const
{
return callMethod<jboolean>(
"inverseTranspose",
"()Z"
);
}
void Matrix4f::load(android::renderscript::Matrix4f arg0) const
{
callMethod<void>(
"load",
"(Landroid/renderscript/Matrix4f;)V",
arg0.object()
);
}
void Matrix4f::loadFrustum(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3, jfloat arg4, jfloat arg5) const
{
callMethod<void>(
"loadFrustum",
"(FFFFFF)V",
arg0,
arg1,
arg2,
arg3,
arg4,
arg5
);
}
void Matrix4f::loadIdentity() const
{
callMethod<void>(
"loadIdentity",
"()V"
);
}
void Matrix4f::loadMultiply(android::renderscript::Matrix4f arg0, android::renderscript::Matrix4f arg1) const
{
callMethod<void>(
"loadMultiply",
"(Landroid/renderscript/Matrix4f;Landroid/renderscript/Matrix4f;)V",
arg0.object(),
arg1.object()
);
}
void Matrix4f::loadOrtho(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3, jfloat arg4, jfloat arg5) const
{
callMethod<void>(
"loadOrtho",
"(FFFFFF)V",
arg0,
arg1,
arg2,
arg3,
arg4,
arg5
);
}
void Matrix4f::loadOrthoWindow(jint arg0, jint arg1) const
{
callMethod<void>(
"loadOrthoWindow",
"(II)V",
arg0,
arg1
);
}
void Matrix4f::loadPerspective(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3) const
{
callMethod<void>(
"loadPerspective",
"(FFFF)V",
arg0,
arg1,
arg2,
arg3
);
}
void Matrix4f::loadProjectionNormalized(jint arg0, jint arg1) const
{
callMethod<void>(
"loadProjectionNormalized",
"(II)V",
arg0,
arg1
);
}
void Matrix4f::loadRotate(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3) const
{
callMethod<void>(
"loadRotate",
"(FFFF)V",
arg0,
arg1,
arg2,
arg3
);
}
void Matrix4f::loadScale(jfloat arg0, jfloat arg1, jfloat arg2) const
{
callMethod<void>(
"loadScale",
"(FFF)V",
arg0,
arg1,
arg2
);
}
void Matrix4f::loadTranslate(jfloat arg0, jfloat arg1, jfloat arg2) const
{
callMethod<void>(
"loadTranslate",
"(FFF)V",
arg0,
arg1,
arg2
);
}
void Matrix4f::multiply(android::renderscript::Matrix4f arg0) const
{
callMethod<void>(
"multiply",
"(Landroid/renderscript/Matrix4f;)V",
arg0.object()
);
}
void Matrix4f::rotate(jfloat arg0, jfloat arg1, jfloat arg2, jfloat arg3) const
{
callMethod<void>(
"rotate",
"(FFFF)V",
arg0,
arg1,
arg2,
arg3
);
}
void Matrix4f::scale(jfloat arg0, jfloat arg1, jfloat arg2) const
{
callMethod<void>(
"scale",
"(FFF)V",
arg0,
arg1,
arg2
);
}
void Matrix4f::set(jint arg0, jint arg1, jfloat arg2) const
{
callMethod<void>(
"set",
"(IIF)V",
arg0,
arg1,
arg2
);
}
void Matrix4f::translate(jfloat arg0, jfloat arg1, jfloat arg2) const
{
callMethod<void>(
"translate",
"(FFF)V",
arg0,
arg1,
arg2
);
}
void Matrix4f::transpose() const
{
callMethod<void>(
"transpose",
"()V"
);
}
} // namespace android::renderscript
| 17.026906 | 111 | 0.629708 | YJBeetle |
c7acf1ea6fe29506547e60ad88931fc236be01e8 | 542 | cc | C++ | Code/0003-longest-substring-without-repeating-characters.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 2 | 2019-12-06T14:08:57.000Z | 2020-01-15T15:25:32.000Z | Code/0003-longest-substring-without-repeating-characters.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 1 | 2020-01-15T16:29:16.000Z | 2020-01-26T12:40:13.000Z | Code/0003-longest-substring-without-repeating-characters.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | null | null | null | class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length();
if (n < 2) {
return n;
}
int result = 1;
int begin = 0;
unordered_map<char, int> m;
for (int i = 0; i < n; i++) {
if (m.find(s[i]) != m.end() && m[s[i]] >= begin) {
result = max(result, i - begin);
begin = m[s[i]] + 1;
}
m[s[i]] = i;
}
result = max(result, n - begin);
return result;
}
}; | 25.809524 | 62 | 0.394834 | SMartQi |
c7adf89a0c49e30a3ce0006128a101253326e2ec | 6,061 | hpp | C++ | include/GlobalNamespace/BeatmapDataLoader_SpecialEventsFilter.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/BeatmapDataLoader_SpecialEventsFilter.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/BeatmapDataLoader_SpecialEventsFilter.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: BeatmapDataLoader
#include "GlobalNamespace/BeatmapDataLoader.hpp"
// Including type: BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapEventType
#include "BeatmapSaveDataVersion2_6_0AndEarlier/BeatmapSaveData.hpp"
// Including type: BeatmapSaveDataVersion3.BeatmapSaveData
#include "BeatmapSaveDataVersion3/BeatmapSaveData.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: HashSet`1<T>
template<typename T>
class HashSet_1;
}
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: EnvironmentKeywords
class EnvironmentKeywords;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter*, "", "BeatmapDataLoader/SpecialEventsFilter");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: BeatmapDataLoader/SpecialEventsFilter
// [TokenAttribute] Offset: FFFFFFFF
class BeatmapDataLoader::SpecialEventsFilter : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private readonly System.Collections.Generic.HashSet`1<BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapEventType> _eventTypesToFilter
// Size: 0x8
// Offset: 0x10
::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>* eventTypesToFilter;
// Field size check
static_assert(sizeof(::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>*) == 0x8);
public:
// Creating conversion operator: operator ::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>*
constexpr operator ::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>*() const noexcept {
return eventTypesToFilter;
}
// Get instance field reference: private readonly System.Collections.Generic.HashSet`1<BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapEventType> _eventTypesToFilter
::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>*& dyn__eventTypesToFilter();
// public System.Void .ctor(BeatmapSaveDataVersion3.BeatmapSaveData/BeatmapSaveDataVersion3.BasicEventTypesWithKeywords basicEventTypesWithKeywords, EnvironmentKeywords environmentKeywords)
// Offset: 0x1369D1C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static BeatmapDataLoader::SpecialEventsFilter* New_ctor(::BeatmapSaveDataVersion3::BeatmapSaveData::BasicEventTypesWithKeywords* basicEventTypesWithKeywords, ::GlobalNamespace::EnvironmentKeywords* environmentKeywords) {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<BeatmapDataLoader::SpecialEventsFilter*, creationType>(basicEventTypesWithKeywords, environmentKeywords)));
}
// public System.Boolean IsEventValid(BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapSaveData/BeatmapSaveDataVersion2_6_0AndEarlier.BeatmapEventType basicBeatmapEventType)
// Offset: 0x136ACE4
bool IsEventValid(::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType basicBeatmapEventType);
}; // BeatmapDataLoader/SpecialEventsFilter
#pragma pack(pop)
static check_size<sizeof(BeatmapDataLoader::SpecialEventsFilter), 16 + sizeof(::System::Collections::Generic::HashSet_1<::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType>*)> __GlobalNamespace_BeatmapDataLoader_SpecialEventsFilterSizeCheck;
static_assert(sizeof(BeatmapDataLoader::SpecialEventsFilter) == 0x18);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter::IsEventValid
// Il2CppName: IsEventValid
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter::*)(::BeatmapSaveDataVersion2_6_0AndEarlier::BeatmapSaveData::BeatmapEventType)>(&GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter::IsEventValid)> {
static const MethodInfo* get() {
static auto* basicBeatmapEventType = &::il2cpp_utils::GetClassFromName("BeatmapSaveDataVersion2_6_0AndEarlier", "BeatmapSaveData/BeatmapEventType")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapDataLoader::SpecialEventsFilter*), "IsEventValid", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{basicBeatmapEventType});
}
};
| 64.478723 | 286 | 0.804983 | RedBrumbler |
c7af199c5ce7c8ebff0e74ee021e01781b89afca | 811 | cc | C++ | 1663/5028028_AC_125MS_452K.cc | twilightgod/twilight-poj-solution | 3af3f0fb0c5f350cdf6421b943c6df02ee3f2f82 | [
"Apache-2.0"
] | 21 | 2015-05-26T10:18:12.000Z | 2021-06-01T09:39:47.000Z | 1663/5028028_AC_125MS_452K.cc | twilightgod/twilight-poj-solution | 3af3f0fb0c5f350cdf6421b943c6df02ee3f2f82 | [
"Apache-2.0"
] | null | null | null | 1663/5028028_AC_125MS_452K.cc | twilightgod/twilight-poj-solution | 3af3f0fb0c5f350cdf6421b943c6df02ee3f2f82 | [
"Apache-2.0"
] | 8 | 2015-09-30T08:41:15.000Z | 2020-03-11T03:49:42.000Z | /**********************************************************************
* Online Judge : POJ
* Problem Title : Number Steps
* ID : 1663
* Date : 4/22/2009
* Time : 20:34:57
* Computer Name : EVERLASTING-PC
***********************************************************************/
#include<iostream>
using namespace std;
int x,y,t;
int SNumber()
{
if(x==y)
{
if(x%2)
{
return 2*x-1;
}
else
{
return 2*x;
}
}
else if(x==y+2)
{
if(x%2)
{
return 2*y+1;
}
else
{
return 2*x-2;
}
}
return -1;
}
int main()
{
//freopen("in_1663.txt","r",stdin);
cin>>t;
while(t--)
{
cin>>x>>y;
int ans=SNumber();
if(ans==-1)
{
cout<<"No Number\n";
}
else
{
cout<<ans<<endl;
}
}
return 0;
}
| 13.516667 | 72 | 0.378545 | twilightgod |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.