repo_id stringlengths 4 98 | size int64 611 5.02M | file_path stringlengths 1 276 | content stringlengths 611 5.02M | shard_id int64 0 109 | quality_score float32 0.5 1 | quality_prediction int8 1 1 | quality_confidence float32 0.5 1 | topic_primary stringclasses 1 value | topic_group stringclasses 1 value | topic_score float32 0.05 1 | topic_all stringclasses 96 values | quality2_score float32 0.5 1 | quality2_prediction int8 1 1 | quality2_confidence float32 0.5 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DustinRepo/JexClient | 5,125 | src/main/java/me/dustin/jex/feature/mod/impl/world/SlimeSpawnMarker.java | package me.dustin.jex.feature.mod.impl.world;
import me.dustin.events.core.EventListener;
import me.dustin.events.core.annotate.EventPointer;
import me.dustin.jex.event.misc.EventSetLevel;
import me.dustin.jex.event.render.EventRender3D;
import me.dustin.jex.event.world.EventSpawnEntity;
import me.dustin.jex.feature.mod.core.Category;
import me.dustin.jex.feature.mod.core.Feature;
import me.dustin.jex.feature.property.Property;
import me.dustin.jex.helper.file.FileHelper;
import me.dustin.jex.helper.file.ModFileHelper;
import me.dustin.jex.helper.misc.ChatHelper;
import me.dustin.jex.helper.misc.Wrapper;
import me.dustin.jex.helper.render.Render3DHelper;
import net.minecraft.entity.mob.SlimeEntity;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.math.Vec3d;
import java.awt.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Objects;
public class SlimeSpawnMarker extends Feature {
public final Property<Boolean> notifyPlayerProperty = new Property.PropertyBuilder<Boolean>(this.getClass())
.name("Notify Player")
.value(true)
.build();
public final Property<Boolean> markSlimeChunksProperty = new Property.PropertyBuilder<Boolean>(this.getClass())
.name("Mark Slime Chunks")
.value(true)
.build();
public final Property<Boolean> writeToFileProperty = new Property.PropertyBuilder<Boolean>(this.getClass())
.name("Write to file")
.value(true)
.parent(markSlimeChunksProperty)
.depends(parent -> (boolean) parent.value())
.build();
public final Property<Color> chunkColorProperty = new Property.PropertyBuilder<Color>(this.getClass())
.name("Chunk Color")
.description("Color of a marked slime chunk")
.value(new Color(0, 255, 38))
.build();
private final ArrayList<ChunkPos> chunkPositions = new ArrayList<>();
private final File chunksFile = new File(ModFileHelper.INSTANCE.getJexDirectory(), "slimes.txt");
public SlimeSpawnMarker() {
super(Category.WORLD, "Notify you when a slime spawns and mark the chunk it spawned in as a slime chunk. Good for finding Slime Chunks on servers without the seed.");
}
@EventPointer
private final EventListener<EventSpawnEntity> eventSpawnEntityEventListener = new EventListener<>(event -> {
if (event.getEntity() instanceof SlimeEntity) {
if (event.getEntity().getY() > 40)
return;
if (notifyPlayerProperty.value())
ChatHelper.INSTANCE.addClientMessage("A Slime has spawned in chunk: \247b" + event.getEntity().getChunkPos().x + " " + event.getEntity().getChunkPos().z);
if (markSlimeChunksProperty.value())
if (!chunkPositions.contains(event.getEntity().getChunkPos())) {
chunkPositions.add(event.getEntity().getChunkPos());
if (writeToFileProperty.value()) {
try {
String server = Wrapper.INSTANCE.getMinecraft().isIntegratedServerRunning() ? "SP world" : Objects.requireNonNull(Wrapper.INSTANCE.getMinecraft().getCurrentServerEntry()).address;
String s = server + ":" + event.getEntity().getChunkPos().x + ":" + event.getEntity().getChunkPos().z + "\n";
FileWriter fileWritter = new FileWriter(chunksFile, true);
BufferedWriter bw = new BufferedWriter(fileWritter);
bw.write(s);
bw.close();
} catch (Exception e) {
ChatHelper.INSTANCE.addClientMessage("Could not write to slimes.txt");
}
}
}
}
});
@EventPointer
private final EventListener<EventRender3D> eventRender3DEventListener = new EventListener<>(event -> {
if (!markSlimeChunksProperty.value())
return;
chunkPositions.forEach(chunkPos -> {
if (Wrapper.INSTANCE.getWorld().getChunkManager().isChunkLoaded(chunkPos.x, chunkPos.z)) {
Vec3d renderVec = Render3DHelper.INSTANCE.getRenderPosition(chunkPos.x * 16, -64, chunkPos.z * 16);
Box box = new Box(renderVec.getX(), renderVec.getY(), renderVec.getZ(), renderVec.getX() + 16, renderVec.getY() + 64 + 40, renderVec.getZ() + 16);
Render3DHelper.INSTANCE.drawBox(((EventRender3D) event).getPoseStack(), box, chunkColorProperty.value().getRGB());
}
});
});
@EventPointer
private final EventListener<EventSetLevel> eventJoinWorldEventListener = new EventListener<>(event -> {
chunkPositions.clear();
});
@Override
public void onEnable() {
if (!chunksFile.exists())
FileHelper.INSTANCE.createFile(ModFileHelper.INSTANCE.getJexDirectory(), "slimes.txt");
super.onEnable();
}
}
| 1 | 0.904704 | 1 | 0.904704 | game-dev | MEDIA | 0.918493 | game-dev | 0.96298 | 1 | 0.96298 |
PeterFWS/Structure-PLP-SLAM | 35,636 | src/PLPSLAM/optimize/local_bundle_adjuster_extended_line.cc | /**
* This file is part of Structure PLP-SLAM.
*
* Copyright 2022 DFKI (German Research Center for Artificial Intelligence)
* Developed by Fangwen Shu <Fangwen.Shu@dfki.de>
*
* If you use this code, please cite the respective publications as
* listed on the github repository.
*
* Structure PLP-SLAM 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.
*
* Structure PLP-SLAM 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 Structure PLP-SLAM. If not, see <http://www.gnu.org/licenses/>.
*/
#include "PLPSLAM/optimize/local_bundle_adjuster_extended_line.h"
#include "PLPSLAM/data/keyframe.h"
#include "PLPSLAM/data/landmark.h"
#include "PLPSLAM/data/map_database.h"
#include "PLPSLAM/optimize/g2o/landmark_vertex_container.h"
#include "PLPSLAM/optimize/g2o/se3/shot_vertex_container.h"
#include "PLPSLAM/optimize/g2o/se3/reproj_edge_wrapper.h"
#include "PLPSLAM/util/converter.h"
#include <unordered_map>
#include <Eigen/StdVector>
#include <g2o/core/solver.h>
#include <g2o/core/block_solver.h>
#include <g2o/core/sparse_optimizer.h>
#include <g2o/core/robust_kernel_impl.h>
#include <g2o/types/sba/types_six_dof_expmap.h>
#include <g2o/solvers/eigen/linear_solver_eigen.h>
#include <g2o/solvers/dense/linear_solver_dense.h>
#include <g2o/solvers/csparse/linear_solver_csparse.h>
#include <g2o/core/optimization_algorithm_levenberg.h>
#include <spdlog/spdlog.h>
// FW: 3D Line using Plücker coordinates, and orthonormal representation (4DOF minimal representation)
#include "PLPSLAM/data/landmark_line.h"
#include "PLPSLAM/optimize/g2o/line3d.h"
#include "PLPSLAM/optimize/g2o/landmark_vertex_line3d.h"
#include "PLPSLAM/optimize/g2o/landmark_vertex_container_line3d.h"
namespace PLPSLAM
{
namespace optimize
{
local_bundle_adjuster_extended_line::local_bundle_adjuster_extended_line(data::map_database *map_db,
const unsigned int num_first_iter,
const unsigned int num_second_iter)
: _map_db(map_db),
num_first_iter_(num_first_iter),
num_second_iter_(num_second_iter)
{
}
void local_bundle_adjuster_extended_line::optimize(data::keyframe *curr_keyfrm, bool *const force_stop_flag) const
{
// FW: the local BA optimizer only happens when a keyframe is detected and inserted into the map
// both 3D point and keyframe will be optimized (called in mapping_module::mapping_with_new_keyframe())
// --------------------------------------------------------------------------------------------------------------------------------------
// ------------------------------------------[1] Aggregate local/fixed keyframes and local landmarks-------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------
// find local keyframes of the current keyframe
std::unordered_map<unsigned int, data::keyframe *> local_keyfrms; // id <-> keyframe*
local_keyfrms[curr_keyfrm->id_] = curr_keyfrm;
const auto curr_covisibilities = curr_keyfrm->graph_node_->get_covisibilities(); // std::vector<keyframe *>
// Aggregate local keyframes
// loop though all the keyframes which have co-visibility -> observe common 3D points
for (auto local_keyfrm : curr_covisibilities)
{
if (!local_keyfrm)
{
continue;
}
if (local_keyfrm->will_be_erased())
{
continue;
}
local_keyfrms[local_keyfrm->id_] = local_keyfrm;
}
// optimize local landmarks seen in local keyframes
std::unordered_map<unsigned int, data::landmark *> local_lms; // id <-> 3D point*
// FW:
std::unordered_map<unsigned int, data::Line *> local_lms_line; // id <-> 3D line*
// Aggregate local landmarks (both points and lines)
// loop through all the local keyframes to find local landmarks
for (auto local_keyfrm : local_keyfrms)
{
// Aggregate 3D points
const auto landmarks = local_keyfrm.second->get_landmarks();
for (auto local_lm : landmarks)
{
if (!local_lm)
{
continue;
}
if (local_lm->will_be_erased())
{
continue;
}
// Avoid duplication
if (local_lms.count(local_lm->id_))
{
// if count = 1
continue;
}
local_lms[local_lm->id_] = local_lm;
}
// FW: Aggregate 3D lines
const auto landmarks_line = local_keyfrm.second->get_landmarks_line();
for (auto local_lm_line : landmarks_line)
{
if (!local_lm_line)
{
continue;
}
if (local_lm_line->will_be_erased())
{
continue;
}
// Avoid duplication
if (local_lms_line.count(local_lm_line->_id))
{
// if count = 1
continue;
}
local_lms_line[local_lm_line->_id] = local_lm_line;
}
}
// "fixed" keyframes: keyframes which observe local landmarks but which are NOT in local keyframes
// those keyframe will be included in optimization, but the pose will not be updated
std::unordered_map<unsigned int, data::keyframe *> fixed_keyfrms;
// FW: Aggregate fixed keyframes
// loop through all the local landmarks we found before to find more (fixed) keyframe
for (auto local_lm : local_lms)
{
const auto observations = local_lm.second->get_observations(); // std::map<keyframe *, unsigned int>
for (auto &obs : observations)
{
auto fixed_keyfrm = obs.first;
if (!fixed_keyfrm)
{
continue;
}
if (fixed_keyfrm->will_be_erased())
{
continue;
}
// Do not add if it belongs to local keyframes
if (local_keyfrms.count(fixed_keyfrm->id_))
{
continue;
}
// Avoid duplication
if (fixed_keyfrms.count(fixed_keyfrm->id_))
{
continue;
}
fixed_keyfrms[fixed_keyfrm->id_] = fixed_keyfrm;
}
}
// FW: Aggregate fixed keyframes using local lines
for (auto local_lm_line : local_lms_line)
{
const auto observations = local_lm_line.second->get_observations(); // std::map<keyframe *, unsigned int>
for (auto &obs : observations)
{
auto fixed_keyfrm = obs.first;
if (!fixed_keyfrm)
{
continue;
}
if (fixed_keyfrm->will_be_erased())
{
continue;
}
// Do not add if it belongs to local keyframes
if (local_keyfrms.count(fixed_keyfrm->id_))
{
continue;
}
// Avoid duplication
if (fixed_keyfrms.count(fixed_keyfrm->id_))
{
continue;
}
fixed_keyfrms[fixed_keyfrm->id_] = fixed_keyfrm;
}
}
if (_setVerbose)
{
spdlog::info("-- LocalBA with line -- [1] Aggregate local/fixed keyframes and local landmarks");
}
// --------------------------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------[2] Build optimizer------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------
// The solver type defines the method to solve the matrix inverse and the structure of the sparse matrix.
// define solver type, such as linear solver, here use Csparse library as the backend solver
auto linear_solver = ::g2o::make_unique<::g2o::LinearSolverCSparse<::g2o::BlockSolverX::PoseMatrixType>>();
// create a solver
auto block_solver = ::g2o::make_unique<::g2o::BlockSolverX>(std::move(linear_solver));
// create the optimization algorithm, such as Gauss-Newton, Gradient-Descent , Levenberg-Marquardt
auto algorithm = new ::g2o::OptimizationAlgorithmLevenberg(std::move(block_solver));
// declaring an optimizer
::g2o::SparseOptimizer optimizer;
// setup the optimizer
optimizer.setAlgorithm(algorithm);
optimizer.setVerbose(false);
if (force_stop_flag)
{
optimizer.setForceStopFlag(force_stop_flag);
}
if (_setVerbose)
{
spdlog::info("-- LocalBA with line -- [2] Build optimizer");
}
// --------------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------[3] Convert keyframe to g2o vertex and set to optimizer----------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------
// shot vertex container, just a vector saves all the vertex
g2o::se3::shot_vertex_container keyfrm_vtx_container(0, local_keyfrms.size() + fixed_keyfrms.size());
// Save the converted keyframes to vertex
std::unordered_map<unsigned int, data::keyframe *> all_keyfrms;
// Set local keyframes to optimizer
for (auto &id_local_keyfrm_pair : local_keyfrms)
{
auto local_keyfrm = id_local_keyfrm_pair.second;
all_keyfrms.emplace(id_local_keyfrm_pair);
auto keyfrm_vtx = keyfrm_vtx_container.create_vertex(local_keyfrm, local_keyfrm->id_ == 0); // local_keyfrm->id_ == 0 return false, this vertex will not remain constant
optimizer.addVertex(keyfrm_vtx);
}
// Set fixed keyframes to optimizer
for (auto &id_fixed_keyfrm_pair : fixed_keyfrms)
{
auto fixed_keyfrm = id_fixed_keyfrm_pair.second;
all_keyfrms.emplace(id_fixed_keyfrm_pair);
auto keyfrm_vtx = keyfrm_vtx_container.create_vertex(fixed_keyfrm, true); // true: this vertex will remain constant
optimizer.addVertex(keyfrm_vtx);
}
if (_setVerbose)
{
spdlog::info("-- LocalBA with line -- [3] Convert keyframe to g2o vertex and set to optimizer");
}
// --------------------------------------------------------------------------------------------------------------------------------------
// --------------------------------------[4] Connect keyframe and landmark vertex with reprojection edge-----------------------
// --------------------------------------------------------------------------------------------------------------------------------------
// Chi-square value with significance level of 5%
// Degrees of freedom n=2
constexpr float chi_sq_2D = 5.99146;
const float sqrt_chi_sq_2D = std::sqrt(chi_sq_2D);
// Degrees of freedom n=3
constexpr float chi_sq_3D = 7.81473;
const float sqrt_chi_sq_3D = std::sqrt(chi_sq_3D);
// [4.1] standard point landmark
// landmark vertex container
g2o::landmark_vertex_container lm_vtx_container(keyfrm_vtx_container.get_max_vertex_id() + 1, local_lms.size());
// container of reprojection edge
using reproj_edge_wrapper = g2o::se3::reproj_edge_wrapper<data::keyframe>;
std::vector<reproj_edge_wrapper> reproj_edge_wraps;
reproj_edge_wraps.reserve(all_keyfrms.size() * local_lms.size());
for (auto &id_local_lm_pair : local_lms)
{
auto local_lm = id_local_lm_pair.second;
// Convert landmark to g2o vertex and set to optimizer
auto lm_vtx = lm_vtx_container.create_vertex(local_lm, false); // false -> vertex not constant, will be optimized
optimizer.addVertex(lm_vtx);
// add point-keyframe edge
const auto observations = local_lm->get_observations();
for (const auto &obs : observations)
{
auto keyfrm = obs.first;
auto idx = obs.second; // keypoint's id
if (!keyfrm)
{
continue;
}
if (keyfrm->will_be_erased())
{
continue;
}
const auto keyfrm_vtx = keyfrm_vtx_container.get_vertex(keyfrm); // keyframe vertex
const auto &undist_keypt = keyfrm->undist_keypts_.at(idx); // undistorted keypoint
const float x_right = keyfrm->stereo_x_right_.at(idx); // if monocular, x_right <0
const float inv_sigma_sq = keyfrm->inv_level_sigma_sq_.at(undist_keypt.octave);
const auto sqrt_chi_sq = (keyfrm->camera_->setup_type_ == camera::setup_type_t::Monocular)
? sqrt_chi_sq_2D
: sqrt_chi_sq_3D;
// create reprojection_error edge between keyframe vertex and landmark vertex
auto reproj_edge_wrap = reproj_edge_wrapper(keyfrm, keyfrm_vtx, local_lm, lm_vtx,
idx, undist_keypt.pt.x, undist_keypt.pt.y, x_right,
inv_sigma_sq, sqrt_chi_sq);
// aggregate edges
reproj_edge_wraps.push_back(reproj_edge_wrap);
optimizer.addEdge(reproj_edge_wrap.edge_);
}
}
if (_setVerbose)
{
spdlog::info("-- LocalBA with line -- [4.1] reprojection edge (standard)");
}
// FW:
// [4.2] add 3D line as vertex, and edge with keyframe
g2o::landmark_vertex_container_line3d line3d_vtx_container(lm_vtx_container.get_max_vertex_id() + 1, local_lms_line.size());
std::vector<reproj_edge_wrapper> reproj_edge_wraps_for_line3d;
reproj_edge_wraps_for_line3d.reserve(all_keyfrms.size() * local_lms_line.size());
if (!local_lms_line.empty())
{
for (auto &id_local_lm_line_pair : local_lms_line)
{
auto local_lm_line = id_local_lm_line_pair.second;
if (!local_lm_line || local_lm_line->will_be_erased())
{
continue;
}
// convert landmark to g2o vertex and set to optimizer
auto line3d_vtx = line3d_vtx_container.create_vertex(local_lm_line->_id, local_lm_line->get_PlueckerCoord(), false);
optimizer.addVertex(line3d_vtx);
// add edge between 3D line and keyframe
const auto observations = local_lm_line->get_observations();
if (observations.empty())
{
continue;
}
for (const auto &obs : observations)
{
auto keyfrm = obs.first;
auto idx = obs.second; // keyline's id
if (!keyfrm)
{
continue;
}
if (keyfrm->will_be_erased())
{
continue;
}
const auto keyfrm_vtx = keyfrm_vtx_container.get_vertex(keyfrm); // keyframe vertex
const auto &keyline = keyfrm->_keylsd.at(idx); // undistorted keyline
const float inv_sigma_sq = keyfrm->_inv_level_sigma_sq_lsd.at(keyline.octave);
const auto sqrt_chi_sq = sqrt_chi_sq_2D;
// create reprojection_error edge between keyframe vertex and 3D line vertex
auto line_reproj_edge = reproj_edge_wrapper(keyfrm, keyfrm_vtx, line3d_vtx, idx,
keyline.getStartPoint(), keyline.getEndPoint(),
inv_sigma_sq, sqrt_chi_sq);
// aggregate edges
reproj_edge_wraps_for_line3d.push_back(line_reproj_edge);
optimizer.addEdge(line_reproj_edge.edge_);
}
}
}
if (_setVerbose)
{
spdlog::info("-- LocalBA with line -- [4.2] reprojection edge (keyframe-line)");
}
// --------------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- [5] Run the first optimization---------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------
if (force_stop_flag)
{
if (*force_stop_flag)
{
return;
}
}
optimizer.initializeOptimization(); // initialize the optimizer we built before in steps [1]-[4]
optimizer.optimize(num_first_iter_); // run the optimizer, num_first_iter_ = 5
if (_setVerbose)
{
spdlog::info("-- LocalBA with line -- [5] Run the first optimization");
}
// --------------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------[6] Remove outliers and run a second optimization----------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------
bool run_robust_BA = true;
if (force_stop_flag)
{
if (*force_stop_flag)
{
run_robust_BA = false;
}
}
if (run_robust_BA)
{
for (auto &reproj_edge_wrap : reproj_edge_wraps)
{
auto edge = reproj_edge_wrap.edge_;
auto local_lm = reproj_edge_wrap.lm_;
if (local_lm->will_be_erased())
{
continue;
}
if (reproj_edge_wrap.is_monocular_)
{
if (chi_sq_2D < edge->chi2() || !reproj_edge_wrap.depth_is_positive())
{
reproj_edge_wrap.set_as_outlier();
}
}
else
{
if (chi_sq_3D < edge->chi2() || !reproj_edge_wrap.depth_is_positive())
{
reproj_edge_wrap.set_as_outlier();
}
}
edge->setRobustKernel(nullptr);
}
// FW: remove 3D line outliers
if (!reproj_edge_wraps_for_line3d.empty())
{
for (auto &line_reproj_edge : reproj_edge_wraps_for_line3d)
{
auto edge = line_reproj_edge.edge_;
auto local_lm_line = line_reproj_edge._lm_line;
if (local_lm_line->will_be_erased())
{
continue;
}
if (chi_sq_2D < edge->chi2() || !line_reproj_edge.depth_is_positive_via_endpoints_trimming())
{
line_reproj_edge.set_as_outlier();
}
edge->setRobustKernel(nullptr);
}
}
// run the second BA, after removing outliers from the graph
optimizer.initializeOptimization();
optimizer.optimize(num_second_iter_); // num_second_iter_ = 10
}
if (_setVerbose)
{
spdlog::info("-- LocalBA with line -- [6] Run the second optimization");
}
// --------------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------[7] Aggregate outliers-------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------
std::vector<std::pair<data::keyframe *, data::landmark *>> outlier_observations;
outlier_observations.reserve(reproj_edge_wraps.size());
// FW:
std::vector<std::pair<data::keyframe *, data::Line *>> outlier_observations_line;
outlier_observations_line.reserve(reproj_edge_wraps_for_line3d.size());
// point
for (auto &reproj_edge_wrap : reproj_edge_wraps)
{
auto edge = reproj_edge_wrap.edge_;
auto local_lm = reproj_edge_wrap.lm_;
if (local_lm->will_be_erased())
{
continue;
}
if (reproj_edge_wrap.is_monocular_)
{
if (chi_sq_2D < edge->chi2() || !reproj_edge_wrap.depth_is_positive())
{
outlier_observations.emplace_back(std::make_pair(reproj_edge_wrap.shot_, reproj_edge_wrap.lm_));
}
}
else
{
if (chi_sq_3D < edge->chi2() || !reproj_edge_wrap.depth_is_positive())
{
outlier_observations.emplace_back(std::make_pair(reproj_edge_wrap.shot_, reproj_edge_wrap.lm_));
}
}
}
// FW: aggregate 3D line outliers
if (!reproj_edge_wraps_for_line3d.empty())
{
for (auto &line_reproj_edge : reproj_edge_wraps_for_line3d)
{
auto edge = line_reproj_edge.edge_;
auto local_lm_line = line_reproj_edge._lm_line;
if (local_lm_line->will_be_erased())
{
continue;
}
if (chi_sq_2D < edge->chi2() || !line_reproj_edge.depth_is_positive_via_endpoints_trimming())
{
outlier_observations_line.emplace_back(std::make_pair(line_reproj_edge.shot_, line_reproj_edge._lm_line));
}
}
}
if (_setVerbose)
{
spdlog::info("-- LocalBA with line -- [7] Aggregate outliers");
}
// --------------------------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------[8] Update information--------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------------------------
{
// lock the map database
std::lock_guard<std::mutex> lock(data::map_database::mtx_database_);
// remove outlier landmark from keyframe, and remove the link between landmark to keyframe
if (!outlier_observations.empty())
{
for (auto &outlier_obs : outlier_observations) // keyframe* <-> 3D point*
{
auto keyfrm = outlier_obs.first;
auto lm = outlier_obs.second;
keyfrm->erase_landmark(lm);
lm->erase_observation(keyfrm);
}
}
if (_setVerbose)
{
spdlog::info("-- LocalBA with line -- [8.1] remove 3D point observation");
}
// FW: remove 3D line observation
if (!outlier_observations_line.empty())
{
for (auto &outlier_obs_line : outlier_observations_line)
{
auto keyfrm = outlier_obs_line.first;
auto lm_line = outlier_obs_line.second;
keyfrm->erase_landmark_line(lm_line);
lm_line->erase_observation(keyfrm);
}
}
if (_setVerbose)
{
spdlog::info("-- LocalBA with line -- [8.2] remove 3D line observation");
}
// Update pose of local keyframe
for (auto id_local_keyfrm_pair : local_keyfrms)
{
auto local_keyfrm = id_local_keyfrm_pair.second;
auto keyfrm_vtx = keyfrm_vtx_container.get_vertex(local_keyfrm);
local_keyfrm->set_cam_pose(keyfrm_vtx->estimate());
}
// Update 3D position of landmark
for (auto id_local_lm_pair : local_lms)
{
auto local_lm = id_local_lm_pair.second;
auto lm_vtx = lm_vtx_container.get_vertex(local_lm);
local_lm->set_pos_in_world(lm_vtx->estimate());
local_lm->update_normal_and_depth();
}
// FW: Update the position of 3D line
if (!local_lms_line.empty())
{
for (auto id_local_lm_line_pair : local_lms_line)
{
auto local_lm_line = id_local_lm_line_pair.second;
auto line3d_vtx = line3d_vtx_container.get_vertex(local_lm_line->_id);
auto pos_w_pluecker = line3d_vtx->estimate(); // Vec6_t: Plücker coordinates
// update Plücker coordinates, for optimization
local_lm_line->set_PlueckerCoord_without_update_endpoints(pos_w_pluecker);
// update endpoints, only for map visualization: endpoints trimming
Vec6_t updated_pose_w;
if (endpoint_trimming(local_lm_line, pos_w_pluecker, updated_pose_w))
{
local_lm_line->set_pos_in_world_without_update_pluecker(updated_pose_w);
local_lm_line->update_information();
}
else
{
local_lm_line->prepare_for_erasing(); // outlier found by trimming
}
}
}
}
if (_setVerbose)
{
spdlog::info("-- LocalBA with line -- [8] Update information");
spdlog::info("");
}
}
bool local_bundle_adjuster_extended_line::endpoint_trimming(data::Line *local_lm_line,
const Vec6_t &plucker_coord,
Vec6_t &updated_pose_w) const
{
// FW:
// references:
// "Elaborate Monocular Point and Line SLAM with Robust Initialization", ICCV'19
// "Building a 3-D line-based map using stereo SLAM", IEEE Transactions on Robotics'15
auto ref_kf = local_lm_line->get_ref_keyframe();
int idx = local_lm_line->get_index_in_keyframe(ref_kf);
if (idx == -1)
{
return false;
}
// [1] get endpoints from the detected line segment
auto keyline = ref_kf->_keylsd.at(idx);
auto sp = keyline.getStartPoint();
auto ep = keyline.getEndPoint();
// [2] get the line function of re-projected 3D line
auto camera = static_cast<camera::perspective *>(ref_kf->camera_);
Mat44_t cam_pose_wc = ref_kf->get_cam_pose();
const Mat33_t rot_cw = cam_pose_wc.block<3, 3>(0, 0);
const Vec3_t trans_cw = cam_pose_wc.block<3, 1>(0, 3);
Mat66_t transformation_line_cw = Eigen::Matrix<double, 6, 6>::Zero();
transformation_line_cw.block<3, 3>(0, 0) = rot_cw;
transformation_line_cw.block<3, 3>(3, 3) = rot_cw;
transformation_line_cw.block<3, 3>(0, 3) = skew(trans_cw) * rot_cw;
Mat33_t _K;
_K << camera->fy_, 0.0, 0.0,
0.0, camera->fx_, 0.0,
-camera->fy_ * camera->cx_, -camera->fx_ * camera->cy_, camera->fx_ * camera->fy_;
Vec3_t reproj_line_function;
reproj_line_function = _K * (transformation_line_cw * plucker_coord).block<3, 1>(0, 0);
double l1 = reproj_line_function(0);
double l2 = reproj_line_function(1);
double l3 = reproj_line_function(2);
// [3] calculate closet point on the re-projected line
double x_sp_closet = -(sp.y - (l2 / l1) * sp.x + (l3 / l2)) * ((l1 * l2) / (l1 * l1 + l2 * l2));
double y_sp_closet = -(l1 / l2) * x_sp_closet - (l3 / l2);
double x_ep_closet = -(ep.y - (l2 / l1) * ep.x + (l3 / l2)) * ((l1 * l2) / (l1 * l1 + l2 * l2));
double y_ep_closet = -(l1 / l2) * x_ep_closet - (l3 / l2);
// [4] calculate another point
double x_0sp = 0;
double y_0sp = sp.y - (l2 / l1) * sp.x;
double x_0ep = 0;
double y_0ep = ep.y - (l2 / l1) * ep.x;
// [5] calculate 3D plane
Mat34_t P;
Mat34_t rotation_translation_combined = Eigen::Matrix<double, 3, 4>::Zero();
rotation_translation_combined.block<3, 3>(0, 0) = rot_cw;
rotation_translation_combined.block<3, 1>(0, 3) = trans_cw;
P = camera->eigen_cam_matrix_ * rotation_translation_combined;
Vec3_t point2d_sp_closet{x_sp_closet, y_sp_closet, 1.0};
Vec3_t point2d_0sp{x_0sp, y_0sp, 1.0};
Vec3_t line_temp_sp = point2d_sp_closet.cross(point2d_0sp);
Vec4_t plane3d_temp_sp = P.transpose() * line_temp_sp;
Vec3_t point2d_ep_closet{x_ep_closet, y_ep_closet, 1.0};
Vec3_t point2d_0ep{x_0ep, y_0ep, 1.0};
Vec3_t line_temp_ep = point2d_ep_closet.cross(point2d_0ep);
Vec4_t plane3d_temp_ep = P.transpose() * line_temp_ep;
// [6] calculate intersection of the 3D plane and 3d line
Mat44_t line3d_pluecker_matrix = Eigen::Matrix<double, 4, 4>::Zero();
Vec3_t m = plucker_coord.head<3>();
Vec3_t d = plucker_coord.tail<3>();
line3d_pluecker_matrix.block<3, 3>(0, 0) = skew(m);
line3d_pluecker_matrix.block<3, 1>(0, 3) = d;
line3d_pluecker_matrix.block<1, 3>(3, 0) = -d.transpose();
Vec4_t intersect_endpoint_sp, intersect_endpoint_ep;
intersect_endpoint_sp = line3d_pluecker_matrix * plane3d_temp_sp;
intersect_endpoint_ep = line3d_pluecker_matrix * plane3d_temp_ep;
updated_pose_w << intersect_endpoint_sp(0) / intersect_endpoint_sp(3),
intersect_endpoint_sp(1) / intersect_endpoint_sp(3),
intersect_endpoint_sp(2) / intersect_endpoint_sp(3),
intersect_endpoint_ep(0) / intersect_endpoint_ep(3),
intersect_endpoint_ep(1) / intersect_endpoint_ep(3),
intersect_endpoint_ep(2) / intersect_endpoint_ep(3);
// Debug:
double distance_of_change_sp = (updated_pose_w.head<3>() - local_lm_line->get_pos_in_world().head<3>()).norm() / ref_kf->compute_median_depth(true);
double distance_of_change_ep = (updated_pose_w.tail<3>() - local_lm_line->get_pos_in_world().tail<3>()).norm() / ref_kf->compute_median_depth(true);
// FW: an elegant way of outlier filtering :)
if (distance_of_change_sp > 0.1 || distance_of_change_ep > 0.1)
{
// spdlog::info("distance of change, sp: {}", distance_of_change_sp);
// spdlog::info("distance of change, ep: {}", distance_of_change_ep);
// std::cout << std::endl;
return false; // change is too big, considered as outlier
}
return true;
}
} // namespace optimize
} // namespace PLPSLAM
| 1 | 0.983715 | 1 | 0.983715 | game-dev | MEDIA | 0.503549 | game-dev | 0.767235 | 1 | 0.767235 |
6v6-Adjustments/6v6-adjustments | 2,104 | src/heroes/dva/init.opy | #!mainFile "../../dev_main.opy"
#!include "heroes/dva/boosters.opy"
#!include "heroes/dva/defense_matrix.opy"
#!include "heroes/dva/hp.opy"
playervar self_destruct_charge
def initDva():
@Name "[dva/init.opy]: initDva()"
# if eventPlayer.isDuplicatingAHero() and not eventPlayer.isInAlternateForm():
# setCustomHp(
# ADJ_DVA_HEALTH_DUPLICATE if eventPlayer.isDuplicatingAHero() or SETTING_ECHO_TANK_HP else ADJ_DVA_HEALTH,
# ADJ_DVA_ARMOR_DUPLICATE if eventPlayer.isDuplicatingAHero() or SETTING_ECHO_TANK_HP else ADJ_DVA_ARMOR,
# 0)
setUltCost(ADJ_DVA_ULT_COST)
removeTankPassive()
if not eventPlayer.isDuplicatingAHero():
removeSelfHealing()
setBaseDamage(eventPlayer, ADJ_DVA_CANNON_DAMAGE / OW2_DVA_CANNON_DAMAGE)
eventPlayer.self_destruct_charge = 0
eventPlayer.max_health_scaler = (ADJ_DVA_PILOT_HEALTH / OW2_DVA_PILOT_HEALTH)
waitUntil(not eventPlayer.isInAlternateForm(), Math.INFINITY)
setCustomHp(
ADJ_DVA_HEALTH_DUPLICATE if eventPlayer.isDuplicatingAHero() or SETTING_ECHO_TANK_HP else ADJ_DVA_HEALTH,
ADJ_DVA_ARMOR_DUPLICATE if eventPlayer.isDuplicatingAHero() or SETTING_ECHO_TANK_HP else ADJ_DVA_ARMOR,
0)
eventPlayer.hero_initialized = true
rule "[dva/init.opy]: Reduce Micro Missiles damage":
@Event playerDealtDamage
@Hero dva
@Condition not eventAbility == Button.ABILITY_2
heal(victim, null, eventDamage - ((ADJ_DVA_MICRO_MISSILES_DAMAGE / ADJ_DVA_MICRO_MISSILES_DAMAGE) * eventDamage/eventPlayer._base_damage_scalar))
rule "[dva/init.opy]: Increase D.va other forms of damage":
@Event playerDealtDamage
@Hero dva
@Condition eventAbility in [Button.MELEE, Button.ULTIMATE]
damage(victim, attacker, (eventDamage / eventPlayer._base_damage_scalar - eventDamage) / eventPlayer._base_damage_scalar)
rule "[dva/init.opy]: Force reset ult charge when DVa exits Mech":
@Event eachPlayer
@Hero dva
@Condition eventPlayer.isInAlternateForm()
if eventPlayer.isUsingUltimate(): return
eventPlayer.setUltCharge(0)
| 1 | 0.910703 | 1 | 0.910703 | game-dev | MEDIA | 0.976308 | game-dev | 0.774127 | 1 | 0.774127 |
MapleStoryUnity/MapleStoryUnity | 1,715 | Assets/JCSUnity/Scripts/Events/Enable/JCS_DisableWithAnimEndEvent.cs | /**
* $File: JCS_DisableWithAnimEndEvent.cs $
* $Date: $
* $Revision: $
* $Creator: Jen-Chieh Shen $
* $Notice: See LICENSE.txt for modification and distribution information
* Copyright (c) 2016 by Shen, Jen-Chieh $
*/
using UnityEngine;
using MyBox;
namespace JCSUnity
{
/// <summary>
/// Disable the game object after the done playing the animation.
/// </summary>
[RequireComponent(typeof(Animator))]
public class JCS_DisableWithAnimEndEvent : MonoBehaviour
{
/* Variables */
private Animator mAnimator = null;
private float mAnimationTimer = 0.0f;
[Separator("Runtime Variables (JCS_DisableWithAnimEndEvent)")]
[Tooltip("Times the animation need to loops to trigger this event.")]
[SerializeField]
private uint mLoopTimes = 1;
[Tooltip("Type of the delta time.")]
[SerializeField]
private JCS_TimeType mTimeType = JCS_TimeType.DELTA_TIME;
/* Setter & Getter */
public uint loopTimes { get { return mLoopTimes; } set { mLoopTimes = value; } }
public JCS_TimeType timeType { get { return mTimeType; } set { mTimeType = value; } }
/* Functions */
private void Awake()
{
mAnimator = GetComponent<Animator>();
}
private void Update()
{
AnimatorStateInfo animatorStateInfo = mAnimator.GetCurrentAnimatorStateInfo(0);
mAnimationTimer += JCS_Time.ItTime(mTimeType);
if (mAnimationTimer > animatorStateInfo.length * mLoopTimes)
{
mAnimationTimer = 0;
gameObject.SetActive(false);
}
}
}
}
| 1 | 0.589568 | 1 | 0.589568 | game-dev | MEDIA | 0.787441 | game-dev | 0.74967 | 1 | 0.74967 |
HearthSim/HSTracker | 1,345 | HSTracker/Hearthstone/RelatedCardsSystem/Cards/Paladin/TyrsTears.swift | //
// TyrsTears.swift
// HSTracker
//
// Created by Francisco Moraes on 11/7/24.
// Copyright © 2024 Benjamin Michotte. All rights reserved.
//
import Foundation
class TyrsTears: ICardWithRelatedCards {
func getCardId() -> String {
return CardIds.Collectible.Paladin.TyrsTears_TyrsTearsToken
}
func shouldShowForOpponent(opponent: Player) -> Bool {
return false
}
func getRelatedCards(player: Player) -> [Card?] {
return player.deadMinionsCards
.compactMap { CardUtils.getProcessedCardFromEntity($0, player) }
.unique()
.filter { $0.isClass(cardClass: player.currentClass ?? .invalid) }
.sorted { $0.cost < $1.cost }
}
required init() {
}
}
class TyrsTearsForged: ICardWithRelatedCards {
func getCardId() -> String {
return CardIds.NonCollectible.Paladin.TyrsTears
}
func shouldShowForOpponent(opponent: Player) -> Bool {
return false
}
func getRelatedCards(player: Player) -> [Card?] {
return player.deadMinionsCards
.compactMap { CardUtils.getProcessedCardFromEntity($0, player) }
.unique()
.filter { $0.isClass(cardClass: player.currentClass ?? .invalid) }
.sorted { $0.cost < $1.cost }
}
required init() {
}
}
| 1 | 0.965536 | 1 | 0.965536 | game-dev | MEDIA | 0.955151 | game-dev | 0.932919 | 1 | 0.932919 |
magefree/mage | 3,399 | Mage.Sets/src/mage/cards/s/SkilledAnimator.java | package mage.cards.s;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.Mode;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.effects.common.continuous.BecomesCreatureTargetEffect;
import mage.constants.SubType;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.Layer;
import mage.constants.SubLayer;
import mage.filter.common.FilterControlledPermanent;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.game.permanent.token.TokenImpl;
import mage.target.TargetPermanent;
/**
*
* @author TheElk801
*/
public final class SkilledAnimator extends CardImpl {
private static final FilterControlledPermanent filter = new FilterControlledPermanent("artifact you control");
static {
filter.add(CardType.ARTIFACT.getPredicate());
}
public SkilledAnimator(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{U}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.ARTIFICER);
this.power = new MageInt(1);
this.toughness = new MageInt(3);
// When Skilled Animator enters the battlefield, target artifact you control becomes an artifact creature with base power and toughness 5/5 for as long as Skilled Animator remains on the battlefield.
Ability ability = new EntersBattlefieldTriggeredAbility(new SkilledAnimatorBecomesCreatureEffect(), false);
ability.addTarget(new TargetPermanent(filter));
this.addAbility(ability);
}
private SkilledAnimator(final SkilledAnimator card) {
super(card);
}
@Override
public SkilledAnimator copy() {
return new SkilledAnimator(this);
}
}
class SkilledAnimatorBecomesCreatureEffect extends BecomesCreatureTargetEffect {
SkilledAnimatorBecomesCreatureEffect() {
super(new SkilledAnimatorToken(), false, false, Duration.WhileOnBattlefield);
this.staticText = "target artifact you control becomes an artifact creature with base power and toughness 5/5 for as long as {this} remains on the battlefield";
}
private SkilledAnimatorBecomesCreatureEffect(final SkilledAnimatorBecomesCreatureEffect effect) {
super(effect);
}
@Override
public SkilledAnimatorBecomesCreatureEffect copy() {
return new SkilledAnimatorBecomesCreatureEffect(this);
}
@Override
public boolean apply(Layer layer, SubLayer sublayer, Ability source, Game game) {
Permanent sourcePermanent = game.getPermanent(source.getSourceId());
if (sourcePermanent == null) {
this.discard();
return false;
}
return super.apply(layer, sublayer, source, game);
}
}
class SkilledAnimatorToken extends TokenImpl {
public SkilledAnimatorToken() {
super("", "5/5 artifact creature as long as {this} is on the battlefield");
cardType.add(CardType.ARTIFACT);
cardType.add(CardType.CREATURE);
power = new MageInt(5);
toughness = new MageInt(5);
}
private SkilledAnimatorToken(final SkilledAnimatorToken token) {
super(token);
}
public SkilledAnimatorToken copy() {
return new SkilledAnimatorToken(this);
}
}
| 1 | 0.926068 | 1 | 0.926068 | game-dev | MEDIA | 0.978858 | game-dev | 0.98929 | 1 | 0.98929 |
HbmMods/Hbm-s-Nuclear-Tech-GIT | 9,624 | src/main/java/com/hbm/inventory/gui/GUIScreenSatInterface.java | package com.hbm.inventory.gui;
import java.util.Arrays;
import java.util.List;
import org.lwjgl.opengl.GL11;
import com.hbm.inventory.recipes.MachineRecipes;
import com.hbm.items.ISatChip;
import com.hbm.items.tool.ItemSatInterface;
import com.hbm.lib.RefStrings;
import com.hbm.packet.PacketDispatcher;
import com.hbm.packet.toserver.SatLaserPacket;
import com.hbm.saveddata.satellites.Satellite.InterfaceActions;
import com.hbm.saveddata.satellites.Satellite.Interfaces;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.PositionedSoundRecord;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.Entity;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.oredict.OreDictionary;
public class GUIScreenSatInterface extends GuiScreen {
protected static final ResourceLocation texture = new ResourceLocation(RefStrings.MODID + ":textures/gui/satellites/gui_sat_interface.png");
protected int xSize = 216;
protected int ySize = 216;
protected int guiLeft;
protected int guiTop;
private final EntityPlayer player;
int x;
int z;
public GUIScreenSatInterface(EntityPlayer player) {
this.player = player;
}
public void updateScreen() {
}
protected void mouseClicked(int i, int j, int k) {
if(ItemSatInterface.currentSat != null && ItemSatInterface.currentSat.ifaceAcs.contains(InterfaceActions.CAN_CLICK)) {
if(i >= this.guiLeft + 8 && i < this.guiLeft + 208 && j >= this.guiTop + 8 && j < this.guiTop + 208 && player != null) {
mc.getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("hbm:item.techBleep"), 1.0F));
int x = this.x - guiLeft + i - 8 - 100;
int z = this.z - guiTop + j - 8 - 100;
PacketDispatcher.wrapper.sendToServer(new SatLaserPacket(x, z, ISatChip.getFreqS(player.getHeldItem())));
}
}
}
public void drawScreen(int mouseX, int mouseY, float f)
{
this.drawDefaultBackground();
this.drawGuiContainerBackgroundLayer(f, mouseX, mouseY);
GL11.glDisable(GL11.GL_LIGHTING);
this.drawGuiContainerForegroundLayer(mouseX, mouseY);
GL11.glEnable(GL11.GL_LIGHTING);
}
public void initGui()
{
super.initGui();
this.guiLeft = (this.width - this.xSize) / 2;
this.guiTop = (this.height - this.ySize) / 2;
x = (int) player.posX;
z = (int) player.posZ;
}
@Override
public boolean doesGuiPauseGame() {
return false;
}
protected void drawGuiContainerForegroundLayer(int i, int j) {
if(ItemSatInterface.currentSat != null && ItemSatInterface.currentSat.ifaceAcs.contains(InterfaceActions.SHOW_COORDS)) {
if(i >= this.guiLeft + 8 && i < this.guiLeft + 208 && j >= this.guiTop + 8 && j < this.guiTop + 208 && player != null) {
int x = this.x - guiLeft + i - 8 - 100;
int z = this.z - guiTop + j - 8 - 100;
func_146283_a(Arrays.asList(new String[] { x + " / " + z }), i, j);
}
}
}
protected void drawGuiContainerBackgroundLayer(float f, int i, int j) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
Minecraft.getMinecraft().getTextureManager().bindTexture(texture);
drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);
if(ItemSatInterface.currentSat == null) {
drawNotConnected();
} else {
if(ItemSatInterface.currentSat.satIface != Interfaces.SAT_PANEL) {
drawNoService();
return;
}
if(ItemSatInterface.currentSat.ifaceAcs.contains(InterfaceActions.HAS_MAP)) {
drawMap();
}
if(ItemSatInterface.currentSat.ifaceAcs.contains(InterfaceActions.HAS_ORES)) {
drawScan();
}
if(ItemSatInterface.currentSat.ifaceAcs.contains(InterfaceActions.HAS_RADAR)) {
drawRadar();
}
}
}
private int scanPos = 0;
private long lastMilli = 0;
private void progresScan() {
if(lastMilli + 25 < System.currentTimeMillis()) {
lastMilli = System.currentTimeMillis();
scanPos++;
}
if(scanPos >= 200)
scanPos -= 200;
}
private int[][] map = new int[200][200];
private void drawMap() {
World world = player.worldObj;
for(int i = -100; i < 100; i++) {
int x = this.x + i;
int z = this.z + scanPos - 100;
int y = world.getHeightValue(x, z) - 1;
map[i + 100][scanPos] = world.getBlock(x, y, z).getMaterial().getMaterialMapColor().colorValue;
}
prontMap();
progresScan();
}
private void drawScan() {
World world = player.worldObj;
for(int i = -100; i < 100; i++) {
int x = this.x + i;
int z = this.z + scanPos - 100;
for(int j = 255; j >= 0; j--) {
int c = getColorFromBlock(new ItemStack(world.getBlock(x, j, z), 1, world.getBlockMetadata(x, j, z)));
if(c != 0) {
map[i + 100][scanPos] = c;
break;
}
}
}
prontMap();
progresScan();
}
private int getColorFromBlock(ItemStack stack) {
if(stack == null || stack.getItem() == null/* || stack.getItemDamage() < 0*/)
return 0;
if(MachineRecipes.mODE(stack, "oreCoal"))
return 0x333333;
if(MachineRecipes.mODE(stack, "oreIron"))
return 0xb2aa92;
if(MachineRecipes.mODE(stack, "oreGold"))
return 0xffe460;
if(MachineRecipes.mODE(stack, "oreSilver"))
return 0xe5e5e5;
if(MachineRecipes.mODE(stack, "oreDiamond"))
return 0x6ed5ef;
if(MachineRecipes.mODE(stack, "oreEmerald"))
return 0x6cf756;
if(MachineRecipes.mODE(stack, "oreLapis"))
return 0x092f7a;
if(MachineRecipes.mODE(stack, "oreRedstone"))
return 0xe50000;
if(MachineRecipes.mODE(stack, "oreTin"))
return 0xa09797;
if(MachineRecipes.mODE(stack, "oreCopper"))
return 0xd16208;
if(MachineRecipes.mODE(stack, "oreLead"))
return 0x384b68;
if(MachineRecipes.mODE(stack, "oreAluminum"))
return 0xdbdbdb;
if(MachineRecipes.mODE(stack, "oreTungsten"))
return 0x333333;
if(MachineRecipes.mODE(stack, "oreTitanium"))
return 0xDDDDDD;
if(MachineRecipes.mODE(stack, "oreUranium"))
return 0x3e4f3c;
if(MachineRecipes.mODE(stack, "oreBeryllium"))
return 0x8e8d7d;
if(MachineRecipes.mODE(stack, "oreSulfur"))
return 0x9b9309;
if(MachineRecipes.mODE(stack, "oreSalpeter") || MachineRecipes.mODE(stack, "oreNiter"))
return 0xa5a09d;
if(MachineRecipes.mODE(stack, "oreFluorite"))
return 0xffffff;
if(MachineRecipes.mODE(stack, "oreSchrabidium"))
return 0x1cffff;
if(MachineRecipes.mODE(stack, "oreRareEarth"))
return 0xffcc99;
return isOre(stack) ? 0xBA00AF : 0x000000;
}
private static boolean isOre(ItemStack stack) {
int[] ids = OreDictionary.getOreIDs(new ItemStack(stack.getItem(), 1, stack.getItemDamage()));
for(int i = 0; i < ids.length; i++) {
String s = OreDictionary.getOreName(ids[i]);
if(s.length() > 3 && s.substring(0, 3).equals("ore"))
return true;
}
return false;
}
private void drawRadar() {
List<Entity> entities = player.worldObj.getEntitiesWithinAABBExcludingEntity(player, AxisAlignedBB.getBoundingBox(player.posX - 100, 0, player.posZ - 100, player.posX + 100, 5000, player.posZ + 100));
if(!entities.isEmpty()) {
for(Entity e : entities) {
if(e.width * e.width * e.height >= 0.5D) {
int x = (int)((e.posX - this.x) / ((double)100 * 2 + 1) * (200D - 8D)) - 4;
int z = (int)((e.posZ - this.z) / ((double)100 * 2 + 1) * (200D - 8D)) - 4 - 9;
int t = 5;
//TODO: fix radar screen implementation
/*if(e instanceof EntityMissileBaseAdvanced) {
t = ((EntityMissileBaseAdvanced)e).getTargetType().ordinal();
}*/
if(e instanceof EntityMob) {
t = 6;
}
if(e instanceof EntityPlayer) {
t = 7;
}
drawTexturedModalRect(guiLeft + 108 + x, guiTop + 117 + z, 216, 8 * t, 8, 8);
}
}
}
}
private void prontMap() {
for(int x = 0; x < 200; x++) {
for(int z = 0; z < 200; z++) {
if(map[x][z] != 0) {
GL11.glColor3ub((byte)((map[x][z] & 0xFF0000) >> 16), (byte)((map[x][z] & 0x00FF00) >> 8), (byte)(map[x][z] & 0x0000FF));
drawTexturedModalRect(guiLeft + 8 + x, guiTop + 8 + z, 216, 216, 1, 1);
}
}
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
private void drawNoService() {
drawTexturedModalRect((this.width - 77) / 2, (this.height - 12) / 2, 0, 228, 77, 12);
}
private void drawNotConnected() {
drawTexturedModalRect((this.width - 121) / 2, (this.height - 12) / 2, 0, 216, 121, 12);
}
protected void keyTyped(char p_73869_1_, int p_73869_2_)
{
if (p_73869_2_ == 1 || p_73869_2_ == this.mc.gameSettings.keyBindInventory.getKeyCode())
{
this.mc.thePlayer.closeScreen();
}
if (p_73869_2_ == this.mc.gameSettings.keyBindForward.getKeyCode())
{
this.z -= 50;
map = new int[200][200];
}
if (p_73869_2_ == this.mc.gameSettings.keyBindBack.getKeyCode())
{
this.z += 50;
map = new int[200][200];
}
if (p_73869_2_ == this.mc.gameSettings.keyBindLeft.getKeyCode())
{
this.x -= 50;
map = new int[200][200];
}
if (p_73869_2_ == this.mc.gameSettings.keyBindRight.getKeyCode())
{
this.x += 50;
map = new int[200][200];
}
}
}
| 1 | 0.854334 | 1 | 0.854334 | game-dev | MEDIA | 0.929372 | game-dev | 0.968592 | 1 | 0.968592 |
BreweryTeam/TheBrewingProject | 2,146 | bukkit/src/main/java/dev/jsinco/brewery/bukkit/command/argument/EnumArgument.java | package dev.jsinco.brewery.bukkit.command.argument;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import dev.jsinco.brewery.bukkit.util.BukkitMessageUtil;
import io.papermc.paper.command.brigadier.argument.CustomArgumentType;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
public class EnumArgument<E extends Enum<E>> implements CustomArgumentType.Converted<E, String> {
private static final DynamicCommandExceptionType ERROR_INVALID_ENUM = new DynamicCommandExceptionType(event ->
BukkitMessageUtil.toBrigadier("tbp.command.illegal-argument-detailed", Placeholder.unparsed("arguments", event.toString()))
);
private final Class<E> eClass;
public EnumArgument(Class<E> eClass) {
this.eClass = eClass;
}
@Override
public E convert(String nativeType) throws CommandSyntaxException {
try {
return E.valueOf(eClass, nativeType.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
throw ERROR_INVALID_ENUM.create(nativeType);
}
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(@NotNull CommandContext<S> context, SuggestionsBuilder builder) {
Arrays.stream(eClass.getEnumConstants())
.map(E::name)
.map(name -> name.toLowerCase(Locale.ROOT))
.filter(enumConstant -> enumConstant.startsWith(builder.getRemainingLowerCase()))
.forEach(builder::suggest);
return builder.buildFuture();
}
@Override
public ArgumentType<String> getNativeType() {
return StringArgumentType.word();
}
}
| 1 | 0.863354 | 1 | 0.863354 | game-dev | MEDIA | 0.798585 | game-dev | 0.890863 | 1 | 0.890863 |
ProjectIgnis/CardScripts | 2,063 | rush/c160402037.lua | --ヴォイドヴェルグ・ゴッドレクイエム
--Voidvelg God Requiem
--Scripted by YoshiDuels
local s,id=GetID()
function s.initial_effect(c)
c:RegisterFlagEffect(FLAG_TRIPLE_TRIBUTE,0,0,1)
--Summon with 3 tribute
local e1=aux.AddNormalSummonProcedure(c,true,true,3,3,SUMMON_TYPE_TRIBUTE+1,aux.Stringid(id,0))
--Destroy all monsters your opponent controls
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetCondition(s.condition)
e2:SetCost(s.cost)
e2:SetTarget(s.target)
e2:SetOperation(s.operation)
c:RegisterEffect(e2)
end
function s.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsStatus(STATUS_SUMMON_TURN) and c:GetSummonType()==SUMMON_TYPE_TRIBUTE+1
end
function s.tdfilter(c)
return c:IsMonster() and c:IsAbleToDeckOrExtraAsCost()
end
function s.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.tdfilter,tp,LOCATION_GRAVE,0,5,nil) end
end
function s.desfilter(c)
return c:IsFaceup() and c:IsNotMaximumModeSide()
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.desfilter,tp,0,LOCATION_MZONE,1,nil) end
local g=Duel.GetMatchingGroup(Card.IsNotMaximumModeSide,tp,0,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,#g,0,0)
end
function s.operation(e,tp,eg,ep,ev,re,r,rp)
--Requirement
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,s.tdfilter,tp,LOCATION_GRAVE,0,5,5,nil)
Duel.HintSelection(g,true)
if Duel.SendtoDeck(g,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)<1 then return end
--Effect
local g1=Duel.GetMatchingGroup(s.desfilter,tp,0,LOCATION_MZONE,nil)
local sg=g1:GetMaxGroup(Card.GetLevel)
if Duel.Destroy(sg,REASON_EFFECT)>0 then
local g2=Duel.GetMatchingGroup(s.desfilter,tp,0,LOCATION_MZONE,nil)
local atk=g2:GetSum(Card.GetAttack)
if #g2>0 and atk>0 and Duel.SelectYesNo(tp,aux.Stringid(id,2)) then
Duel.Damage(1-tp,atk,REASON_EFFECT)
end
end
end | 1 | 0.910981 | 1 | 0.910981 | game-dev | MEDIA | 0.991148 | game-dev | 0.962225 | 1 | 0.962225 |
GodotVR/godot_arcore | 2,230 | plugin/src/main/cpp/arcore_wrapper.cpp | //
// Created by luca on 20.08.24.
//
#include "arcore_wrapper.h"
#include "utils.h"
JNIEnv *ARCoreWrapper::env = nullptr;
// Is this used?
jobject ARCoreWrapper::arcore_plugin_instance = nullptr;
jobject ARCoreWrapper::godot_instance = nullptr;
jobject ARCoreWrapper::activity = nullptr;
jclass ARCoreWrapper::godot_class = nullptr;
jclass ARCoreWrapper::activity_class = nullptr;
ARCoreWrapper::ARCoreWrapper() {}
ARCoreWrapper::~ARCoreWrapper() {}
void ARCoreWrapper::initialize_environment(JNIEnv *p_env, jobject p_activity) {
env = p_env;
activity = p_env->NewGlobalRef(p_activity);
// Get info about our Godot class to get pointers
godot_class = p_env->FindClass("org/godotengine/godot/Godot");
if (godot_class) {
godot_class = (jclass)p_env->NewGlobalRef(godot_class);
} else {
ALOGE("ARCorePlugin: Can't find org/godotengine/godot/Godot");
return;
}
activity_class = p_env->FindClass("android/app/Activity");
if (activity_class) {
activity_class = (jclass)p_env->NewGlobalRef(activity_class);
} else {
ALOGE("ARCorePlugin: Can't find android/app/Activity");
return;
}
}
void ARCoreWrapper::uninitialize_environment(JNIEnv *env) {
if (arcore_plugin_instance) {
ALOGV("ARCorePlugin: ARCore instance found.");
env->DeleteGlobalRef(arcore_plugin_instance);
arcore_plugin_instance = nullptr;
env->DeleteGlobalRef(godot_instance);
env->DeleteGlobalRef(godot_class);
env->DeleteGlobalRef(activity);
env->DeleteGlobalRef(activity_class);
}
}
JNIEnv *ARCoreWrapper::get_env() {
return env;
}
jobject ARCoreWrapper::get_godot_class() {
return godot_class;
}
jobject ARCoreWrapper::get_activity() {
return activity;
}
jobject ARCoreWrapper::get_global_context() {
jclass activityThread = env->FindClass("android/app/ActivityThread");
jmethodID currentActivityThread = env->GetStaticMethodID(activityThread, "currentActivityThread", "()Landroid/app/ActivityThread;");
jobject activityThreadObj = env->CallStaticObjectMethod(activityThread, currentActivityThread);
jmethodID getApplication = env->GetMethodID(activityThread, "getApplication", "()Landroid/app/Application;");
jobject context = env->CallObjectMethod(activityThreadObj, getApplication);
return context;
}
| 1 | 0.876212 | 1 | 0.876212 | game-dev | MEDIA | 0.772217 | game-dev | 0.697714 | 1 | 0.697714 |
oot-pc-port/oot-pc-port | 2,779 | asm/non_matchings/overlays/actors/ovl_En_Bigokuta/func_809BD84C.s | glabel func_809BD84C
/* 00BEC 809BD84C 27BDFFE0 */ addiu $sp, $sp, 0xFFE0 ## $sp = FFFFFFE0
/* 00BF0 809BD850 AFB00018 */ sw $s0, 0x0018($sp)
/* 00BF4 809BD854 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000
/* 00BF8 809BD858 AFBF001C */ sw $ra, 0x001C($sp)
/* 00BFC 809BD85C AFA50024 */ sw $a1, 0x0024($sp)
/* 00C00 809BD860 0C02927F */ jal SkelAnime_FrameUpdateMatrix
/* 00C04 809BD864 2484014C */ addiu $a0, $a0, 0x014C ## $a0 = 0000014C
/* 00C08 809BD868 860E0196 */ lh $t6, 0x0196($s0) ## 00000196
/* 00C0C 809BD86C 2401000D */ addiu $at, $zero, 0x000D ## $at = 0000000D
/* 00C10 809BD870 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 00C14 809BD874 25CFFFFF */ addiu $t7, $t6, 0xFFFF ## $t7 = FFFFFFFF
/* 00C18 809BD878 A60F0196 */ sh $t7, 0x0196($s0) ## 00000196
/* 00C1C 809BD87C 86020196 */ lh $v0, 0x0196($s0) ## 00000196
/* 00C20 809BD880 10410003 */ beq $v0, $at, .L809BD890
/* 00C24 809BD884 2401FFEC */ addiu $at, $zero, 0xFFEC ## $at = FFFFFFEC
/* 00C28 809BD888 54410005 */ bnel $v0, $at, .L809BD8A0
/* 00C2C 809BD88C 24010001 */ addiu $at, $zero, 0x0001 ## $at = 00000001
.L809BD890:
/* 00C30 809BD890 0C00BE0A */ jal Audio_PlayActorSound2
/* 00C34 809BD894 24053906 */ addiu $a1, $zero, 0x3906 ## $a1 = 00003906
/* 00C38 809BD898 86020196 */ lh $v0, 0x0196($s0) ## 00000196
/* 00C3C 809BD89C 24010001 */ addiu $at, $zero, 0x0001 ## $at = 00000001
.L809BD8A0:
/* 00C40 809BD8A0 54410004 */ bnel $v0, $at, .L809BD8B4
/* 00C44 809BD8A4 8618001C */ lh $t8, 0x001C($s0) ## 0000001C
/* 00C48 809BD8A8 0C03D6B3 */ jal func_800F5ACC
/* 00C4C 809BD8AC 24040038 */ addiu $a0, $zero, 0x0038 ## $a0 = 00000038
/* 00C50 809BD8B0 8618001C */ lh $t8, 0x001C($s0) ## 0000001C
.L809BD8B4:
/* 00C54 809BD8B4 24010001 */ addiu $at, $zero, 0x0001 ## $at = 00000001
/* 00C58 809BD8B8 57010004 */ bnel $t8, $at, .L809BD8CC
/* 00C5C 809BD8BC 8FBF001C */ lw $ra, 0x001C($sp)
/* 00C60 809BD8C0 0C26F4DC */ jal func_809BD370
/* 00C64 809BD8C4 02002025 */ or $a0, $s0, $zero ## $a0 = 00000000
/* 00C68 809BD8C8 8FBF001C */ lw $ra, 0x001C($sp)
.L809BD8CC:
/* 00C6C 809BD8CC 8FB00018 */ lw $s0, 0x0018($sp)
/* 00C70 809BD8D0 27BD0020 */ addiu $sp, $sp, 0x0020 ## $sp = 00000000
/* 00C74 809BD8D4 03E00008 */ jr $ra
/* 00C78 809BD8D8 00000000 */ nop
| 1 | 0.771559 | 1 | 0.771559 | game-dev | MEDIA | 0.660769 | game-dev | 0.575263 | 1 | 0.575263 |
elmi2305/Nightmare-Mode-CE-3.x | 7,440 | src/main/java/com/itlesports/nightmaremode/block/tileEntities/TileEntitySteelLocker.java | package com.itlesports.nightmaremode.block.tileEntities;
import btw.util.sounds.BTWSoundManager;
import com.itlesports.nightmaremode.block.blocks.BlockSteelLocker;
import com.itlesports.nightmaremode.rendering.ContainerSteelLocker;
import net.minecraft.src.*;
public class TileEntitySteelLocker extends TileEntity implements IInventory {
public static final int SLOT_COLS = 19;
public static final int SLOT_ROWS = 7;
public static final int SLOT_TOTAL = SLOT_COLS * SLOT_ROWS;
public float lidAngle;
public float prevLidAngle;
public int numUsingPlayers;
private int ticksSinceSync;
private int cachedChestType = -1;
private String customName;
private ItemStack[] chestContents = new ItemStack[SLOT_TOTAL];
@Override public int getSizeInventory() { return SLOT_TOTAL; }
@Override public ItemStack getStackInSlot(int i) { return chestContents[i]; }
@Override
public ItemStack decrStackSize(int i, int count) {
if (chestContents[i] != null) {
ItemStack ret;
if (chestContents[i].stackSize <= count) {
ret = chestContents[i];
chestContents[i] = null;
} else {
ret = chestContents[i].splitStack(count);
if (chestContents[i].stackSize == 0) chestContents[i] = null;
}
onInventoryChanged();
return ret;
}
return null;
}
@Override
public ItemStack getStackInSlotOnClosing(int i) {
if (chestContents[i] != null) {
ItemStack s = chestContents[i];
chestContents[i] = null;
return s;
}
return null;
}
@Override
public void setInventorySlotContents(int i, ItemStack stack) {
chestContents[i] = stack;
if (stack != null && stack.stackSize > getInventoryStackLimit())
stack.stackSize = getInventoryStackLimit();
onInventoryChanged();
}
@Override
public String getInvName() {
return isInvNameLocalized() ? customName : "container.steelLocker";
}
@Override
public boolean isInvNameLocalized() {
return customName != null && !customName.isEmpty();
}
public void setChestGuiName(String name) {
this.customName = name;
}
@Override
public int getInventoryStackLimit() { return 64; }
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return worldObj.getBlockTileEntity(xCoord,yCoord,zCoord) == this &&
player.getDistanceSq(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5) <= 64D;
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack stack) { return true; }
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
chestContents = new ItemStack[SLOT_TOTAL];
if (nbt.hasKey("CustomName"))
customName = nbt.getString("CustomName");
NBTTagList list = nbt.getTagList("Items");
for (int i=0;i<list.tagCount();i++) {
NBTTagCompound tag = (NBTTagCompound)list.tagAt(i);
int slot = tag.getByte("Slot") & 255;
if (slot < chestContents.length) {
chestContents[slot] = ItemStack.loadItemStackFromNBT(tag);
}
}
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
NBTTagList list = new NBTTagList();
for (int i=0;i<chestContents.length;i++) {
if (chestContents[i] != null) {
NBTTagCompound tag = new NBTTagCompound();
tag.setByte("Slot",(byte)i);
chestContents[i].writeToNBT(tag);
list.appendTag(tag);
}
}
nbt.setTag("Items", list);
if (isInvNameLocalized()) nbt.setString("CustomName", customName);
}
@Override
public void onInventoryChanged() {
super.onInventoryChanged();
if (worldObj != null) {
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}
@Override
public void updateEntity() {
super.updateEntity();
++ticksSinceSync;
if (!worldObj.isRemote && numUsingPlayers != 0 &&
(ticksSinceSync + xCoord + yCoord + zCoord) % 200 == 0) {
numUsingPlayers = 0;
float range = 5F;
for (Object o : worldObj.getEntitiesWithinAABB(
EntityPlayer.class,
AxisAlignedBB.getAABBPool().getAABB(
xCoord - range, yCoord - range, zCoord - range,
xCoord + 1 + range, yCoord + 1 + range, zCoord + 1 + range))) {
EntityPlayer p = (EntityPlayer)o;
if (p.openContainer instanceof ContainerSteelLocker cont) {
if (cont.getChestInventory() == this) ++numUsingPlayers;
}
}
}
prevLidAngle = lidAngle;
float speed = 0.1F;
if (numUsingPlayers > 0 && lidAngle == 0F) {
worldObj.playSoundEffect(
xCoord + 0.5, yCoord + 0.5, zCoord + 0.5,
BTWSoundManager.CHEST_OPEN.sound(),
0.5F,
worldObj.rand.nextFloat()*0.1F + 0.9F);
}
if ((numUsingPlayers == 0 && lidAngle > 0F) || (numUsingPlayers > 0 && lidAngle < 1F)) {
float prev = lidAngle;
if (numUsingPlayers > 0) lidAngle += speed;
else lidAngle -= speed;
if (lidAngle > 1F) lidAngle = 1F;
if (lidAngle < 0.5F && prev >= 0.5F) {
worldObj.playSoundEffect(
xCoord + 0.5, yCoord + 0.5, zCoord + 0.5,
BTWSoundManager.CHEST_CLOSE.sound(),
0.5F,
worldObj.rand.nextFloat()*0.1F + 0.9F);
}
if (lidAngle < 0F) lidAngle = 0F;
}
}
@Override
public boolean receiveClientEvent(int id, int value) {
if (id == 1) {
numUsingPlayers = value;
return true;
}
return super.receiveClientEvent(id,value);
}
public void openChest() {
if (numUsingPlayers < 0) numUsingPlayers = 0;
++numUsingPlayers;
worldObj.addBlockEvent(xCoord,yCoord,zCoord,getBlockType().blockID,1,numUsingPlayers);
worldObj.notifyBlocksOfNeighborChange(xCoord,yCoord,zCoord,getBlockType().blockID);
worldObj.notifyBlocksOfNeighborChange(xCoord,yCoord-1,zCoord,getBlockType().blockID);
}
public void closeChest() {
if (getBlockType() instanceof BlockSteelLocker) {
--numUsingPlayers;
worldObj.addBlockEvent(xCoord,yCoord,zCoord,getBlockType().blockID,1,numUsingPlayers);
worldObj.notifyBlocksOfNeighborChange(xCoord,yCoord,zCoord,getBlockType().blockID);
worldObj.notifyBlocksOfNeighborChange(xCoord,yCoord-1,zCoord,getBlockType().blockID);
}
}
public int getChestType() {
if (cachedChestType == -1) {
if (getBlockType() instanceof BlockSteelLocker b) cachedChestType = b.chestType;
else cachedChestType = 0;
}
return cachedChestType;
}
public void clearContents() {
for (int i=0;i<getSizeInventory();i++) chestContents[i] = null;
onInventoryChanged();
}
} | 1 | 0.908192 | 1 | 0.908192 | game-dev | MEDIA | 0.902488 | game-dev | 0.992543 | 1 | 0.992543 |
Stefanuk12/ROBLOX | 8,339 | Universal/Aiming/NPC.lua | if (getgenv().AimingNPC) then
return getgenv().AimingNPC
end
-- // Services
local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local GuiService = game:GetService("GuiService")
local RunService = game:GetService("RunService")
-- // Vars
local Heartbeat = RunService.Heartbeat
local LocalPlayer = Players.LocalPlayer
local CurrentCamera = Workspace.CurrentCamera
local Mouse = LocalPlayer:GetMouse()
-- // Optimisation Vars (ugly)
local Drawingnew = Drawing.new
local Color3fromRGB = Color3.fromRGB
local Vector2new = Vector2.new
local GetGuiInset = GuiService.GetGuiInset
local Randomnew = Random.new
local mathfloor = math.floor
local CharacterAdded = LocalPlayer.CharacterAdded
local CharacterAddedWait = CharacterAdded.Wait
local WorldToViewportPoint = CurrentCamera.WorldToViewportPoint
local RaycastParamsnew = RaycastParams.new
local EnumRaycastFilterTypeBlacklist = Enum.RaycastFilterType.Blacklist
local Raycast = Workspace.Raycast
local Instancenew = Instance.new
local IsDescendantOf = Instancenew("Part").IsDescendantOf
local FindFirstChildWhichIsA = Instancenew("Part").FindFirstChildWhichIsA
local FindFirstChild = Instancenew("Part").FindFirstChild
-- // Silent Aim Vars
local AimingNPC = {
Enabled = true,
ShowFOV = true,
FOV = 60,
FOVSides = 12,
FOVColour = Color3fromRGB(231, 84, 128),
VisibleCheck = true,
HitChance = 100,
Selected = nil,
SelectedPart = nil,
TargetPart = {"Head", "HumanoidRootPart"},
RaycastIgnore = nil
}
getgenv().AimingNPC = AimingNPC
-- // Create circle
local circle = Drawingnew("Circle")
circle.Transparency = 1
circle.Thickness = 2
circle.Color = AimingNPC.FOVColour
circle.Filled = false
AimingNPC.FOVCircle = circle
-- // Update
function AimingNPC.UpdateFOV()
-- // Make sure the circle exists
if not (circle) then
return
end
-- // Set Circle Properties
circle.Visible = AimingNPC.ShowFOV
circle.Radius = (AimingNPC.FOV * 3)
circle.Position = Vector2new(Mouse.X, Mouse.Y + GetGuiInset(GuiService).Y)
circle.NumSides = AimingNPC.FOVSides
circle.Color = AimingNPC.FOVColour
-- // Return circle
return circle
end
-- // Custom Functions
local CalcChance = function(percentage)
-- // Floor the percentage
percentage = mathfloor(percentage)
-- // Get the chance
local chance = mathfloor(Randomnew().NextNumber(Randomnew(), 0, 1) * 100) / 100
-- // Return
return chance <= percentage / 100
end
-- // Customisable Checking Functions: Is a part visible
function AimingNPC.IsPartVisible(Part, PartDescendant)
-- // Vars
local Character = LocalPlayer.Character or CharacterAddedWait(CharacterAdded)
local Origin = CurrentCamera.CFrame.Position
local _, OnScreen = WorldToViewportPoint(CurrentCamera, Part.Position)
-- //
if (OnScreen) then
-- // Vars
local raycastParams = RaycastParamsnew()
raycastParams.FilterType = EnumRaycastFilterTypeBlacklist
-- // Raycast Ignore
raycastParams.FilterDescendantsInstances = AimingNPC.RaycastIgnore or {Character, CurrentCamera}
-- // Cast ray
local Result = Raycast(Workspace, Origin, Part.Position - Origin, raycastParams)
-- // Make sure we get a result
if (Result) then
-- // Vars
local PartHit = Result.Instance
local Visible = (not PartHit or IsDescendantOf(PartHit, PartDescendant))
-- // Return
return Visible
end
end
-- // Return
return false
end
-- // Get the Direction, Normal and Material
function AimingNPC.Raycast(Origin, Destination, UnitMultiplier)
if (typeof(Origin) == "Vector3" and typeof(Destination) == "Vector3") then
-- // Handling
if (not UnitMultiplier) then UnitMultiplier = 1 end
-- // Vars
local Direction = (Destination - Origin).Unit * UnitMultiplier
local Result = Raycast(Workspace, Origin, Direction)
-- // Make sure we have a result
if (Result) then
local Normal = Result.Normal
local Material = Result.Material
return Direction, Normal, Material
end
end
-- // Return
return nil
end
-- // Check Health
function AimingNPC.CheckHealth(NPC)
-- // Get Humanoid
local Humanoid = FindFirstChildWhichIsA(NPC, "Humanoid")
-- // Get Health
local Health = (Humanoid and Humanoid.Health or 0)
-- //
return Health > 0
end
-- // Check if has target and is enabled
function AimingNPC.Check()
return (AimingNPC.Enabled == true and AimingNPC.Selected and AimingNPC.SelectedPart)
end
-- // Get Closest Target Part
function AimingNPC.GetClosestTargetPartToCursor(NPC)
local TargetParts = AimingNPC.TargetPart
-- // Vars
local ClosestPart = nil
local ClosestPartPosition = nil
local ClosestPartOnScreen = false
local ClosestPartMagnitudeFromMouse = nil
local ShortestDistance = 1/0
-- //
local function CheckTargetPart(TargetPart)
-- // Convert string -> Instance
if (typeof(TargetPart) == "string") then
TargetPart = FindFirstChild(NPC, TargetPart)
end
-- // Make sure we have a target
if not (TargetPart) then
return
end
-- // Get the length between Mouse and Target Part (on screen)
local PartPos, onScreen = WorldToViewportPoint(CurrentCamera, TargetPart.Position)
local GuiInset = GetGuiInset(GuiService)
local Magnitude = (Vector2new(PartPos.X, PartPos.Y - GuiInset.Y) - Vector2new(Mouse.X, Mouse.Y)).Magnitude
-- //
if (Magnitude < ShortestDistance) then
ClosestPart = TargetPart
ClosestPartPosition = PartPos
ClosestPartOnScreen = onScreen
ClosestPartMagnitudeFromMouse = Magnitude
ShortestDistance = Magnitude
end
end
-- // String check
if (typeof(TargetParts) == "string") then
-- // Check if it all
if (TargetParts == "All") then
-- // Loop through NPC children
for _, v in ipairs(NPC:GetChildren()) do
-- // See if it a part
if not (v:IsA("BasePart")) then
continue
end
-- // Check it
CheckTargetPart(v)
end
else
-- // Individual
CheckTargetPart(TargetParts)
end
end
-- //
if (typeof(TargetParts) == "table") then
-- // Loop through all target parts and check them
for _, TargetPartName in ipairs(TargetParts) do
CheckTargetPart(TargetPartName)
end
end
-- //
return ClosestPart, ClosestPartPosition, ClosestPartOnScreen, ClosestPartMagnitudeFromMouse
end
-- // Returns all of the NPCs to target
function AimingNPC.GetNPCs()
return {} --Workspace.NPCs:GetChildren()
end
-- //
function AimingNPC.GetClosestNPCToCursor()
-- // Vars
local TargetPart = nil
local ClosestNPC = nil
local Chance = CalcChance(AimingNPC.HitChance)
local ShortestDistance = 1/0
-- // Chance
if (not Chance) then
AimingNPC.Selected = nil
AimingNPC.SelectedPart = nil
return nil
end
-- // Loop through all NPCs
for _, NPC in ipairs(AimingNPC.GetNPCs()) do
-- // Vars
local TargetPartTemp, _, _, Magnitude = AimingNPC.GetClosestTargetPartToCursor(NPC)
-- // Check if part exists and health
if (TargetPartTemp and AimingNPC.CheckHealth(NPC)) then
-- // Check if is in FOV
if (circle.Radius > Magnitude and Magnitude < ShortestDistance) then
-- // Check if Visible
if (AimingNPC.VisibleCheck and not AimingNPC.IsPartVisible(TargetPartTemp, NPC)) then continue end
-- // Set vars
ClosestNPC = NPC
ShortestDistance = Magnitude
TargetPart = TargetPartTemp
end
end
end
-- // End
AimingNPC.Selected = ClosestNPC
AimingNPC.SelectedPart = TargetPart
end
-- // Heartbeat Function
Heartbeat:Connect(function()
AimingNPC.UpdateFOV()
AimingNPC.GetClosestNPCToCursor()
end)
-- //
return AimingNPC | 1 | 0.946759 | 1 | 0.946759 | game-dev | MEDIA | 0.970634 | game-dev | 0.935494 | 1 | 0.935494 |
HbmMods/Hbm-s-Nuclear-Tech-GIT | 8,087 | src/main/java/com/hbm/tileentity/machine/TileEntityCoreStabilizer.java | package com.hbm.tileentity.machine;
import com.hbm.handler.CompatHandler;
import com.hbm.inventory.container.ContainerCoreStabilizer;
import com.hbm.inventory.gui.GUICoreStabilizer;
import com.hbm.items.ModItems;
import com.hbm.items.machine.ItemLens;
import com.hbm.tileentity.IGUIProvider;
import com.hbm.tileentity.TileEntityMachineBase;
import com.hbm.util.CompatEnergyControl;
import api.hbm.energymk2.IEnergyReceiverMK2;
import api.hbm.redstoneoverradio.IRORInteractive;
import api.hbm.redstoneoverradio.IRORValueProvider;
import api.hbm.tile.IInfoProviderEC;
import cpw.mods.fml.common.Optional;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import li.cil.oc.api.machine.Arguments;
import li.cil.oc.api.machine.Callback;
import li.cil.oc.api.machine.Context;
import li.cil.oc.api.network.SimpleComponent;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
@Optional.InterfaceList({@Optional.Interface(iface = "li.cil.oc.api.network.SimpleComponent", modid = "OpenComputers")})
public class TileEntityCoreStabilizer extends TileEntityMachineBase implements IEnergyReceiverMK2, SimpleComponent, IGUIProvider, IInfoProviderEC, CompatHandler.OCComponent, IRORValueProvider, IRORInteractive {
public long power;
public static final long maxPower = 2500000000L;
public int watts;
public int beam;
public static final int range = 15;
public TileEntityCoreStabilizer() {
super(1);
}
@Override
public String getName() {
return "container.dfcStabilizer";
}
@Override
public void updateEntity() {
if(!worldObj.isRemote) {
this.updateConnections();
watts = MathHelper.clamp_int(watts, 1, 100);
int demand = (int) Math.pow(watts, 4);
beam = 0;
if(power >= demand && slots[0] != null && slots[0].getItem() == ModItems.ams_lens && ItemLens.getLensDamage(slots[0]) < ((ItemLens)ModItems.ams_lens).maxDamage) {
ForgeDirection dir = ForgeDirection.getOrientation(this.getBlockMetadata());
for(int i = 1; i <= range; i++) {
int x = xCoord + dir.offsetX * i;
int y = yCoord + dir.offsetY * i;
int z = zCoord + dir.offsetZ * i;
TileEntity te = worldObj.getTileEntity(x, y, z);
if(te instanceof TileEntityCore) {
TileEntityCore core = (TileEntityCore)te;
core.field = Math.max(core.field, watts);
this.power -= demand;
beam = i;
long dmg = ItemLens.getLensDamage(slots[0]);
dmg += watts;
if(dmg >= ((ItemLens)ModItems.ams_lens).maxDamage)
slots[0] = null;
else
ItemLens.setLensDamage(slots[0], dmg);
break;
}
if(!worldObj.getBlock(x, y, z).isAir(worldObj, x, y, z))
break;
}
}
this.networkPackNT(250);
}
}
private void updateConnections() {
for(ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS)
this.trySubscribe(worldObj, xCoord + dir.offsetX, yCoord + dir.offsetY, zCoord + dir.offsetZ, dir);
}
@Override
public void serialize(ByteBuf buf) {
super.serialize(buf);
buf.writeLong(power);
buf.writeInt(watts);
buf.writeInt(beam);
}
@Override
public void deserialize(ByteBuf buf) {
super.deserialize(buf);
this.power = buf.readLong();
this.watts = buf.readInt();
this.beam = buf.readInt();
}
public long getPowerScaled(long i) {
return (power * i) / maxPower;
}
public int getWattsScaled(int i) {
return (watts * i) / 100;
}
@Override
public void setPower(long i) {
this.power = i;
}
@Override
public long getPower() {
return this.power;
}
@Override
public long getMaxPower() {
return this.maxPower;
}
@Override
public boolean canConnect(ForgeDirection dir) {
return dir != ForgeDirection.UNKNOWN;
}
@Override
public AxisAlignedBB getRenderBoundingBox() {
return TileEntity.INFINITE_EXTENT_AABB;
}
@Override
@SideOnly(Side.CLIENT)
public double getMaxRenderDistanceSquared() {
return 65536.0D;
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
power = nbt.getLong("power");
watts = nbt.getInteger("watts");
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
nbt.setLong("power", power);
nbt.setInteger("watts", watts);
}
// do some opencomputer stuff
@Override
@Optional.Method(modid = "OpenComputers")
public String getComponentName() {
return "dfc_stabilizer";
}
@Callback(direct = true)
@Optional.Method(modid = "OpenComputers")
public Object[] getEnergyInfo(Context context, Arguments args) {
return new Object[] {getPower(), getMaxPower()};
}
@Callback(direct = true)
@Optional.Method(modid = "OpenComputers")
public Object[] getInput(Context context, Arguments args) {
return new Object[] {watts};
}
@Callback(direct = true)
@Optional.Method(modid = "OpenComputers")
public Object[] getDurability(Context context, Arguments args) {
if(slots[0] != null && slots[0].getItem() == ModItems.ams_lens && ItemLens.getLensDamage(slots[0]) < ((ItemLens)ModItems.ams_lens).maxDamage) {
return new Object[] {ItemLens.getLensDamage(slots[0])};
}
return new Object[] {"N/A"};
}
@Callback(direct = true)
@Optional.Method(modid = "OpenComputers")
public Object[] getInfo(Context context, Arguments args) {
Object lens_damage_buf;
if(slots[0] != null && slots[0].getItem() == ModItems.ams_lens && ItemLens.getLensDamage(slots[0]) < ((ItemLens)ModItems.ams_lens).maxDamage) {
lens_damage_buf = ItemLens.getLensDamage(slots[0]);
} else {
lens_damage_buf = "N/A";
}
return new Object[] {power, maxPower, watts, lens_damage_buf};
}
@Callback(direct = true, limit = 4)
@Optional.Method(modid = "OpenComputers")
public Object[] setInput(Context context, Arguments args) {
int newOutput = args.checkInteger(0);
watts = MathHelper.clamp_int(newOutput, 0, 100);
return new Object[] {};
}
@Override
public Container provideContainer(int ID, EntityPlayer player, World world, int x, int y, int z) {
return new ContainerCoreStabilizer(player.inventory, this);
}
@Override
@SideOnly(Side.CLIENT)
public Object provideGUI(int ID, EntityPlayer player, World world, int x, int y, int z) {
return new GUICoreStabilizer(player.inventory, this);
}
@Override
public void provideExtraInfo(NBTTagCompound data) {
int demand = (int) Math.pow(watts, 4);
long damage = ItemLens.getLensDamage(slots[0]);
ItemLens lens = (ItemLens) com.hbm.items.ModItems.ams_lens;
if(getPower() >= demand && slots[0] != null && slots[0].getItem() == lens && damage < 432000000L)
data.setDouble(CompatEnergyControl.D_CONSUMPTION_HE, demand);
else
data.setDouble(CompatEnergyControl.D_CONSUMPTION_HE, 0);
}
@Override
public String[] getFunctionInfo() {
return new String[] {
PREFIX_VALUE + "durability",
PREFIX_VALUE + "durabilitypercent",
PREFIX_FUNCTION + "setpower" + NAME_SEPARATOR + "percent",
};
}
@Override
public String provideRORValue(String name) {
if((PREFIX_VALUE + "durability").equals(name)) return (slots[0] != null && slots[0].getItem() == ModItems.ams_lens) ? "" + (((ItemLens) slots[0].getItem()).maxDamage - ItemLens.getLensDamage(slots[0])) : "0";
if((PREFIX_VALUE + "durabilitypercent").equals(name)) return (slots[0] != null && slots[0].getItem() == ModItems.ams_lens) ? "" + ((((ItemLens) slots[0].getItem()).maxDamage - ItemLens.getLensDamage(slots[0])) * 100 / ((ItemLens) slots[0].getItem()).maxDamage) : "0";
return null;
}
@Override
public String runRORFunction(String name, String[] params) {
if((PREFIX_FUNCTION + "setpower").equals(name) && params.length > 0) {
int watts = IRORInteractive.parseInt(params[0], 0, 100);
this.watts = watts;
this.markChanged();
return null;
}
return null;
}
}
| 1 | 0.971372 | 1 | 0.971372 | game-dev | MEDIA | 0.849067 | game-dev | 0.951685 | 1 | 0.951685 |
Mercy-Collective/mercy-framework | 5,952 | Mercy-VoiceServer/resources/[CFX]/[gameplay]/playernames/playernames_cl.lua | local mpGamerTags = {}
local mpGamerTagSettings = {}
local gtComponent = {
GAMER_NAME = 0,
CREW_TAG = 1,
healthArmour = 2,
BIG_TEXT = 3,
AUDIO_ICON = 4,
MP_USING_MENU = 5,
MP_PASSIVE_MODE = 6,
WANTED_STARS = 7,
MP_DRIVER = 8,
MP_CO_DRIVER = 9,
MP_TAGGED = 10,
GAMER_NAME_NEARBY = 11,
ARROW = 12,
MP_PACKAGES = 13,
INV_IF_PED_FOLLOWING = 14,
RANK_TEXT = 15,
MP_TYPING = 16
}
local function makeSettings()
return {
alphas = {},
colors = {},
healthColor = false,
toggles = {},
wantedLevel = false
}
end
local templateStr
function updatePlayerNames()
-- re-run this function the next frame
SetTimeout(0, updatePlayerNames)
-- return if no template string is set
if not templateStr then
return
end
-- get local coordinates to compare to
local localCoords = GetEntityCoords(PlayerPedId())
-- for each valid player index
for _, i in ipairs(GetActivePlayers()) do
-- if the player exists
if i ~= PlayerId() then
-- get their ped
local ped = GetPlayerPed(i)
local pedCoords = GetEntityCoords(ped)
-- make a new settings list if needed
if not mpGamerTagSettings[i] then
mpGamerTagSettings[i] = makeSettings()
end
-- check the ped, because changing player models may recreate the ped
-- also check gamer tag activity in case the game deleted the gamer tag
if not mpGamerTags[i] or mpGamerTags[i].ped ~= ped or not IsMpGamerTagActive(mpGamerTags[i].tag) then
local nameTag = formatPlayerNameTag(i, templateStr)
-- remove any existing tag
if mpGamerTags[i] then
RemoveMpGamerTag(mpGamerTags[i].tag)
end
-- store the new tag
mpGamerTags[i] = {
tag = CreateMpGamerTag(GetPlayerPed(i), nameTag, false, false, '', 0),
ped = ped
}
end
-- store the tag in a local
local tag = mpGamerTags[i].tag
-- should the player be renamed? this is set by events
if mpGamerTagSettings[i].rename then
SetMpGamerTagName(tag, formatPlayerNameTag(i, templateStr))
mpGamerTagSettings[i].rename = nil
end
-- check distance
local distance = #(pedCoords - localCoords)
-- show/hide based on nearbyness/line-of-sight
-- nearby checks are primarily to prevent a lot of LOS checks
if distance < 250 and HasEntityClearLosToEntity(PlayerPedId(), ped, 17) then
SetMpGamerTagVisibility(tag, gtComponent.GAMER_NAME, true)
SetMpGamerTagVisibility(tag, gtComponent.healthArmour, IsPlayerTargettingEntity(PlayerId(), ped))
SetMpGamerTagVisibility(tag, gtComponent.AUDIO_ICON, NetworkIsPlayerTalking(i))
SetMpGamerTagAlpha(tag, gtComponent.AUDIO_ICON, 255)
SetMpGamerTagAlpha(tag, gtComponent.healthArmour, 255)
-- override settings
local settings = mpGamerTagSettings[i]
for k, v in pairs(settings.toggles) do
SetMpGamerTagVisibility(tag, gtComponent[k], v)
end
for k, v in pairs(settings.alphas) do
SetMpGamerTagAlpha(tag, gtComponent[k], v)
end
for k, v in pairs(settings.colors) do
SetMpGamerTagColour(tag, gtComponent[k], v)
end
if settings.wantedLevel then
SetMpGamerTagWantedLevel(tag, settings.wantedLevel)
end
if settings.healthColor then
SetMpGamerTagHealthBarColour(tag, settings.healthColor)
end
else
SetMpGamerTagVisibility(tag, gtComponent.GAMER_NAME, false)
SetMpGamerTagVisibility(tag, gtComponent.healthArmour, false)
SetMpGamerTagVisibility(tag, gtComponent.AUDIO_ICON, false)
end
elseif mpGamerTags[i] then
RemoveMpGamerTag(mpGamerTags[i].tag)
mpGamerTags[i] = nil
end
end
end
local function getSettings(id)
local i = GetPlayerFromServerId(tonumber(id))
if not mpGamerTagSettings[i] then
mpGamerTagSettings[i] = makeSettings()
end
return mpGamerTagSettings[i]
end
RegisterNetEvent('playernames:configure')
AddEventHandler('playernames:configure', function(id, key, ...)
local args = table.pack(...)
if key == 'tglc' then
getSettings(id).toggles[args[1]] = args[2]
elseif key == 'seta' then
getSettings(id).alphas[args[1]] = args[2]
elseif key == 'setc' then
getSettings(id).colors[args[1]] = args[2]
elseif key == 'setw' then
getSettings(id).wantedLevel = args[1]
elseif key == 'sehc' then
getSettings(id).healthColor = args[1]
elseif key == 'rnme' then
getSettings(id).rename = true
elseif key == 'name' then
getSettings(id).serverName = args[1]
getSettings(id).rename = true
elseif key == 'tpl' then
for _, v in pairs(mpGamerTagSettings) do
v.rename = true
end
templateStr = args[1]
end
end)
AddEventHandler('playernames:extendContext', function(i, cb)
cb('serverName', getSettings(GetPlayerServerId(i)).serverName)
end)
AddEventHandler('onResourceStop', function(name)
if name == GetCurrentResourceName() then
for _, v in pairs(mpGamerTags) do
RemoveMpGamerTag(v.tag)
end
end
end)
SetTimeout(0, function()
TriggerServerEvent('playernames:init')
end)
-- run this function every frame
SetTimeout(0, updatePlayerNames)
| 1 | 0.929051 | 1 | 0.929051 | game-dev | MEDIA | 0.927321 | game-dev | 0.977199 | 1 | 0.977199 |
RavenProject/Ravencoin | 23,459 | src/rpc/rewards.cpp | // Copyright (c) 2019-2020 The Raven Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assets/assets.h"
#include "assets/assetdb.h"
#include "assets/messages.h"
#include <map>
#include "tinyformat.h"
#include <boost/algorithm/string.hpp>
#include "amount.h"
#include "base58.h"
#include "chain.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "httpserver.h"
#include "validation.h"
#include "net.h"
#include "policy/feerate.h"
#include "policy/fees.h"
#include "policy/policy.h"
#include "policy/rbf.h"
#include "rpc/mining.h"
#include "rpc/safemode.h"
#include "rpc/server.h"
#include "script/sign.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
#include "wallet/coincontrol.h"
#include "wallet/feebumper.h"
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
#include "assets/snapshotrequestdb.h"
#include "assets/assetsnapshotdb.h"
#ifdef ENABLE_WALLET
//// Collect information about transactions that are pending commit
//struct PendingTransaction
//{
// std::string id;
// std::shared_ptr<CWalletTx> ptr;
// std::shared_ptr<CReserveKey> reserveKey;
// std::shared_ptr<UniValue> result;
// CAmount fee;
// CAmount totalAmt;
// std::vector<OwnerAndAmount> payments;
//
// PendingTransaction(
// const std::string & p_txnID,
// std::shared_ptr<CWalletTx> p_txnPtr,
// std::shared_ptr<CReserveKey> p_reserveKey,
// std::shared_ptr<UniValue> p_result,
// CAmount p_txnFee,
// CAmount p_txnAmount,
// std::vector<OwnerAndAmount> & p_payments
// )
// {
// id = p_txnID;
// ptr = p_txnPtr;
// reserveKey = p_reserveKey;
// result = p_result;
// fee = p_txnFee;
// totalAmt = p_txnAmount;
// payments = std::move(p_payments);
// }
//};
UniValue requestsnapshot(const JSONRPCRequest& request) {
if (request.fHelp || request.params.size() < 2)
throw std::runtime_error(
"requestsnapshot \"asset_name\" block_height\n"
"\nSchedules a snapshot of the specified asset at the specified block height.\n"
"\nArguments:\n"
"1. \"asset_name\" (string, required) The asset name for which the snapshot will be taken\n"
"2. \"block_height\" (number, required) The block height at which the snapshot will be take\n"
"\nResult:\n"
"{\n"
" request_status: \"Added\",\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("requestsnapshot", "\"TRONCO\" 12345")
+ HelpExampleRpc("requestsnapshot", "\"PHATSTACKS\" 34987")
);
if (!fAssetIndex) {
return "_This rpc call is not functional unless -assetindex is enabled. To enable, please run the wallet with -assetindex, this will require a reindex to occur";
}
// Extract parameters
std::string asset_name = request.params[0].get_str();
int block_height = request.params[1].get_int();
AssetType ownershipAssetType;
if (!IsAssetNameValid(asset_name, ownershipAssetType))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid asset_name: Please use a valid asset name"));
if (ownershipAssetType == AssetType::UNIQUE || ownershipAssetType == AssetType::OWNER || ownershipAssetType == AssetType::MSGCHANNEL)
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid asset_name: OWNER, UNQIUE, MSGCHANNEL assets are not allowed for this call"));
auto currentActiveAssetCache = GetCurrentAssetCache();
if (!currentActiveAssetCache)
return "_Couldn't get current asset cache.";
CNewAsset asset;
if (!currentActiveAssetCache->GetAssetMetaDataIfExists(asset_name, asset))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid asset_name: asset does not exist."));
if (block_height <= chainActive.Height()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid block_height: block height should be greater than current active chain height"));
}
if (!pSnapshotRequestDb)
throw JSONRPCError(RPC_DATABASE_ERROR, std::string("Snapshot Request database is not setup. Please restart wallet to try again"));
// Build our snapshot request record for scheduling
if (pSnapshotRequestDb->ScheduleSnapshot(asset_name, block_height)) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("request_status", "Added"));
return obj;
}
throw JSONRPCError(RPC_MISC_ERROR, std::string("Failed to add requested snapshot to database"));
}
UniValue getsnapshotrequest(const JSONRPCRequest& request) {
if (request.fHelp || request.params.size() < 2)
throw std::runtime_error(
"getsnapshotrequest \"asset_name\" block_height\n"
"\nRetrieves the specified snapshot request details.\n"
"\nArguments:\n"
"1. \"asset_name\" (string, required) The asset name for which the snapshot will be taken\n"
"2. \"block_height\" (number, required) The block height at which the snapshot will be take\n"
"\nResult:\n"
"{\n"
" asset_name: (string),\n"
" block_height: (number),\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getsnapshotrequest", "\"TRONCO\" 12345")
+ HelpExampleRpc("getsnapshotrequest", "\"PHATSTACKS\" 34987")
);
if (!fAssetIndex) {
return "_This rpc call is not functional unless -assetindex is enabled. To enable, please run the wallet with -assetindex, this will require a reindex to occur";
}
// Extract parameters
std::string asset_name = request.params[0].get_str();
int block_height = request.params[1].get_int();
if (!pSnapshotRequestDb)
throw JSONRPCError(RPC_DATABASE_ERROR, std::string("Snapshot Request database is not setup. Please restart wallet to try again"));
// Retrieve the specified snapshot request
CSnapshotRequestDBEntry snapshotRequest;
if (pSnapshotRequestDb->RetrieveSnapshotRequest(asset_name, block_height, snapshotRequest)) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("asset_name", snapshotRequest.assetName));
obj.push_back(Pair("block_height", snapshotRequest.heightForSnapshot));
return obj;
}
else {
LogPrint(BCLog::REWARDS, "Failed to retrieve specified snapshot request for asset '%s' at height %d!\n",
asset_name.c_str(), block_height);
}
throw JSONRPCError(RPC_MISC_ERROR, std::string("Failed to retrieve specified snapshot request"));
}
UniValue listsnapshotrequests(const JSONRPCRequest& request) {
if (request.fHelp || request.params.size() > 2)
throw std::runtime_error(
"listsnapshotrequests [\"asset_name\" [block_height]]\n"
"\nList snapshot request details.\n"
"\nArguments:\n"
"asset_name: (string, optional) List only requests for a specific asset (default is \"\" for ALL)\n"
"block_height: (number, optional) List only requests for a particular block height (default is 0 for ALL)\n"
"\nResult:\n"
"[\n"
" {\n"
" asset_name: (string),\n"
" block_height: (number)\n"
" }\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listsnapshotrequests", "")
+ HelpExampleRpc("listsnapshotrequests", "\"TRONCO\" 345333")
);
if (!fAssetIndex)
return "_This rpc call is not functional unless -assetindex is enabled. To enable, please run the wallet with -assetindex, this will require a reindex to occur";
// Extract parameters
std::string asset_name = "";
int block_height = 0;
if (request.params.size() > 0)
asset_name = request.params[0].get_str();
if (request.params.size() > 1)
block_height = request.params[1].get_int();
if (!pSnapshotRequestDb)
throw JSONRPCError(RPC_DATABASE_ERROR, std::string("Snapshot Request database is not setup. Please restart wallet to try again"));
UniValue result(UniValue::VARR);
std::set<CSnapshotRequestDBEntry> entries;
if (pSnapshotRequestDb->RetrieveSnapshotRequestsForHeight(asset_name, block_height, entries)) {
for (auto const &entry : entries) {
UniValue item(UniValue::VOBJ);
item.push_back(Pair("asset_name", entry.assetName));
item.push_back(Pair("block_height", entry.heightForSnapshot));
result.push_back(item);
}
return result;
}
else {
LogPrint(BCLog::REWARDS, "Failed to cancel specified snapshot request for asset '%s' at height %d!\n",
asset_name.c_str(), block_height);
}
return NullUniValue;
}
UniValue cancelsnapshotrequest(const JSONRPCRequest& request) {
if (request.fHelp || request.params.size() < 2)
throw std::runtime_error(
"cancelsnapshotrequest \"asset_name\" block_height\n"
"\nCancels the specified snapshot request.\n"
"\nArguments:\n"
"1. \"asset_name\" (string, required) The asset name for which the snapshot will be taken\n"
"2. \"block_height\" (number, required) The block height at which the snapshot will be take\n"
"\nResult:\n"
"{\n"
" request_status: (string),\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("cancelsnapshotrequest", "\"TRONCO\" 12345")
+ HelpExampleRpc("cancelsnapshotrequest", "\"PHATSTACKS\" 34987")
);
if (!fAssetIndex) {
return "_This rpc call is not functional unless -assetindex is enabled. To enable, please run the wallet with -assetindex, this will require a reindex to occur";
}
// Extract parameters
std::string asset_name = request.params[0].get_str();
int block_height = request.params[1].get_int();
if (!pSnapshotRequestDb)
throw JSONRPCError(RPC_DATABASE_ERROR, std::string("Snapshot Request database is not setup. Please restart wallet to try again"));
// Retrieve the specified reward
if (pSnapshotRequestDb->RemoveSnapshotRequest(asset_name, block_height)) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("request_status", "Removed"));
return obj;
}
else {
LogPrint(BCLog::REWARDS, "Failed to cancel specified snapshot request for asset '%s' at height %d!\n",
asset_name.c_str(), block_height);
}
throw JSONRPCError(RPC_MISC_ERROR, std::string("Failed to remove specified snapshot request"));
}
UniValue distributereward(const JSONRPCRequest& request) {
if (request.fHelp || request.params.size() < 4)
throw std::runtime_error(
"distributereward \"asset_name\" snapshot_height \"distribution_asset_name\" gross_distribution_amount ( \"exception_addresses\" ) (\"change_address\") (\"dry_run\")\n"
"\nSplits the specified amount of the distribution asset to all owners of asset_name that are not in the optional exclusion_addresses\n"
"\nArguments:\n"
"1. \"asset_name\" (string, required) The reward will be distributed all owners of this asset\n"
"2. \"snapshot_height\" (number, required) The block height of the ownership snapshot\n"
"3. \"distribution_asset_name\" (string, required) The name of the asset that will be distributed, or RVN\n"
"4. \"gross_distribution_amount\" (number, required) The amount of the distribution asset that will be split amongst all owners\n"
"5. \"exception_addresses\" (string, optional) Ownership addresses that should be excluded\n"
"6. \"change_address\" (string, optional) If the rewards can't be fully distributed. The change will be sent to this address\n"
"\nResult:\n"
"{\n"
" error_txn_gen_failed: (string),\n"
" error_nsf: (string),\n"
" error_rejects: (string),\n"
" error_db_update: (string),\n"
" batch_results: [\n"
" {\n"
" transaction_id: (string),\n"
" error_txn_rejected: (string),\n"
" total_amount: (number),\n"
" fee: (number),\n"
" expected_count: (number),\n"
" actual_count: (number),\n"
" }\n"
" ]\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("distributereward", "\"TRONCO\" 12345 \"RVN\" 1000")
+ HelpExampleCli("distributereward", "\"PHATSTACKS\" 12345 \"DIVIDENDS\" 1000 \"mwN7xC3yomYdvJuVXkVC7ymY9wNBjWNduD,n4Rf18edydDaRBh7t6gHUbuByLbWEoWUTg\"")
+ HelpExampleRpc("distributereward", "\"TRONCO\" 34987 \"DIVIDENDS\" 100000")
+ HelpExampleRpc("distributereward", "\"PHATSTACKS\" 34987 \"RVN\" 100000 \"mwN7xC3yomYdvJuVXkVC7ymY9wNBjWNduD,n4Rf18edydDaRBh7t6gHUbuByLbWEoWUTg\"")
);
if (!fAssetIndex) {
return "_This rpc call is not functional unless -assetindex is enabled. To enable, please run the wallet with -assetindex, this will require a reindex to occur";
}
// Figure out which wallet to use
CWallet * const walletPtr = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(walletPtr, request.fHelp)) {
UniValue ret(UniValue::VSTR);
ret.push_back("Rewards system requires a wallet.");
return ret;
}
ObserveSafeMode();
LOCK2(cs_main, walletPtr->cs_wallet);
EnsureWalletIsUnlocked(walletPtr);
// Extract parameters
std::string asset_name(request.params[0].get_str());
int snapshot_height = request.params[1].get_int();
std::string distribution_asset_name(request.params[2].get_str());
CAmount distribution_amount = AmountFromValue(request.params[3], (distribution_asset_name == "RVN"));
std::string exception_addresses;
if (request.params.size() > 4) {
exception_addresses = request.params[4].get_str();
//LogPrint(BCLog::REWARDS, "Excluding \"%s\"\n", exception_addresses.c_str());
}
std::string change_address = "";
if (request.params.size() > 5) {
change_address = request.params[5].get_str();
if (!change_address.empty() && !IsValidDestinationString(change_address))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid change address: Use a valid RVN address"));
}
AssetType ownershipAssetType;
AssetType distributionAssetType;
if (!IsAssetNameValid(asset_name, ownershipAssetType))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid asset_name: Please use a valid asset name"));
if (ownershipAssetType == AssetType::UNIQUE || ownershipAssetType == AssetType::OWNER || ownershipAssetType == AssetType::MSGCHANNEL)
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid asset_name: OWNER, UNQIUE, MSGCHANNEL assets are not allowed for this call"));
if (snapshot_height > chainActive.Height()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid snapshot_height: block height should be less than or equal to the current active chain height"));
}
if (distribution_asset_name != "RVN") {
if (!IsAssetNameValid(distribution_asset_name, distributionAssetType))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid distribution_asset_name: Please use a valid asset name"));
if (distributionAssetType == AssetType::UNIQUE || distributionAssetType == AssetType::OWNER || distributionAssetType == AssetType::MSGCHANNEL)
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid distribution_asset_name: OWNER, UNQIUE, MSGCHANNEL assets are not allowed for this call"));
std::pair<int, std::string> errorPair;
if (!VerifyWalletHasAsset(distribution_asset_name + OWNER_TAG, errorPair))
throw JSONRPCError(RPC_INVALID_REQUEST, std::string("Wallet doesn't have the ownership token(!) for the distribution asset"));
}
if (chainActive.Height() - snapshot_height < gArgs.GetArg("-minrewardheight", MINIMUM_REWARDS_PAYOUT_HEIGHT)) {
throw JSONRPCError(RPC_INVALID_REQUEST, std::string(
"For security of the rewards payout, it is recommended to wait until chain is 60 blocks ahead of the snapshot height. You can modify this by using the -minrewardsheight."));
}
if (!passets)
throw JSONRPCError(RPC_DATABASE_ERROR, std::string("Asset cache not setup. Please restart wallet to try again"));
CNewAsset assetMetaData;
if (!passets->GetAssetMetaDataIfExists(asset_name, assetMetaData))
throw JSONRPCError(RPC_INVALID_REQUEST, std::string("The asset hasn't been created: ") + asset_name);
if (!passetsdb)
throw JSONRPCError(RPC_DATABASE_ERROR, std::string("Assets database is not setup. Please restart wallet to try again"));
if (!pAssetSnapshotDb)
throw JSONRPCError(RPC_DATABASE_ERROR, std::string("Asset Snapshot database is not setup. Please restart wallet to try again"));
if (!pSnapshotRequestDb)
throw JSONRPCError(RPC_DATABASE_ERROR, std::string("Snapshot Request database is not setup. Please restart wallet to try again"));
if (!pSnapshotRequestDb->ContainsSnapshotRequest(asset_name, snapshot_height))
throw JSONRPCError(RPC_INVALID_REQUEST, std::string("Snapshot request not found"));
CRewardSnapshot distribRewardSnapshotData(asset_name, distribution_asset_name, exception_addresses, distribution_amount, snapshot_height);
if (!AddDistributeRewardSnapshot(distribRewardSnapshotData))
throw JSONRPCError(RPC_INVALID_REQUEST, std::string("Distribution of reward has already be created. You must remove the distribution before creating another one"));
// Trigger the distribution
DistributeRewardSnapshot(walletPtr, distribRewardSnapshotData);
return "Created reward distribution";
}
UniValue getdistributestatus(const JSONRPCRequest& request) {
if (request.fHelp || request.params.size() < 4)
throw std::runtime_error(
"getdistributestatus \"asset_name\" snapshot_height \"distribution_asset_name\" gross_distribution_amount ( \"exception_addresses\" )\n"
"\nGive information about the status of the distribution\n"
"\nArguments:\n"
"1. \"asset_name\" (string, required) The reward will be distributed all owners of this asset\n"
"2. \"snapshot_height\" (number, required) The block height of the ownership snapshot\n"
"3. \"distribution_asset_name\" (string, required) The name of the asset that will be distributed, or RVN\n"
"4. \"gross_distribution_amount\" (number, required) The amount of the distribution asset that will be split amongst all owners\n"
"5. \"exception_addresses\" (string, optional) Ownership addresses that should be excluded\n"
"\nExamples:\n"
+ HelpExampleCli("getdistributestatus", "\"TRONCO\" 12345 \"RVN\" 1000")
+ HelpExampleCli("getdistributestatus", "\"PHATSTACKS\" 12345 \"DIVIDENDS\" 1000 \"mwN7xC3yomYdvJuVXkVC7ymY9wNBjWNduD,n4Rf18edydDaRBh7t6gHUbuByLbWEoWUTg\"")
+ HelpExampleRpc("getdistributestatus", "\"TRONCO\" 34987 \"DIVIDENDS\" 100000")
+ HelpExampleRpc("getdistributestatus", "\"PHATSTACKS\" 34987 \"RVN\" 100000 \"mwN7xC3yomYdvJuVXkVC7ymY9wNBjWNduD,n4Rf18edydDaRBh7t6gHUbuByLbWEoWUTg\"")
);
if (!fAssetIndex) {
return "_This rpc call is not functional unless -assetindex is enabled. To enable, please run the wallet with -assetindex, this will require a reindex to occur";
}
ObserveSafeMode();
// Extract parameters
std::string asset_name(request.params[0].get_str());
int snapshot_height = request.params[1].get_int();
std::string distribution_asset_name(request.params[2].get_str());
CAmount distribution_amount = AmountFromValue(request.params[3], (distribution_asset_name == "RVN"));
std::string exception_addresses;
if (request.params.size() > 4) {
exception_addresses = request.params[4].get_str();
//LogPrint(BCLog::REWARDS, "Excluding \"%s\"\n", exception_addresses.c_str());
}
if (!pDistributeSnapshotDb)
throw JSONRPCError(RPC_INVALID_REQUEST, std::string("Snapshot request database is not setup. Please restart wallet to try again"));
CRewardSnapshot distribRewardSnapshotData(asset_name, distribution_asset_name, exception_addresses, distribution_amount, snapshot_height);
auto hash = distribRewardSnapshotData.GetHash();
CRewardSnapshot temp;
if (!pDistributeSnapshotDb->RetrieveDistributeSnapshotRequest(hash, temp)) {
return "Distribution not found";
}
UniValue responseObj(UniValue::VOBJ);
responseObj.push_back(std::make_pair("Asset Name", temp.strOwnershipAsset));
responseObj.push_back(std::make_pair("Height", std::to_string(temp.nHeight)));
responseObj.push_back(std::make_pair("Distribution Name", temp.strDistributionAsset));
responseObj.push_back(std::make_pair("Distribution Amount", ValueFromAmount(temp.nDistributionAmount)));
responseObj.push_back(std::make_pair("Status", temp.nStatus));
return responseObj;
}
#endif
static const CRPCCommand commands[] =
{ // category name actor (function) argNames
// ----------- ------------------------ ----------------------- ----------
#ifdef ENABLE_WALLET
{ "rewards", "requestsnapshot", &requestsnapshot, {"asset_name", "block_height"}},
{ "rewards", "getsnapshotrequest", &getsnapshotrequest, {"asset_name", "block_height"}},
{ "rewards", "listsnapshotrequests", &listsnapshotrequests, {"asset_name", "block_height"}},
{ "rewards", "cancelsnapshotrequest", &cancelsnapshotrequest, {"asset_name", "block_height"}},
{ "rewards", "distributereward", &distributereward, {"asset_name", "snapshot_height", "distribution_asset_name", "gross_distribution_amount", "exception_addresses", "change_address"}},
{ "rewards", "getdistributestatus", &getdistributestatus, {"asset_name", "block_height", "distribution_asset_name", "gross_distribution_amount", "exception_addresses"}}
#endif
};
void RegisterRewardsRPCCommands(CRPCTable &t)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
| 1 | 0.947913 | 1 | 0.947913 | game-dev | MEDIA | 0.376372 | game-dev | 0.921978 | 1 | 0.921978 |
CitizensDev/Citizens2 | 8,018 | v1_20_R4/src/main/java/net/citizensnpcs/nms/v1_20_R4/entity/BoggedController.java | package net.citizensnpcs.nms.v1_20_R4.entity;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_20_R4.CraftServer;
import org.bukkit.craftbukkit.v1_20_R4.entity.CraftBogged;
import org.bukkit.craftbukkit.v1_20_R4.entity.CraftEntity;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.nms.v1_20_R4.util.ForwardingNPCHolder;
import net.citizensnpcs.nms.v1_20_R4.util.NMSBoundingBox;
import net.citizensnpcs.nms.v1_20_R4.util.NMSImpl;
import net.citizensnpcs.npc.CitizensNPC;
import net.citizensnpcs.npc.ai.NPCHolder;
import net.citizensnpcs.util.NMS;
import net.citizensnpcs.util.Util;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.tags.TagKey;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.monster.Bogged;
import net.minecraft.world.entity.vehicle.AbstractMinecart;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.PushReaction;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
public class BoggedController extends MobEntityController {
public BoggedController() {
super(EntityBoggedNPC.class);
}
@Override
public org.bukkit.entity.Bogged getBukkitEntity() {
return (org.bukkit.entity.Bogged) super.getBukkitEntity();
}
public static class BoggedNPC extends CraftBogged implements ForwardingNPCHolder {
public BoggedNPC(EntityBoggedNPC entity) {
super((CraftServer) Bukkit.getServer(), entity);
}
}
public static class EntityBoggedNPC extends Bogged implements NPCHolder {
private final CitizensNPC npc;
public EntityBoggedNPC(EntityType<? extends Bogged> types, Level level) {
this(types, level, null);
}
public EntityBoggedNPC(EntityType<? extends Bogged> types, Level level, NPC npc) {
super(types, level);
this.npc = (CitizensNPC) npc;
}
@Override
public boolean broadcastToPlayer(ServerPlayer player) {
return NMS.shouldBroadcastToPlayer(npc, () -> super.broadcastToPlayer(player));
}
@Override
protected boolean canRide(Entity entity) {
if (npc != null && (entity instanceof Boat || entity instanceof AbstractMinecart))
return !npc.isProtected();
return super.canRide(entity);
}
@Override
public boolean causeFallDamage(float f, float f1, DamageSource damagesource) {
if (npc == null || !npc.isFlyable())
return super.causeFallDamage(f, f1, damagesource);
return false;
}
@Override
public void checkDespawn() {
if (npc == null) {
super.checkDespawn();
}
}
@Override
protected void checkFallDamage(double d0, boolean flag, BlockState iblockdata, BlockPos blockposition) {
if (npc == null || !npc.isFlyable()) {
super.checkFallDamage(d0, flag, iblockdata, blockposition);
}
}
@Override
public void customServerAiStep() {
super.customServerAiStep();
if (npc != null) {
NMSImpl.updateMinecraftAIState(npc, this);
npc.update();
}
}
@Override
protected SoundEvent getAmbientSound() {
return NMSImpl.getSoundEffect(npc, super.getAmbientSound(), NPC.Metadata.AMBIENT_SOUND);
}
@Override
public CraftEntity getBukkitEntity() {
if (npc != null && !(super.getBukkitEntity() instanceof NPCHolder)) {
NMSImpl.setBukkitEntity(this, new BoggedNPC(this));
}
return super.getBukkitEntity();
}
@Override
protected SoundEvent getDeathSound() {
return NMSImpl.getSoundEffect(npc, super.getDeathSound(), NPC.Metadata.DEATH_SOUND);
}
@Override
protected SoundEvent getHurtSound(DamageSource damagesource) {
return NMSImpl.getSoundEffect(npc, super.getHurtSound(damagesource), NPC.Metadata.HURT_SOUND);
}
@Override
public float getJumpPower() {
return NMS.getJumpPower(npc, super.getJumpPower());
}
@Override
public int getMaxFallDistance() {
return NMS.getFallDistance(npc, super.getMaxFallDistance());
}
@Override
public NPC getNPC() {
return npc;
}
@Override
public PushReaction getPistonPushReaction() {
return Util.callPistonPushEvent(npc) ? PushReaction.IGNORE : super.getPistonPushReaction();
}
@Override
public boolean isLeashed() {
return NMSImpl.isLeashed(npc, super::isLeashed, this);
}
@Override
public boolean isPushable() {
return npc == null ? super.isPushable()
: npc.data().<Boolean> get(NPC.Metadata.COLLIDABLE, !npc.isProtected());
}
@Override
public void knockback(double strength, double dx, double dz) {
NMS.callKnockbackEvent(npc, (float) strength, dx, dz, evt -> super.knockback((float) evt.getStrength(),
evt.getKnockbackVector().getX(), evt.getKnockbackVector().getZ()));
}
@Override
protected AABB makeBoundingBox() {
return NMSBoundingBox.makeBB(npc, super.makeBoundingBox());
}
@Override
public boolean onClimbable() {
if (npc == null || !npc.isFlyable())
return super.onClimbable();
else
return false;
}
@Override
public void onSyncedDataUpdated(EntityDataAccessor<?> datawatcherobject) {
if (npc == null) {
super.onSyncedDataUpdated(datawatcherobject);
return;
}
NMSImpl.checkAndUpdateHeight(this, datawatcherobject, super::onSyncedDataUpdated);
}
@Override
public void push(Entity entity) {
// this method is called by both the entities involved - cancelling
// it will not stop the NPC from moving.
super.push(entity);
if (npc != null) {
Util.callCollisionEvent(npc, entity.getBukkitEntity());
}
}
@Override
public boolean save(CompoundTag save) {
return npc == null ? super.save(save) : false;
}
@Override
public Entity teleportTo(ServerLevel worldserver, Vec3 location) {
if (npc == null)
return super.teleportTo(worldserver, location);
return NMSImpl.teleportAcrossWorld(this, worldserver, location);
}
@Override
public void travel(Vec3 vec3d) {
if (npc == null || !npc.isFlyable()) {
super.travel(vec3d);
} else {
NMSImpl.flyingMoveLogic(this, vec3d);
}
}
@Override
public boolean updateFluidHeightAndDoFluidPushing(TagKey<Fluid> tagkey, double d0) {
if (npc == null)
return super.updateFluidHeightAndDoFluidPushing(tagkey, d0);
Vec3 old = getDeltaMovement().add(0, 0, 0);
boolean res = super.updateFluidHeightAndDoFluidPushing(tagkey, d0);
if (!npc.isPushableByFluids()) {
setDeltaMovement(old);
}
return res;
}
}
}
| 1 | 0.933707 | 1 | 0.933707 | game-dev | MEDIA | 0.993543 | game-dev | 0.971341 | 1 | 0.971341 |
hrydgard/ppsspp | 2,120 | UI/GameScreen.h | // Copyright (c) 2013- PPSSPP Project.
// 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, version 2.0 or later versions.
// 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 2.0 for more details.
// A copy of the GPL 2.0 should have been included with the program.
// If not, see http://www.gnu.org/licenses/
// Official git repository and contact information can be found at
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
#pragma once
#include <functional>
#include "UI/MiscScreens.h"
#include "Common/UI/UIScreen.h"
#include "Common/File/Path.h"
#include "UI/GameInfoCache.h"
class NoticeView;
// Game screen: Allows you to start a game, delete saves, delete the game,
// set game specific settings, etc.
// Uses GameInfoCache heavily to implement the functionality.
// Should possibly merge this with the PauseScreen.
class GameScreen : public UIDialogScreenWithGameBackground {
public:
GameScreen(const Path &gamePath, bool inGame);
~GameScreen();
void update() override;
ScreenRenderFlags render(ScreenRenderMode mode) override;
const char *tag() const override { return "Game"; }
protected:
void CreateViews() override;
private:
// Event handlers
void OnPlay(UI::EventParams &e);
void OnGameSettings(UI::EventParams &e);
void OnDeleteSaveData(UI::EventParams &e);
void OnDeleteGame(UI::EventParams &e);
void OnSwitchBack(UI::EventParams &e);
void OnRemoveFromRecent(UI::EventParams &e);
void OnCreateConfig(UI::EventParams &e);
void OnDeleteConfig(UI::EventParams &e);
void OnCwCheat(UI::EventParams &e);
void OnSetBackground(UI::EventParams &e);
std::string CRC32string;
bool isHomebrew_ = false;
bool inGame_ = false;
// Keep track of progressive loading of metadata.
GameInfoFlags knownFlags_ = GameInfoFlags::EMPTY;
bool knownHasCRC_ = false;
};
| 1 | 0.786198 | 1 | 0.786198 | game-dev | MEDIA | 0.949874 | game-dev | 0.608715 | 1 | 0.608715 |
shxzu/Simp | 21,344 | src/main/java/net/minecraft/client/gui/achievement/GuiAchievements.java | package net.minecraft.client.gui.achievement;
import java.io.IOException;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiOptionButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.IProgressMeter;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.resources.I18n;
import net.minecraft.init.Blocks;
import net.minecraft.network.play.client.C16PacketClientStatus;
import net.minecraft.stats.Achievement;
import net.minecraft.stats.AchievementList;
import net.minecraft.stats.StatFileWriter;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.input.Mouse;
public class GuiAchievements extends GuiScreen implements IProgressMeter
{
private static final int field_146572_y = AchievementList.minDisplayColumn * 24 - 112;
private static final int field_146571_z = AchievementList.minDisplayRow * 24 - 112;
private static final int field_146559_A = AchievementList.maxDisplayColumn * 24 - 77;
private static final int field_146560_B = AchievementList.maxDisplayRow * 24 - 77;
private static final ResourceLocation ACHIEVEMENT_BACKGROUND = new ResourceLocation("textures/gui/achievement/achievement_background.png");
protected GuiScreen parentScreen;
protected int field_146555_f = 256;
protected int field_146557_g = 202;
protected int field_146563_h;
protected int field_146564_i;
protected float field_146570_r = 1.0F;
protected double field_146569_s;
protected double field_146568_t;
protected double field_146567_u;
protected double field_146566_v;
protected double field_146565_w;
protected double field_146573_x;
private int field_146554_D;
private final StatFileWriter statFileWriter;
private boolean loadingAchievements = true;
public GuiAchievements(GuiScreen parentScreenIn, StatFileWriter statFileWriterIn)
{
this.parentScreen = parentScreenIn;
this.statFileWriter = statFileWriterIn;
int i = 141;
int j = 141;
this.field_146569_s = this.field_146567_u = this.field_146565_w = AchievementList.openInventory.displayColumn * 24 - i / 2 - 12;
this.field_146568_t = this.field_146566_v = this.field_146573_x = AchievementList.openInventory.displayRow * 24 - j / 2;
}
public void initGui()
{
this.mc.getNetHandler().addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.REQUEST_STATS));
this.buttonList.clear();
this.buttonList.add(new GuiOptionButton(1, this.width / 2 + 24, this.height / 2 + 74, 80, 20, I18n.format("gui.done")));
}
protected void actionPerformed(GuiButton button) throws IOException
{
if (!this.loadingAchievements)
{
if (button.id == 1)
{
this.mc.displayGuiScreen(this.parentScreen);
}
}
}
protected void keyTyped(char typedChar, int keyCode) throws IOException
{
if (keyCode == this.mc.gameSettings.keyBindInventory.getKeyCode())
{
this.mc.displayGuiScreen(null);
this.mc.setIngameFocus();
}
else
{
super.keyTyped(typedChar, keyCode);
}
}
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
if (this.loadingAchievements)
{
this.drawDefaultBackground();
this.drawCenteredString(this.fontRendererObj, I18n.format("multiplayer.downloadingStats"), this.width / 2, this.height / 2, 16777215);
this.drawCenteredString(this.fontRendererObj, lanSearchStates[(int)(Minecraft.getSystemTime() / 150L % (long)lanSearchStates.length)], this.width / 2, this.height / 2 + this.fontRendererObj.FONT_HEIGHT * 2, 16777215);
}
else
{
if (Mouse.isButtonDown(0))
{
int i = (this.width - this.field_146555_f) / 2;
int j = (this.height - this.field_146557_g) / 2;
int k = i + 8;
int l = j + 17;
if ((this.field_146554_D == 0 || this.field_146554_D == 1) && mouseX >= k && mouseX < k + 224 && mouseY >= l && mouseY < l + 155)
{
if (this.field_146554_D == 0)
{
this.field_146554_D = 1;
}
else
{
this.field_146567_u -= (float)(mouseX - this.field_146563_h) * this.field_146570_r;
this.field_146566_v -= (float)(mouseY - this.field_146564_i) * this.field_146570_r;
this.field_146565_w = this.field_146569_s = this.field_146567_u;
this.field_146573_x = this.field_146568_t = this.field_146566_v;
}
this.field_146563_h = mouseX;
this.field_146564_i = mouseY;
}
}
else
{
this.field_146554_D = 0;
}
int i1 = Mouse.getDWheel();
float f3 = this.field_146570_r;
if (i1 < 0)
{
this.field_146570_r += 0.25F;
}
else if (i1 > 0)
{
this.field_146570_r -= 0.25F;
}
this.field_146570_r = MathHelper.clamp_float(this.field_146570_r, 1.0F, 2.0F);
if (this.field_146570_r != f3)
{
float f5 = f3 - this.field_146570_r;
float f4 = f3 * (float)this.field_146555_f;
float f = f3 * (float)this.field_146557_g;
float f1 = this.field_146570_r * (float)this.field_146555_f;
float f2 = this.field_146570_r * (float)this.field_146557_g;
this.field_146567_u -= (f1 - f4) * 0.5F;
this.field_146566_v -= (f2 - f) * 0.5F;
this.field_146565_w = this.field_146569_s = this.field_146567_u;
this.field_146573_x = this.field_146568_t = this.field_146566_v;
}
if (this.field_146565_w < (double)field_146572_y)
{
this.field_146565_w = field_146572_y;
}
if (this.field_146573_x < (double)field_146571_z)
{
this.field_146573_x = field_146571_z;
}
if (this.field_146565_w >= (double)field_146559_A)
{
this.field_146565_w = field_146559_A - 1;
}
if (this.field_146573_x >= (double)field_146560_B)
{
this.field_146573_x = field_146560_B - 1;
}
this.drawDefaultBackground();
this.drawAchievementScreen(mouseX, mouseY, partialTicks);
GlStateManager.disableLighting();
GlStateManager.disableDepth();
this.drawTitle();
GlStateManager.enableLighting();
GlStateManager.enableDepth();
}
}
public void doneLoading()
{
if (this.loadingAchievements)
{
this.loadingAchievements = false;
}
}
public void updateScreen()
{
if (!this.loadingAchievements)
{
this.field_146569_s = this.field_146567_u;
this.field_146568_t = this.field_146566_v;
double d0 = this.field_146565_w - this.field_146567_u;
double d1 = this.field_146573_x - this.field_146566_v;
if (d0 * d0 + d1 * d1 < 4.0D)
{
this.field_146567_u += d0;
this.field_146566_v += d1;
}
else
{
this.field_146567_u += d0 * 0.85D;
this.field_146566_v += d1 * 0.85D;
}
}
}
protected void drawTitle()
{
int i = (this.width - this.field_146555_f) / 2;
int j = (this.height - this.field_146557_g) / 2;
this.fontRendererObj.drawString(I18n.format("gui.achievements"), i + 15, j + 5, 4210752);
}
protected void drawAchievementScreen(int p_146552_1_, int p_146552_2_, float p_146552_3_)
{
int i = MathHelper.floor_double(this.field_146569_s + (this.field_146567_u - this.field_146569_s) * (double)p_146552_3_);
int j = MathHelper.floor_double(this.field_146568_t + (this.field_146566_v - this.field_146568_t) * (double)p_146552_3_);
if (i < field_146572_y)
{
i = field_146572_y;
}
if (j < field_146571_z)
{
j = field_146571_z;
}
if (i >= field_146559_A)
{
i = field_146559_A - 1;
}
if (j >= field_146560_B)
{
j = field_146560_B - 1;
}
int k = (this.width - this.field_146555_f) / 2;
int l = (this.height - this.field_146557_g) / 2;
int i1 = k + 16;
int j1 = l + 17;
this.zLevel = 0.0F;
GlStateManager.depthFunc(518);
GlStateManager.pushMatrix();
GlStateManager.translate((float)i1, (float)j1, -200.0F);
GlStateManager.scale(1.0F / this.field_146570_r, 1.0F / this.field_146570_r, 0.0F);
GlStateManager.enableTexture2D();
GlStateManager.disableLighting();
GlStateManager.enableRescaleNormal();
GlStateManager.enableColorMaterial();
int k1 = i + 288 >> 4;
int l1 = j + 288 >> 4;
int i2 = (i + 288) % 16;
int j2 = (j + 288) % 16;
int k2 = 4;
int l2 = 8;
int i3 = 10;
int j3 = 22;
int k3 = 37;
Random random = new Random();
float f = 16.0F / this.field_146570_r;
float f1 = 16.0F / this.field_146570_r;
for (int l3 = 0; (float)l3 * f - (float)j2 < 155.0F; ++l3)
{
float f2 = 0.6F - (float)(l1 + l3) / 25.0F * 0.3F;
GlStateManager.color(f2, f2, f2, 1.0F);
for (int i4 = 0; (float)i4 * f1 - (float)i2 < 224.0F; ++i4)
{
random.setSeed(this.mc.getSession().getPlayerID().hashCode() + k1 + i4 + (l1 + l3) * 16L);
int j4 = random.nextInt(1 + l1 + l3) + (l1 + l3) / 2;
TextureAtlasSprite textureatlassprite = this.func_175371_a(Blocks.sand);
if (j4 <= 37 && l1 + l3 != 35)
{
if (j4 == 22)
{
if (random.nextInt(2) == 0)
{
textureatlassprite = this.func_175371_a(Blocks.diamond_ore);
}
else
{
textureatlassprite = this.func_175371_a(Blocks.redstone_ore);
}
}
else if (j4 == 10)
{
textureatlassprite = this.func_175371_a(Blocks.iron_ore);
}
else if (j4 == 8)
{
textureatlassprite = this.func_175371_a(Blocks.coal_ore);
}
else if (j4 > 4)
{
textureatlassprite = this.func_175371_a(Blocks.stone);
}
else if (j4 > 0)
{
textureatlassprite = this.func_175371_a(Blocks.dirt);
}
}
else
{
Block block = Blocks.bedrock;
textureatlassprite = this.func_175371_a(block);
}
this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture);
this.drawTexturedModalRect(i4 * 16 - i2, l3 * 16 - j2, textureatlassprite, 16, 16);
}
}
GlStateManager.enableDepth();
GlStateManager.depthFunc(515);
this.mc.getTextureManager().bindTexture(ACHIEVEMENT_BACKGROUND);
for (int j5 = 0; j5 < AchievementList.achievementList.size(); ++j5)
{
Achievement achievement1 = AchievementList.achievementList.get(j5);
if (achievement1.parentAchievement != null)
{
int k5 = achievement1.displayColumn * 24 - i + 11;
int l5 = achievement1.displayRow * 24 - j + 11;
int j6 = achievement1.parentAchievement.displayColumn * 24 - i + 11;
int k6 = achievement1.parentAchievement.displayRow * 24 - j + 11;
boolean flag = this.statFileWriter.hasAchievementUnlocked(achievement1);
boolean flag1 = this.statFileWriter.canUnlockAchievement(achievement1);
int k4 = this.statFileWriter.func_150874_c(achievement1);
if (k4 <= 4)
{
int l4 = -16777216;
if (flag)
{
l4 = -6250336;
}
else if (flag1)
{
l4 = -16711936;
}
this.drawHorizontalLine(k5, j6, l5, l4);
this.drawVerticalLine(j6, l5, k6, l4);
if (k5 > j6)
{
this.drawTexturedModalRect(k5 - 11 - 7, l5 - 5, 114, 234, 7, 11);
}
else if (k5 < j6)
{
this.drawTexturedModalRect(k5 + 11, l5 - 5, 107, 234, 7, 11);
}
else if (l5 > k6)
{
this.drawTexturedModalRect(k5 - 5, l5 - 11 - 7, 96, 234, 11, 7);
}
else if (l5 < k6)
{
this.drawTexturedModalRect(k5 - 5, l5 + 11, 96, 241, 11, 7);
}
}
}
}
Achievement achievement = null;
float f3 = (float)(p_146552_1_ - i1) * this.field_146570_r;
float f4 = (float)(p_146552_2_ - j1) * this.field_146570_r;
RenderHelper.enableGUIStandardItemLighting();
GlStateManager.disableLighting();
GlStateManager.enableRescaleNormal();
GlStateManager.enableColorMaterial();
for (int i6 = 0; i6 < AchievementList.achievementList.size(); ++i6)
{
Achievement achievement2 = AchievementList.achievementList.get(i6);
int l6 = achievement2.displayColumn * 24 - i;
int j7 = achievement2.displayRow * 24 - j;
if (l6 >= -24 && j7 >= -24 && (float)l6 <= 224.0F * this.field_146570_r && (float)j7 <= 155.0F * this.field_146570_r)
{
int l7 = this.statFileWriter.func_150874_c(achievement2);
if (this.statFileWriter.hasAchievementUnlocked(achievement2))
{
float f5 = 0.75F;
GlStateManager.color(f5, f5, f5, 1.0F);
}
else if (this.statFileWriter.canUnlockAchievement(achievement2))
{
float f6 = 1.0F;
GlStateManager.color(f6, f6, f6, 1.0F);
}
else if (l7 < 3)
{
float f7 = 0.3F;
GlStateManager.color(f7, f7, f7, 1.0F);
}
else if (l7 == 3)
{
float f8 = 0.2F;
GlStateManager.color(f8, f8, f8, 1.0F);
}
else
{
if (l7 != 4)
{
continue;
}
float f9 = 0.1F;
GlStateManager.color(f9, f9, f9, 1.0F);
}
this.mc.getTextureManager().bindTexture(ACHIEVEMENT_BACKGROUND);
if (achievement2.getSpecial())
{
this.drawTexturedModalRect(l6 - 2, j7 - 2, 26, 202, 26, 26);
}
else
{
this.drawTexturedModalRect(l6 - 2, j7 - 2, 0, 202, 26, 26);
}
if (!this.statFileWriter.canUnlockAchievement(achievement2))
{
float f10 = 0.1F;
GlStateManager.color(f10, f10, f10, 1.0F);
this.itemRender.isNotRenderingEffectsInGUI(false);
}
GlStateManager.enableLighting();
GlStateManager.enableCull();
this.itemRender.renderItemAndEffectIntoGUI(achievement2.theItemStack, l6 + 3, j7 + 3);
GlStateManager.blendFunc(770, 771);
GlStateManager.disableLighting();
if (!this.statFileWriter.canUnlockAchievement(achievement2))
{
this.itemRender.isNotRenderingEffectsInGUI(true);
}
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
if (f3 >= (float)l6 && f3 <= (float)(l6 + 22) && f4 >= (float)j7 && f4 <= (float)(j7 + 22))
{
achievement = achievement2;
}
}
}
GlStateManager.disableDepth();
GlStateManager.enableBlend();
GlStateManager.popMatrix();
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(ACHIEVEMENT_BACKGROUND);
this.drawTexturedModalRect(k, l, 0, 0, this.field_146555_f, this.field_146557_g);
this.zLevel = 0.0F;
GlStateManager.depthFunc(515);
GlStateManager.disableDepth();
GlStateManager.enableTexture2D();
super.drawScreen(p_146552_1_, p_146552_2_, p_146552_3_);
if (achievement != null)
{
String s = achievement.getStatName().getUnformattedText();
String s1 = achievement.getDescription();
int i7 = p_146552_1_ + 12;
int k7 = p_146552_2_ - 4;
int i8 = this.statFileWriter.func_150874_c(achievement);
if (this.statFileWriter.canUnlockAchievement(achievement))
{
int j8 = Math.max(this.fontRendererObj.getStringWidth(s), 120);
int i9 = this.fontRendererObj.splitStringWidth(s1, j8);
if (this.statFileWriter.hasAchievementUnlocked(achievement))
{
i9 += 12;
}
this.drawGradientRect(i7 - 3, k7 - 3, i7 + j8 + 3, k7 + i9 + 3 + 12, -1073741824, -1073741824);
this.fontRendererObj.drawSplitString(s1, i7, k7 + 12, j8, -6250336);
if (this.statFileWriter.hasAchievementUnlocked(achievement))
{
this.fontRendererObj.drawStringWithShadow(I18n.format("achievement.taken"), (float)i7, (float)(k7 + i9 + 4), -7302913);
}
}
else if (i8 == 3)
{
s = I18n.format("achievement.unknown");
int k8 = Math.max(this.fontRendererObj.getStringWidth(s), 120);
String s2 = (new ChatComponentTranslation("achievement.requires", achievement.parentAchievement.getStatName())).getUnformattedText();
int i5 = this.fontRendererObj.splitStringWidth(s2, k8);
this.drawGradientRect(i7 - 3, k7 - 3, i7 + k8 + 3, k7 + i5 + 12 + 3, -1073741824, -1073741824);
this.fontRendererObj.drawSplitString(s2, i7, k7 + 12, k8, -9416624);
}
else if (i8 < 3)
{
int l8 = Math.max(this.fontRendererObj.getStringWidth(s), 120);
String s3 = (new ChatComponentTranslation("achievement.requires", achievement.parentAchievement.getStatName())).getUnformattedText();
int j9 = this.fontRendererObj.splitStringWidth(s3, l8);
this.drawGradientRect(i7 - 3, k7 - 3, i7 + l8 + 3, k7 + j9 + 12 + 3, -1073741824, -1073741824);
this.fontRendererObj.drawSplitString(s3, i7, k7 + 12, l8, -9416624);
}
else
{
s = null;
}
if (s != null)
{
this.fontRendererObj.drawStringWithShadow(s, (float)i7, (float)k7, this.statFileWriter.canUnlockAchievement(achievement) ? (achievement.getSpecial() ? -128 : -1) : (achievement.getSpecial() ? -8355776 : -8355712));
}
}
GlStateManager.enableDepth();
GlStateManager.enableLighting();
RenderHelper.disableStandardItemLighting();
}
private TextureAtlasSprite func_175371_a(Block p_175371_1_)
{
return Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(p_175371_1_.getDefaultState());
}
public boolean doesGuiPauseGame()
{
return !this.loadingAchievements;
}
}
| 1 | 0.801221 | 1 | 0.801221 | game-dev | MEDIA | 0.564023 | game-dev | 0.747129 | 1 | 0.747129 |
elastic/ml-cpp | 6,816 | lib/core/CMemoryUsage.cc | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the following additional limitation. Functionality enabled by the
* files subject to the Elastic License 2.0 may only be used in production when
* invoked by an Elasticsearch process with a license key installed that permits
* use of machine learning features. You may not use this file except in
* compliance with the Elastic License 2.0 and the foregoing additional
* limitation.
*/
#include <core/CMemoryUsage.h>
#include <core/CLoggerTrace.h>
#include <core/CMemoryDef.h>
#include <core/CMemoryUsageJsonWriter.h>
#include <list>
#include <map>
#include <sstream>
#include <vector>
namespace ml {
namespace core {
class CMemoryUsage::CImpl {
public:
static CImpl& impl(TMemoryUsagePtr ptr) { return *ptr->m_Impl; }
public:
CImpl() : m_Description{"", 0ULL} {}
TMemoryUsagePtr addChild() {
auto child = std::make_shared<CMemoryUsage>();
m_Children.push_back(child);
return child;
}
TMemoryUsagePtr addChild(std::size_t initialAmount) {
auto child = std::make_shared<CMemoryUsage>();
impl(child).m_Description.s_Memory = initialAmount;
m_Children.push_back(child);
return child;
}
void addItem(const SMemoryUsage& item) { m_Items.push_back(item); }
void addItem(const std::string& name, std::size_t memory) {
SMemoryUsage item(name, memory);
this->addItem(item);
}
void setName(const SMemoryUsage& item) {
std::size_t initialAmount = m_Description.s_Memory;
m_Description = item;
m_Description.s_Memory += initialAmount;
}
void setName(const std::string& name, std::size_t memory) {
SMemoryUsage item(name, memory);
this->setName(item);
}
void setName(const std::string& name) {
SMemoryUsage item(name, 0);
this->setName(item);
}
std::size_t usage() const {
std::size_t mem = m_Description.s_Memory;
for (const auto& item : m_Items) {
mem += item.s_Memory;
}
for (const auto& child : m_Children) {
mem += child->usage();
}
return mem;
}
std::size_t unusage() const {
std::size_t mem = m_Description.s_Unused;
for (const auto& item : m_Items) {
mem += item.s_Unused;
}
for (const auto& child : m_Children) {
mem += child->unusage();
}
return mem;
}
void print(std::ostream& outStream) const {
CMemoryUsageJsonWriter writer(outStream);
this->summary(writer);
writer.finalise();
}
void compress() {
using TStrSizeMap = std::map<std::string, std::size_t>;
if (!m_Children.empty()) {
TStrSizeMap itemsByName;
for (const auto& child : m_Children) {
++itemsByName[impl(child).m_Description.s_Name];
LOG_TRACE(<< "Item " << impl(child).m_Description.s_Name << " : "
<< itemsByName[impl(child).m_Description.s_Name]);
}
for (const auto & [ name, count ] : itemsByName) {
// Add up the usage of duplicate items and then delete them.
if (count > 1) {
auto equal = [name_ = name](const TMemoryUsagePtr& child) {
return impl(child).m_Description.s_Name == name_;
};
auto firstChildItr = std::find_if(m_Children.begin(),
m_Children.end(), equal);
auto childItr = firstChildItr;
++childItr;
while ((childItr = std::find_if(childItr, m_Children.end(), equal)) !=
m_Children.end()) {
LOG_TRACE(<< "Trying to remove " << *childItr);
impl(*firstChildItr).m_Description.s_Memory +=
(*childItr)->usage();
impl(*firstChildItr).m_Description.s_Unused +=
(*childItr)->unusage();
childItr = m_Children.erase(childItr);
}
impl(*firstChildItr).m_Description.s_Name +=
" [*" + std::to_string(count) + "]";
}
}
}
for (auto& child : m_Children) {
child->compress();
}
}
private:
using TMemoryUsagePtrList = std::list<TMemoryUsagePtr>;
using TMemoryUsageVec = std::vector<SMemoryUsage>;
private:
//! Give out data to the JSON writer to format, recursively
void summary(CMemoryUsageJsonWriter& writer) const {
writer.startObject();
writer.addItem(m_Description);
if (m_Items.size() > 0) {
writer.startArray("items");
for (const auto& item : m_Items) {
writer.startObject();
writer.addItem(item);
writer.endObject();
}
writer.endArray();
}
if (!m_Children.empty()) {
writer.startArray("subItems");
for (const auto& child : m_Children) {
impl(child).summary(writer);
}
writer.endArray();
}
writer.endObject();
}
private:
//! Collection of child items
TMemoryUsagePtrList m_Children;
//! Collection of component items within this node
TMemoryUsageVec m_Items;
//! Description of this item
SMemoryUsage m_Description;
};
CMemoryUsage::CMemoryUsage() : m_Impl{std::make_unique<CImpl>()} {
}
CMemoryUsage::~CMemoryUsage() = default;
CMemoryUsage::TMemoryUsagePtr CMemoryUsage::addChild() {
return m_Impl->addChild();
}
CMemoryUsage::TMemoryUsagePtr CMemoryUsage::addChild(std::size_t initialAmount) {
return m_Impl->addChild(initialAmount);
}
void CMemoryUsage::addItem(const SMemoryUsage& item) {
m_Impl->addItem(item);
}
void CMemoryUsage::addItem(const std::string& name, std::size_t memory) {
m_Impl->addItem(name, memory);
}
void CMemoryUsage::setName(const SMemoryUsage& item) {
m_Impl->setName(item);
}
void CMemoryUsage::setName(const std::string& name, std::size_t memory) {
m_Impl->setName(name, memory);
}
void CMemoryUsage::setName(const std::string& name) {
m_Impl->setName(name);
}
std::size_t CMemoryUsage::usage() const {
return m_Impl->usage();
}
std::size_t CMemoryUsage::unusage() const {
return m_Impl->unusage();
}
void CMemoryUsage::compress() {
m_Impl->compress();
}
void CMemoryUsage::print(std::ostream& outStream) const {
m_Impl->print(outStream);
}
}
}
| 1 | 0.908197 | 1 | 0.908197 | game-dev | MEDIA | 0.206737 | game-dev | 0.927035 | 1 | 0.927035 |
opensim-org/opensim-core | 14,846 | OpenSim/Moco/MocoGoal/MocoContactImpulseTrackingGoal.cpp | /* -------------------------------------------------------------------------- *
* OpenSim Moco: MocoContactImpulseTrackingGoal.cpp *
* -------------------------------------------------------------------------- *
* Copyright (c) 2022 Stanford University and the Authors *
* *
* Author(s): Nicos Haralabidis *
* *
* 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 "MocoContactImpulseTrackingGoal.h"
#include <OpenSim/Simulation/Model/SmoothSphereHalfSpaceForce.h>
using namespace OpenSim;
using RefPtrMSF = SimTK::ReferencePtr<const MocoScaleFactor>;
MocoContactImpulseTrackingGoalGroup::MocoContactImpulseTrackingGoalGroup() {
constructProperties();
}
MocoContactImpulseTrackingGoalGroup::MocoContactImpulseTrackingGoalGroup(
const std::vector<std::string>& contactForcePaths,
const std::string& externalForceName) {
constructProperties();
for (const auto& path : contactForcePaths) {
append_contact_force_paths(path);
}
set_external_force_name(externalForceName);
}
MocoContactImpulseTrackingGoalGroup::MocoContactImpulseTrackingGoalGroup(
const std::vector<std::string>& contactForcePaths,
const std::string& externalForceName,
const std::vector<std::string>& altFramePaths) :
MocoContactImpulseTrackingGoalGroup(contactForcePaths, externalForceName) {
for (const auto& path : altFramePaths) {
append_alternative_frame_paths(path);
}
}
void MocoContactImpulseTrackingGoalGroup::constructProperties() {
constructProperty_contact_force_paths();
constructProperty_external_force_name("");
constructProperty_alternative_frame_paths();
}
void MocoContactImpulseTrackingGoal::constructProperties() {
constructProperty_contact_groups();
constructProperty_external_loads();
constructProperty_external_loads_file("");
constructProperty_impulse_axis(-1);
}
void MocoContactImpulseTrackingGoal::setExternalLoadsFile(
const std::string& extLoadsFile) {
updProperty_external_loads().clear();
set_external_loads_file(extLoadsFile);
}
void MocoContactImpulseTrackingGoal::setExternalLoads(const ExternalLoads& extLoads) {
updProperty_external_loads_file().clear();
set_external_loads(extLoads);
}
void MocoContactImpulseTrackingGoal::addScaleFactor(const std::string& name,
const std::string& externalForceName,
const MocoBounds& bounds) {
// Check that the contact group associated with the provided external force
// name exists.
bool foundContactGroup = false;
for (int ig = 0; ig < getProperty_contact_groups().size(); ++ig) {
const auto& group = get_contact_groups(ig);
if (externalForceName == group.get_external_force_name()) {
foundContactGroup = true;
}
}
OPENSIM_THROW_IF_FRMOBJ(!foundContactGroup, Exception,
"Contact group associated with external force '{}' not found.",
externalForceName);
// Update the scale factor map so we can retrieve the correct MocoScaleFactor
// for this contact group during initialization.
m_scaleFactorMap[externalForceName] = name;
// Append the scale factor to the MocoGoal.
appendScaleFactor(MocoScaleFactor(name, bounds));
}
void MocoContactImpulseTrackingGoal::initializeOnModelImpl(const Model& model) const {
// Calculate the denominator.
m_denominator = model.getTotalMass(model.getWorkingState());
const double gravityAccelMagnitude = model.get_gravity().norm();
if (gravityAccelMagnitude > SimTK::SignificantReal) {
m_denominator *= gravityAccelMagnitude;
}
// Get the ExternalLoads object.
std::unique_ptr<ExternalLoads> extLoadsFromFile;
const ExternalLoads* extLoads;
if (!getProperty_external_loads().empty()) {
OPENSIM_THROW_IF_FRMOBJ(!getProperty_external_loads_file().empty(),
Exception,
"Expected either an ExternalLoads file or object, but both "
"were provided.");
extLoads = &get_external_loads();
}
else if (!get_external_loads_file().empty()) {
extLoadsFromFile = std::make_unique<ExternalLoads>(
get_external_loads_file(), true);
extLoads = extLoadsFromFile.get();
}
else {
OPENSIM_THROW_FRMOBJ(Exception, "No ExternalLoads provided.");
}
// Spline the data.
const std::string dataFilePath =
convertRelativeFilePathToAbsoluteFromXMLDocument(
extLoads->getDocumentFileName(),
extLoads->getDataFileName());
TimeSeriesTable data(dataFilePath);
GCVSplineSet allRefSplines(data);
// Each ExternalForce has an applied_to_body property. For the ExternalForce
// to be properly paired with a group of contact force components, the
// contact force components must also apply forces to the same body. Here,
// we find which of the two bodies in each contact force component matches
// the ExternalForce body.
const auto& scaleFactors = getModel().getComponentList<MocoScaleFactor>();
for (int ig = 0; ig < getProperty_contact_groups().size(); ++ig) {
const auto& group = get_contact_groups(ig);
OPENSIM_THROW_IF_FRMOBJ(
!extLoads->contains(group.get_external_force_name()), Exception,
"External force '{}' not found.",
group.get_external_force_name());
const auto& extForce =
extLoads->get(group.get_external_force_name());
GroupInfo groupInfo;
for (int ic = 0; ic < group.getProperty_contact_force_paths().size();
++ic) {
const auto& path = group.get_contact_force_paths(ic);
const auto& contactForce =
model.getComponent<SmoothSphereHalfSpaceForce>(path);
int recordOffset = findRecordOffset(group, contactForce,
extForce.get_applied_to_body());
groupInfo.contacts.push_back(
std::make_pair(&contactForce, recordOffset));
}
// Gather the relevant data splines for this contact group.
// We assume that the "x", "y", and "z" columns could have been in any
// order.
const std::string& forceID = extForce.get_force_identifier();
groupInfo.refSplines.cloneAndAppend(allRefSplines.get(forceID + "x"));
groupInfo.refSplines.cloneAndAppend(allRefSplines.get(forceID + "y"));
groupInfo.refSplines.cloneAndAppend(allRefSplines.get(forceID + "z"));
// Check which frame the contact force data is expressed in.
groupInfo.refExpressedInFrame = nullptr;
if (extForce.get_force_expressed_in_body() != "ground") {
const auto& forceExpressedInBody =
extForce.get_force_expressed_in_body();
if (model.hasComponent<PhysicalFrame>(forceExpressedInBody)) {
groupInfo.refExpressedInFrame =
&model.getComponent<PhysicalFrame>(
forceExpressedInBody);
}
else if (model.hasComponent<PhysicalFrame>(
"./bodyset/" + forceExpressedInBody)) {
groupInfo.refExpressedInFrame =
&model.getComponent<PhysicalFrame>(
"./bodyset/" + forceExpressedInBody);
}
else {
OPENSIM_THROW_FRMOBJ(Exception,
"Could not find '{}' in the model or the BodySet.",
forceExpressedInBody);
}
}
m_groups.push_back(groupInfo);
// Check to see if the model contains a MocoScaleFactor associated with
// this contact group.
RefPtrMSF thisScaleFactorRef;
bool foundScaleFactor = false;
for (const auto& scaleFactor : scaleFactors) {
if (m_scaleFactorMap[group.get_external_force_name()] == scaleFactor.getName()) {
thisScaleFactorRef = &scaleFactor;
foundScaleFactor = true;
}
}
// If we didn't find a MocoScaleFactor for this force direction, set
// the reference pointer to null.
if (!foundScaleFactor) {
thisScaleFactorRef = nullptr;
}
m_scaleFactorRefs.push_back(thisScaleFactorRef);
// Check that the length of scale factors == 1; As the goal does not
// support multiple integrals currently
if (m_scaleFactorRefs.size() != 1)
OPENSIM_THROW_FRMOBJ(Exception,
"Expected size of scale factors to be 1, but "
" got '{}.",
m_scaleFactorRefs.size());
}
// Which axis should the impulse be tracked for?
if (get_impulse_axis() < 0 || get_impulse_axis() > 2)
OPENSIM_THROW_FRMOBJ(Exception,
"Expected 'impulse_axis' to be either 0, 1 or 2, but "
"got '{}'.",
get_impulse_axis());
// Check the number of contact groups which have been added;
// The MocoImpulseTrackingGoal currently only supports tracking
// the impulse from a single limb at a time
if (getProperty_contact_groups().size() > 1)
OPENSIM_THROW_FRMOBJ(Exception,
"Expected a single (1) contact group, but "
"got '{}'.",
getProperty_contact_groups().size());
setRequirements(1, 1, SimTK::Stage::Velocity);
}
int MocoContactImpulseTrackingGoal::findRecordOffset(
const MocoContactImpulseTrackingGoalGroup& group,
const SmoothSphereHalfSpaceForce& contactForce,
const std::string& appliedToBody) const {
// Is the ExternalForce applied to the sphere's body?
const auto& sphereBase =
contactForce.getConnectee<ContactSphere>("sphere")
.getConnectee<PhysicalFrame>("frame")
.findBaseFrame();
const std::string& sphereBaseName = sphereBase.getName();
if (sphereBaseName == appliedToBody) {
// We want the first 3 entries in
// SmoothSphereHalfSpaceForce::getRecordValues(), which contain
// forces on the sphere.
return 0;
}
// Is the ExternalForce applied to the half space's body?
const auto& halfSpaceBase =
contactForce.getConnectee<ContactHalfSpace>("half_space")
.getConnectee<PhysicalFrame>("frame")
.findBaseFrame();
const std::string& halfSpaceBaseName = halfSpaceBase.getName();
if (halfSpaceBaseName == appliedToBody) {
// We want the forces applied to the half space, which are
// entries 6, 7, 8 in
// SmoothSphereHalfSpaceForce::getRecordValues().
return 6;
}
// Check the group's alternative frames.
// Check each alternative frame path in the order provided. As soon as one
// of these paths matches the name of the sphere base frame or
// half space base frame, use the contact forces applied to that base frame.
const auto& sphereBasePath = sphereBase.getAbsolutePathString();
const auto& halfSpaceBasePath = halfSpaceBase.getAbsolutePathString();
for (int ia = 0; ia < group.getProperty_alternative_frame_paths().size();
++ia) {
const auto& path = group.get_alternative_frame_paths(ia);
if (path == sphereBasePath) { return 0; }
if (path == halfSpaceBasePath) { return 6; }
}
OPENSIM_THROW_FRMOBJ(Exception,
"Contact force '{}' has sphere base frame '{}' and half space base "
"frame '{}'. One of these frames should match the applied_to_body "
"setting ('{}') of ExternalForce '{}', or match one of the "
"alternative_frame_paths, but no match found.",
contactForce.getAbsolutePathString(), sphereBaseName,
halfSpaceBaseName, appliedToBody, group.get_external_force_name());
}
void MocoContactImpulseTrackingGoal::calcIntegrandImpl(
const IntegrandInput& input, double& integrand) const {
const auto& state = input.state;
const auto& time = state.getTime();
getModel().realizeVelocity(state);
SimTK::Vector timeVec(1, time);
integrand = 0;
SimTK::Vec3 force_ref;
for (int ig = 0; ig < (int)m_groups.size(); ++ig) {
// Get contact groups.
const auto& group = m_groups[ig];
// Model force.
double force_model(0);
for (const auto& entry : group.contacts) {
Array<double> recordValues = entry.first->getRecordValues(state);
const auto& recordOffset = entry.second;
force_model += recordValues[recordOffset + get_impulse_axis()];
}
// Reference force.
for (int ir = 0; ir < force_ref.size(); ++ir) {
force_ref[ir] = group.refSplines[ir].calcValue(timeVec);
}
// Re-express the reference force.
if (group.refExpressedInFrame) {
group.refExpressedInFrame->expressVectorInGround(state, force_ref);
}
// Apply scale factors for this marker, if they exist.
const auto& scaleFactorRef = m_scaleFactorRefs[ig];
double scaleFactor = 1.0;
if (scaleFactorRef != nullptr) {
scaleFactor = scaleFactorRef->getScaleFactor();
}
double error = force_model - scaleFactor * force_ref[get_impulse_axis()];
integrand += error;
}
}
void MocoContactImpulseTrackingGoal::printDescriptionImpl() const {
log_info(" impulse axis: {}", get_impulse_axis());
for (int ig = 0; ig < getProperty_contact_groups().size(); ++ig) {
const auto& group = get_contact_groups(ig);
log_info(" group {}: ExternalForce: {}",
ig, group.get_external_force_name());
log_info(" forces:");
for (int ic = 0; ic < group.getProperty_contact_force_paths().size();
++ic) {
log_info(" {}", group.get_contact_force_paths(ic));
}
}
} | 1 | 0.957771 | 1 | 0.957771 | game-dev | MEDIA | 0.709203 | game-dev | 0.896669 | 1 | 0.896669 |
DarkstarProject/darkstar | 3,804 | scripts/zones/Kazham/npcs/Mumupp.lua | -----------------------------------
-- Area: Kazham
-- NPC: Mumupp
-- Standard Info NPC
-----------------------------------
require("scripts/globals/pathfind");
-----------------------------------
local path =
{
94.732452, -15.000000, -114.034622,
94.210846, -15.000000, -114.989388,
93.508865, -15.000000, -116.274101,
94.584877, -15.000000, -116.522118,
95.646988, -15.000000, -116.468452,
94.613518, -15.000000, -116.616562,
93.791100, -15.000000, -115.858505,
94.841835, -15.000000, -116.108437,
93.823380, -15.000000, -116.712860,
94.986847, -15.000000, -116.571831,
94.165512, -15.000000, -115.965698,
95.005806, -15.000000, -116.519707,
93.935555, -15.000000, -116.706291,
94.943497, -15.000000, -116.578346,
93.996826, -15.000000, -115.932816,
95.060165, -15.000000, -116.180840,
94.081062, -15.000000, -115.923836,
95.246490, -15.000000, -116.215691,
94.234077, -15.000000, -115.960793
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(dsp.path.first(path));
onPath(npc);
end;
function onPath(npc)
dsp.path.patrol(npc, path);
end;
function onTrade(player,npc,trade)
-- item IDs
-- 483 Broken Mithran Fishing Rod
-- 22 Workbench
-- 1008 Ten of Coins
-- 1157 Sands of Silence
-- 1158 Wandering Bulb
-- 904 Giant Fish Bones
-- 4599 Blackened Toad
-- 905 Wyvern Skull
-- 1147 Ancient Salt
-- 4600 Lucky Egg
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, dsp.quest.id.outlands.THE_OPO_OPO_AND_I);
local progress = player:getCharVar("OPO_OPO_PROGRESS");
local failed = player:getCharVar("OPO_OPO_FAILED");
local goodtrade = trade:hasItemQty(1008,1);
local badtrade = (trade:hasItemQty(483,1) or trade:hasItemQty(22,1) or trade:hasItemQty(1157,1) or trade:hasItemQty(1158,1) or trade:hasItemQty(904,1) or trade:hasItemQty(4599,1) or trade:hasItemQty(905,1) or trade:hasItemQty(1147,1) or trade:hasItemQty(4600,1));
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if progress == 2 or failed == 3 then
if goodtrade then
player:startEvent(221);
elseif badtrade then
player:startEvent(231);
end
end
end
end;
function onTrigger(player,npc)
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, dsp.quest.id.outlands.THE_OPO_OPO_AND_I);
local progress = player:getCharVar("OPO_OPO_PROGRESS");
local failed = player:getCharVar("OPO_OPO_FAILED");
local retry = player:getCharVar("OPO_OPO_RETRY");
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if retry >= 1 then -- has failed on future npc so disregard previous successful trade
player:startEvent(199);
npc:wait();
elseif (progress == 2 or failed == 3) then
player:startEvent(209); -- asking for ten of coins
elseif (progress >= 3 or failed >= 4) then
player:startEvent(244); -- happy with ten of coins
end
else
player:startEvent(199);
npc:wait();
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option,npc)
if (csid == 221) then -- correct trade, onto next opo
if player:getCharVar("OPO_OPO_PROGRESS") == 2 then
player:tradeComplete();
player:setCharVar("OPO_OPO_PROGRESS",3);
player:setCharVar("OPO_OPO_FAILED",0);
else
player:setCharVar("OPO_OPO_FAILED",4);
end
elseif (csid == 231) then -- wrong trade, restart at first opo
player:setCharVar("OPO_OPO_FAILED",1);
player:setCharVar("OPO_OPO_RETRY",3);
else
npc:wait(0);
end
end;
| 1 | 0.944924 | 1 | 0.944924 | game-dev | MEDIA | 0.99315 | game-dev | 0.964803 | 1 | 0.964803 |
stakwork/sphinx-relay | 4,763 | src/tests/controllers/deleteMessages.test.ts | import test from 'ava'
import { randomText } from '../utils/helpers'
import { deleteTribe, leaveTribe, disappearingMessages } from '../utils/del'
import { createTribe, joinTribe } from '../utils/save'
import {
sendTribeMessageAndCheckDecryption,
sendBoost,
getTribeMessages,
} from '../utils/msg'
import nodes from '../nodes'
/*
npx ava src/tests/controllers/deleteMessages.test.ts --verbose --serial --timeout=2m
*/
test('test message deleter: create tribe, join tribe, send messages, boost messages, delete messages, check number of messages, leave tribe, delete tribe', async (t) => {
await messageDeleter(t, 0, 1, 2)
})
export async function messageDeleter(t, index1, index2, index3) {
//TWO NODES SEND IMAGES WITHIN A TRIBE ===>
let node1 = nodes[index1]
let node2 = nodes[index2]
let node3 = nodes[index3]
t.truthy(node3, 'this test requires three nodes')
console.log(
`Checking boost messages in tribe for ${node1.alias} and ${node2.alias} and ${node3.alias}`
)
//NODE1 CREATES A TRIBE
let tribe = await createTribe(t, node1)
t.truthy(tribe, 'tribe should have been created by node1')
//NODE2 JOINS TRIBE CREATED BY NODE1
if (node1.routeHint) tribe.owner_route_hint = node1.routeHint
let join = await joinTribe(t, node2, tribe)
t.true(join, 'node2 should join tribe')
//NODE3 JOINS TRIBE CREATED BY NODE1
if (node1.routeHint) tribe.owner_route_hint = node1.routeHint
let join2 = await joinTribe(t, node3, tribe)
t.true(join2, 'node3 should join tribe')
//NODE1 SENDS A MESSAGE IN THE TRIBE AND NODE2 CHECKS TO SEE IF THEY RECEIVED THE MESSAGE
const text = randomText()
let tribeMessage1 = await sendTribeMessageAndCheckDecryption(
t,
node1,
node2,
text,
tribe
)
t.truthy(tribeMessage1, 'node1 should send message to tribe')
//NODE2 SENDS A MESSAGE IN THE TRIBE AND NODE3 CHECKS TO SEE IF THEY RECEIVED THE MESSAGE
const text2 = randomText()
let tribeMessage2 = await sendTribeMessageAndCheckDecryption(
t,
node2,
node3,
text2,
tribe
)
t.truthy(tribeMessage2, 'node2 should send message to tribe')
//NODE3 SENDS A MESSAGE IN THE TRIBE AND NODE1 CHECKS TO SEE IF THEY RECEIVED THE MESSAGE
const text3 = randomText()
let tribeMessage3 = await sendTribeMessageAndCheckDecryption(
t,
node3,
node1,
text3,
tribe
)
t.truthy(tribeMessage3, 'node3 should send message to tribe')
const text4 = randomText()
let tribeMessage4 = await sendTribeMessageAndCheckDecryption(
t,
node3,
node1,
text4,
tribe
)
t.truthy(tribeMessage4, 'node3 should send message to tribe')
const text5 = randomText()
let tribeMessage5 = await sendTribeMessageAndCheckDecryption(
t,
node3,
node1,
text5,
tribe
)
t.truthy(tribeMessage5, 'node3 should send message to tribe')
const text6 = randomText()
let tribeMessage6 = await sendTribeMessageAndCheckDecryption(
t,
node3,
node1,
text6,
tribe
)
t.truthy(tribeMessage6, 'node3 should send message to tribe')
const text7 = randomText()
let tribeMessage7 = await sendTribeMessageAndCheckDecryption(
t,
node3,
node1,
text7,
tribe
)
t.truthy(tribeMessage7, 'node3 should send message to tribe')
const text8 = randomText()
let tribeMessage8 = await sendTribeMessageAndCheckDecryption(
t,
node3,
node1,
text8,
tribe
)
t.truthy(tribeMessage8, 'node3 should send message to tribe')
//NODE1 SENDS A BOOST ON NODE2'S MESSAGE
const boost = await sendBoost(t, node1, node2, tribeMessage2, 11, tribe)
t.true(boost.success)
//NODE2 SENDS A BOOST ON NODE3'S MESSAGE
const boost2 = await sendBoost(t, node2, node3, tribeMessage3, 12, tribe)
t.true(boost2.success)
//NODE3 SENDS A BOOST ON NODE1'S MESSAGE
const boost3 = await sendBoost(t, node3, node1, tribeMessage1, 13, tribe)
t.true(boost3.success)
const boost4 = await sendBoost(t, node1, node3, tribeMessage4, 13, tribe)
t.true(boost4.success)
const boost5 = await sendBoost(t, node1, node3, tribeMessage5, 13, tribe)
t.true(boost5.success)
const deleteMessage = await disappearingMessages(t, node1)
t.true(deleteMessage, 'Messages should be deleted')
const tribeMessages = await getTribeMessages(t, node1, tribe)
t.true(
tribeMessages.length === 10,
'The total number of message left should be 10'
)
//NODE2 LEAVES TRIBE
let left2 = await leaveTribe(t, node2, tribe)
t.true(left2, 'node2 should leave tribe')
//NODE3 LEAVES TRIBE
let left3 = await leaveTribe(t, node3, tribe)
t.true(left3, 'node3 should leave tribe')
//NODE1 DELETES TRIBE
let delTribe2 = await deleteTribe(t, node1, tribe)
t.true(delTribe2, 'node1 should delete tribe')
}
| 1 | 0.627557 | 1 | 0.627557 | game-dev | MEDIA | 0.32877 | game-dev | 0.545964 | 1 | 0.545964 |
genshinsim/gcsim | 2,015 | internal/characters/chiori/plunge.go | package chiori
import (
"errors"
"github.com/genshinsim/gcsim/internal/frames"
"github.com/genshinsim/gcsim/pkg/core/action"
"github.com/genshinsim/gcsim/pkg/core/attacks"
"github.com/genshinsim/gcsim/pkg/core/attributes"
"github.com/genshinsim/gcsim/pkg/core/combat"
"github.com/genshinsim/gcsim/pkg/core/info"
"github.com/genshinsim/gcsim/pkg/core/player"
)
var lowPlungeFramesC []int
const lowPlungeHitmarkC = 41
const (
lowPlungePoiseDMG = 100.0
lowPlungeRadius = 3.0
)
func init() {
lowPlungeFramesC = frames.InitAbilSlice(69) // Low Plunge -> J/Walk
lowPlungeFramesC[action.ActionAttack] = 54
lowPlungeFramesC[action.ActionSkill] = 53
lowPlungeFramesC[action.ActionBurst] = 54
lowPlungeFramesC[action.ActionDash] = 44
lowPlungeFramesC[action.ActionSwap] = 56
}
func (c *char) LowPlungeAttack(p map[string]int) (action.Info, error) {
defer c.Core.Player.SetAirborne(player.Grounded)
// last action hold skill
if c.Core.Player.LastAction.Type == action.ActionSkill &&
c.Core.Player.LastAction.Param["hold"] >= 1 {
return c.lowPlungeC(), nil
}
return action.Info{}, errors.New("low_plunge can only be used after hold skill")
}
func (c *char) lowPlungeC() action.Info {
c.tryTriggerA1TailoringNA()
ai := info.AttackInfo{
ActorIndex: c.Index(),
Abil: "Low Plunge Attack",
AttackTag: attacks.AttackTagPlunge,
ICDTag: attacks.ICDTagNone,
ICDGroup: attacks.ICDGroupDefault,
StrikeType: attacks.StrikeTypeBlunt,
PoiseDMG: lowPlungePoiseDMG,
Element: attributes.Physical,
Durability: 25,
Mult: lowPlunge[c.TalentLvlAttack()],
}
c.Core.QueueAttack(
ai,
combat.NewCircleHitOnTarget(c.Core.Combat.Player(), info.Point{Y: 1}, lowPlungeRadius),
lowPlungeHitmarkC,
lowPlungeHitmarkC,
)
return action.Info{
Frames: frames.NewAbilFunc(lowPlungeFramesC),
AnimationLength: lowPlungeFramesC[action.InvalidAction],
CanQueueAfter: lowPlungeFramesC[action.ActionDash],
State: action.PlungeAttackState,
}
}
| 1 | 0.810903 | 1 | 0.810903 | game-dev | MEDIA | 0.912128 | game-dev | 0.581464 | 1 | 0.581464 |
bepu/bepuphysics1 | 41,950 | BEPUphysics/CollisionTests/CollisionAlgorithms/TriangleConvexPairTester.cs | using System;
using BEPUphysics.CollisionTests.CollisionAlgorithms.GJK;
using BEPUphysics.CollisionShapes.ConvexShapes;
using BEPUutilities;
using BEPUphysics.Settings;
using BEPUutilities.DataStructures;
namespace BEPUphysics.CollisionTests.CollisionAlgorithms
{
///<summary>
/// Persistent tester that compares triangles against convex objects.
///</summary>
public class TriangleConvexPairTester : TrianglePairTester
{
internal ConvexShape convex;
internal CollisionState state = CollisionState.Plane;
/// <summary>
/// The number of updates between attempts to reset to the cheaper Plane collision state instead of more expensive GJK-based tests.
/// This is used by the ExternalSeparated state because it only generates a boolean result.
/// ExternalNear, which DOES generate contact information, also uses it to reduce the frequency of voronoi region tests.
/// Deep just transitions to ExternalNear when penetration is slight rather than trying to jump to Plane.
/// </summary>
private const int EscapeAttemptPeriod = 10;
int escapeAttempts;
Vector3 localSeparatingAxis;
//Relies on the triangle being located in the local space of the convex object. The convex transform is used to transform the
//contact points back from the convex's local space into world space.
///<summary>
/// Generates a contact between the triangle and convex.
///</summary>
/// <param name="triangle">Triangle to test the convex against. The input triangle should be transformed into the local space of the convex.</param>
///<param name="contactList">Contact between the shapes, if any.</param>
///<returns>Whether or not the shapes are colliding.</returns>
public override bool GenerateContactCandidates(TriangleShape triangle, out TinyStructList<ContactData> contactList)
{
switch (state)
{
case CollisionState.Plane:
return DoPlaneTest(triangle, out contactList);
case CollisionState.ExternalSeparated:
return DoExternalSeparated(triangle, out contactList);
case CollisionState.ExternalNear:
return DoExternalNear(triangle, out contactList);
case CollisionState.Deep:
return DoDeepContact(triangle, out contactList);
default:
contactList = new TinyStructList<ContactData>();
return false;
}
}
private bool DoPlaneTest(TriangleShape triangle, out TinyStructList<ContactData> contactList)
{
//Find closest point between object and plane.
Vector3 reverseNormal;
Vector3 ab, ac;
Vector3.Subtract(ref triangle.vB, ref triangle.vA, out ab);
Vector3.Subtract(ref triangle.vC, ref triangle.vA, out ac);
Vector3.Cross(ref ac, ref ab, out reverseNormal);
//Convex position dot normal is ALWAYS zero. The thing to look at is the plane's 'd'.
//If the distance along the normal is positive, then the convex is 'behind' that normal.
float dotA;
Vector3.Dot(ref triangle.vA, ref reverseNormal, out dotA);
contactList = new TinyStructList<ContactData>();
switch (triangle.sidedness)
{
case TriangleSidedness.DoubleSided:
if (dotA < 0)
{
//The reverse normal is pointing towards the convex.
//It needs to point away from the convex so that the direction
//will get the proper extreme point.
Vector3.Negate(ref reverseNormal, out reverseNormal);
dotA = -dotA;
}
break;
case TriangleSidedness.Clockwise:
//if (dotA < 0)
//{
// //The reverse normal is pointing towards the convex.
// return false;
//}
break;
case TriangleSidedness.Counterclockwise:
//if (dotA > 0)
//{
// //The reverse normal is pointing away from the convex.
// return false;
//}
//The reverse normal is pointing towards the convex.
//It needs to point away from the convex so that the direction
//will get the proper extreme point.
Vector3.Negate(ref reverseNormal, out reverseNormal);
dotA = -dotA;
break;
}
Vector3 extremePoint;
convex.GetLocalExtremePointWithoutMargin(ref reverseNormal, out extremePoint);
//See if the extreme point is within the face or not.
//It might seem like the easy "depth" test should come first, since a barycentric
//calculation takes a bit more time. However, transferring from plane to depth is 'rare'
//(like all transitions), and putting this test here is logically closer to its requirements'
//computation.
if (GetVoronoiRegion(triangle, ref extremePoint) != VoronoiRegion.ABC)
{
state = CollisionState.ExternalSeparated;
return DoExternalSeparated(triangle, out contactList);
}
float dotE;
Vector3.Dot(ref extremePoint, ref reverseNormal, out dotE);
float t = (dotA - dotE) / reverseNormal.LengthSquared();
Vector3 offset;
Vector3.Multiply(ref reverseNormal, t, out offset);
//Compare the distance from the plane to the convex object.
float distanceSquared = offset.LengthSquared();
float marginSum = triangle.collisionMargin + convex.collisionMargin;
//TODO: Could just normalize early and avoid computing point plane before it's necessary.
//Exposes a sqrt but...
if (t <= 0 || distanceSquared < marginSum * marginSum)
{
//The convex object is in the margin of the plane.
//All that's left is to create the contact.
var contact = new ContactData();
//Displacement is from A to B. point = A + t * AB, where t = marginA / margin.
if (marginSum > Toolbox.Epsilon) //This can be zero! It would cause a NaN is unprotected.
Vector3.Multiply(ref offset, convex.collisionMargin / marginSum, out contact.Position); //t * AB
else contact.Position = new Vector3();
Vector3.Add(ref extremePoint, ref contact.Position, out contact.Position); //A + t * AB.
float normalLength = reverseNormal.Length();
Vector3.Divide(ref reverseNormal, normalLength, out contact.Normal);
float distance = normalLength * t;
contact.PenetrationDepth = marginSum - distance;
if (contact.PenetrationDepth > marginSum)
{
//Check to see if the inner sphere is touching the plane.
//This does not override other tests; there can be more than one contact from a single triangle.
ContactData alternateContact;
if (TryInnerSphereContact(triangle, out alternateContact))// && alternateContact.PenetrationDepth > contact.PenetrationDepth)
{
contactList.Add(ref alternateContact);
}
//The convex object is stuck deep in the plane!
//The most problematic case for this is when
//an object is right on top of a cliff.
//The lower, vertical triangle may occasionally detect
//a contact with the object, but would compute an extremely
//deep depth if the normal plane test was used.
//Verify that the depth is correct by trying another approach.
CollisionState previousState = state;
state = CollisionState.ExternalNear;
TinyStructList<ContactData> alternateContacts;
if (DoExternalNear(triangle, out alternateContacts))
{
alternateContacts.Get(0, out alternateContact);
if (alternateContact.PenetrationDepth + .01f < contact.PenetrationDepth) //Bias against the subtest's result, since the plane version will probably have a better position.
{
//It WAS a bad contact.
contactList.Add(ref alternateContact);
//DoDeepContact (which can be called from within DoExternalNear) can generate two contacts, but the second contact would just be an inner sphere (which we already generated).
//DoExternalNear can only generate one contact. So we only need the first contact!
//TODO: This is a fairly fragile connection between the two stages. Consider robustifying. (Also, the TryInnerSphereContact is done twice! This process is very rare for marginful pairs, though)
}
else
{
//Well, it really is just that deep.
contactList.Add(ref contact);
state = previousState;
}
}
else
{
//If the external near test finds that there was no collision at all,
//just return to plane testing. If the point turns up outside the face region
//next time, the system will adapt.
state = previousState;
return false;
}
}
else
{
contactList.Add(ref contact);
}
return true;
}
return false;
}
private bool DoExternalSeparated(TriangleShape triangle, out TinyStructList<ContactData> contactList)
{
if (GJKToolbox.AreShapesIntersecting(convex, triangle, ref Toolbox.RigidIdentity, ref Toolbox.RigidIdentity, ref localSeparatingAxis))
{
state = CollisionState.ExternalNear;
return DoExternalNear(triangle, out contactList);
}
TryToEscape();
contactList = new TinyStructList<ContactData>();
return false;
}
private bool DoExternalNear(TriangleShape triangle, out TinyStructList<ContactData> contactList)
{
Vector3 closestA, closestB;
//Don't bother trying to do any clever caching. The continually transforming simplex makes it very rarely useful.
//TODO: Initialize the simplex of the GJK method using the 'true' center of the triangle.
//If left unmodified, the simplex that is used in GJK will just be a point at 0,0,0, which of course is at the origin.
//This causes an instant-out, always. Not good!
//By giving the contributing simplex the average centroid, it has a better guess.
Vector3 triangleCentroid;
Vector3.Add(ref triangle.vA, ref triangle.vB, out triangleCentroid);
Vector3.Add(ref triangleCentroid, ref triangle.vC, out triangleCentroid);
Vector3.Multiply(ref triangleCentroid, .33333333f, out triangleCentroid);
var initialSimplex = new CachedSimplex { State = SimplexState.Point, LocalSimplexB = { A = triangleCentroid } };
if (GJKToolbox.GetClosestPoints(convex, triangle, ref Toolbox.RigidIdentity, ref Toolbox.RigidIdentity, ref initialSimplex, out closestA, out closestB))
{
state = CollisionState.Deep;
return DoDeepContact(triangle, out contactList);
}
Vector3 displacement;
Vector3.Subtract(ref closestB, ref closestA, out displacement);
float distanceSquared = displacement.LengthSquared();
float margin = convex.collisionMargin + triangle.collisionMargin;
contactList = new TinyStructList<ContactData>();
if (distanceSquared < margin * margin)
{
//Try to generate a contact.
var contact = new ContactData();
//Determine if the normal points in the appropriate direction given the sidedness of the triangle.
if (triangle.sidedness != TriangleSidedness.DoubleSided)
{
Vector3 triangleNormal, ab, ac;
Vector3.Subtract(ref triangle.vB, ref triangle.vA, out ab);
Vector3.Subtract(ref triangle.vC, ref triangle.vA, out ac);
Vector3.Cross(ref ab, ref ac, out triangleNormal);
float dot;
Vector3.Dot(ref triangleNormal, ref displacement, out dot);
if (triangle.sidedness == TriangleSidedness.Clockwise && dot > 0)
return false;
if (triangle.sidedness == TriangleSidedness.Counterclockwise && dot < 0)
return false;
}
//Displacement is from A to B. point = A + t * AB, where t = marginA / margin.
if (margin > Toolbox.Epsilon) //This can be zero! It would cause a NaN if unprotected.
Vector3.Multiply(ref displacement, convex.collisionMargin / margin, out contact.Position); //t * AB
else contact.Position = new Vector3();
Vector3.Add(ref closestA, ref contact.Position, out contact.Position); //A + t * AB.
contact.Normal = displacement;
float distance = (float)Math.Sqrt(distanceSquared);
Vector3.Divide(ref contact.Normal, distance, out contact.Normal);
contact.PenetrationDepth = margin - distance;
contactList.Add(ref contact);
TryToEscape(triangle, ref contact.Position);
return true;
}
//Too far to make a contact- move back to separation.
state = CollisionState.ExternalSeparated;
return false;
}
private bool DoDeepContact(TriangleShape triangle, out TinyStructList<ContactData> contactList)
{
//Find the origin to triangle center offset.
Vector3 center;
Vector3.Add(ref triangle.vA, ref triangle.vB, out center);
Vector3.Add(ref center, ref triangle.vC, out center);
Vector3.Multiply(ref center, 1f / 3f, out center);
ContactData contact;
contactList = new TinyStructList<ContactData>();
if (MPRToolbox.AreLocalShapesOverlapping(convex, triangle, ref center, ref Toolbox.RigidIdentity))
{
float dot;
Vector3 triangleNormal, ab, ac;
Vector3.Subtract(ref triangle.vB, ref triangle.vA, out ab);
Vector3.Subtract(ref triangle.vC, ref triangle.vA, out ac);
Vector3.Cross(ref ab, ref ac, out triangleNormal);
float lengthSquared = triangleNormal.LengthSquared();
if (lengthSquared < Toolbox.Epsilon * .01f)
{
//Degenerate triangle! That's no good.
//Just use the direction pointing from A to B, "B" being the triangle. That direction is center - origin, or just center.
MPRToolbox.LocalSurfaceCast(convex, triangle, ref Toolbox.RigidIdentity, ref center, out contact.PenetrationDepth, out contact.Normal, out contact.Position);
}
else
{
//Normalize the normal.
Vector3.Divide(ref triangleNormal, (float)Math.Sqrt(lengthSquared), out triangleNormal);
//TODO: This tests all three edge axes with a full MPR raycast. That's not really necessary; the correct edge normal should be discoverable, resulting in a single MPR raycast.
//Find the edge directions that will be tested with MPR.
Vector3 AO, BO, CO;
Vector3 AB, BC, CA;
Vector3.Subtract(ref center, ref triangle.vA, out AO);
Vector3.Subtract(ref center, ref triangle.vB, out BO);
Vector3.Subtract(ref center, ref triangle.vC, out CO);
Vector3.Subtract(ref triangle.vB, ref triangle.vA, out AB);
Vector3.Subtract(ref triangle.vC, ref triangle.vB, out BC);
Vector3.Subtract(ref triangle.vA, ref triangle.vC, out CA);
//We don't have to worry about degenerate triangles here because we've already handled that possibility above.
Vector3 ABnormal, BCnormal, CAnormal;
//Project the center onto the edge to find the direction from the center to the edge AB.
Vector3.Dot(ref AO, ref AB, out dot);
Vector3.Multiply(ref AB, dot / AB.LengthSquared(), out ABnormal);
Vector3.Subtract(ref AO, ref ABnormal, out ABnormal);
ABnormal.Normalize();
//Project the center onto the edge to find the direction from the center to the edge BC.
Vector3.Dot(ref BO, ref BC, out dot);
Vector3.Multiply(ref BC, dot / BC.LengthSquared(), out BCnormal);
Vector3.Subtract(ref BO, ref BCnormal, out BCnormal);
BCnormal.Normalize();
//Project the center onto the edge to find the direction from the center to the edge BC.
Vector3.Dot(ref CO, ref CA, out dot);
Vector3.Multiply(ref CA, dot / CA.LengthSquared(), out CAnormal);
Vector3.Subtract(ref CO, ref CAnormal, out CAnormal);
CAnormal.Normalize();
MPRToolbox.LocalSurfaceCast(convex, triangle, ref Toolbox.RigidIdentity, ref ABnormal, out contact.PenetrationDepth, out contact.Normal);
//Check to see if the normal is facing in the proper direction, considering that this may not be a two-sided triangle.
Vector3.Dot(ref triangleNormal, ref contact.Normal, out dot);
if ((triangle.sidedness == TriangleSidedness.Clockwise && dot > 0) || (triangle.sidedness == TriangleSidedness.Counterclockwise && dot < 0))
{
//Normal was facing the wrong way.
//Instead of ignoring it entirely, correct the direction to as close as it can get by removing any component parallel to the triangle normal.
Vector3 previousNormal = contact.Normal;
Vector3.Dot(ref contact.Normal, ref triangleNormal, out dot);
Vector3 p;
Vector3.Multiply(ref contact.Normal, dot, out p);
Vector3.Subtract(ref contact.Normal, ref p, out contact.Normal);
float length = contact.Normal.LengthSquared();
if (length > Toolbox.Epsilon)
{
//Renormalize the corrected normal.
Vector3.Divide(ref contact.Normal, (float)Math.Sqrt(length), out contact.Normal);
Vector3.Dot(ref contact.Normal, ref previousNormal, out dot);
contact.PenetrationDepth *= dot;
}
else
{
contact.PenetrationDepth = float.MaxValue;
contact.Normal = new Vector3();
}
}
Vector3 candidateNormal;
float candidateDepth;
MPRToolbox.LocalSurfaceCast(convex, triangle, ref Toolbox.RigidIdentity, ref BCnormal, out candidateDepth, out candidateNormal);
//Check to see if the normal is facing in the proper direction, considering that this may not be a two-sided triangle.
Vector3.Dot(ref triangleNormal, ref candidateNormal, out dot);
if ((triangle.sidedness == TriangleSidedness.Clockwise && dot > 0) || (triangle.sidedness == TriangleSidedness.Counterclockwise && dot < 0))
{
//Normal was facing the wrong way.
//Instead of ignoring it entirely, correct the direction to as close as it can get by removing any component parallel to the triangle normal.
Vector3 previousNormal = candidateNormal;
Vector3.Dot(ref candidateNormal, ref triangleNormal, out dot);
Vector3 p;
Vector3.Multiply(ref candidateNormal, dot, out p);
Vector3.Subtract(ref candidateNormal, ref p, out candidateNormal);
float length = candidateNormal.LengthSquared();
if (length > Toolbox.Epsilon)
{
//Renormalize the corrected normal.
Vector3.Divide(ref candidateNormal, (float)Math.Sqrt(length), out candidateNormal);
Vector3.Dot(ref candidateNormal, ref previousNormal, out dot);
candidateDepth *= dot;
}
else
{
contact.PenetrationDepth = float.MaxValue;
contact.Normal = new Vector3();
}
}
if (candidateDepth < contact.PenetrationDepth)
{
contact.Normal = candidateNormal;
contact.PenetrationDepth = candidateDepth;
}
MPRToolbox.LocalSurfaceCast(convex, triangle, ref Toolbox.RigidIdentity, ref CAnormal, out candidateDepth, out candidateNormal);
//Check to see if the normal is facing in the proper direction, considering that this may not be a two-sided triangle.
Vector3.Dot(ref triangleNormal, ref candidateNormal, out dot);
if ((triangle.sidedness == TriangleSidedness.Clockwise && dot > 0) || (triangle.sidedness == TriangleSidedness.Counterclockwise && dot < 0))
{
//Normal was facing the wrong way.
//Instead of ignoring it entirely, correct the direction to as close as it can get by removing any component parallel to the triangle normal.
Vector3 previousNormal = candidateNormal;
Vector3.Dot(ref candidateNormal, ref triangleNormal, out dot);
Vector3 p;
Vector3.Multiply(ref candidateNormal, dot, out p);
Vector3.Subtract(ref candidateNormal, ref p, out candidateNormal);
float length = candidateNormal.LengthSquared();
if (length > Toolbox.Epsilon)
{
//Renormalize the corrected normal.
Vector3.Divide(ref candidateNormal, (float)Math.Sqrt(length), out candidateNormal);
Vector3.Dot(ref candidateNormal, ref previousNormal, out dot);
candidateDepth *= dot;
}
else
{
contact.PenetrationDepth = float.MaxValue;
contact.Normal = new Vector3();
}
}
if (candidateDepth < contact.PenetrationDepth)
{
contact.Normal = candidateNormal;
contact.PenetrationDepth = candidateDepth;
}
//Try the depth along the positive triangle normal.
//If it's clockwise, this direction is unnecessary (the resulting normal would be invalidated by the onesidedness of the triangle).
if (triangle.sidedness != TriangleSidedness.Clockwise)
{
MPRToolbox.LocalSurfaceCast(convex, triangle, ref Toolbox.RigidIdentity, ref triangleNormal, out candidateDepth, out candidateNormal);
if (candidateDepth < contact.PenetrationDepth)
{
contact.Normal = candidateNormal;
contact.PenetrationDepth = candidateDepth;
}
}
//Try the depth along the negative triangle normal.
//If it's counterclockwise, this direction is unnecessary (the resulting normal would be invalidated by the onesidedness of the triangle).
if (triangle.sidedness != TriangleSidedness.Counterclockwise)
{
Vector3.Negate(ref triangleNormal, out triangleNormal);
MPRToolbox.LocalSurfaceCast(convex, triangle, ref Toolbox.RigidIdentity, ref triangleNormal, out candidateDepth, out candidateNormal);
if (candidateDepth < contact.PenetrationDepth)
{
contact.Normal = candidateNormal;
contact.PenetrationDepth = candidateDepth;
}
}
}
MPRToolbox.RefinePenetration(convex, triangle, ref Toolbox.RigidIdentity, contact.PenetrationDepth, ref contact.Normal, out contact.PenetrationDepth, out contact.Normal, out contact.Position);
//It's possible for the normal to still face the 'wrong' direction according to one sided triangles.
if (triangle.sidedness != TriangleSidedness.DoubleSided)
{
Vector3.Dot(ref triangleNormal, ref contact.Normal, out dot);
if (dot < 0)
{
//Skip the add process.
goto InnerSphere;
}
}
contact.Id = -1;
if (contact.PenetrationDepth < convex.collisionMargin + triangle.collisionMargin)
{
state = CollisionState.ExternalNear; //If it's emerged from the deep contact, we can go back to using the preferred GJK method.
}
contactList.Add(ref contact);
}
InnerSphere:
if (TryInnerSphereContact(triangle, out contact))
{
contactList.Add(ref contact);
}
if (contactList.Count > 0)
return true;
state = CollisionState.ExternalSeparated;
return false;
}
void TryToEscape()
{
if (++escapeAttempts == EscapeAttemptPeriod)
{
escapeAttempts = 0;
state = CollisionState.Plane;
}
}
void TryToEscape(TriangleShape triangle, ref Vector3 position)
{
if (++escapeAttempts == EscapeAttemptPeriod && GetVoronoiRegion(triangle, ref position) == VoronoiRegion.ABC)
{
escapeAttempts = 0;
state = CollisionState.Plane;
}
}
private bool TryInnerSphereContact(TriangleShape triangle, out ContactData contact)
{
Vector3 closestPoint;
Toolbox.GetClosestPointOnTriangleToPoint(ref triangle.vA, ref triangle.vB, ref triangle.vC, ref Toolbox.ZeroVector, out closestPoint);
float length = closestPoint.LengthSquared();
float minimumRadius = convex.MinimumRadius * (MotionSettings.CoreShapeScaling + .01f);
if (length < minimumRadius * minimumRadius)
{
Vector3 triangleNormal, ab, ac;
Vector3.Subtract(ref triangle.vB, ref triangle.vA, out ab);
Vector3.Subtract(ref triangle.vC, ref triangle.vA, out ac);
Vector3.Cross(ref ab, ref ac, out triangleNormal);
float dot;
Vector3.Dot(ref closestPoint, ref triangleNormal, out dot);
if ((triangle.sidedness == TriangleSidedness.Clockwise && dot > 0) || (triangle.sidedness == TriangleSidedness.Counterclockwise && dot < 0))
{
//Normal was facing the wrong way.
contact = new ContactData();
return false;
}
length = (float)Math.Sqrt(length);
contact.Position = closestPoint;
if (length > Toolbox.Epsilon) //Watch out for NaN's!
{
Vector3.Divide(ref closestPoint, length, out contact.Normal);
}
else
{
//The direction is undefined. Use the triangle's normal.
//One sided triangles can only face in the appropriate direction.
float normalLength = triangleNormal.LengthSquared();
if (triangleNormal.LengthSquared() > Toolbox.Epsilon)
{
Vector3.Divide(ref triangleNormal, (float)Math.Sqrt(normalLength), out triangleNormal);
if (triangle.sidedness == TriangleSidedness.Clockwise)
contact.Normal = triangleNormal;
else
Vector3.Negate(ref triangleNormal, out contact.Normal);
}
else
{
//Degenerate triangle!
contact = new ContactData();
return false;
}
}
//Compute the actual depth of the contact.
//This is conservative; the minimum radius is guaranteed to be no larger than the shape itself.
//But that's ok- this is strictly a deep contact protection scheme. Other contacts will make the objects separate.
contact.PenetrationDepth = convex.MinimumRadius - length;
contact.Id = -1;
return true;
}
contact = new ContactData();
return false;
}
///<summary>
/// Determines what voronoi region a given point is in.
///</summary>
///<param name="p">Point to test.</param>
///<returns>Voronoi region containing the point.</returns>
private VoronoiRegion GetVoronoiRegion(TriangleShape triangle, ref Vector3 p)
{
//The point we are comparing against the triangle is 0,0,0, so instead of storing an "A->P" vector,
//just use -A.
//Same for B->, C->P...
Vector3 ab, ac, ap;
Vector3.Subtract(ref triangle.vB, ref triangle.vA, out ab);
Vector3.Subtract(ref triangle.vC, ref triangle.vA, out ac);
Vector3.Subtract(ref p, ref triangle.vA, out ap);
//Check to see if it's outside A.
float APdotAB, APdotAC;
Vector3.Dot(ref ap, ref ab, out APdotAB);
Vector3.Dot(ref ap, ref ac, out APdotAC);
if (APdotAC <= 0f && APdotAB <= 0)
{
//It is A!
return VoronoiRegion.A;
}
//Check to see if it's outside B.
float BPdotAB, BPdotAC;
Vector3 bp;
Vector3.Subtract(ref p, ref triangle.vB, out bp);
Vector3.Dot(ref ab, ref bp, out BPdotAB);
Vector3.Dot(ref ac, ref bp, out BPdotAC);
if (BPdotAB >= 0f && BPdotAC <= BPdotAB)
{
//It is B!
return VoronoiRegion.B;
}
//Check to see if it's outside AB.
float vc = APdotAB * BPdotAC - BPdotAB * APdotAC;
if (vc <= 0 && APdotAB > 0 && BPdotAB < 0) //Note > and < instead of => <=; avoids possibly division by zero
{
return VoronoiRegion.AB;
}
//Check to see if it's outside C.
float CPdotAB, CPdotAC;
Vector3 cp;
Vector3.Subtract(ref p, ref triangle.vC, out cp);
Vector3.Dot(ref ab, ref cp, out CPdotAB);
Vector3.Dot(ref ac, ref cp, out CPdotAC);
if (CPdotAC >= 0f && CPdotAB <= CPdotAC)
{
//It is C!
return VoronoiRegion.C;
}
//Check if it's outside AC.
float vb = CPdotAB * APdotAC - APdotAB * CPdotAC;
if (vb <= 0f && APdotAC > 0f && CPdotAC < 0f) //Note > instead of >= and < instead of <=; prevents bad denominator
{
return VoronoiRegion.AC;
}
//Check if it's outside BC.
float va = BPdotAB * CPdotAC - CPdotAB * BPdotAC;
if (va <= 0f && (BPdotAC - BPdotAB) > 0f && (CPdotAB - CPdotAC) > 0f)//Note > instead of >= and < instead of <=; prevents bad denominator
{
return VoronoiRegion.BC;
}
//On the face of the triangle.
return VoronoiRegion.ABC;
}
///<summary>
/// Initializes the pair tester.
///</summary>
///<param name="convex">Convex shape to use.</param>
public override void Initialize(ConvexShape convex)
{
this.convex = convex;
}
/// <summary>
/// Cleans up the pair tester.
/// </summary>
public override void CleanUp()
{
convex = null;
state = CollisionState.Plane;
escapeAttempts = 0;
localSeparatingAxis = new Vector3();
Updated = false;
}
internal enum CollisionState
{
Plane,
ExternalSeparated,
ExternalNear,
Deep
}
public override VoronoiRegion GetRegion(TriangleShape triangle, ref ContactData contact)
{
//Deep contact can produce non-triangle normals while still being within the triangle.
//To solve this problem, find the voronoi region to which the contact belongs using its normal.
//The voronoi region will be either the most extreme vertex, or the edge that includes
//the first and second most extreme vertices.
//If the normal dotted with an extreme edge direction is near 0, then it belongs to the edge.
//Otherwise, it belongs to the vertex.
//MPR tends to produce 'approximate' normals, though.
//Use a fairly forgiving epsilon.
float dotA, dotB, dotC;
Vector3.Dot(ref triangle.vA, ref contact.Normal, out dotA);
Vector3.Dot(ref triangle.vB, ref contact.Normal, out dotB);
Vector3.Dot(ref triangle.vC, ref contact.Normal, out dotC);
//Since normal points from convex to triangle always, reverse dot signs.
dotA = -dotA;
dotB = -dotB;
dotC = -dotC;
float faceEpsilon = .01f;
const float edgeEpsilon = .01f;
float edgeDot;
Vector3 edgeDirection;
if (dotA > dotB && dotA > dotC)
{
//A is extreme.
if (dotB > dotC)
{
//B is second most extreme.
if (Math.Abs(dotA - dotC) < faceEpsilon)
{
//The normal is basically a face normal. This can happen at the edges occasionally.
return VoronoiRegion.ABC;
}
else
{
Vector3.Subtract(ref triangle.vB, ref triangle.vA, out edgeDirection);
Vector3.Dot(ref edgeDirection, ref contact.Normal, out edgeDot);
if (edgeDot * edgeDot < edgeDirection.LengthSquared() * edgeEpsilon)
return VoronoiRegion.AB;
else
return VoronoiRegion.A;
}
}
else
{
//C is second most extreme.
if (Math.Abs(dotA - dotB) < faceEpsilon)
{
//The normal is basically a face normal. This can happen at the edges occasionally.
return VoronoiRegion.ABC;
}
else
{
Vector3.Subtract(ref triangle.vC, ref triangle.vA, out edgeDirection);
Vector3.Dot(ref edgeDirection, ref contact.Normal, out edgeDot);
if (edgeDot * edgeDot < edgeDirection.LengthSquared() * edgeEpsilon)
return VoronoiRegion.AC;
else
return VoronoiRegion.A;
}
}
}
else if (dotB > dotC)
{
//B is extreme.
if (dotC > dotA)
{
//C is second most extreme.
if (Math.Abs(dotB - dotA) < faceEpsilon)
{
//The normal is basically a face normal. This can happen at the edges occasionally.
return VoronoiRegion.ABC;
}
else
{
Vector3.Subtract(ref triangle.vC, ref triangle.vB, out edgeDirection);
Vector3.Dot(ref edgeDirection, ref contact.Normal, out edgeDot);
if (edgeDot * edgeDot < edgeDirection.LengthSquared() * edgeEpsilon)
return VoronoiRegion.BC;
else
return VoronoiRegion.B;
}
}
else
{
//A is second most extreme.
if (Math.Abs(dotB - dotC) < faceEpsilon)
{
//The normal is basically a face normal. This can happen at the edges occasionally.
return VoronoiRegion.ABC;
}
else
{
Vector3.Subtract(ref triangle.vA, ref triangle.vB, out edgeDirection);
Vector3.Dot(ref edgeDirection, ref contact.Normal, out edgeDot);
if (edgeDot * edgeDot < edgeDirection.LengthSquared() * edgeEpsilon)
return VoronoiRegion.AB;
else
return VoronoiRegion.B;
}
}
}
else
{
//C is extreme.
if (dotA > dotB)
{
//A is second most extreme.
if (Math.Abs(dotC - dotB) < faceEpsilon)
{
//The normal is basically a face normal. This can happen at the edges occasionally.
return VoronoiRegion.ABC;
}
else
{
Vector3.Subtract(ref triangle.vA, ref triangle.vC, out edgeDirection);
Vector3.Dot(ref edgeDirection, ref contact.Normal, out edgeDot);
if (edgeDot * edgeDot < edgeDirection.LengthSquared() * edgeEpsilon)
return VoronoiRegion.AC;
else
return VoronoiRegion.C;
}
}
else
{
//B is second most extreme.
if (Math.Abs(dotC - dotA) < faceEpsilon)
{
//The normal is basically a face normal. This can happen at the edges occasionally.
return VoronoiRegion.ABC;
}
else
{
Vector3.Subtract(ref triangle.vB, ref triangle.vC, out edgeDirection);
Vector3.Dot(ref edgeDirection, ref contact.Normal, out edgeDot);
if (edgeDot * edgeDot < edgeDirection.LengthSquared() * edgeEpsilon)
return VoronoiRegion.BC;
else
return VoronoiRegion.C;
}
}
}
}
public override bool ShouldCorrectContactNormal
{
get
{
return state == CollisionState.Deep;
}
}
}
}
| 1 | 0.962857 | 1 | 0.962857 | game-dev | MEDIA | 0.974604 | game-dev | 0.979285 | 1 | 0.979285 |
Mathijs-Bakker/Zenject-Hero | 3,381 | Assets/Plugins/Zenject/OptionalExtras/TestFramework/SceneTestFixture.cs | #if UNITY_EDITOR
using System.Collections.Generic;
using Zenject.Internal;
using ModestTree;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using Zenject;
using System.Collections;
using UnityEngine.TestTools;
using Assert = ModestTree.Assert;
using System.Linq;
// Ignore warning about using SceneManager.UnloadScene instead of SceneManager.UnloadSceneAsync
#pragma warning disable 618
namespace Zenject
{
public abstract class SceneTestFixture
{
readonly List<DiContainer> _sceneContainers = new List<DiContainer>();
bool _hasLoadedScene;
DiContainer _sceneContainer;
protected DiContainer SceneContainer
{
get { return _sceneContainer; }
}
protected IEnumerable<DiContainer> SceneContainers
{
get { return _sceneContainers; }
}
public IEnumerator LoadScene(string sceneName)
{
return LoadScenes(sceneName);
}
public IEnumerator LoadScenes(params string[] sceneNames)
{
Assert.That(!_hasLoadedScene, "Attempted to load scene twice!");
_hasLoadedScene = true;
// Clean up any leftovers from previous test
ZenjectTestUtil.DestroyEverythingExceptTestRunner(false);
Assert.That(SceneContainers.IsEmpty());
for (int i = 0; i < sceneNames.Length; i++)
{
var sceneName = sceneNames[i];
Assert.That(Application.CanStreamedLevelBeLoaded(sceneName),
"Cannot load scene '{0}' for test '{1}'. The scenes used by SceneTestFixture derived classes must be added to the build settings for the test to work",
sceneName, GetType());
Log.Info("Loading scene '{0}' for testing", sceneName);
var loader = SceneManager.LoadSceneAsync(sceneName, i == 0 ? LoadSceneMode.Single : LoadSceneMode.Additive);
while (!loader.isDone)
{
yield return null;
}
SceneContext sceneContext = null;
if (ProjectContext.HasInstance)
// ProjectContext might be null if scene does not have a scene context
{
var scene = SceneManager.GetSceneByName(sceneName);
sceneContext = ProjectContext.Instance.Container.Resolve<SceneContextRegistry>()
.TryGetSceneContextForScene(scene);
}
_sceneContainers.Add(sceneContext.Container);
}
_sceneContainer = _sceneContainers.Where(x => x != null).Last();
if (_sceneContainer != null)
{
_sceneContainer.Inject(this);
}
}
[SetUp]
public virtual void SetUp()
{
StaticContext.Clear();
SetMemberDefaults();
}
void SetMemberDefaults()
{
_hasLoadedScene = false;
_sceneContainer = null;
_sceneContainers.Clear();
}
[TearDown]
public virtual void Teardown()
{
ZenjectTestUtil.DestroyEverythingExceptTestRunner(true);
StaticContext.Clear();
SetMemberDefaults();
}
}
}
#endif
| 1 | 0.796801 | 1 | 0.796801 | game-dev | MEDIA | 0.658616 | game-dev,testing-qa | 0.872925 | 1 | 0.872925 |
OpenRA/OpenRA | 2,168 | OpenRA.Mods.Cnc/Traits/Infiltration/InfiltrateForTransform.cs | #region Copyright & License Information
/*
* Copyright (c) The OpenRA Developers and Contributors
* This file is part of OpenRA, which is free software. It is made
* available to you 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. For more
* information, see COPYING.
*/
#endregion
using OpenRA.Mods.Common;
using OpenRA.Mods.Common.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Primitives;
using OpenRA.Traits;
namespace OpenRA.Mods.Cnc.Traits
{
[Desc("Transform into a different actor type.")]
sealed class InfiltrateForTransformInfo : TraitInfo
{
[ActorReference]
[FieldLoader.Require]
public readonly string IntoActor = null;
public readonly int ForceHealthPercentage = 0;
public readonly bool SkipMakeAnims = true;
[Desc("Experience to grant to the infiltrating player.")]
public readonly int PlayerExperience = 0;
[Desc("The `TargetTypes` from `Targetable` that are allowed to enter.")]
public readonly BitSet<TargetableType> Types = default;
public override object Create(ActorInitializer init) { return new InfiltrateForTransform(init, this); }
}
sealed class InfiltrateForTransform : INotifyInfiltrated
{
readonly InfiltrateForTransformInfo info;
readonly string faction;
public InfiltrateForTransform(ActorInitializer init, InfiltrateForTransformInfo info)
{
this.info = info;
faction = init.GetValue<FactionInit, string>(init.Self.Owner.Faction.InternalName);
}
void INotifyInfiltrated.Infiltrated(Actor self, Actor infiltrator, BitSet<TargetableType> types)
{
if (!info.Types.Overlaps(types))
return;
var transform = new Transform(info.IntoActor)
{
ForceHealthPercentage = info.ForceHealthPercentage,
Faction = faction,
SkipMakeAnims = info.SkipMakeAnims
};
var facing = self.TraitOrDefault<IFacing>();
if (facing != null)
transform.Facing = facing.Facing;
infiltrator.Owner.PlayerActor.TraitOrDefault<PlayerExperience>()?.GiveExperience(info.PlayerExperience);
self.QueueActivity(false, transform);
}
}
}
| 1 | 0.712498 | 1 | 0.712498 | game-dev | MEDIA | 0.827993 | game-dev | 0.812799 | 1 | 0.812799 |
relaxng/jing-trang | 1,697 | mod/infer/src/main/com/thaiopensource/xml/infer/DatatypeInferrer.java | package com.thaiopensource.xml.infer;
import com.thaiopensource.xml.util.Name;
class DatatypeInferrer {
private final DatatypeRepertoire.Type[] possibleTypes;
private int nTypes;
private int typicalMask = 0;
private final String uri;
private boolean allWhiteSpace = true;
DatatypeInferrer(DatatypeRepertoire datatypes, String value) {
uri = DatatypeRepertoire.getUri();
possibleTypes = new DatatypeRepertoire.Type[datatypes.size()];
for (int i = 0; i < possibleTypes.length; i++)
possibleTypes[i] = datatypes.get(i);
nTypes = possibleTypes.length;
addValue(value);
}
public void addValue(String value) {
int nDeleted = 0;
for (int i = 0; i < nTypes; i++) {
if (!possibleTypes[i].matches(value))
nDeleted++;
else {
if (possibleTypes[i].isTypical(value))
typicalMask |= 1 << possibleTypes[i].getIndex();
if (nDeleted > 0) {
possibleTypes[i - nDeleted] = possibleTypes[i];
possibleTypes[i] = null;
}
}
}
nTypes -= nDeleted;
if (!isWhiteSpace(value))
allWhiteSpace = false;
}
static boolean isWhiteSpace(String value) {
for (int i = 0; i < value.length(); i++)
switch (value.charAt(i)) {
case ' ':
case '\t':
case '\n':
case '\r':
break;
default:
return false;
}
return true;
}
public Name getTypeName() {
for (int i = 0; i < nTypes; i++)
if (((1 << possibleTypes[i].getIndex()) & typicalMask) != 0)
return new Name(uri, possibleTypes[i].getName());
return null;
}
public boolean isAllWhiteSpace() {
return allWhiteSpace;
}
}
| 1 | 0.97406 | 1 | 0.97406 | game-dev | MEDIA | 0.211029 | game-dev | 0.990864 | 1 | 0.990864 |
aurilisdev/Electrodynamics | 13,709 | src/main/java/electrodynamics/datagen/server/recipe/types/custom/item2item/ElectrodynamicsMineralCrusherRecipes.java | package electrodynamics.datagen.server.recipe.types.custom.item2item;
import electrodynamics.Electrodynamics;
import electrodynamics.common.item.subtype.SubtypeCrystal;
import electrodynamics.common.item.subtype.SubtypeDust;
import electrodynamics.common.item.subtype.SubtypeImpureDust;
import electrodynamics.common.item.subtype.SubtypeOxide;
import electrodynamics.common.item.subtype.SubtypePlate;
import electrodynamics.common.item.subtype.SubtypeRawOre;
import electrodynamics.common.recipe.categories.item2item.specificmachines.MineralCrusherRecipe;
import electrodynamics.registers.ElectrodynamicsItems;
import net.minecraft.data.recipes.RecipeOutput;
import net.minecraft.tags.ItemTags;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.block.Blocks;
import net.neoforged.neoforge.common.Tags;
import voltaic.common.recipe.recipeutils.ProbableItem;
import voltaic.common.tags.VoltaicTags;
import voltaic.datagen.utils.server.recipe.AbstractRecipeGenerator;
import voltaic.datagen.utils.server.recipe.builders.BaseRecipeBuilder;
import voltaic.datagen.utils.server.recipe.builders.Item2ItemBuilder;
public class ElectrodynamicsMineralCrusherRecipes extends AbstractRecipeGenerator {
public static double MINERALCRUSHER_USAGE_PER_TICK = 450.0;
public static int MINERALCRUSHER_REQUIRED_TICKS = 200;
public final String modID;
public ElectrodynamicsMineralCrusherRecipes(String modID) {
this.modID = modID;
}
public ElectrodynamicsMineralCrusherRecipes() {
this(Electrodynamics.ID);
}
@Override
public void addRecipes(RecipeOutput output) {
for (SubtypePlate plate : SubtypePlate.values()) {
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_PLATE.getValue(plate)), 0.1F, 200, 450.0, "plate_" + plate.name() + "_from_ingot", modID)
//
.addItemTagInput(plate.sourceIngot, 1)
//
.save(output);
}
for (SubtypeCrystal crystal : SubtypeCrystal.values()) {
if (crystal.crushedItem != null && crystal != SubtypeCrystal.halite) {
newRecipe(new ItemStack(crystal.crushedItem.get()), 0.0F, 200, 450.0, "imp_dust_" + crystal.name() + "_from_crystal", modID)
//
.addItemStackInput(new ItemStack(ElectrodynamicsItems.ITEMS_CRYSTAL.getValue(crystal)))
//
.save(output);
}
}
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_DUST.getValue(SubtypeDust.salt), 1), 0.1F, 200, 450.0, "salt_from_halite_crystal", modID)
//
.addItemStackInput(new ItemStack(ElectrodynamicsItems.ITEMS_CRYSTAL.getValue(SubtypeCrystal.halite)))
//
.save(output);
for (SubtypeRawOre raw : SubtypeRawOre.values()) {
if (raw.crushedItem != null) {
if (raw == SubtypeRawOre.titanium || raw == SubtypeRawOre.chromium) {
newRecipe(new ItemStack(raw.crushedItem.get(), 3), 0.5F, 200, 450.0, "oxide_" + raw.name() + "_from_raw_ore", modID)
//
.addItemTagInput(raw.tag, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.iron)), 0.3))
//
.save(output);
} else {
newRecipe(new ItemStack(raw.crushedItem.get(), 3), 0.3F, 200, 450.0, "imp_dust_" + raw.name() + "_from_raw_ore", modID)
//
.addItemTagInput(raw.tag, 1)
//
.save(output);
}
}
}
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.iron), 3), 0.3F, 200, 450.0, "imp_dust_iron_from_raw_ore", modID)
//
.addItemTagInput(Tags.Items.RAW_MATERIALS_IRON, 1)
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.gold), 3), 0.3F, 200, 450.0, "imp_dust_gold_from_raw_ore", modID)
//
.addItemTagInput(Tags.Items.RAW_MATERIALS_GOLD, 1)
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.copper), 3), 0.3F, 200, 450.0, "imp_dust_copper_from_raw_ore", modID)
//
.addItemTagInput(Tags.Items.RAW_MATERIALS_COPPER, 1)
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_OXIDE.getValue(SubtypeOxide.chromite), 3), 0.3F, 200, 450.0, "oxide_chromite_from_ore", modID)
//
.addItemTagInput(VoltaicTags.Items.ORE_CHROMIUM, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.iron)), 0.4))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.copper), 3), 0.3F, 200, 450.0, "imp_dust_copper_from_ore", modID)
//
.addItemTagInput(ItemTags.COPPER_ORES, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.gold)), 0.1))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.gold), 3), 0.3F, 200, 450.0, "imp_dust_gold_from_ore", modID)
//
.addItemTagInput(ItemTags.GOLD_ORES, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.silver)), 0.2))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.iron), 3), 0.3F, 200, 450.0, "imp_dust_iron_from_ore", modID)
//
.addItemTagInput(ItemTags.IRON_ORES, 1)
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.lead), 3), 0.3F, 200, 450.0, "imp_dust_lead_from_ore", modID)
//
.addItemTagInput(VoltaicTags.Items.ORE_LEAD, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.silver)), 0.4))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.molybdenum), 3), 0.3F, 200, 450.0, "imp_dust_molybdenum_from_ore", modID)
//
.addItemTagInput(VoltaicTags.Items.ORE_MOLYBDENUM, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(ElectrodynamicsItems.ITEMS_DUST.getValue(SubtypeDust.sulfur)), 0.3))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.netherite), 3), 0.3F, 200, 450.0, "imp_dust_netherite_from_ore", modID)
//
.addItemTagInput(Tags.Items.ORES_NETHERITE_SCRAP, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(Items.COAL), 0.3))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.silver), 3), 0.2F, 200, 450.0, "imp_dust_silver_from_ore", modID)
//
.addItemTagInput(VoltaicTags.Items.ORE_SILVER, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.gold)), 0.1))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.tin), 3), 0.3F, 200, 450.0, "imp_dust_tin_from_ore", modID)
//
.addItemTagInput(VoltaicTags.Items.ORE_TIN, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(Items.QUARTZ), 0.3))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.vanadium), 3), 0.3F, 200, 450.0, "imp_dust_vanadium_from_ore", modID)
//
.addItemTagInput(VoltaicTags.Items.ORE_VANADIUM, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(ElectrodynamicsItems.ITEMS_DUST.getValue(SubtypeDust.lead)), 0.2))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_DUST.getValue(SubtypeDust.niter), 4), 0.1F, 200, 450.0, "niter_dust_from_ore", modID)
//
.addItemTagInput(VoltaicTags.Items.ORE_SALTPETER, 1)
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_DUST.getValue(SubtypeDust.sulfur), 4), 0.1F, 200, 450.0, "sulfur_dust_from_ore", modID)
//
.addItemTagInput(VoltaicTags.Items.ORE_SULFUR, 1)
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_OXIDE.getValue(SubtypeOxide.dititanium), 3), 0.5F, 200, 450.0, "oxide_titanium_from_ore", modID)
//
.addItemTagInput(VoltaicTags.Items.ORE_TITANIUM, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(ElectrodynamicsItems.ITEMS_IMPUREDUST.getValue(SubtypeImpureDust.iron)), 0.3))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEM_COMPOSITEPLATING.get(), 1), 1F, 200, 450.0, "composite_plate", modID)
//
.addItemStackInput(new ItemStack(ElectrodynamicsItems.ITEM_RAWCOMPOSITEPLATING.get()))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_DUST.getValue(SubtypeDust.obsidian), 2), 0.1F, 200, 450.0, "dust_obsidian_from_obsidian", modID)
//
.addItemTagInput(Tags.Items.OBSIDIANS, 1)
//
.save(output);
newRecipe(new ItemStack(Items.FLINT, 1), 0.1F, 200, 450.0, "flint_from_gravel", modID)
//
.addItemTagInput(Tags.Items.GRAVELS, 1)
//
.addItemBiproduct(new ProbableItem(new ItemStack(Items.SAND), 0.2))
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_DUST.getValue(SubtypeDust.salt), 5), 0.1F, 200, 450.0, "salt_from_halite_ore", modID)
//
.addItemTagInput(VoltaicTags.Items.ORE_SALT, 1)
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEMS_RAWORE.getValue(SubtypeRawOre.fluorite), 2), 0.1F, 200, 450.0, "fluorite_crystal_from_fluorite_ore", modID)
//
.addItemTagInput(VoltaicTags.Items.ORE_FLUORITE, 1)
//
.save(output);
newRecipe(new ItemStack(ElectrodynamicsItems.ITEM_SHEETPLASTIC.get(), 2), 0.1F, 200, 450.0, "plastic_sheet_from_plastic_fibers", modID)
//
.addItemStackInput(new ItemStack(ElectrodynamicsItems.ITEM_PLASTIC_FIBERS.get()))
//
.addItemBiproduct(new ProbableItem(new ItemStack(ElectrodynamicsItems.ITEMS_OXIDE.getValue(SubtypeOxide.chromiumdisilicide)), 1.0))
//
.save(output);
newRecipe(new ItemStack(Items.GLOWSTONE_DUST, 4), 0, 200, 450.0, "glowstone_dust_from_glowstone_block", modID)
//
.addItemStackInput(new ItemStack(Blocks.GLOWSTONE))
//
.save(output);
newRecipe(new ItemStack(Items.AMETHYST_SHARD, 4), 0, 200, 300, "amethyst_shard_from_amethyst_block", modID)
//
.addItemStackInput(new ItemStack(Items.AMETHYST_BLOCK))
//
.save(output);
newRecipe(new ItemStack(Items.QUARTZ, 4), 0, 200, 450, "nether_quartz_from_quartz_block", modID)
//
.addItemStackInput(new ItemStack(Blocks.QUARTZ_BLOCK))
//
.save(output);
newRecipe(new ItemStack(Items.BLAZE_POWDER, 10), 0, 100, 500, "blaze_powder_from_blaze_rod", modID)
//
.addItemTagInput(Tags.Items.RODS_BLAZE, 1)
//
.save(output);
newRecipe(new ItemStack(Items.WIND_CHARGE, 10), 0, 100, 500, "wind_charge_from_breeze_rod", modID)
//
.addItemTagInput(Tags.Items.RODS_BREEZE, 1)
//
.save(output);
}
public Item2ItemBuilder<MineralCrusherRecipe> newRecipe(ItemStack stack, float xp, int ticks, double usagePerTick, String name, String group) {
return new Item2ItemBuilder<>(MineralCrusherRecipe::new, stack, BaseRecipeBuilder.RecipeCategory.ITEM_2_ITEM, modID, "mineral_crusher/" + name, group, xp, ticks, usagePerTick);
}
}
| 1 | 0.943907 | 1 | 0.943907 | game-dev | MEDIA | 0.991951 | game-dev | 0.877591 | 1 | 0.877591 |
SkyFireArchives/SkyFireEMU_old | 12,892 | src/server/scripts/Spells/spell_druid.cpp | /*
* Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/>
* Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/>
* Copyright (C) 2005-2012 ScriptDev2 <http://http://www.scriptdev2.com/>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Scripts for spells with SPELLFAMILY_DRUID and SPELLFAMILY_GENERIC spells used by druid players.
* Ordered alphabetically using scriptname.
* Scriptnames of files in this file should be prefixed with "spell_dru_".
*/
#include "ScriptPCH.h"
#include "SpellAuraEffects.h"
enum DruidSpells
{
DRUID_INCREASED_MOONFIRE_DURATION = 38414,
DRUID_NATURES_SPLENDOR = 57865
};
// 62606 - Savage Defense
class spell_dru_savage_defense : public SpellScriptLoader
{
public:
spell_dru_savage_defense() : SpellScriptLoader("spell_dru_savage_defense") { }
class spell_dru_savage_defense_AuraScript : public AuraScript
{
PrepareAuraScript(spell_dru_savage_defense_AuraScript);
uint32 absorbPct;
bool Load()
{
absorbPct = SpellMgr::CalculateSpellEffectAmount(GetSpellProto(), EFFECT_0, GetCaster());
return true;
}
void CalculateAmount(AuraEffect const * /*aurEff*/, int32 & amount, bool & /*canBeRecalculated*/)
{
// Set absorbtion amount to unlimited
amount = -1;
}
void Absorb(AuraEffect * aurEff, DamageInfo & /*dmgInfo*/, uint32 & absorbAmount)
{
absorbAmount = uint32(CalculatePctN(GetTarget()->GetTotalAttackPowerValue(BASE_ATTACK), absorbPct));
aurEff->SetAmount(0);
}
void Register()
{
DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dru_savage_defense_AuraScript::CalculateAmount, EFFECT_0, SPELL_AURA_SCHOOL_ABSORB);
OnEffectAbsorb += AuraEffectAbsorbFn(spell_dru_savage_defense_AuraScript::Absorb, EFFECT_0);
}
};
AuraScript *GetAuraScript() const
{
return new spell_dru_savage_defense_AuraScript();
}
};
class spell_dru_t10_restoration_4p_bonus : public SpellScriptLoader
{
public:
spell_dru_t10_restoration_4p_bonus() : SpellScriptLoader("spell_dru_t10_restoration_4p_bonus") { }
class spell_dru_t10_restoration_4p_bonus_SpellScript : public SpellScript
{
PrepareSpellScript(spell_dru_t10_restoration_4p_bonus_SpellScript);
void FilterTargets(std::list<Unit*>& unitList)
{
unitList.remove(GetTargetUnit());
std::list<Unit*> tempTargets;
std::list<Unit*>::iterator end = unitList.end(), itr = unitList.begin();
for (; itr != end; ++itr)
if (GetCaster()->IsInRaidWith(*itr))
tempTargets.push_back(*itr);
itr = tempTargets.begin();
std::advance(itr, urand(0, tempTargets.size()-1));
unitList.clear();
unitList.push_back(*itr);
}
void Register()
{
OnUnitTargetSelect += SpellUnitTargetFn(spell_dru_t10_restoration_4p_bonus_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_AREA_ALLY_DST);
}
};
SpellScript* GetSpellScript() const
{
return new spell_dru_t10_restoration_4p_bonus_SpellScript();
}
};
// 54846 Glyph of Starfire
class spell_dru_glyph_of_starfire : public SpellScriptLoader
{
public:
spell_dru_glyph_of_starfire() : SpellScriptLoader("spell_dru_glyph_of_starfire") { }
class spell_dru_glyph_of_starfire_SpellScript : public SpellScript
{
PrepareSpellScript(spell_dru_glyph_of_starfire_SpellScript);
bool Validate(SpellEntry const * /*spellEntry*/)
{
if (!sSpellStore.LookupEntry(DRUID_INCREASED_MOONFIRE_DURATION))
return false;
if (!sSpellStore.LookupEntry(DRUID_NATURES_SPLENDOR))
return false;
return true;
}
void HandleScriptEffect(SpellEffIndex /*effIndex*/)
{
Unit* caster = GetCaster();
if (Unit* unitTarget = GetHitUnit())
if (AuraEffect const * aurEff = unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00000002, 0, 0, caster->GetGUID()))
{
Aura* aura = aurEff->GetBase();
uint32 countMin = aura->GetMaxDuration();
uint32 countMax = GetSpellMaxDuration(aura->GetSpellProto()) + 9000;
if (caster->HasAura(DRUID_INCREASED_MOONFIRE_DURATION))
countMax += 3000;
if (caster->HasAura(DRUID_NATURES_SPLENDOR))
countMax += 3000;
if (countMin < countMax)
{
aura->SetDuration(uint32(aura->GetDuration() + 3000));
aura->SetMaxDuration(countMin + 3000);
}
}
}
void Register()
{
OnEffect += SpellEffectFn(spell_dru_glyph_of_starfire_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const
{
return new spell_dru_glyph_of_starfire_SpellScript();
}
};
// 69366 - Moonkin Form passive
class spell_dru_moonkin_form_passive : public SpellScriptLoader
{
public:
spell_dru_moonkin_form_passive() : SpellScriptLoader("spell_dru_moonkin_form_passive") { }
class spell_dru_moonkin_form_passive_AuraScript : public AuraScript
{
PrepareAuraScript(spell_dru_moonkin_form_passive_AuraScript);
uint32 absorbPct;
bool Load()
{
absorbPct = SpellMgr::CalculateSpellEffectAmount(GetSpellProto(), EFFECT_0, GetCaster());
return true;
}
void CalculateAmount(AuraEffect const * /*aurEff*/, int32 & amount, bool & /*canBeRecalculated*/)
{
// Set absorbtion amount to unlimited
amount = -1;
}
void Absorb(AuraEffect * /*aurEff*/, DamageInfo & dmgInfo, uint32 & absorbAmount)
{
// reduces all damage taken while Stunned in Cat Form
if (GetTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & (UNIT_FLAG_STUNNED))
absorbAmount = CalculatePctN(dmgInfo.GetDamage(), absorbPct);
}
void Register()
{
DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dru_moonkin_form_passive_AuraScript::CalculateAmount, EFFECT_0, SPELL_AURA_SCHOOL_ABSORB);
OnEffectAbsorb += AuraEffectAbsorbFn(spell_dru_moonkin_form_passive_AuraScript::Absorb, EFFECT_0);
}
};
AuraScript *GetAuraScript() const
{
return new spell_dru_moonkin_form_passive_AuraScript();
}
};
// 33851 - Primal Tenacity
class spell_dru_primal_tenacity : public SpellScriptLoader
{
public:
spell_dru_primal_tenacity() : SpellScriptLoader("spell_dru_primal_tenacity") { }
class spell_dru_primal_tenacity_AuraScript : public AuraScript
{
PrepareAuraScript(spell_dru_primal_tenacity_AuraScript);
uint32 absorbPct;
bool Load()
{
absorbPct = SpellMgr::CalculateSpellEffectAmount(GetSpellProto(), EFFECT_1, GetCaster());
return true;
}
void CalculateAmount(AuraEffect const * /*aurEff*/, int32 & amount, bool & /*canBeRecalculated*/)
{
// Set absorbtion amount to unlimited
amount = -1;
}
void Absorb(AuraEffect * /*aurEff*/, DamageInfo & dmgInfo, uint32 & absorbAmount)
{
// reduces all damage taken while Stunned in Cat Form
if ((GetTarget()->GetShapeshiftForm() == FORM_CAT) && (GetTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & (UNIT_FLAG_STUNNED)))
absorbAmount = CalculatePctN(dmgInfo.GetDamage(), absorbPct);
}
void Register()
{
DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dru_primal_tenacity_AuraScript::CalculateAmount, EFFECT_1, SPELL_AURA_SCHOOL_ABSORB);
OnEffectAbsorb += AuraEffectAbsorbFn(spell_dru_primal_tenacity_AuraScript::Absorb, EFFECT_1);
}
};
AuraScript *GetAuraScript() const
{
return new spell_dru_primal_tenacity_AuraScript();
}
};
// 50334 Berserk
class spell_dru_berserk : public SpellScriptLoader
{
public:
spell_dru_berserk() : SpellScriptLoader("spell_dru_berserk") {}
class spell_dru_berserk_AuraScript : public AuraScript
{
PrepareAuraScript(spell_dru_berserk_AuraScript);
void HandleEffectApply(AuraEffect const * /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
if (Unit* target = GetTarget())
if (target->GetTypeId() == TYPEID_PLAYER)
target->ToPlayer()->RemoveSpellCategoryCooldown(971, true);
}
void Register()
{
OnEffectApply += AuraEffectApplyFn(spell_dru_berserk_AuraScript::HandleEffectApply, EFFECT_2, SPELL_AURA_MECHANIC_IMMUNITY, AURA_EFFECT_HANDLE_REAL);
}
};
AuraScript* GetAuraScript() const
{
return new spell_dru_berserk_AuraScript();
}
};
class spell_dru_starfall_aoe : public SpellScriptLoader
{
public:
spell_dru_starfall_aoe() : SpellScriptLoader("spell_dru_starfall_aoe") { }
class spell_dru_starfall_aoe_SpellScript : public SpellScript
{
PrepareSpellScript(spell_dru_starfall_aoe_SpellScript);
void FilterTargets(std::list<Unit*>& unitList)
{
unitList.remove(GetTargetUnit());
}
void Register()
{
OnUnitTargetSelect += SpellUnitTargetFn(spell_dru_starfall_aoe_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_AREA_ENEMY_DST);
}
};
SpellScript *GetSpellScript() const
{
return new spell_dru_starfall_aoe_SpellScript();
}
};
class spell_druid_rejuvenation : public SpellScriptLoader
{
public:
spell_druid_rejuvenation() : SpellScriptLoader("spell_druid_rejuvenation") { }
class spell_druid_rejuvenation_SpellScript : public SpellScript
{
PrepareSpellScript(spell_druid_rejuvenation_SpellScript)
bool Validate(SpellEntry const * /*spellEntry*/)
{
return true;
}
void HandleDummy(SpellEffIndex /*effIndex*/)
{
if (Unit * caster = GetCaster())
{
if (caster->GetTypeId() != TYPEID_PLAYER)
return;
caster->ToPlayer()->KilledMonsterCredit(44175, 0);
}
}
void Register()
{
OnEffect += SpellEffectFn(spell_druid_rejuvenation_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_APPLY_AURA);
}
};
SpellScript* GetSpellScript() const
{
return new spell_druid_rejuvenation_SpellScript();
}
};
void AddSC_druid_spell_scripts()
{
new spell_dru_savage_defense();
new spell_dru_t10_restoration_4p_bonus();
new spell_dru_glyph_of_starfire();
new spell_dru_moonkin_form_passive();
new spell_dru_primal_tenacity();
new spell_dru_berserk();
new spell_dru_starfall_aoe();
new spell_druid_rejuvenation();
} | 1 | 0.809158 | 1 | 0.809158 | game-dev | MEDIA | 0.662775 | game-dev | 0.94534 | 1 | 0.94534 |
Sandertv/gophertunnel | 1,560 | minecraft/protocol/packet/player_action.go | package packet
import (
"github.com/sandertv/gophertunnel/minecraft/protocol"
)
// PlayerAction is sent by the client when it executes any action, for example starting to sprint, swim,
// starting the breaking of a block, dropping an item, etc.
type PlayerAction struct {
// EntityRuntimeID is the runtime ID of the player. The runtime ID is unique for each world session, and
// entities are generally identified in packets using this runtime ID.
EntityRuntimeID uint64
// ActionType is the ID of the action that was executed by the player. It is one of the constants that may
// be found in protocol/player.go.
ActionType int32
// BlockPosition is the position of the target block, if the action with the ActionType set concerned a
// block. If that is not the case, the block position will be zero.
BlockPosition protocol.BlockPos
// ResultPosition is the position of the action's result. When a UseItemOn action is sent, this is the position of
// the block clicked, but when a block is placed, this is the position at which the block will be placed.
ResultPosition protocol.BlockPos
// BlockFace is the face of the target block that was touched. If the action with the ActionType set
// concerned a block. If not, the face is always 0.
BlockFace int32
}
// ID ...
func (*PlayerAction) ID() uint32 {
return IDPlayerAction
}
func (pk *PlayerAction) Marshal(io protocol.IO) {
io.Varuint64(&pk.EntityRuntimeID)
io.Varint32(&pk.ActionType)
io.UBlockPos(&pk.BlockPosition)
io.UBlockPos(&pk.ResultPosition)
io.Varint32(&pk.BlockFace)
}
| 1 | 0.863314 | 1 | 0.863314 | game-dev | MEDIA | 0.867571 | game-dev | 0.865678 | 1 | 0.865678 |
LetsMakeAnIndieGame/PhysicsShmup | 1,988 | core/src/com/mygdx/game/systems/HealthBarSystem.java | package com.mygdx.game.systems;
import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.mygdx.game.components.*;
import com.mygdx.game.components.graphics.RenderableComponent;
import com.mygdx.game.components.graphics.SpriteComponent;
import com.mygdx.game.components.physics.PositionComponent;
import com.mygdx.managers.EntityManager;
public class HealthBarSystem extends IteratingSystem {
ComponentMapper<AttachedComponent> attachedMap = ComponentMapper.getFor(AttachedComponent.class);
ComponentMapper<PositionComponent> positionMap = ComponentMapper.getFor(PositionComponent.class);
ComponentMapper<SpriteComponent> spriteMap = ComponentMapper.getFor(SpriteComponent.class);
ComponentMapper<EnemyDataComponent> dataMap = ComponentMapper.getFor(EnemyDataComponent.class);
public HealthBarSystem() {
super(Family.all(HealthBarComponent.class, AttachedComponent.class, PositionComponent.class).get());
}
@Override
public void processEntity(Entity entity, float deltaTime) {
PositionComponent posCom = positionMap.get(entity);
AttachedComponent attCom = attachedMap.get(entity);
SpriteComponent spriteCom = spriteMap.get(entity);
PositionComponent attPosCom = positionMap.get(attCom.attachedTo);
SpriteComponent attSprite = spriteMap.get(attCom.attachedTo);
EnemyDataComponent dataCom = dataMap.get(attCom.attachedTo);
spriteCom.sprites.get(1).setScale(dataCom.health / (float) dataCom.maxHealth, 1);
posCom.x = attPosCom.x;
posCom.y = attPosCom.y + attSprite.sprites.first().getHeight() + 20; // 20 looks better with properly sized sprites
if (spriteCom.sprites.get(1).getScaleX() <= 0) {
entity.remove(RenderableComponent.class);
EntityManager.setToDestroy(entity);
}
}
}
| 1 | 0.700236 | 1 | 0.700236 | game-dev | MEDIA | 0.852441 | game-dev | 0.959267 | 1 | 0.959267 |
cogbt/COGBT | 5,559 | qapi/qapi-clone-visitor.c | /*
* Copy one QAPI object to another
*
* Copyright (C) 2016 Red Hat, Inc.
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*
*/
#include "qemu/osdep.h"
#include "qapi/clone-visitor.h"
#include "qapi/visitor-impl.h"
#include "qapi/error.h"
#include "qapi/qmp/qnull.h"
struct QapiCloneVisitor {
Visitor visitor;
size_t depth;
};
static QapiCloneVisitor *to_qcv(Visitor *v)
{
return container_of(v, QapiCloneVisitor, visitor);
}
static bool qapi_clone_start_struct(Visitor *v, const char *name, void **obj,
size_t size, Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
if (!obj) {
assert(qcv->depth);
/* Only possible when visiting an alternate's object
* branch. Nothing further to do here, since the earlier
* visit_start_alternate() already copied memory. */
return true;
}
*obj = g_memdup(*obj, size);
qcv->depth++;
return true;
}
static void qapi_clone_end(Visitor *v, void **obj)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
if (obj) {
qcv->depth--;
}
}
static bool qapi_clone_start_list(Visitor *v, const char *name,
GenericList **listp, size_t size,
Error **errp)
{
return qapi_clone_start_struct(v, name, (void **)listp, size, errp);
}
static GenericList *qapi_clone_next_list(Visitor *v, GenericList *tail,
size_t size)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/* Unshare the tail of the list cloned by g_memdup() */
tail->next = g_memdup(tail->next, size);
return tail->next;
}
static bool qapi_clone_start_alternate(Visitor *v, const char *name,
GenericAlternate **obj, size_t size,
Error **errp)
{
return qapi_clone_start_struct(v, name, (void **)obj, size, errp);
}
static bool qapi_clone_type_int64(Visitor *v, const char *name, int64_t *obj,
Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/* Value was already cloned by g_memdup() */
return true;
}
static bool qapi_clone_type_uint64(Visitor *v, const char *name,
uint64_t *obj, Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/* Value was already cloned by g_memdup() */
return true;
}
static bool qapi_clone_type_bool(Visitor *v, const char *name, bool *obj,
Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/* Value was already cloned by g_memdup() */
return true;
}
static bool qapi_clone_type_str(Visitor *v, const char *name, char **obj,
Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/*
* Pointer was already cloned by g_memdup; create fresh copy.
* Note that as long as qobject-output-visitor accepts NULL instead of
* "", then we must do likewise. However, we want to obey the
* input visitor semantics of never producing NULL when the empty
* string is intended.
*/
*obj = g_strdup(*obj ?: "");
return true;
}
static bool qapi_clone_type_number(Visitor *v, const char *name, double *obj,
Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
/* Value was already cloned by g_memdup() */
return true;
}
static bool qapi_clone_type_null(Visitor *v, const char *name, QNull **obj,
Error **errp)
{
QapiCloneVisitor *qcv = to_qcv(v);
assert(qcv->depth);
*obj = qnull();
return true;
}
static void qapi_clone_free(Visitor *v)
{
g_free(v);
}
static Visitor *qapi_clone_visitor_new(void)
{
QapiCloneVisitor *v;
v = g_malloc0(sizeof(*v));
v->visitor.type = VISITOR_CLONE;
v->visitor.start_struct = qapi_clone_start_struct;
v->visitor.end_struct = qapi_clone_end;
v->visitor.start_list = qapi_clone_start_list;
v->visitor.next_list = qapi_clone_next_list;
v->visitor.end_list = qapi_clone_end;
v->visitor.start_alternate = qapi_clone_start_alternate;
v->visitor.end_alternate = qapi_clone_end;
v->visitor.type_int64 = qapi_clone_type_int64;
v->visitor.type_uint64 = qapi_clone_type_uint64;
v->visitor.type_bool = qapi_clone_type_bool;
v->visitor.type_str = qapi_clone_type_str;
v->visitor.type_number = qapi_clone_type_number;
v->visitor.type_null = qapi_clone_type_null;
v->visitor.free = qapi_clone_free;
return &v->visitor;
}
void *qapi_clone(const void *src, bool (*visit_type)(Visitor *, const char *,
void **, Error **))
{
Visitor *v;
void *dst = (void *) src; /* Cast away const */
if (!src) {
return NULL;
}
v = qapi_clone_visitor_new();
visit_type(v, NULL, &dst, &error_abort);
visit_free(v);
return dst;
}
void qapi_clone_members(void *dst, const void *src, size_t sz,
bool (*visit_type_members)(Visitor *, void *,
Error **))
{
Visitor *v;
v = qapi_clone_visitor_new();
memcpy(dst, src, sz);
to_qcv(v)->depth++;
visit_type_members(v, dst, &error_abort);
visit_free(v);
}
| 1 | 0.863492 | 1 | 0.863492 | game-dev | MEDIA | 0.364628 | game-dev | 0.787249 | 1 | 0.787249 |
OpenCubicChunks/CubicChunks3 | 7,674 | src_old/test/java/io/github/opencubicchunks/cubicchunks/mock/TestBlockGetter.java | package io.github.opencubicchunks.cubicchunks.mock;
import static io.github.opencubicchunks.cc_core.api.CubicConstants.SECTION_DIAMETER;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import io.github.opencubicchunks.cc_core.api.CubePos;
import io.github.opencubicchunks.cc_core.api.CubicConstants;
import io.github.opencubicchunks.cc_core.utils.Coords;
import io.github.opencubicchunks.cc_core.world.CubicLevelHeightAccessor;
import io.github.opencubicchunks.cubicchunks.world.level.chunk.CubeAccess;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.ticks.TickContainerAccess;
import org.apache.commons.lang3.NotImplementedException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mockito.Mockito;
public class TestBlockGetter implements BlockGetter {
private static final CubicVanillaLevelHeightAccessor MOCK_LEVEL_HEIGHT_ACCESSOR;
static {
MOCK_LEVEL_HEIGHT_ACCESSOR = Mockito.mock(CubicVanillaLevelHeightAccessor.class);
Mockito.when(MOCK_LEVEL_HEIGHT_ACCESSOR.generates2DChunks()).thenReturn(false);
Mockito.when(MOCK_LEVEL_HEIGHT_ACCESSOR.isCubic()).thenReturn(true);
Mockito.when(MOCK_LEVEL_HEIGHT_ACCESSOR.worldStyle()).thenReturn(CubicLevelHeightAccessor.WorldStyle.CUBIC);
Mockito.when(MOCK_LEVEL_HEIGHT_ACCESSOR.getSectionsCount()).thenReturn(0);
}
private final Map<CubePos, TestCube> cubes = new HashMap<>();
private final TestHeightmap heightmap = new TestHeightmap();
public void addCube(TestCube cube) {
// update the global heightmap with the cube's blocks
for (int blockX = cube.getCubePos().minCubeX(), maxX = blockX + CubicConstants.DIAMETER_IN_BLOCKS; blockX < maxX; blockX++) {
for (int blockZ = cube.getCubePos().minCubeZ(), maxZ = blockZ + CubicConstants.DIAMETER_IN_BLOCKS; blockZ < maxZ; blockZ++) {
for (int blockY = cube.getCubePos().minCubeY(), maxY = blockY + CubicConstants.DIAMETER_IN_BLOCKS; blockY < maxY; blockY++) {
heightmap.update(blockX, blockY, blockZ, cube.getBlockState(new BlockPos(blockX, blockY, blockZ)));
}
}
}
// add the cube
this.cubes.put(cube.getCubePos(), cube);
}
public TestHeightmap getHeightmap() {
return this.heightmap;
}
public void setBlockState(BlockPos pos, BlockState state) {
TestCube cube = this.cubes.get(CubePos.from(pos));
cube.setBlockStateLocal(pos, state);
this.heightmap.update(pos.getX(), pos.getY(), pos.getZ(), state);
}
@Nullable @Override public BlockEntity getBlockEntity(BlockPos pos) {
throw new NotImplementedException(TestBlockGetter.class.toString());
}
@Nullable public BlockState getNullableBlockState(BlockPos pos) {
TestCube cube = this.cubes.get(CubePos.from(pos));
if (cube == null) {
return null;
}
return cube.getBlockState(pos);
}
@Override public BlockState getBlockState(BlockPos pos) {
TestCube cube = this.cubes.get(CubePos.from(pos));
if (cube == null) {
return Blocks.BEDROCK.defaultBlockState();
}
return cube.getBlockState(pos);
}
@Override public FluidState getFluidState(BlockPos pos) {
throw new NotImplementedException(TestBlockGetter.class.toString());
}
@Override public int getHeight() {
throw new NotImplementedException(TestBlockGetter.class.toString());
}
@Override public int getMinBuildHeight() {
throw new NotImplementedException(TestBlockGetter.class.toString());
}
public static class TestCube extends CubeAccess implements BlockGetter {
private final BlockState[][] sections = new BlockState[CubicConstants.SECTION_COUNT][];
public TestCube(CubePos cubePos) {
super(cubePos, MOCK_LEVEL_HEIGHT_ACCESSOR, null, MOCK_LEVEL_HEIGHT_ACCESSOR, null, 0, null, null);
for (int i = 0; i < this.sections.length; i++) {
this.sections[i] = new BlockState[SECTION_DIAMETER * SECTION_DIAMETER * SECTION_DIAMETER];
}
}
private static int blockIndex(int x, int y, int z) {
return x + SECTION_DIAMETER * (y + z * SECTION_DIAMETER);
}
public void setBlockStateLocal(BlockPos pos, BlockState state) {
int index = Coords.blockToIndex(pos);
this.sections[index][
blockIndex(
pos.getX() & 15,
pos.getY() & 15,
pos.getZ() & 15)
] = state;
}
@Nullable @Override public BlockState setBlockState(BlockPos pos, BlockState state, boolean isMoving) {
throw new NotImplementedException();
}
@Nullable @Override public BlockEntity getBlockEntity(BlockPos pos) {
throw new NotImplementedException(TestBlockGetter.class.toString());
}
@NotNull @Override public BlockState getBlockState(BlockPos pos) {
int index = Coords.blockToIndex(pos);
BlockState state = this.sections[index][
blockIndex(
pos.getX() & 15,
pos.getY() & 15,
pos.getZ() & 15)
];
return state != null ? state : Blocks.AIR.defaultBlockState();
}
@Override public FluidState getFluidState(BlockPos pos) {
throw new NotImplementedException(TestBlockGetter.class.toString());
}
@Override public int getHeight() {
throw new NotImplementedException(TestBlockGetter.class.toString());
}
@Override public void setBlockEntity(BlockEntity blockEntity) {
throw new NotImplementedException();
}
@Override public void addEntity(Entity entity) {
throw new NotImplementedException();
}
@Override public ChunkStatus getStatus() {
return ChunkStatus.LIGHT;
}
@Override public void removeBlockEntity(BlockPos pos) {
throw new NotImplementedException();
}
@Nullable @Override public CompoundTag getBlockEntityNbtForSaving(BlockPos pos) {
throw new NotImplementedException();
}
@Override public Stream<BlockPos> getLights() {
throw new NotImplementedException();
}
@Override public TickContainerAccess<Block> getBlockTicks() {
throw new NotImplementedException();
}
@Override public TickContainerAccess<Fluid> getFluidTicks() {
throw new NotImplementedException();
}
@Override public TicksToSave getTicksForSerialization() {
throw new NotImplementedException();
}
@Override public int getMinBuildHeight() {
throw new NotImplementedException(TestBlockGetter.class.toString());
}
}
interface CubicVanillaLevelHeightAccessor extends CubicLevelHeightAccessor, LevelHeightAccessor {
}
}
| 1 | 0.838891 | 1 | 0.838891 | game-dev | MEDIA | 0.937391 | game-dev | 0.925492 | 1 | 0.925492 |
NAMERIO/namerio.biz-resurviv | 9,410 | src/packets/receiving/inputPacket.ts | import { ReceivingPacket } from "../receivingPacket";
import {
Constants,
GameMode,
InputType,
ScopeTypes
} from "../../utils/constants";
import { objectCollision, sameLayer } from "../../utils/math";
import type { SurvivBitStream } from "../../utils/survivBitStream";
import { Config, TypeToId } from "../../utils/data";
import { Vec2 } from "planck";
import { type Obstacle } from "../../game/objects/obstacle";
import { Loot } from "../../game/objects/loot";
let i = 0;
export class InputPacket extends ReceivingPacket {
deserialize(stream: SurvivBitStream): void {
const p = this.p;
if (p.dead) return;
stream.readUint8(); // Discard second byte (this.seq)
// Movement
p.movingLeft = stream.readBoolean();
p.movingRight = stream.readBoolean();
p.movingUp = stream.readBoolean();
p.movingDown = stream.readBoolean();
// Shooting
const shootStart = stream.readBoolean();
p.shootStart = p.shootStart ? true : shootStart;
p.shootHold = stream.readBoolean();
// Mobile stuff
stream.readBoolean(); // Portrait
const touchMoveActive = stream.readBoolean();
if (touchMoveActive) {
if (!p.isMobile) {
p.isMobile = true;
p.zoom = Constants.scopeZoomRadius.mobile["1xscope"];
}
p.touchMoveDir = stream.readUnitVec(8);
// Detect when the player isn't moving
if (p.touchMoveDir.x === 1 && p.touchMoveDir.y > 0 && p.touchMoveDir.y < 0.01) {
p.touchMoveDir = Vec2(0, 0);
}
stream.readUint8(); // Touch move len
}
// Direction
const direction = stream.readUnitVec(10);
if (p.direction !== direction) {
// if (p.direction.x !== direction.x && p.direction.y !== direction.y) {
p.direction = direction;
p.moving = true;
}
p.distanceToMouse = stream.readFloat(0, Constants.MouseMaxDist, 8); // Distance to mouse
// Other inputs
const inputCount = stream.readBits(4);
for (let i = 0; i < inputCount; i++) {
const input = stream.readUint8();
switch (input) { // TODO Remove redundant code
case InputType.Interact: {
//if theres no revive keybind set default to interact keybind
p.revive();
let minDistInteractable = Number.MAX_VALUE; let minDist = Number.MAX_VALUE;
let minDistInteractableObject, minDistObject;
for (const object of p.visibleObjects) {
if (object.interactable && sameLayer(p.layer, object.layer)) {
const record = objectCollision(object, p.position, p.scale + object.interactionRad);
if (record?.collided) {
if ((object as any).isDoor) p.interactWith(object as Obstacle);
else if (record.distance < minDist) {
if (record.distance < minDistInteractable && (!(object instanceof Loot) || object.canPickUpItem(p))) {
minDistInteractable = record.distance;
minDistInteractableObject = object;
}
minDist = record.distance;
minDistObject = object;
}
}
}
}
if (minDistInteractableObject) {
p.interactWith(minDistInteractableObject);
} else if (minDistObject) {
p.interactWith(minDistObject);
}
break;
}
case InputType.Loot: {
let minDistInteractable = Number.MAX_VALUE; let minDist = Number.MAX_VALUE;
let minDistInteractableObject, minDistObject;
for (const object of p.visibleObjects) {
if (object instanceof Loot && object.interactable && sameLayer(p.layer, object.layer)) {
const record = objectCollision(object, p.position, p.scale + object.interactionRad);
if (record?.collided && record.distance < minDist) {
if (record.distance < minDistInteractable && object.canPickUpItem(p)) {
minDistInteractable = record.distance;
minDistInteractableObject = object;
}
minDist = record.distance;
minDistObject = object;
}
}
}
if (minDistInteractableObject) {
p.interactWith(minDistInteractableObject);
} else if (minDistObject) {
p.interactWith(minDistObject);
}
break;
}
case InputType.Use: {
for (const object of p.visibleObjects) {
if (((object as any).isDoor || (object as any).isButton || (object as any).isPuzzlePiece) && sameLayer(object.layer, p.layer)) {
const record = objectCollision(object, p.position, p.scale + object.interactionRad);
if (record?.collided) p.interactWith(object as Obstacle);
}
}
break;
}
case InputType.EquipPrimary:
p.switchSlot(0);
break;
case InputType.EquipSecondary:
p.switchSlot(1);
break;
case InputType.EquipMelee:
p.switchSlot(2);
break;
case InputType.EquipThrowable:
p.switchSlot(3);
break;
case InputType.EquipPrevWeap:
p.switchSlot(p.selectedWeaponSlot - 1, true);
break;
case InputType.EquipNextWeap:
p.switchSlot(p.selectedWeaponSlot + 1, true);
break;
case InputType.SwapWeapSlots:
p.swapWeaponSlots();
break;
case InputType.EquipOtherGun:
if (p.weapons[0]?.typeId && p.weapons[1]?.typeId) p.switchSlot(p.selectedWeaponSlot === 0 ? 1 : 0);
else if (p.selectedWeaponSlot === 2 && p.weapons[0]?.typeId) p.switchSlot(0);
else if (p.selectedWeaponSlot === 2 && p.weapons[1]?.typeId) p.switchSlot(1);
else p.switchSlot(2);
break;
case InputType.EquipLastWeap:
p.switchSlot(p.lastWeaponSlot);
break;
case InputType.EquipNextScope:
p.setScope(ScopeTypes[ScopeTypes.indexOf(p.scope.typeString) + 1], true);
break;
case InputType.EquipPrevScope:
p.setScope(ScopeTypes[ScopeTypes.indexOf(p.scope.typeString) - 1], true);
break;
case InputType.Reload:
p.reload();
break;
case InputType.Cancel:
p.cancelAction();
break;
case InputType.StowWeapons:
p.switchSlot(2);
break;
case InputType.UseBandage:
p.useBandage();
break;
case InputType.UseHealthKit:
p.useMedkit();
break;
case InputType.UseSoda:
p.useSoda();
break;
case InputType.UsePainkiller:
p.usePills();
break;
case InputType.Revive:
p.revive();
break;
}
}
// Item use logic
switch (stream.readGameType()) {
case TypeToId.bandage:
p.useBandage();
break;
case TypeToId.healthkit:
p.useMedkit();
break;
case TypeToId.soda:
p.useSoda();
break;
case TypeToId.painkiller:
p.usePills();
break;
case TypeToId["1xscope"]:
p.setScope("1xscope");
break;
case TypeToId["2xscope"]:
p.setScope("2xscope");
break;
case TypeToId["4xscope"]:
p.setScope("4xscope");
break;
case TypeToId["8xscope"]:
p.setScope("8xscope");
break;
case TypeToId["15xscope"]:
p.setScope("15xscope");
break;
}
stream.readBits(6); // Padding
}
}
| 1 | 0.946826 | 1 | 0.946826 | game-dev | MEDIA | 0.897629 | game-dev | 0.985471 | 1 | 0.985471 |
Fluorohydride/ygopro-scripts | 2,205 | c25137581.lua | --潜伏するG
local s,id,o=GetID()
function s.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,id)
e1:SetCondition(s.spcon)
e1:SetTarget(s.sptg)
e1:SetOperation(s.spop)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_FLIP)
e2:SetCondition(s.descon)
e2:SetTarget(s.destg)
e2:SetOperation(s.desop)
c:RegisterEffect(e2)
end
function s.spcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(Card.IsSummonPlayer,1,nil,1-tp)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEDOWN_DEFENSE) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToChain() and Duel.SpecialSummonStep(c,0,tp,tp,false,false,POS_FACEDOWN_DEFENSE) then
Duel.ConfirmCards(1-tp,c)
c:RegisterFlagEffect(id,RESET_EVENT+RESETS_STANDARD,0,1)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetLabelObject(c)
e1:SetOperation(s.flipup)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
Duel.SpecialSummonComplete()
end
function s.flipup(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetLabelObject()
if c:GetFlagEffect(id)>0 then Duel.ChangePosition(c,POS_FACEUP_DEFENSE) end
e:Reset()
end
function s.descon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()==PHASE_END
end
function s.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local g=Duel.GetMatchingGroup(Card.IsSummonType,tp,LOCATION_MZONE,LOCATION_MZONE,nil,SUMMON_TYPE_SPECIAL)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,#g,0,0)
end
function s.desop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(Card.IsSummonType,tp,LOCATION_MZONE,LOCATION_MZONE,nil,SUMMON_TYPE_SPECIAL)
Duel.Destroy(g,REASON_EFFECT)
end
| 1 | 0.868325 | 1 | 0.868325 | game-dev | MEDIA | 0.979656 | game-dev | 0.947903 | 1 | 0.947903 |
GTNewHorizons/GT5-Unofficial | 5,035 | src/main/java/gtPlusPlus/core/block/general/antigrief/BlockWitherProof.java | package gtPlusPlus.core.block.general.antigrief;
import static gregtech.api.enums.Mods.GTPlusPlus;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.entity.boss.IBossDisplayData;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.Explosion;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import gregtech.api.util.StringUtils;
import gtPlusPlus.core.creative.AddToCreativeTab;
import gtPlusPlus.core.util.Utils;
public class BlockWitherProof extends Block {
public BlockWitherProof() {
super(Material.redstoneLight);
this.setBlockName(StringUtils.sanitizeString("blockBlackGate"));
this.setBlockTextureName(GTPlusPlus.ID + ":" + "blockFrameGt");
this.setCreativeTab(AddToCreativeTab.tabBlock);
this.setHardness(-1F);
this.setResistance(5000.0F);
this.setHarvestLevel("pickaxe", 3);
this.setStepSound(soundTypeMetal);
GameRegistry.registerBlock(this, StringUtils.sanitizeString("blockBlackGate"));
}
@Override
@SideOnly(Side.CLIENT)
public int getRenderBlockPass() {
return 1;
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(final IIconRegister iIcon) {
this.blockIcon = iIcon.registerIcon(GTPlusPlus.ID + ":" + "blockFrameGt");
}
@Override
public void onBlockExploded(final World world, final int x, final int y, final int z, final Explosion explosion) {
// prevent from being destroyed by wither and nukes.
}
@Override
public boolean canDropFromExplosion(final Explosion p_149659_1_) {
return false;
}
@Override
public boolean canEntityDestroy(final IBlockAccess world, final int x, final int y, final int z,
final Entity entity) {
if ((entity == null) || !entity.isEntityAlive()) {
return false;
}
if (entity instanceof IBossDisplayData) {
return false;
} else {
return super.canEntityDestroy(world, x, y, z, entity);
}
}
// Colour Handling
private static final int mWitherColour = Utils.rgbtoHexValue(32, 32, 32);
@Override
public int colorMultiplier(final IBlockAccess par1IBlockAccess, final int par2, final int par3, final int par4) {
return mWitherColour;
}
@Override
public int getRenderColor(final int aMeta) {
return mWitherColour;
}
@Override
public boolean canCreatureSpawn(final EnumCreatureType type, final IBlockAccess world, final int x, final int y,
final int z) {
return false;
}
@Override
public void breakBlock(World p_149749_1_, int p_149749_2_, int p_149749_3_, int p_149749_4_, Block p_149749_5_,
int p_149749_6_) {
super.breakBlock(p_149749_1_, p_149749_2_, p_149749_3_, p_149749_4_, p_149749_5_, p_149749_6_);
}
@Override
public float getPlayerRelativeBlockHardness(EntityPlayer aPlayer, World p_149737_2_, int p_149737_3_,
int p_149737_4_, int p_149737_5_) {
if (aPlayer instanceof EntityPlayerMP) {
return 1f;
}
return -1f;
}
@Override
public float getExplosionResistance(Entity p_149638_1_) {
return Float.MAX_VALUE;
}
@Override
public void onBlockClicked(World p_149699_1_, int p_149699_2_, int p_149699_3_, int p_149699_4_,
EntityPlayer p_149699_5_) {
super.onBlockClicked(p_149699_1_, p_149699_2_, p_149699_3_, p_149699_4_, p_149699_5_);
}
@Override
public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity) {
if ((entity == null) || !entity.isEntityAlive()) {
return;
}
if (!(entity instanceof IBossDisplayData)) {
super.onEntityCollidedWithBlock(world, x, y, z, entity);
}
}
@Override
public void harvestBlock(World p_149636_1_, EntityPlayer p_149636_2_, int p_149636_3_, int p_149636_4_,
int p_149636_5_, int p_149636_6_) {
super.harvestBlock(p_149636_1_, p_149636_2_, p_149636_3_, p_149636_4_, p_149636_5_, p_149636_6_);
}
@Override
public boolean canHarvestBlock(EntityPlayer player, int meta) {
if (player instanceof EntityPlayerMP) {
return true;
}
return super.canHarvestBlock(player, meta);
}
@Override
public float getExplosionResistance(Entity par1Entity, World world, int x, int y, int z, double explosionX,
double explosionY, double explosionZ) {
return Float.MAX_VALUE;
}
}
| 1 | 0.621262 | 1 | 0.621262 | game-dev | MEDIA | 0.988629 | game-dev | 0.515344 | 1 | 0.515344 |
organicmaps/organicmaps | 36,776 | libs/drape_frontend/user_event_stream.cpp | #include "drape_frontend/user_event_stream.hpp"
#include "drape_frontend/animation/follow_animation.hpp"
#include "drape_frontend/animation/linear_animation.hpp"
#include "drape_frontend/animation/parallel_animation.hpp"
#include "drape_frontend/animation/scale_animation.hpp"
#include "drape_frontend/animation/sequence_animation.hpp"
#include "drape_frontend/animation_constants.hpp"
#include "drape_frontend/animation_system.hpp"
#include "drape_frontend/animation_utils.hpp"
#include "drape_frontend/screen_animations.hpp"
#include "drape_frontend/screen_operations.hpp"
#include "drape_frontend/visual_params.hpp"
#include "platform/platform.hpp"
#include "base/macros.hpp"
#include <cmath>
#ifdef DEBUG
#define TEST_CALL(action) \
if (m_testFn) \
m_testFn(action)
#else
#define TEST_CALL(action)
#endif
namespace df
{
namespace
{
uint64_t constexpr kDoubleTapPauseMs = 250;
uint64_t constexpr kLongTouchMs = 500;
uint64_t constexpr kKineticDelayMs = 500;
float constexpr kForceTapThreshold = 0.75;
size_t GetValidTouchesCount(std::array<Touch, 2> const & touches)
{
size_t result = 0;
if (touches[0].m_id != -1)
++result;
if (touches[1].m_id != -1)
++result;
return result;
}
} // namespace
#ifdef DEBUG
char const * UserEventStream::BEGIN_DRAG = "BeginDrag";
char const * UserEventStream::DRAG = "Drag";
char const * UserEventStream::END_DRAG = "EndDrag";
char const * UserEventStream::BEGIN_SCALE = "BeginScale";
char const * UserEventStream::SCALE = "Scale";
char const * UserEventStream::END_SCALE = "EndScale";
char const * UserEventStream::BEGIN_TAP_DETECTOR = "BeginTap";
char const * UserEventStream::LONG_TAP_DETECTED = "LongTap";
char const * UserEventStream::SHORT_TAP_DETECTED = "ShortTap";
char const * UserEventStream::CANCEL_TAP_DETECTOR = "CancelTap";
char const * UserEventStream::TRY_FILTER = "TryFilter";
char const * UserEventStream::END_FILTER = "EndFilter";
char const * UserEventStream::CANCEL_FILTER = "CancelFilter";
char const * UserEventStream::TWO_FINGERS_TAP = "TwoFingersTap";
char const * UserEventStream::BEGIN_DOUBLE_TAP_AND_HOLD = "BeginDoubleTapAndHold";
char const * UserEventStream::DOUBLE_TAP_AND_HOLD = "DoubleTapAndHold";
char const * UserEventStream::END_DOUBLE_TAP_AND_HOLD = "EndDoubleTapAndHold";
#endif
void TouchEvent::SetFirstTouch(const Touch & touch)
{
m_touches[0] = touch;
}
void TouchEvent::SetSecondTouch(Touch const & touch)
{
m_touches[1] = touch;
}
void TouchEvent::PrepareTouches(std::array<Touch, 2> const & previousTouches)
{
if (GetValidTouchesCount(m_touches) == 2 && GetValidTouchesCount(previousTouches) > 0)
{
if (previousTouches[0].m_id == m_touches[1].m_id)
Swap();
}
}
void TouchEvent::SetFirstMaskedPointer(uint8_t firstMask)
{
m_pointersMask = (m_pointersMask & 0xFF00) | static_cast<uint16_t>(firstMask);
}
uint8_t TouchEvent::GetFirstMaskedPointer() const
{
return static_cast<uint8_t>(m_pointersMask & 0xFF);
}
void TouchEvent::SetSecondMaskedPointer(uint8_t secondMask)
{
ASSERT(secondMask == INVALID_MASKED_POINTER || GetFirstMaskedPointer() != INVALID_MASKED_POINTER, ());
m_pointersMask = (static_cast<uint16_t>(secondMask) << 8) | (m_pointersMask & 0xFF);
}
uint8_t TouchEvent::GetSecondMaskedPointer() const
{
return static_cast<uint8_t>((m_pointersMask & 0xFF00) >> 8);
}
size_t TouchEvent::GetMaskedCount()
{
return static_cast<size_t>(GetFirstMaskedPointer() != INVALID_MASKED_POINTER) +
static_cast<size_t>(GetSecondMaskedPointer() != INVALID_MASKED_POINTER);
}
void TouchEvent::Swap()
{
auto swapIndex = [](uint8_t index) -> uint8_t
{
if (index == INVALID_MASKED_POINTER)
return index;
return index ^ 0x1;
};
std::swap(m_touches[0], m_touches[1]);
SetFirstMaskedPointer(swapIndex(GetFirstMaskedPointer()));
SetSecondMaskedPointer(swapIndex(GetSecondMaskedPointer()));
}
std::string DebugPrint(Touch const & t)
{
return DebugPrint(t.m_location) + "; " + std::to_string(t.m_id) + "; " + std::to_string(t.m_force);
}
std::string DebugPrint(TouchEvent const & e)
{
return std::to_string(e.m_type) + "; { " + DebugPrint(e.m_touches[0]) + " }";
}
UserEventStream::UserEventStream()
: m_state(STATE_EMPTY)
, m_animationSystem(AnimationSystem::Instance())
, m_startDragOrg(m2::PointD::Zero())
, m_startDoubleTapAndHold(m2::PointD::Zero())
, m_dragThreshold(math::Pow2(VisualParams::Instance().GetDragThreshold()))
{}
void UserEventStream::AddEvent(drape_ptr<UserEvent> && event)
{
std::lock_guard guard(m_lock);
m_events.emplace_back(std::move(event));
}
ScreenBase const & UserEventStream::ProcessEvents(bool & modelViewChanged, bool & viewportChanged, bool & activeFrame)
{
TEventsList events;
{
std::lock_guard guard(m_lock);
std::swap(m_events, events);
}
m2::RectD const prevPixelRect = GetCurrentScreen().PixelRect();
activeFrame = false;
viewportChanged = false;
m_modelViewChanged = !events.empty() || m_state == STATE_SCALE || m_state == STATE_DRAG;
for (auto const & e : events)
{
bool breakAnim = false;
switch (e->GetType())
{
case UserEvent::EventType::Scale:
{
ref_ptr<ScaleEvent> scaleEvent = make_ref(e);
breakAnim = OnSetScale(scaleEvent);
TouchCancel(m_touches);
}
break;
case UserEvent::EventType::Move:
{
ref_ptr<MoveEvent> moveEvent = make_ref(e);
breakAnim = OnMove(moveEvent);
TouchCancel(m_touches);
}
break;
case UserEvent::EventType::Resize:
{
ref_ptr<ResizeEvent> resizeEvent = make_ref(e);
m_navigator.OnSize(resizeEvent->GetWidth(), resizeEvent->GetHeight());
if (!m_visibleViewport.IsValid())
m_visibleViewport = m2::RectD(0, 0, resizeEvent->GetWidth(), resizeEvent->GetHeight());
viewportChanged = true;
breakAnim = true;
TouchCancel(m_touches);
if (m_state == STATE_DOUBLE_TAP_HOLD)
EndDoubleTapAndHold(m_touches[0]);
}
break;
case UserEvent::EventType::SetAnyRect:
{
m_needTrackCenter = false;
ref_ptr<SetAnyRectEvent> anyRectEvent = make_ref(e);
breakAnim = OnSetAnyRect(anyRectEvent);
TouchCancel(m_touches);
}
break;
case UserEvent::EventType::SetRect:
{
m_needTrackCenter = false;
ref_ptr<SetRectEvent> rectEvent = make_ref(e);
breakAnim = OnSetRect(rectEvent);
TouchCancel(m_touches);
}
break;
case UserEvent::EventType::SetCenter:
{
m_needTrackCenter = false;
ref_ptr<SetCenterEvent> centerEvent = make_ref(e);
breakAnim = OnSetCenter(centerEvent);
TouchCancel(m_touches);
}
break;
case UserEvent::EventType::Touch:
{
m_needTrackCenter = false;
ref_ptr<TouchEvent> touchEvent = make_ref(e);
breakAnim = ProcessTouch(*touchEvent.get());
}
break;
case UserEvent::EventType::Rotate:
{
m_needTrackCenter = false;
ref_ptr<RotateEvent> rotateEvent = make_ref(e);
breakAnim = OnRotate(rotateEvent);
}
break;
case UserEvent::EventType::FollowAndRotate:
{
m_needTrackCenter = false;
ref_ptr<FollowAndRotateEvent> followEvent = make_ref(e);
breakAnim = SetFollowAndRotate(followEvent->GetUserPos(), followEvent->GetPixelZero(), followEvent->GetAzimuth(),
followEvent->GetPreferredZoomLelel(), followEvent->GetAutoScale(),
followEvent->IsAnim(), followEvent->IsAutoScale(),
followEvent->GetOnFinishAction(), followEvent->GetParallelAnimCreator());
}
break;
case UserEvent::EventType::AutoPerspective:
{
m_needTrackCenter = false;
ref_ptr<SetAutoPerspectiveEvent> perspectiveEvent = make_ref(e);
SetAutoPerspective(perspectiveEvent->IsAutoPerspective());
}
break;
case UserEvent::EventType::VisibleViewport:
{
ref_ptr<SetVisibleViewportEvent> viewportEvent = make_ref(e);
breakAnim = OnNewVisibleViewport(viewportEvent);
}
break;
case UserEvent::EventType::Scroll:
{
ref_ptr<ScrollEvent> scrollEvent = make_ref(e);
breakAnim = OnScroll(scrollEvent);
TouchCancel(m_touches);
}
break;
case UserEvent::EventType::ActiveFrame:
{
activeFrame = true;
}
break;
default: ASSERT(false, ()); break;
}
if (breakAnim)
m_modelViewChanged = true;
}
ApplyAnimations();
if (GetValidTouchesCount(m_touches) == 1)
{
if (m_state == STATE_WAIT_DOUBLE_TAP)
DetectShortTap(m_touches[0]);
else if (m_state == STATE_TAP_DETECTION)
DetectLongTap(m_touches[0]);
}
if (m_modelViewChanged)
m_animationSystem.UpdateLastScreen(GetCurrentScreen());
modelViewChanged = m_modelViewChanged;
m_modelViewChanged = false;
if (!viewportChanged)
{
double constexpr kEps = 1e-5;
viewportChanged = !m2::IsEqualSize(prevPixelRect, GetCurrentScreen().PixelRect(), kEps, kEps);
}
return m_navigator.Screen();
}
void UserEventStream::ApplyAnimations()
{
if (m_animationSystem.AnimationExists(Animation::Object::MapPlane))
{
ScreenBase screen;
if (m_animationSystem.GetScreen(GetCurrentScreen(), screen))
m_navigator.SetFromScreen(screen);
m_modelViewChanged = true;
}
}
ScreenBase const & UserEventStream::GetCurrentScreen() const
{
return m_navigator.Screen();
}
m2::RectD const & UserEventStream::GetVisibleViewport() const
{
return m_visibleViewport;
}
bool UserEventStream::OnSetScale(ref_ptr<ScaleEvent> scaleEvent)
{
double factor = scaleEvent->GetFactor();
m2::PointD scaleCenter = scaleEvent->GetPxPoint();
if (m_listener)
m_listener->CorrectScalePoint(scaleCenter);
if (scaleEvent->IsAnim())
{
auto followAnim = m_animationSystem.FindAnimation<MapFollowAnimation>(Animation::Type::MapFollow);
if (followAnim == nullptr)
{
auto const parallelAnim =
m_animationSystem.FindAnimation<ParallelAnimation>(Animation::Type::Parallel, kParallelFollowAnim.c_str());
if (parallelAnim != nullptr)
followAnim = parallelAnim->FindAnimation<MapFollowAnimation>(Animation::Type::MapFollow);
}
if (followAnim != nullptr && followAnim->HasScale())
{
// Scaling is not possible if current follow animation does pixel offset.
if (followAnim->HasPixelOffset() && !followAnim->IsAutoZoom())
return false;
// Reset follow animation with scaling if we apply scale explicitly.
ResetAnimations(Animation::Type::MapFollow);
ResetAnimations(Animation::Type::Parallel, kParallelFollowAnim);
}
m2::PointD glbScaleCenter = m_navigator.PtoG(m_navigator.P3dtoP(scaleCenter));
if (m_listener)
m_listener->CorrectGlobalScalePoint(glbScaleCenter);
ScreenBase const & startScreen = GetCurrentScreen();
auto anim = GetScaleAnimation(startScreen, scaleCenter, glbScaleCenter, factor);
anim->SetOnFinishAction([this](ref_ptr<Animation> animation)
{
if (m_listener)
m_listener->OnAnimatedScaleEnded();
});
m_animationSystem.CombineAnimation(std::move(anim));
return false;
}
ResetMapPlaneAnimations();
m_navigator.Scale(scaleCenter, factor);
if (m_listener)
m_listener->OnAnimatedScaleEnded();
return true;
}
bool UserEventStream::OnMove(ref_ptr<MoveEvent> moveEvent)
{
double const factorX = moveEvent->GetFactorX();
double const factorY = moveEvent->GetFactorY();
ScreenBase screen;
GetTargetScreen(screen);
auto const & rect = screen.PixelRectIn3d();
screen.Move(factorX * rect.SizeX(), -factorY * rect.SizeY());
ShrinkAndScaleInto(screen, df::GetWorldRect());
return SetScreen(screen, moveEvent->IsAnim());
}
bool UserEventStream::OnSetAnyRect(ref_ptr<SetAnyRectEvent> anyRectEvent)
{
return SetRect(anyRectEvent->GetRect(), anyRectEvent->IsAnim(), anyRectEvent->FitInViewport(),
anyRectEvent->UseVisibleViewport());
}
bool UserEventStream::OnSetRect(ref_ptr<SetRectEvent> rectEvent)
{
return SetRect(rectEvent->GetRect(), rectEvent->GetZoom(), rectEvent->GetApplyRotation(), rectEvent->IsAnim(),
rectEvent->UseVisibleViewport(), rectEvent->GetParallelAnimCreator());
}
bool UserEventStream::OnSetCenter(ref_ptr<SetCenterEvent> centerEvent)
{
m2::PointD const & center = centerEvent->GetCenter();
auto const zoom = centerEvent->GetZoom();
auto const scaleFactor = centerEvent->GetScaleFactor();
if (centerEvent->TrackVisibleViewport())
{
m_needTrackCenter = true;
m_trackedCenter = center;
}
ScreenBase screen = GetCurrentScreen();
if (zoom != kDoNotChangeZoom)
{
screen.SetFromParams(center, screen.GetAngle(), GetScreenScale(zoom));
screen.MatchGandP3d(center, m_visibleViewport.Center());
}
else if (scaleFactor > 0.0)
{
screen.SetOrg(center);
ApplyScale(m_visibleViewport.Center(), scaleFactor, screen);
}
else
{
GetTargetScreen(screen);
screen.MatchGandP3d(center, m_visibleViewport.Center());
}
ShrinkAndScaleInto(screen, df::GetWorldRect());
return SetScreen(screen, centerEvent->IsAnim(), centerEvent->GetParallelAnimCreator());
}
bool UserEventStream::OnRotate(ref_ptr<RotateEvent> rotateEvent)
{
return SetAngle(rotateEvent->GetTargetAzimuth(), rotateEvent->IsAnim(), rotateEvent->GetParallelAnimCreator());
}
bool UserEventStream::OnNewVisibleViewport(ref_ptr<SetVisibleViewportEvent> viewportEvent)
{
m2::RectD const prevVisibleViewport = m_visibleViewport;
m_visibleViewport = viewportEvent->GetRect();
m2::PointD gOffset;
ScreenBase screen;
auto const hasOffset =
m_listener->OnNewVisibleViewport(prevVisibleViewport, m_visibleViewport, !m_needTrackCenter, gOffset);
if (m_needTrackCenter)
{
GetTargetScreen(screen);
screen.MatchGandP3d(m_trackedCenter, m_visibleViewport.Center());
ShrinkAndScaleInto(screen, df::GetWorldRect());
return SetScreen(screen, true /* isAnim */);
}
else if (hasOffset)
{
screen = GetCurrentScreen();
screen.MoveG(gOffset);
return SetScreen(screen, true /* isAnim */);
}
return false;
}
bool UserEventStream::OnScroll(ref_ptr<ScrollEvent> scrollEvent)
{
double const distanceX = scrollEvent->GetDistanceX();
double const distanceY = scrollEvent->GetDistanceY();
ScreenBase screen;
GetTargetScreen(screen);
screen.Move(-distanceX, -distanceY);
ShrinkAndScaleInto(screen, df::GetWorldRect());
if (m_listener)
m_listener->OnScrolled({-distanceX, -distanceY});
return SetScreen(screen, false);
}
bool UserEventStream::SetAngle(double azimuth, bool isAnim, TAnimationCreator const & parallelAnimCreator)
{
ScreenBase screen;
GetTargetScreen(screen);
m2::PointD pt = m_visibleViewport.Center();
m2::PointD gPt = screen.PtoG(screen.P3dtoP(pt));
if (screen.isPerspective())
{
return SetFollowAndRotate(gPt, pt, azimuth, kDoNotChangeZoom, kDoNotAutoZoom, isAnim, false /* isAutoScale */,
nullptr /* onFinishAction */, parallelAnimCreator);
}
screen.SetAngle(azimuth);
screen.MatchGandP3d(gPt, pt);
return SetScreen(screen, isAnim, parallelAnimCreator);
}
bool UserEventStream::SetRect(m2::RectD rect, int zoom, bool applyRotation, bool isAnim, bool useVisibleViewport,
TAnimationCreator const & parallelAnimCreator)
{
CheckMinGlobalRect(rect, kDefault3dScale);
CheckMinMaxVisibleScale(rect, zoom, kDefault3dScale);
m2::AnyRectD targetRect = applyRotation ? ToRotated(m_navigator, rect) : m2::AnyRectD(rect);
return SetRect(targetRect, isAnim, true /* fitInViewport */, useVisibleViewport, parallelAnimCreator);
}
bool UserEventStream::SetRect(m2::AnyRectD const & rect, bool isAnim, bool fitInViewport, bool useVisibleViewport,
TAnimationCreator const & parallelAnimCreator)
{
ScreenBase tmp = GetCurrentScreen();
if (fitInViewport)
{
auto viewportRect = tmp.PixelRectIn3d();
if (useVisibleViewport && m_visibleViewport.IsValid())
viewportRect = m_visibleViewport;
tmp.SetFromRects(rect, viewportRect);
tmp.MatchGandP3d(rect.GlobalCenter(), viewportRect.Center());
}
else
{
tmp.SetFromRects(rect, tmp.PixelRect());
}
return SetScreen(tmp, isAnim, parallelAnimCreator);
}
bool UserEventStream::SetScreen(ScreenBase const & endScreen, bool isAnim,
TAnimationCreator const & parallelAnimCreator)
{
if (isAnim)
{
ScreenBase const & screen = GetCurrentScreen();
drape_ptr<Animation> anim = GetRectAnimation(screen, endScreen);
if (!df::IsAnimationAllowed(anim->GetDuration(), screen))
{
anim.reset();
double const moveDuration = PositionInterpolator::GetMoveDuration(screen.GetOrg(), endScreen.GetOrg(), screen);
if (moveDuration > kMaxAnimationTimeSec)
anim = GetPrettyMoveAnimation(screen, endScreen);
}
else
{
anim->SetMaxDuration(kMaxAnimationTimeSec);
}
if (anim != nullptr)
{
if (parallelAnimCreator != nullptr)
{
drape_ptr<ParallelAnimation> parallelAnim = make_unique_dp<ParallelAnimation>();
parallelAnim->SetCustomType(kParallelLinearAnim);
parallelAnim->AddAnimation(parallelAnimCreator(nullptr /* syncAnim */));
parallelAnim->AddAnimation(std::move(anim));
m_animationSystem.CombineAnimation(std::move(parallelAnim));
}
else
{
m_animationSystem.CombineAnimation(std::move(anim));
}
return false;
}
}
ResetMapPlaneAnimations();
m_navigator.SetFromScreen(endScreen);
return true;
}
bool UserEventStream::InterruptFollowAnimations(bool force)
{
Animation const * followAnim = m_animationSystem.FindAnimation<MapFollowAnimation>(Animation::Type::MapFollow);
if (followAnim == nullptr)
followAnim =
m_animationSystem.FindAnimation<SequenceAnimation>(Animation::Type::Sequence, kPrettyFollowAnim.c_str());
if (followAnim == nullptr)
followAnim =
m_animationSystem.FindAnimation<ParallelAnimation>(Animation::Type::Parallel, kParallelFollowAnim.c_str());
if (followAnim == nullptr)
followAnim =
m_animationSystem.FindAnimation<ParallelAnimation>(Animation::Type::Parallel, kParallelLinearAnim.c_str());
if (followAnim != nullptr)
{
if (force || followAnim->CouldBeInterrupted())
ResetAnimations(followAnim->GetType(), followAnim->GetCustomType(), !followAnim->CouldBeInterrupted());
else
return false;
}
return true;
}
bool UserEventStream::SetFollowAndRotate(m2::PointD const & userPos, m2::PointD const & pixelPos, double azimuth,
int preferredZoomLevel, double autoScale, bool isAnim, bool isAutoScale,
Animation::TAction const & onFinishAction,
TAnimationCreator const & parallelAnimCreator)
{
// Reset current follow-and-rotate animation if possible.
if (isAnim && !InterruptFollowAnimations(false /* force */))
return false;
ScreenBase const & currentScreen = GetCurrentScreen();
ScreenBase screen = currentScreen;
if (preferredZoomLevel == kDoNotChangeZoom && !isAutoScale)
{
GetTargetScreen(screen);
screen.SetAngle(-azimuth);
}
else
{
screen.SetFromParams(userPos, -azimuth, isAutoScale ? autoScale : GetScreenScale(preferredZoomLevel));
}
screen.MatchGandP3d(userPos, pixelPos);
ShrinkAndScaleInto(screen, df::GetWorldRect());
if (isAnim)
{
drape_ptr<Animation> anim;
double const moveDuration =
PositionInterpolator::GetMoveDuration(currentScreen.GetOrg(), screen.GetOrg(), currentScreen.PixelRectIn3d(),
(currentScreen.GetScale() + screen.GetScale()) / 2.0);
if (moveDuration > kMaxAnimationTimeSec)
{
// Run pretty move animation if we are far from userPos.
anim = GetPrettyFollowAnimation(currentScreen, userPos, screen.GetScale(), -azimuth, pixelPos);
}
else
{
// Run follow-and-rotate animation.
anim = GetFollowAnimation(currentScreen, userPos, screen.GetScale(), -azimuth, pixelPos, isAutoScale);
}
if (preferredZoomLevel != kDoNotChangeZoom)
{
anim->SetCouldBeInterrupted(false);
anim->SetCouldBeBlended(false);
}
anim->SetOnFinishAction(onFinishAction);
if (parallelAnimCreator != nullptr)
{
drape_ptr<ParallelAnimation> parallelAnim = make_unique_dp<ParallelAnimation>();
parallelAnim->SetCustomType(kParallelFollowAnim);
parallelAnim->AddAnimation(
parallelAnimCreator(anim->GetType() == Animation::Type::MapFollow ? make_ref(anim) : nullptr));
parallelAnim->AddAnimation(std::move(anim));
m_animationSystem.CombineAnimation(std::move(parallelAnim));
}
else
{
m_animationSystem.CombineAnimation(std::move(anim));
}
return false;
}
ResetMapPlaneAnimations();
m_navigator.SetFromScreen(screen);
return true;
}
void UserEventStream::SetAutoPerspective(bool isAutoPerspective)
{
if (isAutoPerspective)
m_navigator.Enable3dMode();
else
m_navigator.Disable3dMode();
m_navigator.SetAutoPerspective(isAutoPerspective);
}
void UserEventStream::ResetAnimations(Animation::Type animType, bool rewind, bool finishAll)
{
bool const hasAnimations = m_animationSystem.HasAnimations();
m_animationSystem.FinishAnimations(animType, rewind, finishAll);
if (hasAnimations)
ApplyAnimations();
}
void UserEventStream::ResetAnimations(Animation::Type animType, std::string const & customType, bool rewind,
bool finishAll)
{
bool const hasAnimations = m_animationSystem.HasAnimations();
m_animationSystem.FinishAnimations(animType, customType, rewind, finishAll);
if (hasAnimations)
ApplyAnimations();
}
void UserEventStream::ResetMapPlaneAnimations()
{
bool const hasAnimations = m_animationSystem.HasAnimations();
m_animationSystem.FinishObjectAnimations(Animation::Object::MapPlane, false /* rewind */, false /* finishAll */);
if (hasAnimations)
ApplyAnimations();
}
m2::AnyRectD UserEventStream::GetCurrentRect() const
{
return m_navigator.Screen().GlobalRect();
}
void UserEventStream::GetTargetScreen(ScreenBase & screen)
{
m_animationSystem.FinishAnimations(Animation::Type::KineticScroll, false /* rewind */, false /* finishAll */);
ApplyAnimations();
m_animationSystem.GetTargetScreen(m_navigator.Screen(), screen);
}
m2::AnyRectD UserEventStream::GetTargetRect()
{
ScreenBase targetScreen;
GetTargetScreen(targetScreen);
return targetScreen.GlobalRect();
}
bool UserEventStream::ProcessTouch(TouchEvent const & touch)
{
ASSERT(touch.GetFirstTouch().m_id != -1, ());
TouchEvent touchEvent = touch;
touchEvent.PrepareTouches(m_touches);
bool isMapTouch = false;
switch (touchEvent.GetTouchType())
{
case TouchEvent::TOUCH_DOWN: isMapTouch = TouchDown(touchEvent.GetTouches()); break;
case TouchEvent::TOUCH_MOVE: isMapTouch = TouchMove(touchEvent.GetTouches()); break;
case TouchEvent::TOUCH_CANCEL: isMapTouch = TouchCancel(touchEvent.GetTouches()); break;
case TouchEvent::TOUCH_UP: isMapTouch = TouchUp(touchEvent.GetTouches()); break;
default: ASSERT(false, ()); break;
}
if (m_listener)
m_listener->OnTouchMapAction(touchEvent.GetTouchType(), isMapTouch);
return isMapTouch;
}
bool UserEventStream::TouchDown(std::array<Touch, 2> const & touches)
{
size_t touchCount = GetValidTouchesCount(touches);
bool isMapTouch = true;
// Interrupt kinetic scroll on touch down.
m_animationSystem.FinishAnimations(Animation::Type::KineticScroll, false /* rewind */, true /* finishAll */);
if (touchCount == 1)
{
if (!DetectDoubleTap(touches[0]))
{
if (m_state == STATE_EMPTY)
{
if (!TryBeginFilter(touches[0]))
{
BeginTapDetector();
m_startDragOrg = touches[0].m_location;
}
else
{
isMapTouch = false;
}
}
}
}
else if (touchCount == 2)
{
switch (m_state)
{
case STATE_EMPTY: BeginTwoFingersTap(touches[0], touches[1]); break;
case STATE_FILTER:
CancelFilter(touches[0]);
BeginScale(touches[0], touches[1]);
break;
case STATE_TAP_DETECTION:
case STATE_WAIT_DOUBLE_TAP:
case STATE_WAIT_DOUBLE_TAP_HOLD:
CancelTapDetector();
BeginTwoFingersTap(touches[0], touches[1]);
break;
case STATE_DOUBLE_TAP_HOLD:
EndDoubleTapAndHold(touches[0]);
BeginScale(touches[0], touches[1]);
break;
case STATE_DRAG:
isMapTouch = EndDrag(touches[0], true /* cancelled */);
BeginScale(touches[0], touches[1]);
break;
default: break;
}
}
UpdateTouches(touches);
return isMapTouch;
}
bool UserEventStream::CheckDrag(std::array<Touch, 2> const & touches, double threshold) const
{
return m_startDragOrg.SquaredLength(m2::PointD(touches[0].m_location)) > threshold;
}
bool UserEventStream::TouchMove(std::array<Touch, 2> const & touches)
{
size_t const touchCount = GetValidTouchesCount(touches);
bool isMapTouch = true;
switch (m_state)
{
case STATE_EMPTY:
if (touchCount == 1)
if (CheckDrag(touches, m_dragThreshold))
BeginDrag(touches[0]);
else
isMapTouch = false;
else
BeginScale(touches[0], touches[1]);
break;
case STATE_TAP_TWO_FINGERS:
if (touchCount == 2)
{
float const threshold = static_cast<float>(m_dragThreshold);
if (m_twoFingersTouches[0].SquaredLength(touches[0].m_location) > threshold ||
m_twoFingersTouches[1].SquaredLength(touches[1].m_location) > threshold)
{
BeginScale(touches[0], touches[1]);
}
else
isMapTouch = false;
}
break;
case STATE_FILTER:
ASSERT_EQUAL(touchCount, 1, ());
isMapTouch = false;
break;
case STATE_TAP_DETECTION:
case STATE_WAIT_DOUBLE_TAP:
if (CheckDrag(touches, m_dragThreshold))
CancelTapDetector();
else
isMapTouch = false;
break;
case STATE_WAIT_DOUBLE_TAP_HOLD:
if (CheckDrag(touches, m_dragThreshold))
StartDoubleTapAndHold(touches[0]);
break;
case STATE_DOUBLE_TAP_HOLD: UpdateDoubleTapAndHold(touches[0]); break;
case STATE_DRAG:
if (touchCount > 1)
{
ASSERT_EQUAL(GetValidTouchesCount(m_touches), 1, ());
EndDrag(m_touches[0], true /* cancelled */);
}
else
{
Drag(touches[0]);
}
break;
case STATE_SCALE:
if (touchCount < 2)
{
ASSERT_EQUAL(GetValidTouchesCount(m_touches), 2, ());
EndScale(m_touches[0], m_touches[1]);
}
else
{
Scale(touches[0], touches[1]);
}
break;
default: ASSERT(false, ()); break;
}
UpdateTouches(touches);
return isMapTouch;
}
bool UserEventStream::TouchCancel(std::array<Touch, 2> const & touches)
{
size_t touchCount = GetValidTouchesCount(touches);
UNUSED_VALUE(touchCount);
bool isMapTouch = true;
switch (m_state)
{
case STATE_EMPTY:
case STATE_WAIT_DOUBLE_TAP:
case STATE_TAP_TWO_FINGERS: isMapTouch = false; break;
case STATE_WAIT_DOUBLE_TAP_HOLD:
case STATE_DOUBLE_TAP_HOLD:
// Do nothing here.
break;
case STATE_FILTER:
ASSERT_EQUAL(touchCount, 1, ());
CancelFilter(touches[0]);
break;
case STATE_TAP_DETECTION:
ASSERT_EQUAL(touchCount, 1, ());
CancelTapDetector();
isMapTouch = false;
break;
case STATE_DRAG:
ASSERT_EQUAL(touchCount, 1, ());
isMapTouch = EndDrag(touches[0], true /* cancelled */);
break;
case STATE_SCALE:
ASSERT_EQUAL(touchCount, 2, ());
EndScale(touches[0], touches[1]);
break;
default: ASSERT(false, ()); break;
}
UpdateTouches(touches);
return isMapTouch;
}
bool UserEventStream::TouchUp(std::array<Touch, 2> const & touches)
{
size_t touchCount = GetValidTouchesCount(touches);
bool isMapTouch = true;
switch (m_state)
{
case STATE_EMPTY:
case STATE_WAIT_DOUBLE_TAP:
isMapTouch = false;
// Can be if long tap or double tap detected.
break;
case STATE_FILTER:
ASSERT_EQUAL(touchCount, 1, ());
EndFilter(touches[0]);
isMapTouch = false;
break;
case STATE_TAP_DETECTION:
if (touchCount == 1)
EndTapDetector(touches[0]);
else
CancelTapDetector();
break;
case STATE_TAP_TWO_FINGERS:
if (touchCount == 2)
EndTwoFingersTap();
break;
case STATE_WAIT_DOUBLE_TAP_HOLD:
ASSERT_EQUAL(touchCount, 1, ());
PerformDoubleTap(touches[0]);
break;
case STATE_DOUBLE_TAP_HOLD: EndDoubleTapAndHold(touches[0]); break;
case STATE_DRAG:
ASSERT_EQUAL(touchCount, 1, ());
isMapTouch = EndDrag(touches[0], false /* cancelled */);
break;
case STATE_SCALE:
if (touchCount < 2)
{
ASSERT_EQUAL(GetValidTouchesCount(m_touches), 2, ());
EndScale(m_touches[0], m_touches[1]);
}
else
{
EndScale(touches[0], touches[1]);
}
break;
default: ASSERT(false, ()); break;
}
UpdateTouches(touches);
return isMapTouch;
}
void UserEventStream::UpdateTouches(std::array<Touch, 2> const & touches)
{
m_touches = touches;
}
void UserEventStream::BeginTwoFingersTap(Touch const & t1, Touch const & t2)
{
TEST_CALL(TWO_FINGERS_TAP);
ASSERT_EQUAL(m_state, STATE_EMPTY, ());
m_state = STATE_TAP_TWO_FINGERS;
m_twoFingersTouches[0] = t1.m_location;
m_twoFingersTouches[1] = t2.m_location;
}
void UserEventStream::EndTwoFingersTap()
{
ASSERT_EQUAL(m_state, STATE_TAP_TWO_FINGERS, ());
m_state = STATE_EMPTY;
if (m_listener)
m_listener->OnTwoFingersTap();
}
void UserEventStream::BeginDrag(Touch const & t)
{
TEST_CALL(BEGIN_DRAG);
ASSERT_EQUAL(m_state, STATE_EMPTY, ());
m_state = STATE_DRAG;
m_startDragOrg = m_navigator.Screen().GetOrg();
if (m_listener)
m_listener->OnDragStarted();
m_navigator.StartDrag(m2::PointD(t.m_location));
if (m_kineticScrollEnabled && !m_scroller.IsActive())
{
ResetMapPlaneAnimations();
m_scroller.Init(m_navigator.Screen());
}
}
void UserEventStream::Drag(Touch const & t)
{
TEST_CALL(DRAG);
ASSERT_EQUAL(m_state, STATE_DRAG, ());
m_navigator.DoDrag(m2::PointD(t.m_location));
if (m_kineticScrollEnabled && m_scroller.IsActive())
m_scroller.Update(m_navigator.Screen());
}
bool UserEventStream::EndDrag(Touch const & t, bool cancelled)
{
TEST_CALL(END_DRAG);
ASSERT_EQUAL(m_state, STATE_DRAG, ());
m_state = STATE_EMPTY;
if (m_listener)
m_listener->OnDragEnded(m_navigator.GtoP(m_navigator.Screen().GetOrg()) - m_navigator.GtoP(m_startDragOrg));
m_startDragOrg = m2::PointD::Zero();
m_navigator.StopDrag(m2::PointD(t.m_location));
if (!cancelled && m_kineticScrollEnabled && m_scroller.IsActive() &&
m_kineticTimer.ElapsedMilliseconds() >= kKineticDelayMs)
{
drape_ptr<Animation> anim = m_scroller.CreateKineticAnimation(m_navigator.Screen());
if (anim != nullptr)
m_animationSystem.CombineAnimation(std::move(anim));
return false;
}
m_scroller.Cancel();
return true;
}
void UserEventStream::BeginScale(Touch const & t1, Touch const & t2)
{
TEST_CALL(BEGIN_SCALE);
if (m_state == STATE_SCALE)
{
Scale(t1, t2);
return;
}
ASSERT(m_state == STATE_EMPTY || m_state == STATE_TAP_TWO_FINGERS, ());
m_state = STATE_SCALE;
m2::PointD touch1(t1.m_location);
m2::PointD touch2(t2.m_location);
if (m_listener)
{
m_listener->OnScaleStarted();
m_listener->CorrectScalePoint(touch1, touch2);
}
m_navigator.StartScale(touch1, touch2);
}
void UserEventStream::Scale(Touch const & t1, Touch const & t2)
{
TEST_CALL(SCALE);
ASSERT_EQUAL(m_state, STATE_SCALE, ());
m2::PointD touch1(t1.m_location);
m2::PointD touch2(t2.m_location);
if (m_listener)
{
if (m_navigator.IsRotatingDuringScale())
m_listener->OnRotated();
m_listener->CorrectScalePoint(touch1, touch2);
}
m_navigator.DoScale(touch1, touch2);
}
void UserEventStream::EndScale(Touch const & t1, Touch const & t2)
{
TEST_CALL(END_SCALE);
ASSERT_EQUAL(m_state, STATE_SCALE, ());
m_state = STATE_EMPTY;
m2::PointD touch1(t1.m_location);
m2::PointD touch2(t2.m_location);
if (m_listener)
{
m_listener->CorrectScalePoint(touch1, touch2);
m_listener->OnScaleEnded();
}
m_navigator.StopScale(touch1, touch2);
m_kineticTimer.Reset();
}
void UserEventStream::BeginTapDetector()
{
TEST_CALL(BEGIN_TAP_DETECTOR);
ASSERT_EQUAL(m_state, STATE_EMPTY, ());
m_state = STATE_TAP_DETECTION;
m_touchTimer.Reset();
}
void UserEventStream::DetectShortTap(Touch const & touch)
{
if (DetectForceTap(touch))
return;
if (m_touchTimer.ElapsedMilliseconds() > kDoubleTapPauseMs)
{
m_state = STATE_EMPTY;
if (m_listener)
m_listener->OnTap(m2::PointD(touch.m_location), false /* isLongTap */);
}
}
void UserEventStream::DetectLongTap(Touch const & touch)
{
ASSERT_EQUAL(m_state, STATE_TAP_DETECTION, ());
if (DetectForceTap(touch))
return;
if (m_touchTimer.ElapsedMilliseconds() > kLongTouchMs)
{
TEST_CALL(LONG_TAP_DETECTED);
m_state = STATE_EMPTY;
if (m_listener)
m_listener->OnTap(m2::PointD(touch.m_location), true /* isLongTap */);
}
}
bool UserEventStream::DetectDoubleTap(Touch const & touch)
{
if (m_state != STATE_WAIT_DOUBLE_TAP || m_touchTimer.ElapsedMilliseconds() > kDoubleTapPauseMs)
return false;
m_state = STATE_WAIT_DOUBLE_TAP_HOLD;
return true;
}
void UserEventStream::PerformDoubleTap(Touch const & touch)
{
ASSERT_EQUAL(m_state, STATE_WAIT_DOUBLE_TAP_HOLD, ());
m_state = STATE_EMPTY;
if (m_listener)
m_listener->OnDoubleTap(m2::PointD(touch.m_location));
}
bool UserEventStream::DetectForceTap(Touch const & touch)
{
if (touch.m_force >= kForceTapThreshold)
{
m_state = STATE_EMPTY;
if (m_listener)
m_listener->OnForceTap(m2::PointD(touch.m_location));
return true;
}
return false;
}
void UserEventStream::EndTapDetector(Touch const & touch)
{
TEST_CALL(SHORT_TAP_DETECTED);
ASSERT_EQUAL(m_state, STATE_TAP_DETECTION, ());
m_state = STATE_WAIT_DOUBLE_TAP;
}
void UserEventStream::CancelTapDetector()
{
TEST_CALL(CANCEL_TAP_DETECTOR);
ASSERT(m_state == STATE_TAP_DETECTION || m_state == STATE_WAIT_DOUBLE_TAP || m_state == STATE_WAIT_DOUBLE_TAP_HOLD,
());
m_state = STATE_EMPTY;
}
bool UserEventStream::TryBeginFilter(Touch const & t)
{
TEST_CALL(TRY_FILTER);
ASSERT_EQUAL(m_state, STATE_EMPTY, ());
if (m_listener && m_listener->OnSingleTouchFiltrate(m2::PointD(t.m_location), TouchEvent::TOUCH_DOWN))
{
m_state = STATE_FILTER;
return true;
}
return false;
}
void UserEventStream::EndFilter(Touch const & t)
{
TEST_CALL(END_FILTER);
ASSERT_EQUAL(m_state, STATE_FILTER, ());
m_state = STATE_EMPTY;
if (m_listener)
m_listener->OnSingleTouchFiltrate(m2::PointD(t.m_location), TouchEvent::TOUCH_UP);
}
void UserEventStream::CancelFilter(Touch const & t)
{
TEST_CALL(CANCEL_FILTER);
ASSERT_EQUAL(m_state, STATE_FILTER, ());
m_state = STATE_EMPTY;
if (m_listener)
m_listener->OnSingleTouchFiltrate(m2::PointD(t.m_location), TouchEvent::TOUCH_CANCEL);
}
void UserEventStream::StartDoubleTapAndHold(Touch const & touch)
{
TEST_CALL(BEGIN_DOUBLE_TAP_AND_HOLD);
ASSERT_EQUAL(m_state, STATE_WAIT_DOUBLE_TAP_HOLD, ());
m_state = STATE_DOUBLE_TAP_HOLD;
m_startDoubleTapAndHold = m_startDragOrg;
if (m_listener)
m_listener->OnScaleStarted();
}
void UserEventStream::UpdateDoubleTapAndHold(Touch const & touch)
{
TEST_CALL(DOUBLE_TAP_AND_HOLD);
ASSERT_EQUAL(m_state, STATE_DOUBLE_TAP_HOLD, ());
float const kPowerModifier = 10.0f;
double const scaleFactor = exp(kPowerModifier * (touch.m_location.y - m_startDoubleTapAndHold.y) /
GetCurrentScreen().PixelRectIn3d().SizeY());
m_startDoubleTapAndHold = touch.m_location;
m2::PointD scaleCenter = m_startDragOrg;
if (m_listener)
m_listener->CorrectScalePoint(scaleCenter);
m_navigator.Scale(scaleCenter, scaleFactor);
}
void UserEventStream::EndDoubleTapAndHold(Touch const & touch)
{
TEST_CALL(END_DOUBLE_TAP_AND_HOLD);
ASSERT_EQUAL(m_state, STATE_DOUBLE_TAP_HOLD, ());
m_state = STATE_EMPTY;
if (m_listener)
m_listener->OnScaleEnded();
}
bool UserEventStream::IsInUserAction() const
{
return m_state == STATE_DRAG || m_state == STATE_SCALE;
}
bool UserEventStream::IsWaitingForActionCompletion() const
{
return m_state != STATE_EMPTY;
}
void UserEventStream::SetKineticScrollEnabled(bool enabled)
{
m_kineticScrollEnabled = enabled;
m_kineticTimer.Reset();
if (!m_kineticScrollEnabled)
m_scroller.Cancel();
}
} // namespace df
| 1 | 0.98161 | 1 | 0.98161 | game-dev | MEDIA | 0.496179 | game-dev | 0.960065 | 1 | 0.960065 |
McJtyMods/RFToolsDimensions | 3,466 | src/main/java/mcjty/rftoolsdim/dimension/biomes/RFTBiomeProvider.java | package mcjty.rftoolsdim.dimension.biomes;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import mcjty.rftoolsdim.dimension.data.DimensionSettings;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryLookupCodec;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.Biomes;
import net.minecraft.world.biome.provider.BiomeProvider;
import net.minecraft.world.gen.feature.structure.Structure;
import net.minecraft.world.gen.layer.Layer;
import net.minecraft.world.gen.layer.LayerUtil;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.stream.Collectors;
import static mcjty.rftoolsdim.dimension.data.DimensionSettings.SETTINGS_CODEC;
public class RFTBiomeProvider extends BiomeProvider {
// public static final Codec<RFTBiomeProvider> CODEC = RegistryLookupCodec.getLookUpCodec(Registry.BIOME_KEY)
// .xmap(RFTBiomeProvider::new, RFTBiomeProvider::getBiomeRegistry).codec();
public static final Codec<RFTBiomeProvider> CODEC = RecordCodecBuilder.create(instance ->
instance.group(
RegistryLookupCodec.create(Registry.BIOME_REGISTRY).forGetter(RFTBiomeProvider::getBiomeRegistry),
SETTINGS_CODEC.fieldOf("settings").forGetter(RFTBiomeProvider::getSettings)
).apply(instance, RFTBiomeProvider::new));
private final Layer genBiomes;
private final List<Biome> biomes;
private final Registry<Biome> biomeRegistry;
private final DimensionSettings settings;
public RFTBiomeProvider(Registry<Biome> biomeRegistry, DimensionSettings settings) {
super(getBiomes(biomeRegistry, settings));
this.settings = settings;
this.biomeRegistry = biomeRegistry;
biomes = getBiomes(biomeRegistry, settings);
this.genBiomes = LayerUtil.getDefaultLayer(settings.getSeed(), false, 4, 4);
}
public DimensionSettings getSettings() {
return settings;
}
private static List<Biome> getBiomes(Registry<Biome> biomeRegistry, DimensionSettings settings) {
List<Biome> biomes;
biomes = settings.getCompiledDescriptor().getBiomes()
.stream().map(biomeRegistry::get).collect(Collectors.toList());
if (biomes.isEmpty()) {
biomes.add(biomeRegistry.get(Biomes.PLAINS.location()));
}
return biomes;
}
public Registry<Biome> getBiomeRegistry() {
return biomeRegistry;
}
@Override
public boolean canGenerateStructure(@Nonnull Structure<?> structure) {
return false;
}
@Nonnull
@Override
protected Codec<? extends BiomeProvider> codec() {
return CODEC;
}
@Nonnull
@Override
public BiomeProvider withSeed(long seed) {
return new RFTBiomeProvider(getBiomeRegistry(), settings);
}
@Nonnull
@Override
public Biome getNoiseBiome(int x, int y, int z) {
switch (settings.getCompiledDescriptor().getBiomeControllerType()) {
case DEFAULT:
return this.genBiomes.get(this.biomeRegistry, x, z);
case CHECKER:
if ((x+y)%2 == 0 || biomes.size() <= 1) {
return biomes.get(0);
} else {
return biomes.get(1);
}
case SINGLE:
return biomes.get(0);
}
return null;
}
}
| 1 | 0.698782 | 1 | 0.698782 | game-dev | MEDIA | 0.328165 | game-dev | 0.725848 | 1 | 0.725848 |
gameoverhack/ofxOpenNI | 7,135 | include/nite/XnVPushDetector.h | /*******************************************************************************
* *
* PrimeSense NITE 1.3 *
* Copyright (C) 2010 PrimeSense Ltd. *
* *
*******************************************************************************/
#ifndef _XNV_PUSH_DETECTOR_H_
#define _XNV_PUSH_DETECTOR_H_
#include "XnVNiteDefs.h"
#include "XnVPointControl.h"
#include "XnV3DVector.h"
class XnVPointBuffer;
class XnVFloatFloatSpecificEvent;
class XnVFloatSpecificEvent;
/**
* A control that identifies pushes - moves in the z axis.
* The XnVPushDetector defines 2 events:
* - A push was identified
* - Stable state restored
*/
class XNV_NITE_API XnVPushDetector :
public XnVPointControl
{
public:
/**
* Type for push event callback
*/
typedef void (XN_CALLBACK_TYPE *PushCB)(XnFloat fVelocity, XnFloat fAngle, void* UserCxt);
/**
* Type for stable event callback
*/
typedef void (XN_CALLBACK_TYPE *StabilizedCB)(XnFloat fVelocity, void* UserCxt);
/**
* Construction.
*
* @param [in] strName Name of the control, for log purposes.
*/
XnVPushDetector(const XnChar* strName = "XnVPushDetector");
~XnVPushDetector();
/**
* Handle the creation of the primary point
*
* @param [in] pContext The hand context of the newly created primary point
* @param [in] ptFocus The point in which the session has started.
*/
void OnPrimaryPointCreate(const XnVHandPointContext* pContext, const XnPoint3D& ptFocus);
/**
* called when the primary point is updated.
* This will cause the algorithm to look for pushes.
*
* @param [in] pContext The hand context of the updated primary point
*/
void OnPrimaryPointUpdate(const XnVHandPointContext* pContext);
/**
* Register to the push event
*
* @param [in] cxt The User's context
* @param [in] pCB the callback to be called when the event is invoked
*
* @return A handle, to allow unregistration
*/
XnCallbackHandle RegisterPush(void* cxt, PushCB pCB);
/**
* Register to the stable event
*
* @param [in] cxt The User's context
* @param [in] pCB the callback to be called when the event is invoked
*
* @return A handle, to allow unregistration
*/
XnCallbackHandle RegisterStabilized(void* cxt, StabilizedCB pCB);
/**
* Unregister from the push event
*
* @param [in] handle The handle provided on registration.
*/
void UnregisterPush(XnCallbackHandle handle);
/**
* Unregister from the stable event
*
* @param [in] handle The handle provided on registration.
*/
void UnregisterStabilized(XnCallbackHandle handle);
/**
* The number of frames it takes to recognize the push.
* Effectively, this means the actual push started this number of frames ago.
*/
XnUInt32 GetPushDuration() const;
/**
* Start push detection over from scratch.
*/
void Reset();
/**
* Get the minimum velocity in the time span to define as push, in m/s
*
* @return the velocity
*/
XnFloat GetPushImmediateMinimumVelocity() const;
/**
* Get the time used to detect push, in ms
*
* @return the time
*/
XnUInt32 GetPushImmediateDuration() const;
/**
* Get the the immediate timespan to skip, in ms
*
* @return the time
*/
XnUInt32 GetPushImmediateOffset() const;
/**
* Get the minimum velocity of the previous time span, in m/s
*
* @return the velocity
*/
XnFloat GetPushPreviousMinimumVelocity() const;
/**
* Get the time of the previous time span, in ms
*
* @return the time
*/
XnUInt32 GetPushPreviousDuration() const;
/**
* Get the time to skip of the previous time span, in ms
*
* @return the time
*/
XnUInt32 GetPushPreviousOffset() const;
/**
* Get the maximum angle between the immediate direction and the Z-axis, in degrees
*
* @return the angle
*/
XnFloat GetPushMaximumAngleBetweenImmediateAndZ() const;
/**
* Get the maximum angle between the immediate direction and the previous direction, in degrees
*
* @return the angle
*/
XnFloat GetPushMinimumAngleBetweenImmediateAndPrevious() const;
/**
* Get the maximum velocity in the time span to define as stable, in m/s
*
* @return the velocity
*/
XnFloat GetStableMaximumVelocity() const;
/**
* Get the time used to detect stable state, in ms
*
* @return the time
*/
XnUInt32 GetStableDuration() const;
/**
* Change the minimum velocity in the time span to define as push. Default is 0.33 m/s
*
* @return the velocity
*/
void SetPushImmediateMinimumVelocity(XnFloat fVelocity);
/**
* Change the time used to detect push. Default is 240ms
*
* @return the time
*/
void SetPushImmediateDuration(XnUInt32 nDuration);
/**
* Change the the immediate timespan to skip. Default is 0ms
*
* @return the time
*/
void SetPushImmediateOffset(XnUInt32 nOffset);
/**
* Change the minimum velocity of the previous time span. Default is 0.17 m/s
*
* @return the velocity
*/
void SetPushPreviousMinimumVelocity(XnFloat fVelocity);
/**
* Change the time of the previous time span. Default is 150 ms
*
* @return the time
*/
void SetPushPreviousDuration(XnUInt32 nDuration);
/**
* Change the time to skip of the previous time span. Default is 240ms
*
* @return the time
*/
void SetPushPreviousOffset(XnUInt32 nOffset);
/**
* Change the maximum angle between the immediate direction and the Z-axis. Default is 30 degrees
*
* @return the angle
*/
void SetPushMaximumAngleBetweenImmediateAndZ(XnFloat fAngle);
/**
* Change the maximum angle between the immediate direction and the previous direction. Default is 20 degrees
*
* @return the angle
*/
void SetPushMinimumAngleBetweenImmediateAndPrevious(XnFloat fAngle);
/**
* Change the maximum velocity in the time span to define as stable. Default is 0.13 m/s
*
* @return the velocity
*/
void SetStableMaximumVelocity(XnFloat fVelocity);
/**
* Get the time used to detect stable state. Default is 360 ms
*
* @return the time
*/
void SetStableDuration(XnUInt32 nDuration);
protected:
XnBool IsPushDetected(const XnV3DVector& vImmediateVelocity, const XnV3DVector& vPreviousVelocity, XnFloat& fZAngle);
XnBool IsStabilized(XnFloat fTime, XnFloat& fVelocity);
void UpdateLines(XnFloat fTime);
void AddPoint(const XnPoint3D& pt, XnFloat fTime);
XnFloat AngleBetweenVectors(const XnV3DVector& v1, const XnV3DVector& v2);
XnBool m_bPushDetected;
XnVPointBuffer* m_pPoints;
XnFloat m_fPushImmediateMinVelocity;
XnUInt32 m_nPushImmediateOffset;
XnUInt32 m_nPushImmediateDuration;
XnFloat m_fPushPreviousMinVelocity;
XnUInt32 m_nPushPreviousOffset;
XnUInt32 m_nPushPreviousDuration;
XnFloat m_fPushMaxAngleFromZ;
XnFloat m_fPushMinAngleImmediateAndPrevious;
XnFloat m_fStableMaxVelocity;
XnUInt32 m_nStableDuration;
// CBs
void PushDetected(XnFloat fVelocity, XnFloat fAngle);
void StabilizedDetected(XnFloat fVelocity);
XnVFloatFloatSpecificEvent* m_pPushCBs;
XnVFloatSpecificEvent* m_pStabilizedCBs;
}; // XnVPushDetector
#endif // _XNV_PUSH_DETECTOR_H_
| 1 | 0.873694 | 1 | 0.873694 | game-dev | MEDIA | 0.437767 | game-dev | 0.50329 | 1 | 0.50329 |
revolucas/CoC-Xray | 2,649 | src/editors/LevelEditor/Edit/ESceneLightTools.h | #ifndef ESceneLightToolsH
#define ESceneLightToolsH
#include "ESceneCustomOTools.H"
#include "xr_efflensflare.h"
class CEditFlare: public CLensFlare{
public:
CEditFlare();
void Load(IReader& F);
void Save(IWriter& F);
void Render();
void DeleteShaders();
void CreateShaders();
};
class ESceneLightTool: public ESceneCustomOTool
{
typedef ESceneCustomOTool inherited;
friend class SceneBuilder;
friend class CLight;
protected:
enum{
flShowSun = (1<<31),
flShowControlName = (1<<30),
};
Flags32 m_Flags;
// hemisphere
u32 m_HemiControl;
// sun
Fvector2 m_SunShadowDir;
// run time
xr_vector<CLight*> frame_light;
void AppendFrameLight (CLight* L);
protected:
// light control
int lcontrol_last_idx;
RTokenVec lcontrols;
void __stdcall OnControlAppendClick (ButtonValue* sender, bool& bDataModified, bool& bSafe);
void __stdcall OnControlRenameRemoveClick (ButtonValue* sender, bool& bDataModified, bool& bSafe);
protected:
// controls
virtual void CreateControls ();
virtual void RemoveControls ();
public:
ESceneLightTool ();
virtual ~ESceneLightTool ();
virtual void Clear (bool bSpecific=false);
// definition
IC LPCSTR ClassName (){return "light";}
IC LPCSTR ClassDesc (){return "Light";}
IC int RenderPriority (){return 10;}
// IO
virtual bool IsNeedSave (){return true;}
virtual bool LoadStream (IReader&);
virtual bool LoadLTX (CInifile&);
virtual void SaveStream (IWriter&);
virtual void SaveLTX (CInifile&, int id);
virtual bool LoadSelection (IReader&);
virtual void SaveSelection (IWriter&);
// utils
virtual bool Validate (bool full_build);
virtual void BeforeRender ();
virtual void OnRender (int priority, bool strictB2F);
virtual void AfterRender ();
void SelectLightsForObject (CCustomObject* obj);
virtual void FillProp (LPCSTR pref, PropItemVec& items);
AnsiString GenLightControlName ();
xr_rtoken* FindLightControl (int id);
RTokenVecIt FindLightControlIt (LPCSTR name);
xr_rtoken* FindLightControl (LPCSTR name){RTokenVecIt it = FindLightControlIt(name); return it!=lcontrols.end()?it:0;}
void AppendLightControl (LPCSTR name, u32* idx=0);
void RemoveLightControl (LPCSTR name);
virtual CCustomObject* CreateObject (LPVOID data, LPCSTR name);
};
#endif // ESceneCustomOToolsH
| 1 | 0.904352 | 1 | 0.904352 | game-dev | MEDIA | 0.597269 | game-dev | 0.60966 | 1 | 0.60966 |
Neat-Lang/neat | 4,697 | demos/advent22/day19.nt | module day19;
macro import std.macro.assert;
macro import std.macro.listcomprehension;
import std.algorithm;
import std.math;
import std.stdio;
import std.string;
struct Resources {
int ore;
int clay;
int obsidian;
int geode;
Resources add(Resources other)
=> Resources(ore + other.ore, clay + other.clay,
obsidian + other.obsidian, geode + other.geode);
Resources addi(int other) => add(Resources(other, other, other, other));
Resources sub(Resources other)
=> Resources(ore - other.ore, clay - other.clay,
obsidian - other.obsidian, geode - other.geode);
int divmin(Resources other) {
mut int res = int.max;
if (other.ore) res = res.min(ore / other.ore);
if (other.clay) res = res.min(clay / other.clay);
if (other.obsidian) res = res.min(obsidian / other.obsidian);
if (other.geode) res = res.min(geode / other.geode);
return res;
}
bool allGrEq(Resources other)
=> ore >= other.ore && clay >= other.clay
&& obsidian >= other.obsidian && geode >= other.geode;
string toString() => "<$ore ore, $clay clay, $obsidian obsidian, $geode geode>";
}
void main()
{
auto findCost = (array, resource) => [
first a.split(" ")[0].atoi for a in array where a.endsWith(resource)
else 0];
auto decodeCost = text => text.split(" and ").(Resources(
ore=that.findCost("ore"),
clay=that.findCost("clay"),
obsidian=that.findCost("obsidian"),
geode=that.findCost("geode")));
auto decodeBlueprint = line => (
oreBot=line.between("ore robot costs ", ".").decodeCost,
clayBot=line.between("clay robot costs ", ".").decodeCost,
obsidianBot=line.between("obsidian robot costs ", ".").decodeCost,
geodeBot=line.between("geode robot costs ", ".").decodeCost);
auto blueprints = stdin.byLine
.filter(a => !a.empty)
.map(decodeBlueprint)
.array;
alias Blueprint = typeof(blueprints[0]);
int rate(int id, int tMax) {
auto blueprint = blueprints[id];
mut int bestGeodes;
int recurse(int minute, Blueprint blueprint, Resources bots, Resources storage) {
int tRem = tMax - minute;
int minPossibleGeodes = storage.geode + bots.geode * tRem;
if (minPossibleGeodes > bestGeodes) {
print("$(id + 1): improved score to $(minPossibleGeodes)");
bestGeodes = minPossibleGeodes;
}
if (minute == tMax) {
return storage.geode;
}
Resources maxPossibleResources = storage.add(bots.addi(tRem * tRem));
int maxAdditionalGeodeBots = maxPossibleResources.divmin(blueprint.geodeBot);
int maxPossibleGeodes = storage.geode + bots.geode * tRem + (maxAdditionalGeodeBots * tRem + 1) / 2;
// print("$tRem $maxPossibleResources $maxPossibleGeodeBots $maxPossibleGeodes");
if (maxPossibleGeodes <= bestGeodes)
return bestGeodes;
mut int maxOutcome = bestGeodes;
void tryBuy(Resources cost, Resources botBuilt) {
if (storage.allGrEq(cost)) {
auto outcome = recurse(
minute + 1, blueprint,
bots.add(botBuilt), storage.sub(cost).add(bots));
if (outcome > maxOutcome) maxOutcome = outcome;
}
}
tryBuy(blueprint.oreBot, Resources(1, 0, 0, 0));
tryBuy(blueprint.clayBot, Resources(0, 1, 0, 0));
tryBuy(blueprint.obsidianBot, Resources(0, 0, 1, 0));
tryBuy(blueprint.geodeBot, Resources(0, 0, 0, 1));
tryBuy(Resources(0, 0, 0, 0), Resources(0, 0, 0, 0));
return maxOutcome;
}
return recurse(0, blueprint, Resources(1, 0, 0, 0), Resources(0, 0, 0, 0));
}
print("blueprints: $blueprints");
auto quality = id => rate(cast(int) id, tMax=24) * (id + 1);
auto qualities = [i.quality for i in 0 .. blueprints.length];
auto sum = [sum a for a in qualities];
print("qualities: $qualities, sum $sum");
auto scores = [rate(cast(int) id, tMax=32) for id in 0 .. min(blueprints.length, 3)];
print("scores: $scores, $(scores.mul)");
}
int mul(R)(R range) {
mut int res = 1;
for (a in range) res *= a;
return res;
}
string between(string text, string from, string to) {
int start = text.find(from);
assert(start != -1);
int end = text[start + from.length .. $].find(to);
assert(end != -1);
return text[start + from.length .. $][0 .. end];
}
| 1 | 0.805047 | 1 | 0.805047 | game-dev | MEDIA | 0.708384 | game-dev | 0.950867 | 1 | 0.950867 |
magefree/mage | 1,722 | Mage.Sets/src/mage/cards/s/SkitterbeamBattalion.java | package mage.cards.s;
import mage.MageInt;
import mage.abilities.common.EntersBattlefieldTriggeredAbility;
import mage.abilities.condition.common.CastFromEverywhereSourceCondition;
import mage.abilities.effects.CreateTokenCopySourceEffect;
import mage.abilities.keyword.HasteAbility;
import mage.abilities.keyword.PrototypeAbility;
import mage.abilities.keyword.TrampleAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class SkitterbeamBattalion extends CardImpl {
public SkitterbeamBattalion(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{9}");
this.subtype.add(SubType.CONSTRUCT);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// Prototype {3}{R}{R} -- 2/2
this.addAbility(new PrototypeAbility(this, "{3}{R}{R}", 2, 2));
// Trample
this.addAbility(TrampleAbility.getInstance());
// Haste
this.addAbility(HasteAbility.getInstance());
// When Skitterbeam Battalion enters the battlefield, if you cast it, create two tokens that are copies of it.
this.addAbility(new EntersBattlefieldTriggeredAbility(new CreateTokenCopySourceEffect(2)
.setText("create two tokens that are copies of it")).withInterveningIf(CastFromEverywhereSourceCondition.instance));
}
private SkitterbeamBattalion(final SkitterbeamBattalion card) {
super(card);
}
@Override
public SkitterbeamBattalion copy() {
return new SkitterbeamBattalion(this);
}
}
| 1 | 0.820503 | 1 | 0.820503 | game-dev | MEDIA | 0.805758 | game-dev | 0.972213 | 1 | 0.972213 |
mbeddr/mbeddr.core | 5,582 | code/languages/com.mbeddr.core/languages/com.mbeddr.core.expressions/solutions/pluginSolution/models/com/mbeddt/core/expressions/pluginSolution/plugin.mps | <?xml version="1.0" encoding="UTF-8"?>
<model ref="r:a296e8c9-b717-45da-a3a4-9f0b7cc360c0(com.mbeddt.core.expressions.pluginSolution.plugin)">
<persistence version="9" />
<languages>
<use id="c3bfea76-7bba-4f0e-b5a2-ff4e7a8d7cf1" name="com.mbeddr.mpsutil.spreferences" version="0" />
<use id="7866978e-a0f0-4cc7-81bc-4d213d9375e1" name="jetbrains.mps.lang.smodel" version="19" />
<use id="f3061a53-9226-4cc5-a443-f952ceaf5816" name="jetbrains.mps.baseLanguage" version="12" />
</languages>
<imports>
<import index="mj1l" ref="r:c371cf98-dcc8-4a43-8eb8-8a8096de18b2(com.mbeddr.core.expressions.structure)" />
<import index="ywuz" ref="r:c6ce92e7-5a98-4a6f-866a-ec8b9e945dd8(com.mbeddr.core.expressions.behavior)" />
</imports>
<registry>
<language id="f3061a53-9226-4cc5-a443-f952ceaf5816" name="jetbrains.mps.baseLanguage">
<concept id="1197027756228" name="jetbrains.mps.baseLanguage.structure.DotExpression" flags="nn" index="2OqwBi">
<child id="1197027771414" name="operand" index="2Oq$k0" />
<child id="1197027833540" name="operation" index="2OqNvi" />
</concept>
<concept id="1137021947720" name="jetbrains.mps.baseLanguage.structure.ConceptFunction" flags="in" index="2VMwT0">
<child id="1137022507850" name="body" index="2VODD2" />
</concept>
<concept id="1068580123155" name="jetbrains.mps.baseLanguage.structure.ExpressionStatement" flags="nn" index="3clFbF">
<child id="1068580123156" name="expression" index="3clFbG" />
</concept>
<concept id="1068580123159" name="jetbrains.mps.baseLanguage.structure.IfStatement" flags="nn" index="3clFbJ">
<child id="1068580123160" name="condition" index="3clFbw" />
<child id="1068580123161" name="ifTrue" index="3clFbx" />
</concept>
<concept id="1068580123136" name="jetbrains.mps.baseLanguage.structure.StatementList" flags="sn" stub="5293379017992965193" index="3clFbS">
<child id="1068581517665" name="statement" index="3cqZAp" />
</concept>
<concept id="1204053956946" name="jetbrains.mps.baseLanguage.structure.IMethodCall" flags="ngI" index="1ndlxa">
<reference id="1068499141037" name="baseMethodDeclaration" index="37wK5l" />
</concept>
</language>
<language id="7866978e-a0f0-4cc7-81bc-4d213d9375e1" name="jetbrains.mps.lang.smodel">
<concept id="1179409122411" name="jetbrains.mps.lang.smodel.structure.Node_ConceptMethodCall" flags="nn" index="2qgKlT" />
<concept id="4040588429969021681" name="jetbrains.mps.lang.smodel.structure.ModuleReferenceExpression" flags="nn" index="3rM5sP">
<property id="4040588429969021683" name="moduleId" index="3rM5sR" />
</concept>
<concept id="4040588429969069898" name="jetbrains.mps.lang.smodel.structure.LanguageReferenceExpression" flags="nn" index="3rNLEe" />
</language>
<language id="ceab5195-25ea-4f22-9b92-103b95ca8c0c" name="jetbrains.mps.lang.core">
<concept id="1169194658468" name="jetbrains.mps.lang.core.structure.INamedConcept" flags="ngI" index="TrEIO">
<property id="1169194664001" name="name" index="TrG5h" />
</concept>
</language>
<language id="c3bfea76-7bba-4f0e-b5a2-ff4e7a8d7cf1" name="com.mbeddr.mpsutil.spreferences">
<concept id="5299504751977339944" name="com.mbeddr.mpsutil.spreferences.structure.Parameter_IsInit" flags="ng" index="U$gdm" />
<concept id="6044976435766352430" name="com.mbeddr.mpsutil.spreferences.structure.InitPageNode" flags="ig" index="U$sw$" />
<concept id="6044976435766352514" name="com.mbeddr.mpsutil.spreferences.structure.Parameter_PageNode" flags="ng" index="U$sy8" />
<concept id="1551477140197502032" name="com.mbeddr.mpsutil.spreferences.structure.ModuleSettings" flags="ng" index="Z6TxH">
<child id="1551477140197679137" name="usedLanguages" index="Z6dgs" />
</concept>
<concept id="6547806146467473938" name="com.mbeddr.mpsutil.spreferences.structure.PreferencePageDescription" flags="ng" index="30z_3H">
<reference id="6547806146467491221" name="rootConcept" index="30zxtE" />
<child id="6044976435766357656" name="initFunction" index="U$vMi" />
<child id="1551477140197502033" name="moduleSettings" index="Z6TxG" />
</concept>
</language>
</registry>
<node concept="30z_3H" id="7Xia6U7QbDd">
<property role="TrG5h" value="Type Size Configuration" />
<ref role="30zxtE" to="mj1l:2TbP0WsJvOO" resolve="TypeSizeConfiguration" />
<node concept="U$sw$" id="7Xia6U7QtEP" role="U$vMi">
<node concept="3clFbS" id="7Xia6U7QzCu" role="2VODD2">
<node concept="3clFbJ" id="4AbBRTN8xwS" role="3cqZAp">
<node concept="3clFbS" id="4AbBRTN8xwV" role="3clFbx">
<node concept="3clFbF" id="7Xia6U7QHI$" role="3cqZAp">
<node concept="2OqwBi" id="7Xia6U7QKGU" role="3clFbG">
<node concept="U$sy8" id="7Xia6U7QHIz" role="2Oq$k0" />
<node concept="2qgKlT" id="7Xia6U7RroZ" role="2OqNvi">
<ref role="37wK5l" to="ywuz:6w9JOkHS5pu" resolve="populateWithDesktopDefault" />
</node>
</node>
</node>
</node>
<node concept="U$gdm" id="4AbBRTN8xz4" role="3clFbw" />
</node>
</node>
</node>
<node concept="Z6TxH" id="7Xia6U7RtLm" role="Z6TxG">
<node concept="3rNLEe" id="7Xia6U7Rua9" role="Z6dgs">
<property role="3rM5sR" value="61c69711-ed61-4850-81d9-7714ff227fb0" />
</node>
</node>
</node>
</model>
| 1 | 0.848412 | 1 | 0.848412 | game-dev | MEDIA | 0.24799 | game-dev | 0.547855 | 1 | 0.547855 |
sambler/myblendercontrib | 62,997 | blenrig/resources/generate_customprops.py | import bpy
#### File to append to the rig via game logic when the intention is to use it in a system that doesn't have the BlenRig addon installed
####### Bones Hiding System #######
from bpy.props import FloatProperty, IntProperty, BoolProperty
def bone_auto_hide(context):
if not bpy.context.screen:
return False
if bpy.context.screen.is_animation_playing == True:
return False
if not bpy.context.active_object:
return False
if (bpy.context.active_object.type in ["ARMATURE"]) and (bpy.context.active_object.mode == 'POSE'):
for b_prop in bpy.context.active_object.data.items():
if b_prop[0] == 'bone_auto_hide' and b_prop[1] == 0:
return False
for prop in bpy.context.active_object.data.items():
if prop[0] == 'rig_name' and prop[1] == 'BlenRig_5':
arm = bpy.context.active_object.data
p_bones = bpy.context.active_object.pose.bones
for b in p_bones:
if ('properties' in b.name):
if ('torso' in b.name):
# Torso FK/IK
prop = int(b.ik_torso)
prop_inv = int(b.inv_torso)
for bone in arm.bones:
if (bone.name in b['bones_ik']):
if prop == 1 or prop_inv == 1:
bone.hide = 1
else:
bone.hide = 0
if (bone.name in b['bones_fk']):
if prop != 1 or prop_inv == 1:
bone.hide = 1
else:
bone.hide = 0
# Torso INV
for bone in arm.bones:
if (bone.name in b['bones_inv']):
if prop_inv == 1:
bone.hide = 0
else:
bone.hide = 1
if ('head' in b.name):
# Neck FK/IK
prop = int(b.ik_head)
for bone in arm.bones:
if (bone.name in b['bones_fk']):
if prop == 1:
bone.hide = 0
else:
bone.hide = 1
if (bone.name in b['bones_ik']):
if prop == 0:
bone.hide = 0
else:
bone.hide = 1
# Head Hinge
prop_hinge = int(b.hinge_head)
for bone in arm.bones:
if (bone.name in b['bones_fk_hinge']):
if prop == 1 or prop_hinge == 0:
bone.hide = 0
else:
bone.hide = 1
if (bone.name in b['bones_ik_hinge']):
if prop == 0 or prop_hinge == 1:
bone.hide = 0
else:
bone.hide = 1
#Left Properties
if ('_L' in b.name):
if ('arm' in b.name):
# Arm_L FK/IK
prop = int(b.ik_arm_L)
prop_hinge = int(b.hinge_hand_L)
for bone in arm.bones:
if (bone.name in b['bones_fk_L']):
if prop == 1:
bone.hide = 0
else:
bone.hide = 1
if (bone.name in b['bones_ik_L']):
if prop == 0:
bone.hide = 0
else:
bone.hide = 1
# HAND_L
if arm['rig_type'] == "Biped":
if (bone.name in b['bones_ik_hand_L']):
if prop == 1 and prop_hinge == 0:
bone.hide = 1
else:
bone.hide = 0
if (bone.name in b['bones_fk_hand_L']):
if prop_hinge == 1:
bone.hide = 1
else:
bone.hide = 0
if (bone.name in b['bones_ik_palm_L']):
if prop == 1 or prop_hinge == 0:
bone.hide = 1
else:
bone.hide = 0
if (bone.name in b['bones_fk_palm_L']):
if prop == 1 or prop_hinge == 0:
bone.hide = 0
else:
bone.hide = 1
# Fingers_L
prop_ik_all = int(b.ik_fing_all_L)
prop_hinge_all = int(b.hinge_fing_all_L)
def fingers_hide(b_name):
for bone in arm.bones:
ik_bones = [b_name]
if (bone.name == b_name):
if prop == 1 or prop_hinge == 1 or prop_ik_all == 1 or prop_hinge_all == 1:
bone.hide = 0
if prop == 0 and prop_hinge == 0 and prop_ik_all == 0 and prop_hinge_all == 0:
bone.hide = 1
return {"FINISHED"}
prop_hinge = int(b.hinge_fing_ind_L)
prop = int(b.ik_fing_ind_L)
fingers_hide('fing_ind_ik_L')
prop_hinge = int(b.hinge_fing_mid_L)
prop = int(b.ik_fing_mid_L)
fingers_hide('fing_mid_ik_L')
prop_hinge = int(b.hinge_fing_ring_L)
prop = int(b.ik_fing_ring_L)
fingers_hide('fing_ring_ik_L')
prop_hinge = int(b.hinge_fing_lit_L)
prop = int(b.ik_fing_lit_L)
fingers_hide('fing_lit_ik_L')
prop_hinge = int(b.hinge_fing_thumb_L)
prop = int(b.ik_fing_thumb_L)
fingers_hide('fing_thumb_ik_L')
if ('leg' in b.name):
# Leg_L FK/IK
prop = int(b.ik_leg_L)
for bone in arm.bones:
if (bone.name in b['bones_fk_L']):
if prop == 1:
bone.hide = 0
else:
bone.hide = 1
if (bone.name in b['bones_ik_L']):
if prop == 0:
bone.hide = 0
else:
bone.hide = 1
# Toes_L FK/IK
prop = int(b.ik_toes_all_L)
prop_hinge = int(b.hinge_toes_all_L)
for bone in arm.bones:
if (bone.name in b['bones_fk_foot_L']):
if prop == 1:
bone.hide = 0
else:
bone.hide = 1
if (bone.name in b['bones_ik_foot_L']):
if prop == 0 or prop_hinge == 1:
bone.hide = 0
else:
bone.hide = 1
#Right Properties
if ('_R' in b.name):
if ('arm' in b.name):
# Arm_R FK/IK
prop = int(b.ik_arm_R)
prop_hinge = int(b.hinge_hand_R)
for bone in arm.bones:
if (bone.name in b['bones_fk_R']):
if prop == 1:
bone.hide = 0
else:
bone.hide = 1
if (bone.name in b['bones_ik_R']):
if prop == 0:
bone.hide = 0
else:
bone.hide = 1
# HAND_R
if arm['rig_type'] == "Biped":
if (bone.name in b['bones_ik_hand_R']):
if prop == 1 and prop_hinge == 0:
bone.hide = 1
else:
bone.hide = 0
if (bone.name in b['bones_fk_hand_R']):
if prop_hinge == 1:
bone.hide = 1
else:
bone.hide = 0
if (bone.name in b['bones_ik_palm_R']):
if prop == 1 or prop_hinge == 0:
bone.hide = 1
else:
bone.hide = 0
if (bone.name in b['bones_fk_palm_R']):
if prop == 1 or prop_hinge == 0:
bone.hide = 0
else:
bone.hide = 1
# Fingers_R
prop_ik_all = int(b.ik_fing_all_R)
prop_hinge_all = int(b.hinge_fing_all_R)
def fingers_hide(b_name):
for bone in arm.bones:
ik_bones = [b_name]
if (bone.name == b_name):
if prop == 1 or prop_hinge == 1 or prop_ik_all == 1 or prop_hinge_all == 1:
bone.hide = 0
if prop == 0 and prop_hinge == 0 and prop_ik_all == 0 and prop_hinge_all == 0:
bone.hide = 1
return {"FINISHED"}
prop_hinge = int(b.hinge_fing_ind_R)
prop = int(b.ik_fing_ind_R)
fingers_hide('fing_ind_ik_R')
prop_hinge = int(b.hinge_fing_mid_R)
prop = int(b.ik_fing_mid_R)
fingers_hide('fing_mid_ik_R')
prop_hinge = int(b.hinge_fing_ring_R)
prop = int(b.ik_fing_ring_R)
fingers_hide('fing_ring_ik_R')
prop_hinge = int(b.hinge_fing_lit_R)
prop = int(b.ik_fing_lit_R)
fingers_hide('fing_lit_ik_R')
prop_hinge = int(b.hinge_fing_thumb_R)
prop = int(b.ik_fing_thumb_R)
fingers_hide('fing_thumb_ik_R')
if ('leg' in b.name):
# Leg_R FK/IK
prop = int(b.ik_leg_R)
for bone in arm.bones:
if (bone.name in b['bones_fk_R']):
if prop == 1:
bone.hide = 0
else:
bone.hide = 1
if (bone.name in b['bones_ik_R']):
if prop == 0:
bone.hide = 0
else:
bone.hide = 1
# Toes_R FK/IK
prop = int(b.ik_toes_all_R)
prop_hinge = int(b.hinge_toes_all_R)
for bone in arm.bones:
if (bone.name in b['bones_fk_foot_R']):
if prop == 1:
bone.hide = 0
else:
bone.hide = 1
if (bone.name in b['bones_ik_foot_R']):
if prop == 0 or prop_hinge == 1:
bone.hide = 0
else:
bone.hide = 1
####### Reproportion Toggle #######
def reproportion_toggle(context):
if not bpy.context.screen:
return False
if bpy.context.screen.is_animation_playing == True:
return False
if not bpy.context.active_object:
return False
if (bpy.context.active_object.type in ["ARMATURE"]) and (bpy.context.active_object.mode == 'POSE'):
for prop in bpy.context.active_object.data.items():
if prop[0] == 'rig_name' and prop[1] == 'BlenRig_5':
prop = bool(bpy.context.active_object.data.reproportion)
p_bones = bpy.context.active_object.pose.bones
if prop == True:
bpy.context.active_object.data.layers[31] = True
for b in p_bones:
for C in b.constraints:
if ('REPROP' in C.name):
C.mute = False
if ('NOREP' in C.name):
C.mute = True
else:
bpy.context.active_object.data.layers[0] = True
bpy.context.active_object.data.layers[31] = False
for b in p_bones:
for C in b.constraints:
if ('REPROP' in C.name):
C.mute = True
if ('NOREP' in C.name):
C.mute = False
rig_toggles(context)
####### Rig Toggles #######
def rig_toggles(context):
if not bpy.context.screen:
return False
if bpy.context.screen.is_animation_playing == True:
return False
if not bpy.context.active_object:
return False
if (bpy.context.active_object.type in ["ARMATURE"]) and (bpy.context.active_object.mode == 'POSE'):
for prop in bpy.context.active_object.data.items():
if prop[0] == 'rig_name' and prop[1] == 'BlenRig_5':
p_bones = bpy.context.active_object.pose.bones
arm = bpy.context.active_object.data
for b in p_bones:
if ('properties' in b.name):
# Left Properties
#Fingers_L
if ('L' in b.name):
if ('arm'in b.name):
prop_fing = int(b.toggle_fingers_L)
for bone in arm.bones:
if (bone.name in b['bones_fingers_def_1_L']):
if prop_fing == 1:
bone.layers[15] = 1
else:
bone.layers[15] = 0
if (bone.name in b['bones_fingers_def_2_L']):
if prop_fing == 1:
bone.layers[15] = 1
bone.layers[31] = 1
else:
bone.layers[15] = 0
bone.layers[31] = 0
if (bone.name in b['bones_fingers_str_L']):
if prop_fing == 1:
bone.layers[31] = 1
else:
bone.layers[31] = 0
if (bone.name in b['bones_fingers_ctrl_1_L']):
if prop_fing == 1:
bone.layers[0] = 1
else:
bone.layers[0] = 0
if (bone.name in b['bones_fingers_ctrl_2_L']):
if prop_fing == 1:
bone.layers[2] = 1
for pbone in p_bones:
if (pbone.name in b['bones_fingers_ctrl_2_L']):
for C in pbone.constraints:
if C.type == 'IK':
C.mute = False
else:
bone.layers[2] = 0
for pbone in p_bones:
if (pbone.name in b['bones_fingers_ctrl_2_L']):
for C in pbone.constraints:
if C.type == 'IK':
C.mute = True
#Toes_L
if ('L' in b.name):
if ('leg'in b.name):
prop_toes = int(b.toggle_toes_L)
for bone in arm.bones:
if (bone.name in b['bones_toes_def_1_L']):
if prop_toes == 1:
bone.layers[15] = 1
else:
bone.layers[15] = 0
if (bone.name in b['bones_toes_def_2_L']):
if prop_toes == 1:
bone.layers[15] = 1
bone.layers[31] = 1
else:
bone.layers[15] = 0
bone.layers[31] = 0
if (bone.name in b['bones_no_toes_def_L']):
if prop_toes == 1:
bone.layers[15] = 0
else:
bone.layers[15] = 1
if (bone.name in b['bones_toes_str_L']):
if prop_toes == 1:
bone.layers[31] = 1
else:
bone.layers[31] = 0
if (bone.name in b['bones_toes_ctrl_1_L']):
if prop_toes == 1:
bone.layers[0] = 1
else:
bone.layers[0] = 0
if (bone.name in b['bones_no_toes_ctrl_L']):
if prop_toes == 1:
bone.layers[0] = 0
else:
bone.layers[0] = 1
if (bone.name in b['bones_toes_ctrl_2_L']):
if prop_toes == 1:
bone.layers[2] = 1
for pbone in p_bones:
if (pbone.name in b['bones_toes_ctrl_2_L']):
for C in pbone.constraints:
if C.type == 'IK':
C.mute = False
else:
bone.layers[2] = 0
for pbone in p_bones:
if (pbone.name in b['bones_toes_ctrl_2_L']):
for C in pbone.constraints:
if C.type == 'IK':
C.mute = True
# Right Properties
#Fingers_R
if ('R' in b.name):
if ('arm'in b.name):
prop_fing = int(b.toggle_fingers_R)
for bone in arm.bones:
if (bone.name in b['bones_fingers_def_1_R']):
if prop_fing == 1:
bone.layers[15] = 1
else:
bone.layers[15] = 0
if (bone.name in b['bones_fingers_def_2_R']):
if prop_fing == 1:
bone.layers[15] = 1
bone.layers[31] = 1
else:
bone.layers[15] = 0
bone.layers[31] = 0
if (bone.name in b['bones_fingers_str_R']):
if prop_fing == 1:
bone.layers[31] = 1
else:
bone.layers[31] = 0
if (bone.name in b['bones_fingers_ctrl_1_R']):
if prop_fing == 1:
bone.layers[0] = 1
else:
bone.layers[0] = 0
if (bone.name in b['bones_fingers_ctrl_2_R']):
if prop_fing == 1:
bone.layers[2] = 1
for pbone in p_bones:
if (pbone.name in b['bones_fingers_ctrl_2_R']):
for C in pbone.constraints:
if C.type == 'IK':
C.mute = False
else:
bone.layers[2] = 0
for pbone in p_bones:
if (pbone.name in b['bones_fingers_ctrl_2_R']):
for C in pbone.constraints:
if C.type == 'IK':
C.mute = True
#Toes_R
if ('R' in b.name):
if ('leg'in b.name):
prop_toes = int(b.toggle_toes_R)
for bone in arm.bones:
if (bone.name in b['bones_toes_def_1_R']):
if prop_toes == 1:
bone.layers[15] = 1
else:
bone.layers[15] = 0
if (bone.name in b['bones_toes_def_2_R']):
if prop_toes == 1:
bone.layers[15] = 1
bone.layers[31] = 1
else:
bone.layers[15] = 0
bone.layers[31] = 0
if (bone.name in b['bones_no_toes_def_R']):
if prop_toes == 1:
bone.layers[15] = 0
else:
bone.layers[15] = 1
if (bone.name in b['bones_toes_str_R']):
if prop_toes == 1:
bone.layers[31] = 1
else:
bone.layers[31] = 0
if (bone.name in b['bones_toes_ctrl_1_R']):
if prop_toes == 1:
bone.layers[0] = 1
else:
bone.layers[0] = 0
if (bone.name in b['bones_no_toes_ctrl_R']):
if prop_toes == 1:
bone.layers[0] = 0
else:
bone.layers[0] = 1
if (bone.name in b['bones_toes_ctrl_2_R']):
if prop_toes == 1:
bone.layers[2] = 1
for pbone in p_bones:
if (pbone.name in b['bones_toes_ctrl_2_R']):
for C in pbone.constraints:
if C.type == 'IK':
C.mute = False
else:
bone.layers[2] = 0
for pbone in p_bones:
if (pbone.name in b['bones_toes_ctrl_2_R']):
for C in pbone.constraints:
if C.type == 'IK':
C.mute = True
####### Rig Optimizations #######
####### Toggle Face Drivers #######
def toggle_face_drivers(context):
if not bpy.context.screen:
return False
if bpy.context.screen.is_animation_playing == True:
return False
if not bpy.context.active_object:
return False
if not context.armature:
return False
for prop in bpy.context.active_object.data.items():
if prop[0] == 'rig_name' and prop[1] == 'BlenRig_5':
prop = bool(bpy.context.active_object.data.toggle_face_drivers)
armobj = bpy.context.active_object
drivers = armobj.animation_data.drivers
data_path_list = ['pose.bones["mouth_corner_R"]["BACK_LIMIT_R"]',
'pose.bones["mouth_corner_R"]["DOWN_LIMIT_R"]',
'pose.bones["mouth_corner_R"]["FORW_LIMIT_R"]',
'pose.bones["mouth_corner_R"]["IN_LIMIT_R"]',
'pose.bones["mouth_corner_R"]["OUT_LIMIT_R"]',
'pose.bones["mouth_corner_R"]["UP_LIMIT_R"]',
'pose.bones["mouth_corner_L"]["UP_LIMIT_L"]',
'pose.bones["mouth_corner_L"]["OUT_LIMIT_L"]',
'pose.bones["mouth_corner_L"]["IN_LIMIT_L"]',
'pose.bones["mouth_corner_L"]["FORW_LIMIT_L"]',
'pose.bones["mouth_corner_L"]["DOWN_LIMIT_L"]',
'pose.bones["mouth_corner_L"]["BACK_LIMIT_L"]',
'pose.bones["mouth_ctrl"]["OUT_LIMIT"]',
'pose.bones["mouth_ctrl"]["IN_LIMIT"]',
'pose.bones["mouth_ctrl"]["SMILE_LIMIT"]',
'pose.bones["mouth_ctrl"]["JAW_ROTATION"]',
'pose.bones["maxi"]["JAW_UP_LIMIT"]',
'pose.bones["maxi"]["JAW_DOWN_LIMIT"]',
'pose.bones["cheek_ctrl_R"]["CHEEK_DOWN_LIMIT_R"]',
'pose.bones["cheek_ctrl_L"]["CHEEK_DOWN_LIMIT_L"]',
'pose.bones["cheek_ctrl_R"]["CHEEK_UP_LIMIT_R"]',
'pose.bones["cheek_ctrl_L"]["CHEEK_UP_LIMIT_L"]',
'pose.bones["cheek_ctrl_R"]["AUTO_SMILE_R"]',
'pose.bones["cheek_ctrl_L"]["AUTO_SMILE_L"]',
'pose.bones["eyelid_low_ctrl_L"]["AUTO_CHEEK_L"]',
'pose.bones["eyelid_low_ctrl_R"]["AUTO_CHEEK_R"]',
'pose.bones["eyelid_low_ctrl_R"]["EYELID_DOWN_LIMIT_R"]',
'pose.bones["eyelid_low_ctrl_L"]["EYELID_DOWN_LIMIT_L"]',
'pose.bones["eyelid_low_ctrl_R"]["EYELID_UP_LIMIT_R"]',
'pose.bones["eyelid_low_ctrl_L"]["EYELID_UP_LIMIT_L"]',
'pose.bones["eyelid_up_ctrl_R"]["EYELID_DOWN_LIMIT_R"]',
'pose.bones["eyelid_up_ctrl_L"]["EYELID_DOWN_LIMIT_L"]',
'pose.bones["eyelid_up_ctrl_R"]["EYELID_UP_LIMIT_R"]',
'pose.bones["eyelid_up_ctrl_L"]["EYELID_UP_LIMIT_L"]',
'pose.bones["mouth_frown_ctrl_R"]["DOWN_LIMIT_R"]',
'pose.bones["mouth_frown_ctrl_L"]["DOWN_LIMIT_L"]',
'pose.bones["nose_frown_ctrl_R"]["UP_LIMIT_R"]',
'pose.bones["nose_frown_ctrl_L"]["UP_LIMIT_L"]',
'pose.bones["lip_up_ctrl_1_mstr_L"]["CORNER_FOLLOW_X_L"]',
'pose.bones["lip_up_ctrl_1_mstr_L"]["CORNER_FOLLOW_Y_L"]',
'pose.bones["lip_up_ctrl_1_mstr_L"]["CORNER_FOLLOW_Z_L"]',
'pose.bones["lip_low_ctrl_1_mstr_L"]["CORNER_FOLLOW_X_L"]',
'pose.bones["lip_low_ctrl_1_mstr_L"]["CORNER_FOLLOW_Y_L"]',
'pose.bones["lip_low_ctrl_1_mstr_L"]["CORNER_FOLLOW_Z_L"]',
'pose.bones["lip_up_ctrl_2_mstr_L"]["CORNER_FOLLOW_X_L"]',
'pose.bones["lip_up_ctrl_2_mstr_L"]["CORNER_FOLLOW_Y_L"]',
'pose.bones["lip_up_ctrl_2_mstr_L"]["CORNER_FOLLOW_Z_L"]',
'pose.bones["lip_low_ctrl_2_mstr_L"]["CORNER_FOLLOW_X_L"]',
'pose.bones["lip_low_ctrl_2_mstr_L"]["CORNER_FOLLOW_Y_L"]',
'pose.bones["lip_low_ctrl_2_mstr_L"]["CORNER_FOLLOW_Z_L"]',
'pose.bones["lip_up_ctrl_3_mstr_L"]["CORNER_FOLLOW_X_L"]',
'pose.bones["lip_up_ctrl_3_mstr_L"]["CORNER_FOLLOW_Y_L"]',
'pose.bones["lip_up_ctrl_3_mstr_L"]["CORNER_FOLLOW_Z_L"]',
'pose.bones["lip_low_ctrl_3_mstr_L"]["CORNER_FOLLOW_X_L"]',
'pose.bones["lip_low_ctrl_3_mstr_L"]["CORNER_FOLLOW_Y_L"]',
'pose.bones["lip_low_ctrl_3_mstr_L"]["CORNER_FOLLOW_Z_L"]',
'pose.bones["lip_up_ctrl_1_mstr_R"]["CORNER_FOLLOW_X_R"]',
'pose.bones["lip_up_ctrl_1_mstr_R"]["CORNER_FOLLOW_Y_R"]',
'pose.bones["lip_up_ctrl_1_mstr_R"]["CORNER_FOLLOW_Z_R"]',
'pose.bones["lip_low_ctrl_1_mstr_R"]["CORNER_FOLLOW_X_R"]',
'pose.bones["lip_low_ctrl_1_mstr_R"]["CORNER_FOLLOW_Y_R"]',
'pose.bones["lip_low_ctrl_1_mstr_R"]["CORNER_FOLLOW_Z_R"]',
'pose.bones["lip_up_ctrl_2_mstr_R"]["CORNER_FOLLOW_X_R"]',
'pose.bones["lip_up_ctrl_2_mstr_R"]["CORNER_FOLLOW_Y_R"]',
'pose.bones["lip_up_ctrl_2_mstr_R"]["CORNER_FOLLOW_Z_R"]',
'pose.bones["lip_low_ctrl_2_mstr_R"]["CORNER_FOLLOW_X_R"]',
'pose.bones["lip_low_ctrl_2_mstr_R"]["CORNER_FOLLOW_Y_R"]',
'pose.bones["lip_low_ctrl_2_mstr_R"]["CORNER_FOLLOW_Z_R"]',
'pose.bones["lip_up_ctrl_3_mstr_R"]["CORNER_FOLLOW_X_R"]',
'pose.bones["lip_up_ctrl_3_mstr_R"]["CORNER_FOLLOW_Y_R"]',
'pose.bones["lip_up_ctrl_3_mstr_R"]["CORNER_FOLLOW_Z_R"]',
'pose.bones["lip_low_ctrl_3_mstr_R"]["CORNER_FOLLOW_X_R"]',
'pose.bones["lip_low_ctrl_3_mstr_R"]["CORNER_FOLLOW_Y_R"]',
'pose.bones["lip_low_ctrl_3_mstr_R"]["CORNER_FOLLOW_Z_R"]',
'pose.bones["mouth_corner_R"]["ACTION_BACK_TOGGLE_R"]',
'pose.bones["mouth_corner_L"]["ACTION_BACK_TOGGLE_L"]',
'pose.bones["mouth_corner_R"]["ACTION_DOWN_TOGGLE_R"]',
'pose.bones["mouth_corner_L"]["ACTION_DOWN_TOGGLE_L"]',
'pose.bones["mouth_corner_R"]["ACTION_FORW_TOGGLE_R"]',
'pose.bones["mouth_corner_L"]["ACTION_FORW_TOGGLE_L"]',
'pose.bones["mouth_corner_R"]["ACTION_IN_TOGGLE_R"]',
'pose.bones["mouth_corner_L"]["ACTION_IN_TOGGLE_L"]',
'pose.bones["mouth_corner_R"]["ACTION_OUT_TOGGLE_R"]',
'pose.bones["mouth_corner_L"]["ACTION_OUT_TOGGLE_L"]',
'pose.bones["mouth_corner_R"]["ACTION_UP_TOGGLE_R"]',
'pose.bones["mouth_corner_L"]["ACTION_UP_TOGGLE_L"]',
'pose.bones["maxi"]["ACTION_UP_DOWN_TOGGLE"]',
'pose.bones["cheek_ctrl_R"]["ACTION_CHEEK_TOGGLE_R"]',
'pose.bones["cheek_ctrl_L"]["ACTION_CHEEK_TOGGLE_L"]',
'pose.bones["mouth_corner_L"]["AUTO_BACK_L"]',
'pose.bones["mouth_corner_R"]["AUTO_BACK_R"]']
for C in drivers:
for vars in C.driver.variables:
for T in vars.targets:
for D in data_path_list:
if D in T.data_path:
if prop == 1:
C.mute = False
else:
C.mute = True
####### Toggle Flex Drivers #######
def toggle_flex_drivers(context):
if not bpy.context.screen:
return False
if bpy.context.screen.is_animation_playing == True:
return False
if not bpy.context.active_object:
return False
if not context.armature:
return False
for prop in bpy.context.active_object.data.items():
if prop[0] == 'rig_name' and prop[1] == 'BlenRig_5':
prop = bool(bpy.context.active_object.data.toggle_flex_drivers)
armobj = bpy.context.active_object
drivers = armobj.animation_data.drivers
data_path_list = ['pose.bones["properties_head"]["flex_head_scale"]',
'pose.bones["properties_head"]["flex_neck_length"]',
'pose.bones["properties_head"]["flex_neck_width"]',
'pose.bones["properties_arm_R"]["flex_arm_length_R"]',
'pose.bones["properties_arm_R"]["flex_arm_uniform_scale_R"]',
'pose.bones["properties_arm_R"]["flex_arm_width_R"]',
'pose.bones["properties_arm_R"]["flex_forearm_length_R"]',
'pose.bones["properties_arm_R"]["flex_forearm_width_R"]',
'pose.bones["properties_arm_R"]["flex_hand_scale_R"]',
'pose.bones["properties_torso"]["flex_torso_height"]',
'pose.bones["properties_torso"]["flex_torso_scale"]',
'pose.bones["properties_torso"]["flex_chest_width"]',
'pose.bones["properties_torso"]["flex_ribs_width"]',
'pose.bones["properties_torso"]["flex_waist_width"]',
'pose.bones["properties_torso"]["flex_pelvis_width"]',
'pose.bones["properties_arm_L"]["flex_arm_length_L"]',
'pose.bones["properties_arm_L"]["flex_arm_uniform_scale_L"]',
'pose.bones["properties_arm_L"]["flex_arm_width_L"]',
'pose.bones["properties_arm_L"]["flex_forearm_length_L"]',
'pose.bones["properties_arm_L"]["flex_forearm_width_L"]',
'pose.bones["properties_arm_L"]["flex_hand_scale_L"]',
'pose.bones["properties_leg_R"]["flex_leg_uniform_scale_R"]',
'pose.bones["properties_leg_R"]["flex_thigh_length_R"]',
'pose.bones["properties_leg_R"]["flex_thigh_width_R"]',
'pose.bones["properties_leg_R"]["flex_shin_length_R"]',
'pose.bones["properties_leg_R"]["flex_shin_width_R"]',
'pose.bones["properties_leg_R"]["flex_foot_scale_R"]',
'pose.bones["properties_leg_R"]["flex_foot_loc_R"]',
'pose.bones["properties_leg_L"]["flex_leg_uniform_scale_L"]',
'pose.bones["properties_leg_L"]["flex_thigh_length_L"]',
'pose.bones["properties_leg_L"]["flex_thigh_width_L"]',
'pose.bones["properties_leg_L"]["flex_shin_length_L"]',
'pose.bones["properties_leg_L"]["flex_shin_width_L"]',
'pose.bones["properties_leg_L"]["flex_foot_scale_L"]',
'pose.bones["properties_leg_L"]["flex_foot_loc_L"]']
for C in drivers:
for vars in C.driver.variables:
for T in vars.targets:
for D in data_path_list:
if D in T.data_path:
if prop == 1:
C.mute = False
else:
C.mute = True
####### Toggle Body Drivers #######
def toggle_body_drivers(context):
if not bpy.context.screen:
return False
if bpy.context.screen.is_animation_playing == True:
return False
if not bpy.context.active_object:
return False
if not context.armature:
return False
for prop in bpy.context.active_object.data.items():
if prop[0] == 'rig_name' and prop[1] == 'BlenRig_5':
prop = bool(bpy.context.active_object.data.toggle_body_drivers)
armobj = bpy.context.active_object
drivers = armobj.animation_data.drivers
data_path_list = ['pose.bones["forearm_ik_R"].constraints["Ik_Initial_Rotation"].to_min_x_rot',
'pose.bones["forearm_ik_L"].constraints["Ik_Initial_Rotation"].to_min_x_rot',
'pose.bones["shin_ik_R"].constraints["Ik_Initial_Rotation"].to_min_x_rot',
'pose.bones["shin_ik_L"].constraints["Ik_Initial_Rotation"].to_min_x_rot',
'pose.bones["properties_arm_R"]["realistic_joints_wrist_R"]',
'pose.bones["properties_arm_L"]["realistic_joints_hand_L"]',
'pose.bones["properties_arm_R"]["realistic_joints_hand_R"]',
'pose.bones["properties_arm_L"]["realistic_joints_wrist_L"]',
'pose.bones["properties_arm_R"]["realistic_joints_elbow_R"]',
'pose.bones["properties_arm_L"]["realistic_joints_elbow_L"]',
'pose.bones["properties_leg_R"]["realistic_joints_knee_R"]',
'pose.bones["properties_leg_L"]["realistic_joints_knee_L"]',
'pose.bones["properties_leg_R"]["realistic_joints_ankle_R"]',
'pose.bones["properties_leg_L"]["realistic_joints_foot_L"]',
'pose.bones["properties_leg_R"]["realistic_joints_foot_R"]',
'pose.bones["properties_leg_L"]["realistic_joints_ankle_L"]',
'pose.bones["foot_roll_ctrl_R"]["FOOT_ROLL_AMPLITUD_R"]',
'pose.bones["foot_roll_ctrl_L"]["FOOT_ROLL_AMPLITUD_L"]',
'pose.bones["foot_roll_ctrl_R"]["TOE_1_ROLL_START_R"]',
'pose.bones["foot_roll_ctrl_L"]["TOE_1_ROLL_START_L"]',
'pose.bones["foot_roll_ctrl_R"]["TOE_2_ROLL_START_R"]',
'pose.bones["foot_roll_ctrl_L"]["TOE_2_ROLL_START_L"]',
'pose.bones["neck_1_fk"]["fk_follow_main"]',
'pose.bones["neck_2_fk"]["fk_follow_main"]',
'pose.bones["neck_3_fk"]["fk_follow_main"]',
'pose.bones["spine_1_fk"]["fk_follow_main"]',
'pose.bones["spine_2_fk"]["fk_follow_main"]',
'pose.bones["spine_3_fk"]["fk_follow_main"]',
'pose.bones["spine_2_inv"]["fk_follow_main"]',
'pose.bones["spine_1_inv"]["fk_follow_main"]',
'pose.bones["pelvis_inv"]["fk_follow_main"]']
for C in drivers:
for vars in C.driver.variables:
for T in vars.targets:
for D in data_path_list:
if D in T.data_path:
if prop == 1:
C.mute = False
else:
C.mute = True
######### Update Function for Properties ##########
def prop_update(self, context):
bone_auto_hide(context)
def reprop_update(self, context):
reproportion_toggle(context)
def rig_toggles_update(self, context):
rig_toggles(context)
def optimize_face(self, context):
toggle_face_drivers(context)
def optimize_flex(self, context):
toggle_flex_drivers(context)
def optimize_body(self, context):
toggle_body_drivers(context)
######### Hanlder for update on load and frame change #########
from bpy.app.handlers import persistent
@persistent
def load_handler(context):
bone_auto_hide(context)
bpy.app.handlers.load_post.append(load_handler)
bpy.app.handlers.frame_change_post.append(load_handler)
@persistent
def load_reproportion_handler(context):
reproportion_toggle(context)
rig_toggles(context)
bpy.app.handlers.load_post.append(load_reproportion_handler)
######### Properties Creation ############
#FK/IK
bpy.types.PoseBone.ik_head = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_head"
)
bpy.types.PoseBone.ik_torso = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_torso"
)
bpy.types.PoseBone.inv_torso = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Invert Torso Hierarchy",
update=prop_update,
name="inv_torso"
)
bpy.types.PoseBone.ik_arm_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_arm_L"
)
bpy.types.PoseBone.ik_arm_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_arm_R"
)
bpy.types.PoseBone.ik_leg_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_leg_L"
)
bpy.types.PoseBone.ik_toes_all_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_toes_all_L"
)
bpy.types.PoseBone.ik_leg_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_leg_R"
)
bpy.types.PoseBone.ik_toes_all_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_toes_all_R"
)
bpy.types.PoseBone.ik_fing_ind_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_ind_L"
)
bpy.types.PoseBone.ik_fing_mid_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_mid_L"
)
bpy.types.PoseBone.ik_fing_ring_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_mid_L"
)
bpy.types.PoseBone.ik_fing_lit_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_lit_L"
)
bpy.types.PoseBone.ik_fing_thumb_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_thumb_L"
)
bpy.types.PoseBone.ik_fing_ind_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_ind_R"
)
bpy.types.PoseBone.ik_fing_mid_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_mid_R"
)
bpy.types.PoseBone.ik_fing_ring_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_mid_R"
)
bpy.types.PoseBone.ik_fing_lit_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_lit_R"
)
bpy.types.PoseBone.ik_fing_thumb_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_thumb_R"
)
bpy.types.PoseBone.ik_fing_all_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_all_R"
)
bpy.types.PoseBone.ik_fing_all_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="IK/FK Toggle",
update=prop_update,
name="ik_fing_all_L"
)
# HINGE
bpy.types.PoseBone.hinge_head = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_head"
)
bpy.types.PoseBone.hinge_neck = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_neck"
)
bpy.types.PoseBone.hinge_arm_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_arm_L"
)
bpy.types.PoseBone.hinge_arm_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_arm_R"
)
bpy.types.PoseBone.hinge_hand_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_hand_L"
)
bpy.types.PoseBone.hinge_hand_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_hand_R"
)
bpy.types.PoseBone.hinge_fing_ind_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_ind_L"
)
bpy.types.PoseBone.hinge_fing_mid_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_mid_L"
)
bpy.types.PoseBone.hinge_fing_ring_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_mid_L"
)
bpy.types.PoseBone.hinge_fing_lit_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_lit_L"
)
bpy.types.PoseBone.hinge_fing_thumb_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_thumb_L"
)
bpy.types.PoseBone.hinge_fing_ind_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_ind_R"
)
bpy.types.PoseBone.hinge_fing_mid_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_mid_R"
)
bpy.types.PoseBone.hinge_fing_ring_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_mid_R"
)
bpy.types.PoseBone.hinge_fing_lit_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_lit_R"
)
bpy.types.PoseBone.hinge_fing_thumb_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_thumb_R"
)
bpy.types.PoseBone.hinge_fing_all_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_all_R"
)
bpy.types.PoseBone.hinge_fing_all_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_fing_all_L"
)
bpy.types.PoseBone.hinge_leg_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_leg_L"
)
bpy.types.PoseBone.hinge_toes_all_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_toes_all_L"
)
bpy.types.PoseBone.hinge_leg_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_leg_R"
)
bpy.types.PoseBone.hinge_toes_all_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Isolate Rotation",
update=prop_update,
name="hinge_toes_all_R"
)
#Stretchy IK
bpy.types.PoseBone.toon_head = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Stretchy IK Toggle",
update=prop_update,
name="toon_head"
)
bpy.types.PoseBone.toon_torso = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Stretchy IK Toggle",
update=prop_update,
name="toon_torso"
)
bpy.types.PoseBone.toon_arm_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Stretchy IK Toggle",
update=prop_update,
name="toon_arm_L"
)
bpy.types.PoseBone.toon_arm_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Stretchy IK Toggle",
update=prop_update,
name="toon_arm_R"
)
bpy.types.PoseBone.toon_leg_L = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Stretchy IK Toggle",
update=prop_update,
name="toon_leg_L"
)
bpy.types.PoseBone.toon_leg_R = FloatProperty(
default=0.000,
min=0.000,
max=1.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Stretchy IK Toggle",
update=prop_update,
name="toon_leg_R"
)
# LOOK SWITCH
bpy.types.PoseBone.look_switch = FloatProperty(
default=3.000,
min=0.000,
max=3.000,
precision=0,
step=100,
options={'ANIMATABLE'},
description="Target of Eyes",
update=prop_update,
name="look_switch"
)
# REPROPORTION
bpy.types.Armature.reproportion = BoolProperty(
default=0,
description="Toggle Reproportion Mode",
update=reprop_update,
name="reproportion"
)
# TOGGLE_FACE_DRIVERS
bpy.types.Armature.toggle_face_drivers = BoolProperty(
default=1,
description="Toggle Face Riggin Drivers",
update=optimize_face,
name="toggle_face_drivers"
)
# TOGGLE_FLEX_DRIVERS
bpy.types.Armature.toggle_flex_drivers = BoolProperty(
default=1,
description="Toggle Flex Scaling",
update=optimize_flex,
name="toggle_flex_drivers"
)
# TOGGLE_BODY_DRIVERS
bpy.types.Armature.toggle_body_drivers = BoolProperty(
default=1,
description="Toggle Body Rigging Drivers",
update=optimize_body,
name="toggle_body_drivers"
)
# TOGGLES
bpy.types.PoseBone.toggle_fingers_L = BoolProperty(
default=0,
description="Toggle fingers in rig",
update=rig_toggles_update,
name="toggle_fingers_L"
)
bpy.types.PoseBone.toggle_toes_L = BoolProperty(
default=0,
description="Toggle toes in rig",
update=rig_toggles_update,
name="toggle_toes_L"
)
bpy.types.PoseBone.toggle_fingers_R = BoolProperty(
default=0,
description="Toggle fingers in rig",
update=rig_toggles_update,
name="toggle_fingers_R"
)
bpy.types.PoseBone.toggle_toes_R = BoolProperty(
default=0,
description="Toggle toes in rig",
update=rig_toggles_update,
name="toggle_toes_R"
) | 1 | 0.860026 | 1 | 0.860026 | game-dev | MEDIA | 0.491022 | game-dev | 0.87689 | 1 | 0.87689 |
MonoGame/MonoGame.Samples | 4,923 | Platformer2D/Platformer2D.Core/Game/VirtualGamePad.cs | using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
namespace Platformer2D
{
class VirtualGamePad
{
private readonly Vector2 baseScreenSize;
private Matrix globalTransformation;
private readonly Texture2D texture;
private float secondsSinceLastInput;
private float opacity;
public VirtualGamePad(Vector2 baseScreenSize, Matrix globalTransformation, Texture2D texture)
{
this.baseScreenSize = baseScreenSize;
this.globalTransformation = Matrix.Invert(globalTransformation);
this.texture = texture;
secondsSinceLastInput = float.MaxValue;
}
public void NotifyPlayerIsMoving()
{
secondsSinceLastInput = 0;
}
public void Update(GameTime gameTime)
{
var secondsElapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
secondsSinceLastInput += secondsElapsed;
//If the player is moving, fade the controls out
// otherwise, if they haven't moved in 4 seconds, fade the controls back in
if (secondsSinceLastInput < 4)
opacity = Math.Max(0, opacity - secondsElapsed * 4);
else
opacity = Math.Min(1, opacity + secondsElapsed * 2);
}
public void Draw(SpriteBatch spriteBatch)
{
var spriteCenter = new Vector2(64, 64);
var color = Color.Multiply(Color.White, opacity);
spriteBatch.Draw(texture, new Vector2(64, baseScreenSize.Y - 64), null, color, -MathHelper.PiOver2, spriteCenter, 1, SpriteEffects.None, 0);
spriteBatch.Draw(texture, new Vector2(192, baseScreenSize.Y - 64), null, color, MathHelper.PiOver2, spriteCenter, 1, SpriteEffects.None, 0);
spriteBatch.Draw(texture, new Vector2(baseScreenSize.X - 128, baseScreenSize.Y - 128), null, color, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
}
/// <summary>
/// Generates a GamePadState based on the touch input provided (as applied to the on screen controls) and the gamepad state
/// </summary>
public GamePadState GetState(TouchCollection touchState, GamePadState gpState)
{
//Work out what buttons are pressed based on the touchState
Buttons buttonsPressed = 0;
foreach (var touch in touchState)
{
if (touch.State == TouchLocationState.Moved || touch.State == TouchLocationState.Pressed)
{
//Scale the touch position to be in _baseScreenSize coordinates
Vector2 pos = touch.Position;
Vector2.Transform(ref pos, ref globalTransformation, out pos);
if (pos.X < 128)
buttonsPressed |= Buttons.DPadLeft;
else if (pos.X < 256)
buttonsPressed |= Buttons.DPadRight;
else if (pos.X >= baseScreenSize.X - 128)
buttonsPressed |= Buttons.A;
}
}
//Combine the buttons of the real gamepad
var gpButtons = gpState.Buttons;
buttonsPressed |= (gpButtons.A == ButtonState.Pressed ? Buttons.A : 0);
buttonsPressed |= (gpButtons.B == ButtonState.Pressed ? Buttons.B : 0);
buttonsPressed |= (gpButtons.X == ButtonState.Pressed ? Buttons.X : 0);
buttonsPressed |= (gpButtons.Y == ButtonState.Pressed ? Buttons.Y : 0);
buttonsPressed |= (gpButtons.Start == ButtonState.Pressed ? Buttons.Start : 0);
buttonsPressed |= (gpButtons.Back == ButtonState.Pressed ? Buttons.Back : 0);
buttonsPressed |= gpState.IsButtonDown(Buttons.DPadDown) ? Buttons.DPadDown : 0;
buttonsPressed |= gpState.IsButtonDown(Buttons.DPadLeft) ? Buttons.DPadLeft : 0;
buttonsPressed |= gpState.IsButtonDown(Buttons.DPadRight) ? Buttons.DPadRight : 0;
buttonsPressed |= gpState.IsButtonDown(Buttons.DPadUp) ? Buttons.DPadUp : 0;
buttonsPressed |= (gpButtons.BigButton == ButtonState.Pressed ? Buttons.BigButton : 0);
buttonsPressed |= (gpButtons.LeftShoulder == ButtonState.Pressed ? Buttons.LeftShoulder : 0);
buttonsPressed |= (gpButtons.RightShoulder == ButtonState.Pressed ? Buttons.RightShoulder : 0);
buttonsPressed |= (gpButtons.LeftStick == ButtonState.Pressed ? Buttons.LeftStick : 0);
buttonsPressed |= (gpButtons.RightStick == ButtonState.Pressed ? Buttons.RightStick : 0);
var buttons = new GamePadButtons(buttonsPressed);
return new GamePadState(gpState.ThumbSticks, gpState.Triggers, buttons, gpState.DPad);
}
}
} | 1 | 0.841685 | 1 | 0.841685 | game-dev | MEDIA | 0.896626 | game-dev | 0.685711 | 1 | 0.685711 |
s0bvi/goldsvet-opensource | 2,386 | casino/app/Games/WildGladiators/PragmaticLib/Multiple.php | <?php
namespace VanguardLTE\Games\WildGladiators\PragmaticLib;
class Multiple
{
public static function getBonanzaMultiple($slotArea, $gameSettings, $currentLog){
$tmp = explode(';', $gameSettings['prm']);
$tmp = explode('~', $tmp[0]);
$prm = $tmp[0]; // multiplier symbol
$prmMultipliers = explode(',',$tmp[1]); // array of possible multiplier values
// rebuild the playing field on reels
$reels = 6;
$tmpSlotArea = array_chunk($slotArea, $reels);
$currentSlotArea = [];
$k = 0;
while ($k < $reels) { // rearrange from rows to rows
$i = 0;
while ($i < $gameSettings['sh']) {
$currentSlotArea[$k][] = $tmpSlotArea[$i][$k];
$i++;
}
$k++;
}
$prmReady = [];
// go through all the coils from the end, and assign multipliers, write in the log which multiplier from which coil
foreach ($currentSlotArea as $reelKey => $reel) {
foreach (array_reverse($reel) as $symbolKey => $symbol) {
if ($symbol == $prm){
$symbolsCount = $gameSettings['sh'] - 1; // arrays start at 0. To find out how many symbols should be in the reel
$prmSymbol = $reelKey + ($reels * ($symbolsCount - $symbolKey)); // calculate position. Coil number, add to the coil position from the beginning
$prmReady[] = [
'Symbol' => $prm,
'Position' => $prmSymbol,
'Multiplier' => self::getMultiplier($currentLog,$prmMultipliers,$reelKey),
'Reel' => $reelKey
];
}
}
}
if ($prmReady) return $prmReady;
else return false;
}
private static function getMultiplier($currentLog, $prmMultipliers, $reelKey){
if ($currentLog && array_key_exists('Multipliers', $currentLog)){
foreach ($currentLog['Multipliers'] as $logMultiplier) {
if ($logMultiplier['Reel'] == $reelKey){
$multiplier = $logMultiplier['Multiplier'];
}
}
}
if (isset($multiplier)) return $multiplier;
else $multiplier = $prmMultipliers[array_rand($prmMultipliers)];
return $multiplier;
}
}
| 1 | 0.759676 | 1 | 0.759676 | game-dev | MEDIA | 0.760325 | game-dev | 0.770832 | 1 | 0.770832 |
lua9520/source-engine-2018-cstrike15_src | 1,791 | game/client/portal2/gameui/contentcontroldialog.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CONTENTCONTROLDIALOG_H
#define CONTENTCONTROLDIALOG_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_controls/Frame.h"
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CContentControlDialog : public vgui::Frame
{
DECLARE_CLASS_SIMPLE( CContentControlDialog, vgui::Frame );
public:
CContentControlDialog(vgui::Panel *parent);
~CContentControlDialog();
virtual void OnCommand( const char *command );
virtual void OnClose();
virtual void Activate();
void ResetPassword();
void ApplyPassword();
bool IsPasswordEnabledInDialog();
bool IsPasswordEnabled() { return ( m_szGorePW[0] != 0 ); }
protected:
void WriteToken( const char *str );
bool CheckPassword( char const *oldPW, char const *newPW, bool enableContentControl );
void UpdateContentControlStatus( void );
void Explain( char const *fmt, ... );
void HashPassword(const char *newPW, char *hashBuffer, int maxlen );
bool EnablePassword(const char *newPW);
bool DisablePassword(const char *oldPW);
enum
{
MAX_GORE_PW = 64,
};
char m_szGorePW[ MAX_GORE_PW ];
bool m_bDefaultPassword;
vgui::Label *m_pStatus;
vgui::Button *m_pOK;
vgui::TextEntry *m_pPassword;
vgui::Label *m_pPasswordLabel;
vgui::Label *m_pPassword2Label;
vgui::TextEntry *m_pPassword2;
vgui::Label *m_pExplain;
};
#endif // CONTENTCONTROLDIALOG_H
| 1 | 0.931826 | 1 | 0.931826 | game-dev | MEDIA | 0.658534 | game-dev | 0.608432 | 1 | 0.608432 |
cmangos/playerbots | 5,882 | playerbot/strategy/warrior/WarriorStrategy.h | #pragma once
#include "playerbot/strategy/generic/ClassStrategy.h"
namespace ai
{
class WarriorStrategy : public ClassStrategy
{
public:
WarriorStrategy(PlayerbotAI* ai);
protected:
virtual void InitCombatTriggers(std::list<TriggerNode*> &triggers) override;
virtual void InitNonCombatTriggers(std::list<TriggerNode*>& triggers) override;
virtual void InitReactionTriggers(std::list<TriggerNode*>& triggers) override;
virtual void InitDeadTriggers(std::list<TriggerNode*>& triggers) override;
};
class WarriorPvpStrategy : public ClassPvpStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitReactionTriggers(std::list<TriggerNode*>& triggers);
static void InitDeadTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorPveStrategy : public ClassPveStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitReactionTriggers(std::list<TriggerNode*>& triggers);
static void InitDeadTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorRaidStrategy : public ClassRaidStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitReactionTriggers(std::list<TriggerNode*>& triggers);
static void InitDeadTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorAoeStrategy : public AoeStrategy
{
public:
WarriorAoeStrategy(PlayerbotAI* ai) : AoeStrategy(ai) {}
protected:
virtual void InitCombatTriggers(std::list<TriggerNode*>& triggers) override;
virtual void InitNonCombatTriggers(std::list<TriggerNode*>& triggers) override;
};
class WarriorAoePvpStrategy : public AoePvpStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorAoePveStrategy : public AoePveStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorAoeRaidStrategy : public AoeRaidStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorCcStrategy : public CcStrategy
{
public:
WarriorCcStrategy(PlayerbotAI* ai) : CcStrategy(ai) {}
protected:
virtual void InitCombatTriggers(std::list<TriggerNode*>& triggers) override;
virtual void InitNonCombatTriggers(std::list<TriggerNode*>& triggers) override;
};
class WarriorCcPvpStrategy : public CcPvpStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorCcPveStrategy : public CcPveStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorCcRaidStrategy : public CcRaidStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorBuffStrategy : public BuffStrategy
{
public:
WarriorBuffStrategy(PlayerbotAI* ai) : BuffStrategy(ai) {}
protected:
virtual void InitCombatTriggers(std::list<TriggerNode*>& triggers) override;
virtual void InitNonCombatTriggers(std::list<TriggerNode*>& triggers) override;
};
class WarriorBuffPvpStrategy : public BuffPvpStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorBuffPveStrategy : public BuffPveStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorBuffRaidStrategy : public BuffRaidStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorBoostStrategy : public BoostStrategy
{
public:
WarriorBoostStrategy(PlayerbotAI* ai) : BoostStrategy(ai) {}
protected:
virtual void InitCombatTriggers(std::list<TriggerNode*>& triggers) override;
virtual void InitNonCombatTriggers(std::list<TriggerNode*>& triggers) override;
};
class WarriorBoostPvpStrategy : public BoostPvpStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorBoostPveStrategy : public BoostPveStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
class WarriorBoostRaidStrategy : public BoostRaidStrategy
{
public:
static void InitCombatTriggers(std::list<TriggerNode*>& triggers);
static void InitNonCombatTriggers(std::list<TriggerNode*>& triggers);
};
}
| 1 | 0.903287 | 1 | 0.903287 | game-dev | MEDIA | 0.89211 | game-dev | 0.704379 | 1 | 0.704379 |
michalkonturek/MKUnits | 5,651 | MKUnits/Classes/MassUnit+Imperial.swift | //
// MassUnit+Imperial.swift
// MKUnits
//
// Copyright (c) 2016 Michal Konturek <michal.konturek@gmail.com>
//
// 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.
//
import Foundation
public extension MassUnit {
/**
Returns ton `[t]` mass unit.
- author: Michal Konturek
*/
public static var ton: MassUnit {
return MassUnit(
name: "ton",
symbol: "t",
ratio: NSDecimalNumber(mantissa: 10160469088, exponent: -7, isNegative: false)
)
}
/**
Returns hundredweight `[cwt]` mass unit.
- author: Michal Konturek
*/
public static var hundredweight: MassUnit {
return MassUnit(
name: "hundredweight",
symbol: "cwt",
ratio: NSDecimalNumber(mantissa: 5080234544, exponent: -8, isNegative: false)
)
}
/**
Returns quarter `[qtr]` mass unit.
- author: Michal Konturek
*/
public static var quarter: MassUnit {
return MassUnit(
name: "quarter",
symbol: "qtr",
ratio: NSDecimalNumber(mantissa: 1270058636, exponent: -8, isNegative: false)
)
}
/**
Returns stone `[st]` mass unit.
- author: Michal Konturek
*/
public static var stone: MassUnit {
return MassUnit(
name: "stone",
symbol: "st",
ratio: NSDecimalNumber(mantissa: 635029, exponent: -5, isNegative: false)
)
}
/**
Returns pound `[lb]` mass unit.
- author: Michal Konturek
*/
public static var pound: MassUnit {
return MassUnit(
name: "pound",
symbol: "lb",
ratio: NSDecimalNumber(mantissa: 45359237, exponent: -8, isNegative: false)
)
}
/**
Returns ounce `[oz]` mass unit.
- author: Michal Konturek
*/
public static var ounce: MassUnit {
return MassUnit(
name: "ounce",
symbol: "oz",
ratio: NSDecimalNumber(mantissa: 28349523125, exponent: -12, isNegative: false)
)
}
/**
Returns drachm `[dr]` mass unit.
- author: Michal Konturek
*/
public static var drachm: MassUnit {
return MassUnit(
name: "drachm",
symbol: "dr",
ratio: NSDecimalNumber(mantissa: 17718451953125, exponent: -16, isNegative: false)
)
}
/**
Returns grain `[gr]` mass unit.
- author: Michal Konturek
*/
public static var grain: MassUnit {
return MassUnit(
name: "grain",
symbol: "gr",
ratio: NSDecimalNumber(mantissa: 6479891, exponent: -11, isNegative: false)
)
}
}
extension ExpressibleByIntegerLiteral {
/**
Returns instance converted as ton quantity.
- author: Michal Konturek
*/
public func ton() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: MassUnit.ton)
}
/**
Returns instance converted as hundredweight quantity.
- author: Michal Konturek
*/
public func hundredweight() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: MassUnit.hundredweight)
}
/**
Returns instance converted as quarter quantity.
- author: Michal Konturek
*/
public func quarter() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: MassUnit.quarter)
}
/**
Returns instance converted as stone quantity.
- author: Michal Konturek
*/
public func stone() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: MassUnit.stone)
}
/**
Returns instance converted as pound quantity.
- author: Michal Konturek
*/
public func pound() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: MassUnit.pound)
}
/**
Returns instance converted as ounce quantity.
- author: Michal Konturek
*/
public func ounce() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: MassUnit.ounce)
}
/**
Returns instance converted as drachm quantity.
- author: Michal Konturek
*/
public func drachm() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: MassUnit.drachm)
}
/**
Returns instance converted as grain quantity.
- author: Michal Konturek
*/
public func grain() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: MassUnit.grain)
}
}
| 1 | 0.57904 | 1 | 0.57904 | game-dev | MEDIA | 0.341351 | game-dev | 0.500408 | 1 | 0.500408 |
benkuper/Blux | 2,585 | Source/Scene/SceneManager.h | /*
==============================================================================
SceneManager.h
Created: 26 Sep 2020 1:49:54pm
Author: bkupe
==============================================================================
*/
#pragma once
class Object;
class ObjectComponent;
class SceneManager :
public BaseManager<Scene>,
public Inspectable::InspectableListener,
public SceneListener,
public OSCRemoteControl::RemoteControlListener,
public Thread
{
public:
juce_DeclareSingleton(SceneManager, true);
SceneManager();
~SceneManager();
Factory<Scene> factory;
float loadTime;
BoolParameter* addLoadToUndo;
FloatParameter* forceLoadTime;
Scene* previousScene;
Scene* currentScene;
StringParameter* previousSceneName;
StringParameter* currentSceneName;
StringParameter* nextSceneName;
Trigger* loadNextSceneTrigger;
Trigger* loadPreviousSceneTrigger;
enum PreviewMode { NONE, NEXT, HOVER, SELECTED };
EnumParameter* previewMode;
BoolParameter* lockUI;
void addItemInternal(Scene* s, var data) override;
void removeItemInternal(Scene* s) override;
void loadScene(Scene* s, float loadTime = -1, bool setUndoIfNeeded = true);
Scene* getNextScene();
Scene* getPreviousScene();
void run() override;
//void lerpSceneParams(float weight);
void askForLoadScene(Scene* s, float time) override;
Array<ChainVizTarget*> getChainVizTargetsForObjectAndComponent(Object* o, ComponentType t);
void processComponent(Object* o, ObjectComponent* c, HashMap<Parameter*, var>& values);
void onContainerTriggerTriggered(Trigger* t) override;
void onContainerParameterChanged(Parameter* p) override;
void processMessage(const OSCMessage& m, const String& clientId) override;
void inspectableDestroyed(Inspectable* i) override;
QueuedNotifier<SceneManagerEvent> sceneManagerNotifier;
void addAsyncSceneManagerListener(AsyncSceneListener* newListener) { sceneManagerNotifier.addListener(newListener); }
void addAsyncCoalescedSceneManagerListener(AsyncSceneListener* newListener) { sceneManagerNotifier.addAsyncCoalescedListener(newListener); }
void removeAsyncSceneManagerListener(AsyncSceneListener* listener) { sceneManagerNotifier.removeListener(listener); }
class SceneLoadAction :
public UndoableAction
{
public:
SceneLoadAction(Scene* prevScene, float prevTime, Scene* s, float time);
~SceneLoadAction() {}
Scene* prevScene;
WeakReference<Inspectable> prevSceneRef;
float prevTime;
Scene* scene;
WeakReference<Inspectable> sceneRef;
float time;
bool perform() override;
bool undo() override;
};
}; | 1 | 0.949331 | 1 | 0.949331 | game-dev | MEDIA | 0.812772 | game-dev,graphics-rendering | 0.938375 | 1 | 0.938375 |
RE-SS3D/SS3D | 2,943 | Assets/Scripts/SS3D/Systems/Substances/Interactions/DispenseSubstanceInteraction.cs | using System;
using SS3D.Interactions;
using SS3D.Interactions.Interfaces;
using SS3D.Interactions.Extensions;
using UnityEngine;
namespace SS3D.Substances
{
public class DispenseSubstanceInteraction : IInteraction
{
public event Action OnInteractionInvalid;
public string Name { get; set; } = "Dispense";
/// <summary>
/// The substance to dispense
/// </summary>
public SubstanceEntry Substance { get; set; }
/// <summary>
/// Checks if the interaction should be possible
/// </summary>
public Predicate<InteractionEvent> CanInteractCallback { get; set; } = _ => true;
/// <summary>
/// If a range check should be automatically performed
/// </summary>
public bool RangeCheck { get; set; }
public virtual string GetGenericName()
{
return Name;
}
public IClientInteraction CreateClient(InteractionEvent interactionEvent)
{
return null;
}
public string GetName(InteractionEvent interactionEvent)
{
return Name;
}
public Sprite GetIcon(InteractionEvent interactionEvent)
{
return null;
}
public bool CanInteract(InteractionEvent interactionEvent)
{
if (RangeCheck && !InteractionExtensions.RangeCheck(interactionEvent))
{
return false;
}
IGameObjectProvider provider = interactionEvent.Source as IGameObjectProvider;
if (provider == null)
{
return false;
}
SubstanceContainer container = provider.GameObject.GetComponent<SubstanceContainer>();
if (container == null)
{
return false;
}
// You cannot dispense to a container that is already full.
if (container.RemainingVolume < 0.01f)
{
return false;
}
return CanInteractCallback.Invoke(interactionEvent);
}
public bool Start(InteractionEvent interactionEvent, InteractionReference reference)
{
if (interactionEvent.Source is IGameObjectProvider provider)
{
SubstanceContainer container = provider.GameObject.GetComponent<SubstanceContainer>();
if (container != null)
{
container.AddSubstance(Substance.Substance, Substance.MilliMoles);
container.SetDirty();
}
}
return false;
}
public bool Update(InteractionEvent interactionEvent, InteractionReference reference)
{
return true;
}
public void Cancel(InteractionEvent interactionEvent, InteractionReference reference)
{
return;
}
}
} | 1 | 0.739342 | 1 | 0.739342 | game-dev | MEDIA | 0.921251 | game-dev | 0.753577 | 1 | 0.753577 |
flame-engine/flame | 3,320 | examples/lib/stories/bridge_libraries/flame_forge2d/widget_example.dart | import 'package:examples/stories/bridge_libraries/flame_forge2d/utils/boundaries.dart';
import 'package:flame/game.dart';
import 'package:flame_forge2d/flame_forge2d.dart' hide Transform;
import 'package:flutter/material.dart';
class WidgetExample extends Forge2DGame {
static const String description = '''
This examples shows how to render a widget on top of a Forge2D body outside
of Flame.
''';
final List<void Function()> updateStates = [];
final Map<int, Body> bodyIdMap = {};
final List<int> addLaterIds = [];
WidgetExample() : super(zoom: 20, gravity: Vector2(0, 10.0));
@override
Future<void> onLoad() async {
super.onLoad();
final boundaries = createBoundaries(this, strokeWidth: 0);
world.addAll(boundaries);
}
Body createBody() {
final bodyDef = BodyDef(
angularVelocity: 3,
position: Vector2.zero(),
type: BodyType.dynamic,
);
final body = world.createBody(bodyDef);
final shape = PolygonShape()..setAsBoxXY(4.6, 0.8);
final fixtureDef = FixtureDef(
shape,
restitution: 0.8,
friction: 0.2,
);
body.createFixture(fixtureDef);
return body;
}
int createBodyId(int id) {
addLaterIds.add(id);
return id;
}
@override
void update(double dt) {
super.update(dt);
addLaterIds.forEach((id) {
if (!bodyIdMap.containsKey(id)) {
bodyIdMap[id] = createBody();
}
});
addLaterIds.clear();
updateStates.forEach((f) => f());
}
}
class BodyWidgetExample extends StatelessWidget {
const BodyWidgetExample({super.key});
@override
Widget build(BuildContext context) {
return GameWidget<WidgetExample>(
game: WidgetExample(),
overlayBuilderMap: {
'button1': (ctx, game) {
return BodyButtonWidget(game, game.createBodyId(1));
},
'button2': (ctx, game) {
return BodyButtonWidget(game, game.createBodyId(2));
},
},
initialActiveOverlays: const ['button1', 'button2'],
);
}
}
class BodyButtonWidget extends StatefulWidget {
final WidgetExample _game;
final int _bodyId;
const BodyButtonWidget(
this._game,
this._bodyId, {
super.key,
});
@override
State<StatefulWidget> createState() {
return _BodyButtonState(_game, _bodyId);
}
}
class _BodyButtonState extends State<BodyButtonWidget> {
final WidgetExample _game;
final int _bodyId;
Body? _body;
_BodyButtonState(this._game, this._bodyId) {
_game.updateStates.add(() {
setState(() {
_body = _game.bodyIdMap[_bodyId];
});
});
}
@override
Widget build(BuildContext context) {
final body = _body;
if (body == null) {
return Container();
} else {
final bodyPosition = _game.worldToScreen(body.position);
return Positioned(
top: bodyPosition.y - 18,
left: bodyPosition.x - 90,
child: Transform.rotate(
angle: body.angle,
child: ElevatedButton(
onPressed: () {
setState(
() => body.applyLinearImpulse(Vector2(0.0, 1000)),
);
},
child: const Text(
'Flying button!',
textScaler: TextScaler.linear(2.0),
),
),
),
);
}
}
}
| 1 | 0.823032 | 1 | 0.823032 | game-dev | MEDIA | 0.932015 | game-dev | 0.661182 | 1 | 0.661182 |
cheese-framework/cheese | 1,198 | core/src/main/java/net/codeocean/cheese/backend/impl/KeysImpl.kt | package net.codeocean.cheese.backend.impl
import android.os.Build
import net.codeocean.cheese.core.api.Keys
object KeysImpl:Keys {
override fun home(): Boolean {
return cn.vove7.auto.core.api.home()
}
override fun back(): Boolean {
return cn.vove7.auto.core.api.back()
}
override fun quickSettings(): Boolean {
return cn.vove7.auto.core.api.quickSettings()
}
override fun powerDialog(): Boolean {
return cn.vove7.auto.core.api.powerDialog()
}
override fun pullNotificationBar(): Boolean {
return cn.vove7.auto.core.api.pullNotificationBar()
}
override fun recents(): Boolean {
return cn.vove7.auto.core.api.recents()
}
override fun lockScreen(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
cn.vove7.auto.core.api.lockScreen()
} else false
}
override fun screenShot(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
cn.vove7.auto.core.api.screenShot()
} else false
}
override fun splitScreen(): Boolean {
return cn.vove7.auto.core.api.splitScreen()
}
} | 1 | 0.689904 | 1 | 0.689904 | game-dev | MEDIA | 0.533499 | game-dev | 0.581928 | 1 | 0.581928 |
andrew-gresyk/FFSM2 | 5,880 | test/test_ancestors.cpp | // FFSM2 (flat state machine for games and interactive applications)
// Created by Andrew Gresyk
#define FFSM2_ENABLE_VERBOSE_DEBUG_LOG
#define FFSM2_DISABLE_TYPEINDEX
#include "tools.hpp"
namespace test_ancestors {
//------------------------------------------------------------------------------
struct Event {
enum class Type {
ENTRY_GUARD,
ENTER,
REENTER,
PRE_UPDATE,
UPDATE,
POST_UPDATE,
PRE_REACT,
REACT,
POST_REACT,
EXIT_GUARD,
EXIT,
COUNT
};
Event(const ffsm2::StateID origin_,
const Type type_)
: origin{origin_}
, type{type_}
{}
Event(const Type type_ = Type::COUNT)
: type{type_}
{}
ffsm2::StateID origin = ffsm2::INVALID_STATE_ID;
Type type;
};
using Events = std::vector<Event>;
//------------------------------------------------------------------------------
void
assertSequence(Events& history,
const Events& reference)
{
const auto count = std::max(history.size(), reference.size());
for (unsigned i = 0; i < count; ++i) {
REQUIRE(i < history.size()); //-V521
REQUIRE(i < reference.size()); //-V521
if (i < history.size() &&
i < reference.size())
{
REQUIRE(history[i].type == reference[i].type); //-V521
REQUIRE(history[i].origin == reference[i].origin); //-V521
}
}
history.clear();
}
////////////////////////////////////////////////////////////////////////////////
using Config = ffsm2::Config
::ContextT<Events&>
::ManualActivation;
using M = ffsm2::MachineT<Config>;
//------------------------------------------------------------------------------
#define S(s) struct s
using FSM = M::Root<S(R),
S(A),
S(B)
>;
#undef S
//------------------------------------------------------------------------------
static_assert(FSM::stateId<R>() == ffsm2::INVALID_STATE_ID, "");
static_assert(FSM::stateId<A>() == 0, "");
static_assert(FSM::stateId<B>() == 1, "");
////////////////////////////////////////////////////////////////////////////////
template <typename T>
struct AncestorT
: FSM::State
{
void entryGuard (GuardControl& control) { control._().emplace_back(stateId<T>(), Event::Type::ENTRY_GUARD); REQUIRE(control.stateId() == stateId<T>()); }
void enter ( PlanControl& control) { control._().emplace_back(stateId<T>(), Event::Type::ENTER); REQUIRE(control.stateId() == stateId<T>()); }
void reenter ( PlanControl& control) { control._().emplace_back(stateId<T>(), Event::Type::REENTER); REQUIRE(control.stateId() == stateId<T>()); }
void preUpdate ( FullControl& control) { control._().emplace_back(stateId<T>(), Event::Type::PRE_UPDATE); REQUIRE(control.stateId() == stateId<T>()); }
void update ( FullControl& control) { control._().emplace_back(stateId<T>(), Event::Type::UPDATE); REQUIRE(control.stateId() == stateId<T>()); }
void postUpdate ( FullControl& control) { control._().emplace_back(stateId<T>(), Event::Type::POST_UPDATE); REQUIRE(control.stateId() == stateId<T>()); }
void preReact (const Event&,
FullControl& control) { control._().emplace_back(stateId<T>(), Event::Type::PRE_REACT); REQUIRE(control.stateId() == stateId<T>()); }
void react (const Event&,
FullControl& control) { control._().emplace_back(stateId<T>(), Event::Type::REACT); REQUIRE(control.stateId() == stateId<T>()); }
void postReact (const Event&,
FullControl& control) { control._().emplace_back(stateId<T>(), Event::Type::POST_REACT); REQUIRE(control.stateId() == stateId<T>()); }
void exitGuard (GuardControl& control) { control._().emplace_back(stateId<T>(), Event::Type::EXIT_GUARD); REQUIRE(control.stateId() == stateId<T>()); }
void exit ( PlanControl& control) { control._().emplace_back(stateId<T>(), Event::Type::EXIT); REQUIRE(control.stateId() == stateId<T>()); }
};
//------------------------------------------------------------------------------
struct R
: FSM::StateT<AncestorT<R>>
{
void entryGuard(GuardControl& control) {
control.changeTo<B>();
}
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
struct A
: FSM::StateT<AncestorT<A>>
{};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
struct B
: FSM::StateT<AncestorT<B>>
{};
////////////////////////////////////////////////////////////////////////////////
TEST_CASE("FSM.Ancestors") {
Events events;
{
FSM::Instance machine{events};
assertSequence(events, {});
machine.enter();
assertSequence(events, {
{ ffsm2::INVALID_STATE_ID, Event::Type::ENTRY_GUARD },
{ FSM::stateId<A>(), Event::Type::ENTRY_GUARD },
{ ffsm2::INVALID_STATE_ID, Event::Type::ENTRY_GUARD },
{ FSM::stateId<B>(), Event::Type::ENTRY_GUARD },
{ FSM::stateId<R>(), Event::Type::ENTER },
{ FSM::stateId<B>(), Event::Type::ENTER },
});
REQUIRE(machine.activeStateId() == FSM::stateId<B>());
machine.update();
assertSequence(events, {
{ FSM::stateId<R>(), Event::Type::PRE_UPDATE },
{ FSM::stateId<B>(), Event::Type::PRE_UPDATE },
{ FSM::stateId<R>(), Event::Type::UPDATE },
{ FSM::stateId<B>(), Event::Type::UPDATE },
{ FSM::stateId<B>(), Event::Type::POST_UPDATE },
{ FSM::stateId<R>(), Event::Type::POST_UPDATE },
});
machine.react(Event{});
assertSequence(events, {
{ FSM::stateId<R>(), Event::Type::PRE_REACT },
{ FSM::stateId<B>(), Event::Type::PRE_REACT },
{ FSM::stateId<R>(), Event::Type::REACT },
{ FSM::stateId<B>(), Event::Type::REACT },
{ FSM::stateId<B>(), Event::Type::POST_REACT },
{ FSM::stateId<R>(), Event::Type::POST_REACT },
});
machine.exit();
assertSequence(events, {
{ FSM::stateId<B>(), Event::Type::EXIT },
{ FSM::stateId<R>(), Event::Type::EXIT },
});
REQUIRE(machine.isActive() == false);
}
assertSequence(events, {});
}
////////////////////////////////////////////////////////////////////////////////
}
| 1 | 0.959724 | 1 | 0.959724 | game-dev | MEDIA | 0.515329 | game-dev | 0.954445 | 1 | 0.954445 |
azonenberg/antikernel | 4,984 | legacy-trunk/tests/NameServer/Splashfile | /***********************************************************************************************************************
* *
* ANTIKERNEL v0.1 *
* *
* Copyright (c) 2012-2016 Andrew D. Zonenberg *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *
* following conditions are met: *
* *
* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *
* following disclaimer. *
* *
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *
* following disclaimer in the documentation and/or other materials provided with the distribution. *
* *
* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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. *
* *
***********************************************************************************************************************/
/**
@file
@author Andrew D. Zonenberg
@brief SPLASH build script for NameServer
*/
#include <splashcore/splashcore.h>
using namespace std;
string g_testname = "NameServer";
SPLASHFILE_EXPORT void CreateNodes(BuildGraph* graph)
{
string srcdir = GetDirOfFile(CanonicalizePath(__FILE__));
//Build the test case
vector<string> source_files;
FindFilesByExtension(srcdir, ".cpp", source_files);
CppCompileFlagList cflags;
cflags.push_back(new CppStandardFlag(CppStandardFlag::CPP_STANDARD_11));
cflags.push_back(new CppOptimizationLevelFlag(CppOptimizationLevelFlag::OPT_LEVEL_NONE));
cflags.push_back(new CppDebugInfoFlag);
cflags.push_back(new CppProfilingFlag);
CppLinkFlagList lflags;
lflags.push_back(new CppLinkLibraryByTargetNameFlag("jtaghal", graph));
lflags.push_back(new CppLinkLibraryByTargetNameFlag("jtagboards", graph));
lflags.push_back(new CppLinkProfilingFlag);
CppExecutableNode::CreateCppExecutableNode(
graph,
source_files,
CppToolchain::CreateDefaultToolchainCached(),
cflags,
lflags,
g_testname,
true);
//Run it
FPGAUnitTestNode::CreateFPGAUnitTestNode(
graph,
"",
g_testname,
"lx9mini");
}
SPLASHFILE_EXPORT void CreateEdges(BuildGraph* graph)
{
string arch = CppToolchain::CreateDefaultToolchainCached()->GetArchitecture();
FPGAUnitTestNode* node = dynamic_cast<FPGAUnitTestNode*>(graph->GetTest(g_testname));
if(node == NULL)
FatalError(g_testname + ": test doesn't exist!");
node->SetTestBinary(graph->GetTargetForArch(g_testname, arch));
node->SetBitstream(graph->GetTarget("JtagPingTestBitstream"));
}
| 1 | 0.950845 | 1 | 0.950845 | game-dev | MEDIA | 0.101845 | game-dev | 0.730578 | 1 | 0.730578 |
hidefuku/AnimeEffects | 10,566 | src/core/BoneInfluenceMap.cpp | #include <float.h>
#include <QtMath>
#include "XC.h"
#include "core/Constant.h"
#include "core/Project.h"
#include "core/LayerMesh.h"
#include "core/BoneInfluenceMap.h"
//#include <QElapsedTimer>
namespace core
{
//-------------------------------------------------------------------------------------------------
BoneInfluenceMap::BoneInfluenceMap()
: mVertexCount(0)
, mMaxBoneCount(0)
, mGroupMtx()
, mBoneList()
, mWorks()
, mBuildTask()
{
}
void BoneInfluenceMap::setMaxBoneCount(int aBoneCount)
{
XC_ASSERT(mBuildTask.isNull());
mMaxBoneCount = aBoneCount;
}
void BoneInfluenceMap::allocate(int aVertexCount, bool aInitialize)
{
// cancel previous task
if (mBuildTask)
{
mBuildTask->cancel();
}
// reallocate
if (mVertexCount != aVertexCount)
{
mWorks.reset();
for (int t = 0; t < 2; ++t)
{
mIndices[t].reset();
mWeights[t].reset();
}
if (aVertexCount > 0)
{
const int dataCount = kBonePerVtxMaxEach * aVertexCount;
for (int t = 0; t < 2; ++t)
{
mIndices[t].reset(new IndicesType[dataCount]);
XC_PTR_ASSERT(mIndices[t]);
if (!mIndices[t]) return;
mWeights[t].reset(new WeightsType[dataCount]);
XC_PTR_ASSERT(mWeights[t]);
if (!mWeights[t]) return;
}
}
}
// initialize
if (aInitialize)
{
for (int t = 0; t < 2; ++t)
{
IndicesType* indices = mIndices[t].data();
WeightsType* weights = mWeights[t].data();
const int count = aVertexCount * kBonePerVtxMaxEach;
for (int i = 0; i < count; ++i) { indices[i] = 0; }
for (int i = 0; i < aVertexCount; ++i)
{
const int ixc = kBonePerVtxMaxEach * i;
weights[ixc] = 1.0f;
for (int k = 1; k < kBonePerVtxMaxEach; ++k)
{
weights[ixc + k] = 0.0f;
}
}
}
}
mVertexCount = aVertexCount;
}
void BoneInfluenceMap::writeAsync(
Project& aProject, const QList<Bone2*>& aTopBones,
const QMatrix4x4& aGroupMtx, const LayerMesh& aMesh)
{
XC_ASSERT(mMaxBoneCount > 0);
// cancel previous task
if (mBuildTask)
{
mBuildTask->cancel();
}
// set group matrix
mGroupMtx = aGroupMtx;
// allocate work buffer
mWorks.reset(new WorkAttribute[mVertexCount]);
XC_PTR_ASSERT(mWorks.data());
if (!mWorks) return;
// initialize work buffer
const gl::Vector3* positions = aMesh.positions();
for (int i = 0; i < mVertexCount; ++i)
{
mWorks[i].clear();
mWorks[i].vertex = positions[i].pos2D();
}
// make bone list
makeBoneList(aTopBones);
#ifdef UNUSE_PARALLEL
build();
(void)aProject;
#else
// create task
mBuildTask.reset(new BuildTask(aProject, *this));
aProject.paralleler().push(*mBuildTask);
#endif
}
BoneInfluenceMap::Accessor BoneInfluenceMap::accessor() const
{
waitBuilding();
return Accessor(*this);
}
void BoneInfluenceMap::makeBoneList(const QList<Bone2*>& aTopBones)
{
mBoneList.params.clear();
// per skeleton
for (const Bone2* topBone : aTopBones)
{
XC_PTR_ASSERT(topBone);
// per bone
for (Bone2::ConstIterator itr = topBone; itr.hasNext();)
{
const Bone2* bone = itr.next();
XC_PTR_ASSERT(bone);
if (bone && mBoneList.params.size() < mMaxBoneCount)
{
BoneParam param;
param.hasParent = (bool)(bone->parent());
if (param.hasParent)
{
param.hasRange = bone->hasValidRange();
param.shape = bone->shape();
}
mBoneList.params.push_back(param);
}
}
}
}
void BoneInfluenceMap::build()
{
// world matrix * vertices
transformVertices();
if (isBuildCanceled()) return;
// write bone weight
writeWeights();
if (isBuildCanceled()) return;
// write vertex attribute
writeVertexAttribute();
if (isBuildCanceled()) return;
// free work buffer
mWorks.reset();
}
void BoneInfluenceMap::transformVertices()
{
for (int i = 0; i < mVertexCount; ++i)
{
mWorks[i].vertex = (mGroupMtx * QVector3D(mWorks[i].vertex)).toVector2D();
}
}
void BoneInfluenceMap::writeWeights()
{
// each bone
for (int i = 0; i < mBoneList.params.size(); ++i)
{
const BoneParam param = mBoneList.params[i];
if (!param.hasParent || !param.hasRange) continue;
// calculate weights
for (int k = 0; k < mVertexCount; ++k)
{
const float weight = param.shape.influence(mWorks[k].vertex);
if (weight >= FLT_EPSILON)
{
mWorks[k].tryPushBoneWeight(i, weight);
}
}
// check canceling
if (isBuildCanceled()) return;
}
}
void BoneInfluenceMap::writeVertexAttribute()
{
static const float kMinPowerSum = 0.01f;
// clear
for (int t = 0; t < 2; ++t)
{
IndicesType* indices = mIndices[t].data();
WeightsType* weights = mWeights[t].data();
const int count = mVertexCount * kBonePerVtxMaxEach;
for (int i = 0; i < count; ++i) { indices[i] = 0; }
for (int i = 0; i < count; ++i) { weights[i] = 0.0f; }
}
// each vertex
for (int i = 0; i < mVertexCount; ++i)
{
const int ixc = i * kBonePerVtxMaxEach;
const WorkAttribute& work = mWorks[i];
if (work.count == 0)
{
// no bone influence
mIndices[0][ixc] = 0;
mWeights[0][ixc] = 1.0f;
}
else if (work.count == 1)
{
// single bone influence
mIndices[0][ixc] = work.id[0];
mWeights[0][ixc] = 1.0f;
}
else
{
// some bones influence
float powerSum = 0.0f;
for (int k = 0; k < work.count; ++k)
{
powerSum += work.weight[k];
}
float weightRate = 1.0f;
float weightAdd = 0.0f;
if (powerSum >= kMinPowerSum)
{
weightRate /= powerSum;
}
else
{
weightAdd = (1.0f - powerSum) / work.count;
}
for (int k = 0; k < work.count; ++k)
{
const int t = k / kBonePerVtxMaxEach;
const int each = ixc + k - t * kBonePerVtxMaxEach;
mIndices[t][each] = work.id[k];
mWeights[t][each] = work.weight[k] * weightRate + weightAdd;
}
}
}
}
bool BoneInfluenceMap::isBuildCanceled() const
{
if (mBuildTask)
{
return mBuildTask->isCanceling();
}
return false;
}
void BoneInfluenceMap::waitBuilding() const
{
#ifndef UNUSE_PARALLEL
// wait current task
if (mBuildTask)
{
mBuildTask->wait();
}
#endif
}
bool BoneInfluenceMap::serialize(Serializer& aOut) const
{
waitBuilding();
// vertex count
aOut.write(mVertexCount);
// max bone count
aOut.write(mMaxBoneCount);
const int count = kBonePerVtxMaxEach * mVertexCount;
// indices
aOut.writeGL(mIndices[0].data(), count);
aOut.writeGL(mIndices[1].data(), count);
// weights
aOut.writeGL(mWeights[0].data(), count);
aOut.writeGL(mWeights[1].data(), count);
return aOut.checkStream();
}
bool BoneInfluenceMap::deserialize(Deserializer& aIn)
{
waitBuilding();
// vertex count
{
int vertexCount = 0;
aIn.read(vertexCount);
// reallocate
allocate(vertexCount, false);
}
// max bone count
aIn.read(mMaxBoneCount);
const int count = kBonePerVtxMaxEach * mVertexCount;
// indices
aIn.readGL(mIndices[0].data(), count);
aIn.readGL(mIndices[1].data(), count);
// weights
aIn.readGL(mWeights[0].data(), count);
aIn.readGL(mWeights[1].data(), count);
return aIn.checkStream();
}
//-------------------------------------------------------------------------------------------------
BoneInfluenceMap::BoneParam::BoneParam()
: hasParent(false)
, hasRange(false)
, shape()
{
}
//-------------------------------------------------------------------------------------------------
void BoneInfluenceMap::WorkAttribute::clear()
{
count = 0;
}
void BoneInfluenceMap::WorkAttribute::tryPushBoneWeight(int aId, float aWeight)
{
if (count < kBonePerVtxMaxAll)
{
id[count] = aId;
weight[count] = aWeight;
++count;
}
else
{
int minId = -1;
float minWeight = aWeight;
for (int i = 0; i < kBonePerVtxMaxAll; ++i)
{
if (weight[i] < minWeight)
{
minId = i;
minWeight = weight[i];
}
}
if (minId != -1)
{
id[minId] = aId;
weight[minId] = aWeight;
}
}
}
//-------------------------------------------------------------------------------------------------
BoneInfluenceMap::BuildTask::BuildTask(Project& aProject, BoneInfluenceMap& aOwner)
: mProject(aProject)
, mOwner(aOwner)
{
}
void BoneInfluenceMap::BuildTask::run()
{
mOwner.build();
}
void BoneInfluenceMap::BuildTask::cancel()
{
mProject.paralleler().cancel(*this);
}
//-------------------------------------------------------------------------------------------------
BoneInfluenceMap::Accessor::Accessor()
: mOwner()
{
}
BoneInfluenceMap::Accessor::Accessor(const BoneInfluenceMap& aOwner)
: mOwner(&aOwner)
{
}
const gl::Vector4I* BoneInfluenceMap::Accessor::indices0() const
{
XC_PTR_ASSERT(mOwner);
return (const gl::Vector4I*)mOwner->mIndices[0].data();
}
const gl::Vector4I* BoneInfluenceMap::Accessor::indices1() const
{
XC_PTR_ASSERT(mOwner);
return (const gl::Vector4I*)mOwner->mIndices[1].data();
}
const gl::Vector4* BoneInfluenceMap::Accessor::weights0() const
{
XC_PTR_ASSERT(mOwner);
return (const gl::Vector4*)mOwner->mWeights[0].data();
}
const gl::Vector4* BoneInfluenceMap::Accessor::weights1() const
{
XC_PTR_ASSERT(mOwner);
return (const gl::Vector4*)mOwner->mWeights[1].data();
}
} // namespace core
| 1 | 0.992937 | 1 | 0.992937 | game-dev | MEDIA | 0.481639 | game-dev,graphics-rendering | 0.995265 | 1 | 0.995265 |
Kong/kubernetes-ingress-controller | 3,388 | internal/dataplane/fallback/fallback_meta.go | package fallback
import (
"github.com/samber/lo"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// GeneratedCacheMetadata contains metadata generated during the fallback process.
type GeneratedCacheMetadata struct {
// BrokenObjects are objects that were reported as broken by the Kong Admin API.
BrokenObjects []ObjectHash
// ExcludedObjects are objects that were excluded from the fallback configuration as they were broken or either of their
// dependencies was broken.
ExcludedObjects []AffectedCacheObjectMetadata
// BackfilledObjects are objects that were backfilled from the last valid cache state as they were broken or either of
// their dependencies was broken.
BackfilledObjects []AffectedCacheObjectMetadata
}
// GeneratedCacheMetadataCollector is a collector for cache metadata generated during the fallback process.
// It's primarily used to deduplicate the metadata and make it easier to work with.
type GeneratedCacheMetadataCollector struct {
brokenObjects []ObjectHash
excludedObjects map[ObjectHash]AffectedCacheObjectMetadata
backfilledObjects map[ObjectHash]AffectedCacheObjectMetadata
}
// AffectedCacheObjectMetadata contains an object and a list of objects that caused it to be excluded or backfilled
// during the fallback process.
type AffectedCacheObjectMetadata struct {
Object client.Object
CausingObjects []ObjectHash
}
// NewGenerateCacheMetadataCollector creates a new GeneratedCacheMetadataCollector instance.
func NewGenerateCacheMetadataCollector(brokenObjects ...ObjectHash) *GeneratedCacheMetadataCollector {
return &GeneratedCacheMetadataCollector{
brokenObjects: brokenObjects,
excludedObjects: make(map[ObjectHash]AffectedCacheObjectMetadata),
backfilledObjects: make(map[ObjectHash]AffectedCacheObjectMetadata),
}
}
// CollectExcluded collects an excluded object (an object that was excluded from the fallback configuration as it was
// broken or one of its dependencies was broken).
func (m *GeneratedCacheMetadataCollector) CollectExcluded(excluded client.Object, causing ObjectHash) {
objHash := GetObjectHash(excluded)
if existingEntry, ok := m.excludedObjects[objHash]; ok {
existingEntry.CausingObjects = append(existingEntry.CausingObjects, causing)
m.excludedObjects[objHash] = existingEntry
} else {
m.excludedObjects[objHash] = AffectedCacheObjectMetadata{Object: excluded, CausingObjects: []ObjectHash{causing}}
}
}
// CollectBackfilled collects a backfilled object (an object that was backfilled from the last valid cache state as that or
// one of its dependencies was broken).
func (m *GeneratedCacheMetadataCollector) CollectBackfilled(backfilled client.Object, causing ObjectHash) {
objHash := GetObjectHash(backfilled)
if existingEntry, ok := m.backfilledObjects[objHash]; ok {
existingEntry.CausingObjects = append(existingEntry.CausingObjects, causing)
m.backfilledObjects[objHash] = existingEntry
} else {
m.backfilledObjects[objHash] = AffectedCacheObjectMetadata{Object: backfilled, CausingObjects: []ObjectHash{causing}}
}
}
// Metadata generates the final cache metadata from the collected data.
func (m *GeneratedCacheMetadataCollector) Metadata() GeneratedCacheMetadata {
return GeneratedCacheMetadata{
BrokenObjects: m.brokenObjects,
ExcludedObjects: lo.Values(m.excludedObjects),
BackfilledObjects: lo.Values(m.backfilledObjects),
}
}
| 1 | 0.882022 | 1 | 0.882022 | game-dev | MEDIA | 0.596494 | game-dev,graphics-rendering | 0.72702 | 1 | 0.72702 |
Potion-Studios/BYG | 3,038 | Fabric/src/main/java/potionstudios/byg/mixin/client/MixinInventoryScreen.java | package potionstudios.byg.mixin.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.ImageButton;
import net.minecraft.client.gui.components.Tooltip;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.client.gui.screens.inventory.InventoryScreen;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.inventory.AbstractContainerMenu;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import potionstudios.byg.BYG;
import potionstudios.byg.BYGConstants;
import potionstudios.byg.client.BiomepediaInventoryConfig;
import potionstudios.byg.client.gui.biomepedia.screen.BiomepediaHomeScreen;
@Mixin(InventoryScreen.class)
public abstract class MixinInventoryScreen<T extends AbstractContainerMenu> extends AbstractContainerScreen<T> {
private ImageButton biomePedia;
public MixinInventoryScreen(T menu, Inventory inventory, Component narrationTitle) {
super(menu, inventory, narrationTitle);
}
@Inject(method = "init", at = @At("RETURN"))
protected void init(CallbackInfo ci) {
if (BYGConstants.BIOMEPEDIA) {
BiomepediaInventoryConfig biomepediaInventoryConfig = BiomepediaInventoryConfig.getConfig(true);
if (biomepediaInventoryConfig.visible()) {
ImageButton biomePedia = new ImageButton(
this.leftPos + biomepediaInventoryConfig.settings().widthOffset(), this.height / 2 - biomepediaInventoryConfig.settings().heightOffset(),
20, 18,
0, 220,
18,
BYG.createLocation("textures/gui/biomepedia.png"),
256, 256,
(button) -> Minecraft.getInstance().setScreen(new BiomepediaHomeScreen(Component.literal(""))),
Component.literal("Lorem Ipsum")
);
biomePedia.setTooltip(Tooltip.create(Component.literal("BYG Biomepedia")));
biomePedia.visible = BiomepediaInventoryConfig.server_value;
biomePedia.active = BiomepediaInventoryConfig.server_value;
addRenderableWidget(this.biomePedia = biomePedia);
}
}
}
@Inject(method = "method_19891(Lnet/minecraft/client/gui/components/Button;)V", at = @At("RETURN"))
protected void updateGuiSize(CallbackInfo ci) {
if (BYGConstants.BIOMEPEDIA) {
if (biomePedia != null) {
BiomepediaInventoryConfig biomepediaInventoryConfig = BiomepediaInventoryConfig.getConfig();
biomePedia.setPosition(this.leftPos + biomepediaInventoryConfig.settings().widthOffset(), this.height / 2 - biomepediaInventoryConfig.settings().heightOffset());
}
}
}
}
| 1 | 0.867844 | 1 | 0.867844 | game-dev | MEDIA | 0.944428 | game-dev | 0.806528 | 1 | 0.806528 |
neurolabusc/MRIcron | 7,982 | npm/dmath/pastring.pas | { **********************************************************************
* Unit PASTRING.PAS *
* Version 1.8 *
* (c) J. Debord, December 2000 *
**********************************************************************
Turbo Pascal string routines
********************************************************************** }
unit PaString;
interface
uses
FMath, FComp, Matrices;
{ *** Global variables controlling the appearance of a numeric string ** }
const
NumLength : Integer = 10; { Length of a numeric field }
MaxDec : Integer = 4; { Max. number of decimal places }
FloatPoint : Boolean = False; { Floating point notation }
NSZero : Boolean = True; { Write non significant zero's }
{ ************************** String routines *************************** }
function LTrim(S : String) : String;
{ ----------------------------------------------------------------------
Removes leading blanks
---------------------------------------------------------------------- }
function RTrim(S : String) : String;
{ ----------------------------------------------------------------------
Removes trailing blanks
---------------------------------------------------------------------- }
function Trim(S : String) : String;
{ ----------------------------------------------------------------------
Removes leading and trailing blanks
---------------------------------------------------------------------- }
function StrChar(N : Byte; C : Char) : String;
{ ----------------------------------------------------------------------
Returns a string made of character C repeated N times
---------------------------------------------------------------------- }
function RFill(S : String; L : Byte) : String;
{ ----------------------------------------------------------------------
Completes string S with trailing blanks for a total length L
---------------------------------------------------------------------- }
function LFill(S : String; L : Byte) : String;
{ ----------------------------------------------------------------------
Completes string S with leading blanks for a total length L
---------------------------------------------------------------------- }
function CFill(S : String; L : Byte) : String;
{ ----------------------------------------------------------------------
Completes string S with leading blanks
to center the string on a total length L
---------------------------------------------------------------------- }
function Replace(S : String; C1, C2 : Char) : String;
{ ----------------------------------------------------------------------
Replaces in string S all the occurences
of character C1 by character C2
---------------------------------------------------------------------- }
function Extract(S : String; var Index : Byte; Delim : Char) : String;
{ ----------------------------------------------------------------------
Extracts a field from a string. Index is the position of the first
character of the field. Delim is the character used to separate
fields (e.g. blank, comma or tabulation). Blanks immediately
following Delim are ignored. Index is updated to the position of
the next field.
---------------------------------------------------------------------- }
procedure Parse(S : String; Delim : Char; Field : PStrVector; var N : Byte);
{ ----------------------------------------------------------------------
Parses a string into its constitutive fields. Delim is the field
separator. The number of fields is returned in N. The fields are
returned in Field^[0]..Field^[N - 1]. Field must be dimensioned in
the calling program.
---------------------------------------------------------------------- }
function FloatToStr(X : Float) : String;
{ ----------------------------------------------------------------------
Converts a real to a string according to the values of the global
variables NumLength, MaxDec, FloatPoint and NSZero
---------------------------------------------------------------------- }
function IntToStr(N : LongInt) : String;
{ ----------------------------------------------------------------------
Converts an integer to a string according to the values of the global
variables NumLength and MaxDec.
---------------------------------------------------------------------- }
function CompToStr(Z : Complex) : String;
{ ----------------------------------------------------------------------
Converts a complex number to a string.
---------------------------------------------------------------------- }
implementation
function LTrim(S : String) : String;
begin
if S <> '' then
repeat
if S[1] = ' ' then Delete(S, 1, 1);
until S[1] <> ' ';
LTrim := S;
end;
function RTrim(S : String) : String;
var
L1 : Byte;
begin
if S <> '' then
repeat
L1 := Length(S);
if S[L1] = ' ' then Delete(S, L1, 1);
until S[L1] <> ' ';
RTrim := S;
end;
function Trim(S : String) : String;
begin
Trim := LTrim(RTrim(S));
end;
function StrChar(N : Byte; C : Char) : String;
var
I : Byte;
S : String;
begin
S := '';
for I := 1 to N do
S := S + C;
StrChar := S;
end;
function RFill(S : String; L : Byte) : String;
var
L1 : Byte;
begin
L1 := Length(S);
if L1 >= L then
RFill := S
else
RFill := S + StrChar(L - L1, ' ');
end;
function LFill(S : String; L : Byte) : String;
var
L1 : Byte;
begin
L1 := Length(S);
if L1 >= L then
LFill := S
else
LFill := StrChar(L - L1, ' ') + S;
end;
function CFill(S : String; L : Byte) : String;
var
L1 : Byte;
begin
L1 := Length(S);
if L1 >= L then
CFill := S
else
CFill := StrChar((L - L1) div 2, ' ') + S;
end;
function Replace(S : String; C1, C2 : Char) : String;
var
S1 : String;
K : Byte;
begin
S1 := S;
K := Pos(C1, S1);
while K > 0 do
begin
S1[K] := C2;
K := Pos(C1, S1);
end;
Replace := S1;
end;
function Extract(S : String; var Index : Byte; Delim : Char) : String;
var
I, L : Byte;
begin
I := Index;
L := Length(S);
{ Search for Delim }
while (I <= L) and (S[I] <> Delim) do
Inc(I);
{ Extract field }
if I = Index then
Extract := ''
else
Extract := Copy(S, Index, I - Index);
{ Skip blanks after Delim }
repeat
Inc(I);
until (I > L) or (S[I] <> ' ');
{ Update Index }
Index := I;
end;
procedure Parse(S : String; Delim : Char; Field : PStrVector; var N : Byte);
var
I, Index, L : Byte;
begin
I := 0;
Index := 1;
L := Length(S);
repeat
Field^[I] := Extract(S, Index, Delim);
Inc(I);
until Index > L;
N := I;
end;
function FloatToStr(X : Float) : String;
var
S : String;
C : Char;
L : Byte;
begin
if FloatPoint then
begin
Str(X:Pred(NumLength), S);
S := ' ' + S;
end
else
begin
Str(X:NumLength:MaxDec, S);
if not NSZero then
repeat
L := Length(S);
C := S[L];
if (C = '0') or (C = '.') then Delete(S, L, 1);
until C <> '0';
end;
FloatToStr := S;
end;
function IntToStr(N : LongInt) : String;
var
S : String;
begin
Str(N:(NumLength - MaxDec - 1), S);
IntToStr := S;
end;
function CompToStr(Z : Complex) : String;
var
S : String;
begin
if Z.Form = Rec then
begin
if Z.Y >= 0.0 then S := ' + ' else S := ' - ';
CompToStr := FloatToStr(Z.X) + S + FloatToStr(Abs(Z.Y)) + ' * i';
end
else
CompToStr := FloatToStr(Z.R) + ' * Exp(' + FloatToStr(Z.Theta) + ' * i)';
end;
end.
| 1 | 0.78263 | 1 | 0.78263 | game-dev | MEDIA | 0.360397 | game-dev | 0.812758 | 1 | 0.812758 |
MATTYOneInc/AionEncomBase_Java8 | 4,846 | AL-Game_SoloPlay_patches/data/scripts/system/handlers/quest/enshar/_25237Protect_The_Oracular_Chamber.java | /*
* =====================================================================================*
* This file is part of Aion-Unique (Aion-Unique Home Software Development) *
* Aion-Unique Development is a closed Aion Project that use Old Aion Project Base *
* Like Aion-Lightning, Aion-Engine, Aion-Core, Aion-Extreme, Aion-NextGen, ArchSoft, *
* Aion-Ger, U3J, Encom And other Aion project, All Credit Content *
* That they make is belong to them/Copyright is belong to them. And All new Content *
* that Aion-Unique make the copyright is belong to Aion-Unique *
* You may have agreement with Aion-Unique Development, before use this Engine/Source *
* You have agree with all of Term of Services agreement with Aion-Unique Development *
* =====================================================================================*
*/
package quest.enshar;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.questEngine.model.QuestDialog;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
import com.aionemu.gameserver.services.QuestService;
/****/
/** MATTYOne DainAvenger Ptich
/****/
public class _25237Protect_The_Oracular_Chamber extends QuestHandler {
private final static int questId = 25237;
private final static int REQUIRED_KILLS = 2; // summ of NPC needed to kill
// NPC ID, that needs to kill
private final static int[] mobs = {205395, 205396, 205397, 205398, 205399, 205400, 205401, 205402, 217476, 217477, 217478, 217479, 217480, 217481, 217482, 217483, 205404, 205405, 205406, 205407, 205408, 205409, 205410, 205411, 217485, 217486, 217487, 217488, 217489, 217490, 217491, 217492};
public _25237Protect_The_Oracular_Chamber() {
super(questId);
}
@Override
public void register() {
qe.registerOnEnterWorld(questId);
qe.registerQuestNpc(804719).addOnTalkEvent(questId);
// register NPC in case to kill
for (int mobId : mobs) {
qe.registerQuestNpc(mobId).addOnKillEvent(questId);
}
}
@Override
public boolean onEnterWorldEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (player.getWorldId() == 220080000) {
if (qs == null) {
env.setQuestId(questId);
if (QuestService.startQuest(env)) {
return true;
}
}
}
return false;
}
@Override
public boolean onKillEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs == null || qs.getStatus() != QuestStatus.START) {
return false;
}
int targetId = env.getTargetId();
int killCount = qs.getQuestVarById(1); // Killed NPC
boolean killCounted = false;
// If we kill the opposite faction, then:
if (env.getVisibleObject() instanceof Player && player.getWorldId() == 220080000) {
Player target = (Player) env.getVisibleObject();
if ((env.getPlayer().getLevel() >= (target.getLevel() - 5)) && (env.getPlayer().getLevel() <= (target.getLevel() + 9))) {
killCounted = true;
}
}
// Check NPC ID from list in top
for (int mobId : mobs) {
if (targetId == mobId) {
killCounted = true;
break;
}
}
if (killCounted) {
killCount++; // Kill counter ++
if (killCount >= REQUIRED_KILLS) {
killCount = REQUIRED_KILLS; // TODO
qs.setQuestVarById(0, 1);
qs.setStatus(QuestStatus.REWARD); // If we made MOBS_KILLS = 2 of NPC, then make status REWARD
}
qs.setQuestVarById(1, killCount); // Update variable
updateQuestStatus(env);
return true;
}
return false;
}
@Override
public boolean onDialogEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
int targetId = env.getTargetId();
if (qs == null || qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 804719) {
if (env.getDialog() == QuestDialog.START_DIALOG) {
return sendQuestDialog(env, 10002);
} else if (env.getDialog() == QuestDialog.SELECT_REWARD) {
return sendQuestDialog(env, 5);
} else {
return sendQuestEndDialog(env);
}
}
}
return false;
}
} | 1 | 0.952544 | 1 | 0.952544 | game-dev | MEDIA | 0.991436 | game-dev | 0.972728 | 1 | 0.972728 |
plooshi/28.30 | 2,324 | 28.30/SDK/MotionTrajectory_classes.hpp | #pragma once
/*
* SDK generated by Dumper-7
*
* https://github.com/Encryqed/Dumper-7
*/
// Package: MotionTrajectory
#include "Basic.hpp"
#include "Engine_classes.hpp"
#include "PoseSearch_structs.hpp"
#include "MotionTrajectory_structs.hpp"
namespace SDK
{
// Class MotionTrajectory.CharacterTrajectoryComponent
// 0x0230 (0x02D0 - 0x00A0)
class UCharacterTrajectoryComponent final : public UActorComponent
{
public:
struct FPoseSearchQueryTrajectory Trajectory; // 0x00A0(0x0010)(BlueprintVisible, BlueprintReadOnly, Transient, Protected, NativeAccessSpecifierProtected)
struct FTrajectorySamplingData SamplingData; // 0x00B0(0x0020)(BlueprintVisible, BlueprintReadOnly, Transient, NoDestructor, Protected, NativeAccessSpecifierProtected)
struct FCharacterTrajectoryData CharacterTrajectoryData; // 0x00D0(0x01E0)(BlueprintVisible, BlueprintReadOnly, Transient, Protected, NativeAccessSpecifierProtected)
uint8 Pad_2B0[0x20]; // 0x02B0(0x0020)(Fixing Struct Size After Last Property [ Dumper-7 ])
public:
void OnMovementUpdated(float DeltaSeconds, const struct FVector& OldLocation, const struct FVector& OldVelocity);
public:
static class UClass* StaticClass()
{
return StaticClassImpl<"CharacterTrajectoryComponent">();
}
static class UCharacterTrajectoryComponent* GetDefaultObj()
{
return GetDefaultObjImpl<UCharacterTrajectoryComponent>();
}
};
static_assert(alignof(UCharacterTrajectoryComponent) == 0x000010, "Wrong alignment on UCharacterTrajectoryComponent");
static_assert(sizeof(UCharacterTrajectoryComponent) == 0x0002D0, "Wrong size on UCharacterTrajectoryComponent");
static_assert(offsetof(UCharacterTrajectoryComponent, Trajectory) == 0x0000A0, "Member 'UCharacterTrajectoryComponent::Trajectory' has a wrong offset!");
static_assert(offsetof(UCharacterTrajectoryComponent, SamplingData) == 0x0000B0, "Member 'UCharacterTrajectoryComponent::SamplingData' has a wrong offset!");
static_assert(offsetof(UCharacterTrajectoryComponent, CharacterTrajectoryData) == 0x0000D0, "Member 'UCharacterTrajectoryComponent::CharacterTrajectoryData' has a wrong offset!");
}
| 1 | 0.891691 | 1 | 0.891691 | game-dev | MEDIA | 0.833668 | game-dev | 0.62632 | 1 | 0.62632 |
libgdx/libgdx | 2,790 | extensions/gdx-bullet/jni/src/bullet/BulletCollision/CollisionShapes/btSphereShape.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_SPHERE_MINKOWSKI_H
#define BT_SPHERE_MINKOWSKI_H
#include "btConvexInternalShape.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types
///The btSphereShape implements an implicit sphere, centered around a local origin with radius.
ATTRIBUTE_ALIGNED16(class) btSphereShape : public btConvexInternalShape
{
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btSphereShape (btScalar radius) : btConvexInternalShape ()
{
m_shapeType = SPHERE_SHAPE_PROXYTYPE;
m_localScaling.setValue(1.0, 1.0, 1.0);
m_implicitShapeDimensions.setZero();
m_implicitShapeDimensions.setX(radius);
m_collisionMargin = radius;
m_padding = 0;
}
virtual btVector3 localGetSupportingVertex(const btVector3& vec)const;
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const;
//notice that the vectors should be unit length
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;
virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const;
virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
btScalar getRadius() const { return m_implicitShapeDimensions.getX() * m_localScaling.getX();}
void setUnscaledRadius(btScalar radius)
{
m_implicitShapeDimensions.setX(radius);
btConvexInternalShape::setMargin(radius);
}
//debugging
virtual const char* getName()const {return "SPHERE";}
virtual void setMargin(btScalar margin)
{
btConvexInternalShape::setMargin(margin);
}
virtual btScalar getMargin() const
{
//to improve gjk behaviour, use radius+margin as the full margin, so never get into the penetration case
//this means, non-uniform scaling is not supported anymore
return getRadius();
}
};
#endif //BT_SPHERE_MINKOWSKI_H
| 1 | 0.878016 | 1 | 0.878016 | game-dev | MEDIA | 0.993998 | game-dev | 0.898017 | 1 | 0.898017 |
pablovacatello/NextUI-PortMaster-Pak | 19,101 | Tools/tg5040/Portmaster.pak/PortMaster/exlibs/charset_normalizer/constant.py | from codecs import BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE
from encodings.aliases import aliases
from re import IGNORECASE, compile as re_compile
from typing import Dict, List, Set, Union
from .assets import FREQUENCIES
# Contain for each eligible encoding a list of/item bytes SIG/BOM
ENCODING_MARKS: Dict[str, Union[bytes, List[bytes]]] = {
"utf_8": BOM_UTF8,
"utf_7": [
b"\x2b\x2f\x76\x38",
b"\x2b\x2f\x76\x39",
b"\x2b\x2f\x76\x2b",
b"\x2b\x2f\x76\x2f",
b"\x2b\x2f\x76\x38\x2d",
],
"gb18030": b"\x84\x31\x95\x33",
"utf_32": [BOM_UTF32_BE, BOM_UTF32_LE],
"utf_16": [BOM_UTF16_BE, BOM_UTF16_LE],
}
TOO_SMALL_SEQUENCE: int = 32
TOO_BIG_SEQUENCE: int = int(10e6)
UTF8_MAXIMAL_ALLOCATION: int = 1112064
UNICODE_RANGES_COMBINED: Dict[str, range] = {
"Control character": range(31 + 1),
"Basic Latin": range(32, 127 + 1),
"Latin-1 Supplement": range(128, 255 + 1),
"Latin Extended-A": range(256, 383 + 1),
"Latin Extended-B": range(384, 591 + 1),
"IPA Extensions": range(592, 687 + 1),
"Spacing Modifier Letters": range(688, 767 + 1),
"Combining Diacritical Marks": range(768, 879 + 1),
"Greek and Coptic": range(880, 1023 + 1),
"Cyrillic": range(1024, 1279 + 1),
"Cyrillic Supplement": range(1280, 1327 + 1),
"Armenian": range(1328, 1423 + 1),
"Hebrew": range(1424, 1535 + 1),
"Arabic": range(1536, 1791 + 1),
"Syriac": range(1792, 1871 + 1),
"Arabic Supplement": range(1872, 1919 + 1),
"Thaana": range(1920, 1983 + 1),
"NKo": range(1984, 2047 + 1),
"Samaritan": range(2048, 2111 + 1),
"Mandaic": range(2112, 2143 + 1),
"Syriac Supplement": range(2144, 2159 + 1),
"Arabic Extended-A": range(2208, 2303 + 1),
"Devanagari": range(2304, 2431 + 1),
"Bengali": range(2432, 2559 + 1),
"Gurmukhi": range(2560, 2687 + 1),
"Gujarati": range(2688, 2815 + 1),
"Oriya": range(2816, 2943 + 1),
"Tamil": range(2944, 3071 + 1),
"Telugu": range(3072, 3199 + 1),
"Kannada": range(3200, 3327 + 1),
"Malayalam": range(3328, 3455 + 1),
"Sinhala": range(3456, 3583 + 1),
"Thai": range(3584, 3711 + 1),
"Lao": range(3712, 3839 + 1),
"Tibetan": range(3840, 4095 + 1),
"Myanmar": range(4096, 4255 + 1),
"Georgian": range(4256, 4351 + 1),
"Hangul Jamo": range(4352, 4607 + 1),
"Ethiopic": range(4608, 4991 + 1),
"Ethiopic Supplement": range(4992, 5023 + 1),
"Cherokee": range(5024, 5119 + 1),
"Unified Canadian Aboriginal Syllabics": range(5120, 5759 + 1),
"Ogham": range(5760, 5791 + 1),
"Runic": range(5792, 5887 + 1),
"Tagalog": range(5888, 5919 + 1),
"Hanunoo": range(5920, 5951 + 1),
"Buhid": range(5952, 5983 + 1),
"Tagbanwa": range(5984, 6015 + 1),
"Khmer": range(6016, 6143 + 1),
"Mongolian": range(6144, 6319 + 1),
"Unified Canadian Aboriginal Syllabics Extended": range(6320, 6399 + 1),
"Limbu": range(6400, 6479 + 1),
"Tai Le": range(6480, 6527 + 1),
"New Tai Lue": range(6528, 6623 + 1),
"Khmer Symbols": range(6624, 6655 + 1),
"Buginese": range(6656, 6687 + 1),
"Tai Tham": range(6688, 6831 + 1),
"Combining Diacritical Marks Extended": range(6832, 6911 + 1),
"Balinese": range(6912, 7039 + 1),
"Sundanese": range(7040, 7103 + 1),
"Batak": range(7104, 7167 + 1),
"Lepcha": range(7168, 7247 + 1),
"Ol Chiki": range(7248, 7295 + 1),
"Cyrillic Extended C": range(7296, 7311 + 1),
"Sundanese Supplement": range(7360, 7375 + 1),
"Vedic Extensions": range(7376, 7423 + 1),
"Phonetic Extensions": range(7424, 7551 + 1),
"Phonetic Extensions Supplement": range(7552, 7615 + 1),
"Combining Diacritical Marks Supplement": range(7616, 7679 + 1),
"Latin Extended Additional": range(7680, 7935 + 1),
"Greek Extended": range(7936, 8191 + 1),
"General Punctuation": range(8192, 8303 + 1),
"Superscripts and Subscripts": range(8304, 8351 + 1),
"Currency Symbols": range(8352, 8399 + 1),
"Combining Diacritical Marks for Symbols": range(8400, 8447 + 1),
"Letterlike Symbols": range(8448, 8527 + 1),
"Number Forms": range(8528, 8591 + 1),
"Arrows": range(8592, 8703 + 1),
"Mathematical Operators": range(8704, 8959 + 1),
"Miscellaneous Technical": range(8960, 9215 + 1),
"Control Pictures": range(9216, 9279 + 1),
"Optical Character Recognition": range(9280, 9311 + 1),
"Enclosed Alphanumerics": range(9312, 9471 + 1),
"Box Drawing": range(9472, 9599 + 1),
"Block Elements": range(9600, 9631 + 1),
"Geometric Shapes": range(9632, 9727 + 1),
"Miscellaneous Symbols": range(9728, 9983 + 1),
"Dingbats": range(9984, 10175 + 1),
"Miscellaneous Mathematical Symbols-A": range(10176, 10223 + 1),
"Supplemental Arrows-A": range(10224, 10239 + 1),
"Braille Patterns": range(10240, 10495 + 1),
"Supplemental Arrows-B": range(10496, 10623 + 1),
"Miscellaneous Mathematical Symbols-B": range(10624, 10751 + 1),
"Supplemental Mathematical Operators": range(10752, 11007 + 1),
"Miscellaneous Symbols and Arrows": range(11008, 11263 + 1),
"Glagolitic": range(11264, 11359 + 1),
"Latin Extended-C": range(11360, 11391 + 1),
"Coptic": range(11392, 11519 + 1),
"Georgian Supplement": range(11520, 11567 + 1),
"Tifinagh": range(11568, 11647 + 1),
"Ethiopic Extended": range(11648, 11743 + 1),
"Cyrillic Extended-A": range(11744, 11775 + 1),
"Supplemental Punctuation": range(11776, 11903 + 1),
"CJK Radicals Supplement": range(11904, 12031 + 1),
"Kangxi Radicals": range(12032, 12255 + 1),
"Ideographic Description Characters": range(12272, 12287 + 1),
"CJK Symbols and Punctuation": range(12288, 12351 + 1),
"Hiragana": range(12352, 12447 + 1),
"Katakana": range(12448, 12543 + 1),
"Bopomofo": range(12544, 12591 + 1),
"Hangul Compatibility Jamo": range(12592, 12687 + 1),
"Kanbun": range(12688, 12703 + 1),
"Bopomofo Extended": range(12704, 12735 + 1),
"CJK Strokes": range(12736, 12783 + 1),
"Katakana Phonetic Extensions": range(12784, 12799 + 1),
"Enclosed CJK Letters and Months": range(12800, 13055 + 1),
"CJK Compatibility": range(13056, 13311 + 1),
"CJK Unified Ideographs Extension A": range(13312, 19903 + 1),
"Yijing Hexagram Symbols": range(19904, 19967 + 1),
"CJK Unified Ideographs": range(19968, 40959 + 1),
"Yi Syllables": range(40960, 42127 + 1),
"Yi Radicals": range(42128, 42191 + 1),
"Lisu": range(42192, 42239 + 1),
"Vai": range(42240, 42559 + 1),
"Cyrillic Extended-B": range(42560, 42655 + 1),
"Bamum": range(42656, 42751 + 1),
"Modifier Tone Letters": range(42752, 42783 + 1),
"Latin Extended-D": range(42784, 43007 + 1),
"Syloti Nagri": range(43008, 43055 + 1),
"Common Indic Number Forms": range(43056, 43071 + 1),
"Phags-pa": range(43072, 43135 + 1),
"Saurashtra": range(43136, 43231 + 1),
"Devanagari Extended": range(43232, 43263 + 1),
"Kayah Li": range(43264, 43311 + 1),
"Rejang": range(43312, 43359 + 1),
"Hangul Jamo Extended-A": range(43360, 43391 + 1),
"Javanese": range(43392, 43487 + 1),
"Myanmar Extended-B": range(43488, 43519 + 1),
"Cham": range(43520, 43615 + 1),
"Myanmar Extended-A": range(43616, 43647 + 1),
"Tai Viet": range(43648, 43743 + 1),
"Meetei Mayek Extensions": range(43744, 43775 + 1),
"Ethiopic Extended-A": range(43776, 43823 + 1),
"Latin Extended-E": range(43824, 43887 + 1),
"Cherokee Supplement": range(43888, 43967 + 1),
"Meetei Mayek": range(43968, 44031 + 1),
"Hangul Syllables": range(44032, 55215 + 1),
"Hangul Jamo Extended-B": range(55216, 55295 + 1),
"High Surrogates": range(55296, 56191 + 1),
"High Private Use Surrogates": range(56192, 56319 + 1),
"Low Surrogates": range(56320, 57343 + 1),
"Private Use Area": range(57344, 63743 + 1),
"CJK Compatibility Ideographs": range(63744, 64255 + 1),
"Alphabetic Presentation Forms": range(64256, 64335 + 1),
"Arabic Presentation Forms-A": range(64336, 65023 + 1),
"Variation Selectors": range(65024, 65039 + 1),
"Vertical Forms": range(65040, 65055 + 1),
"Combining Half Marks": range(65056, 65071 + 1),
"CJK Compatibility Forms": range(65072, 65103 + 1),
"Small Form Variants": range(65104, 65135 + 1),
"Arabic Presentation Forms-B": range(65136, 65279 + 1),
"Halfwidth and Fullwidth Forms": range(65280, 65519 + 1),
"Specials": range(65520, 65535 + 1),
"Linear B Syllabary": range(65536, 65663 + 1),
"Linear B Ideograms": range(65664, 65791 + 1),
"Aegean Numbers": range(65792, 65855 + 1),
"Ancient Greek Numbers": range(65856, 65935 + 1),
"Ancient Symbols": range(65936, 65999 + 1),
"Phaistos Disc": range(66000, 66047 + 1),
"Lycian": range(66176, 66207 + 1),
"Carian": range(66208, 66271 + 1),
"Coptic Epact Numbers": range(66272, 66303 + 1),
"Old Italic": range(66304, 66351 + 1),
"Gothic": range(66352, 66383 + 1),
"Old Permic": range(66384, 66431 + 1),
"Ugaritic": range(66432, 66463 + 1),
"Old Persian": range(66464, 66527 + 1),
"Deseret": range(66560, 66639 + 1),
"Shavian": range(66640, 66687 + 1),
"Osmanya": range(66688, 66735 + 1),
"Osage": range(66736, 66815 + 1),
"Elbasan": range(66816, 66863 + 1),
"Caucasian Albanian": range(66864, 66927 + 1),
"Linear A": range(67072, 67455 + 1),
"Cypriot Syllabary": range(67584, 67647 + 1),
"Imperial Aramaic": range(67648, 67679 + 1),
"Palmyrene": range(67680, 67711 + 1),
"Nabataean": range(67712, 67759 + 1),
"Hatran": range(67808, 67839 + 1),
"Phoenician": range(67840, 67871 + 1),
"Lydian": range(67872, 67903 + 1),
"Meroitic Hieroglyphs": range(67968, 67999 + 1),
"Meroitic Cursive": range(68000, 68095 + 1),
"Kharoshthi": range(68096, 68191 + 1),
"Old South Arabian": range(68192, 68223 + 1),
"Old North Arabian": range(68224, 68255 + 1),
"Manichaean": range(68288, 68351 + 1),
"Avestan": range(68352, 68415 + 1),
"Inscriptional Parthian": range(68416, 68447 + 1),
"Inscriptional Pahlavi": range(68448, 68479 + 1),
"Psalter Pahlavi": range(68480, 68527 + 1),
"Old Turkic": range(68608, 68687 + 1),
"Old Hungarian": range(68736, 68863 + 1),
"Rumi Numeral Symbols": range(69216, 69247 + 1),
"Brahmi": range(69632, 69759 + 1),
"Kaithi": range(69760, 69839 + 1),
"Sora Sompeng": range(69840, 69887 + 1),
"Chakma": range(69888, 69967 + 1),
"Mahajani": range(69968, 70015 + 1),
"Sharada": range(70016, 70111 + 1),
"Sinhala Archaic Numbers": range(70112, 70143 + 1),
"Khojki": range(70144, 70223 + 1),
"Multani": range(70272, 70319 + 1),
"Khudawadi": range(70320, 70399 + 1),
"Grantha": range(70400, 70527 + 1),
"Newa": range(70656, 70783 + 1),
"Tirhuta": range(70784, 70879 + 1),
"Siddham": range(71040, 71167 + 1),
"Modi": range(71168, 71263 + 1),
"Mongolian Supplement": range(71264, 71295 + 1),
"Takri": range(71296, 71375 + 1),
"Ahom": range(71424, 71487 + 1),
"Warang Citi": range(71840, 71935 + 1),
"Zanabazar Square": range(72192, 72271 + 1),
"Soyombo": range(72272, 72367 + 1),
"Pau Cin Hau": range(72384, 72447 + 1),
"Bhaiksuki": range(72704, 72815 + 1),
"Marchen": range(72816, 72895 + 1),
"Masaram Gondi": range(72960, 73055 + 1),
"Cuneiform": range(73728, 74751 + 1),
"Cuneiform Numbers and Punctuation": range(74752, 74879 + 1),
"Early Dynastic Cuneiform": range(74880, 75087 + 1),
"Egyptian Hieroglyphs": range(77824, 78895 + 1),
"Anatolian Hieroglyphs": range(82944, 83583 + 1),
"Bamum Supplement": range(92160, 92735 + 1),
"Mro": range(92736, 92783 + 1),
"Bassa Vah": range(92880, 92927 + 1),
"Pahawh Hmong": range(92928, 93071 + 1),
"Miao": range(93952, 94111 + 1),
"Ideographic Symbols and Punctuation": range(94176, 94207 + 1),
"Tangut": range(94208, 100351 + 1),
"Tangut Components": range(100352, 101119 + 1),
"Kana Supplement": range(110592, 110847 + 1),
"Kana Extended-A": range(110848, 110895 + 1),
"Nushu": range(110960, 111359 + 1),
"Duployan": range(113664, 113823 + 1),
"Shorthand Format Controls": range(113824, 113839 + 1),
"Byzantine Musical Symbols": range(118784, 119039 + 1),
"Musical Symbols": range(119040, 119295 + 1),
"Ancient Greek Musical Notation": range(119296, 119375 + 1),
"Tai Xuan Jing Symbols": range(119552, 119647 + 1),
"Counting Rod Numerals": range(119648, 119679 + 1),
"Mathematical Alphanumeric Symbols": range(119808, 120831 + 1),
"Sutton SignWriting": range(120832, 121519 + 1),
"Glagolitic Supplement": range(122880, 122927 + 1),
"Mende Kikakui": range(124928, 125151 + 1),
"Adlam": range(125184, 125279 + 1),
"Arabic Mathematical Alphabetic Symbols": range(126464, 126719 + 1),
"Mahjong Tiles": range(126976, 127023 + 1),
"Domino Tiles": range(127024, 127135 + 1),
"Playing Cards": range(127136, 127231 + 1),
"Enclosed Alphanumeric Supplement": range(127232, 127487 + 1),
"Enclosed Ideographic Supplement": range(127488, 127743 + 1),
"Miscellaneous Symbols and Pictographs": range(127744, 128511 + 1),
"Emoticons range(Emoji)": range(128512, 128591 + 1),
"Ornamental Dingbats": range(128592, 128639 + 1),
"Transport and Map Symbols": range(128640, 128767 + 1),
"Alchemical Symbols": range(128768, 128895 + 1),
"Geometric Shapes Extended": range(128896, 129023 + 1),
"Supplemental Arrows-C": range(129024, 129279 + 1),
"Supplemental Symbols and Pictographs": range(129280, 129535 + 1),
"CJK Unified Ideographs Extension B": range(131072, 173791 + 1),
"CJK Unified Ideographs Extension C": range(173824, 177983 + 1),
"CJK Unified Ideographs Extension D": range(177984, 178207 + 1),
"CJK Unified Ideographs Extension E": range(178208, 183983 + 1),
"CJK Unified Ideographs Extension F": range(183984, 191471 + 1),
"CJK Compatibility Ideographs Supplement": range(194560, 195103 + 1),
"Tags": range(917504, 917631 + 1),
"Variation Selectors Supplement": range(917760, 917999 + 1),
}
UNICODE_SECONDARY_RANGE_KEYWORD: List[str] = [
"Supplement",
"Extended",
"Extensions",
"Modifier",
"Marks",
"Punctuation",
"Symbols",
"Forms",
"Operators",
"Miscellaneous",
"Drawing",
"Block",
"Shapes",
"Supplemental",
"Tags",
]
RE_POSSIBLE_ENCODING_INDICATION = re_compile(
r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)",
IGNORECASE,
)
IANA_SUPPORTED: List[str] = sorted(
filter(
lambda x: x.endswith("_codec") is False
and x not in {"rot_13", "tactis", "mbcs"},
list(set(aliases.values())),
)
)
IANA_SUPPORTED_COUNT: int = len(IANA_SUPPORTED)
# pre-computed code page that are similar using the function cp_similarity.
IANA_SUPPORTED_SIMILAR: Dict[str, List[str]] = {
"cp037": ["cp1026", "cp1140", "cp273", "cp500"],
"cp1026": ["cp037", "cp1140", "cp273", "cp500"],
"cp1125": ["cp866"],
"cp1140": ["cp037", "cp1026", "cp273", "cp500"],
"cp1250": ["iso8859_2"],
"cp1251": ["kz1048", "ptcp154"],
"cp1252": ["iso8859_15", "iso8859_9", "latin_1"],
"cp1253": ["iso8859_7"],
"cp1254": ["iso8859_15", "iso8859_9", "latin_1"],
"cp1257": ["iso8859_13"],
"cp273": ["cp037", "cp1026", "cp1140", "cp500"],
"cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"],
"cp500": ["cp037", "cp1026", "cp1140", "cp273"],
"cp850": ["cp437", "cp857", "cp858", "cp865"],
"cp857": ["cp850", "cp858", "cp865"],
"cp858": ["cp437", "cp850", "cp857", "cp865"],
"cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"],
"cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"],
"cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"],
"cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"],
"cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"],
"cp866": ["cp1125"],
"iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"],
"iso8859_11": ["tis_620"],
"iso8859_13": ["cp1257"],
"iso8859_14": [
"iso8859_10",
"iso8859_15",
"iso8859_16",
"iso8859_3",
"iso8859_9",
"latin_1",
],
"iso8859_15": [
"cp1252",
"cp1254",
"iso8859_10",
"iso8859_14",
"iso8859_16",
"iso8859_3",
"iso8859_9",
"latin_1",
],
"iso8859_16": [
"iso8859_14",
"iso8859_15",
"iso8859_2",
"iso8859_3",
"iso8859_9",
"latin_1",
],
"iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"],
"iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"],
"iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"],
"iso8859_7": ["cp1253"],
"iso8859_9": [
"cp1252",
"cp1254",
"cp1258",
"iso8859_10",
"iso8859_14",
"iso8859_15",
"iso8859_16",
"iso8859_3",
"iso8859_4",
"latin_1",
],
"kz1048": ["cp1251", "ptcp154"],
"latin_1": [
"cp1252",
"cp1254",
"cp1258",
"iso8859_10",
"iso8859_14",
"iso8859_15",
"iso8859_16",
"iso8859_3",
"iso8859_4",
"iso8859_9",
],
"mac_iceland": ["mac_roman", "mac_turkish"],
"mac_roman": ["mac_iceland", "mac_turkish"],
"mac_turkish": ["mac_iceland", "mac_roman"],
"ptcp154": ["cp1251", "kz1048"],
"tis_620": ["iso8859_11"],
}
CHARDET_CORRESPONDENCE: Dict[str, str] = {
"iso2022_kr": "ISO-2022-KR",
"iso2022_jp": "ISO-2022-JP",
"euc_kr": "EUC-KR",
"tis_620": "TIS-620",
"utf_32": "UTF-32",
"euc_jp": "EUC-JP",
"koi8_r": "KOI8-R",
"iso8859_1": "ISO-8859-1",
"iso8859_2": "ISO-8859-2",
"iso8859_5": "ISO-8859-5",
"iso8859_6": "ISO-8859-6",
"iso8859_7": "ISO-8859-7",
"iso8859_8": "ISO-8859-8",
"utf_16": "UTF-16",
"cp855": "IBM855",
"mac_cyrillic": "MacCyrillic",
"gb2312": "GB2312",
"gb18030": "GB18030",
"cp932": "CP932",
"cp866": "IBM866",
"utf_8": "utf-8",
"utf_8_sig": "UTF-8-SIG",
"shift_jis": "SHIFT_JIS",
"big5": "Big5",
"cp1250": "windows-1250",
"cp1251": "windows-1251",
"cp1252": "Windows-1252",
"cp1253": "windows-1253",
"cp1255": "windows-1255",
"cp1256": "windows-1256",
"cp1254": "Windows-1254",
"cp949": "CP949",
}
COMMON_SAFE_ASCII_CHARACTERS: Set[str] = {
"<",
">",
"=",
":",
"/",
"&",
";",
"{",
"}",
"[",
"]",
",",
"|",
'"',
"-",
}
KO_NAMES: Set[str] = {"johab", "cp949", "euc_kr"}
ZH_NAMES: Set[str] = {"big5", "cp950", "big5hkscs", "hz"}
LANGUAGE_SUPPORTED_COUNT: int = len(FREQUENCIES)
# Logging LEVEL below DEBUG
TRACE: int = 5
| 1 | 0.580576 | 1 | 0.580576 | game-dev | MEDIA | 0.469479 | game-dev | 0.643595 | 1 | 0.643595 |
pprp/ACBench | 1,133 | thirdpartys/AgentBoard/agentboard/environment/pddl_env/pddlgym/pddl/glibrearrangement/problem5.pddl | (define (problem rearrangement)
(:domain glibrearrangement)
(:objects
monkey-0 - moveable
pawn-1 - moveable
bear-2 - moveable
robot - moveable
loc-0-0 - static
loc-0-1 - static
loc-0-2 - static
loc-0-3 - static
loc-1-0 - static
loc-1-1 - static
loc-1-2 - static
loc-1-3 - static
loc-2-0 - static
loc-2-1 - static
loc-2-2 - static
loc-2-3 - static
loc-3-0 - static
loc-3-1 - static
loc-3-2 - static
loc-3-3 - static
)
(:init
(ismonkey monkey-0)
(ispawn pawn-1)
(isbear bear-2)
(isrobot robot)
(at monkey-0 loc-3-2)
(at pawn-1 loc-0-3)
(at bear-2 loc-2-2)
(at robot loc-3-3)
(handsfree robot)
; action literals
(pick monkey-0)
(place monkey-0)
(pick pawn-1)
(place pawn-1)
(pick bear-2)
(place bear-2)
(moveto loc-0-0)
(moveto loc-0-1)
(moveto loc-0-2)
(moveto loc-0-3)
(moveto loc-1-0)
(moveto loc-1-1)
(moveto loc-1-2)
(moveto loc-1-3)
(moveto loc-2-0)
(moveto loc-2-1)
(moveto loc-2-2)
(moveto loc-2-3)
(moveto loc-3-0)
(moveto loc-3-1)
(moveto loc-3-2)
(moveto loc-3-3)
)
(:goal (and (at bear-2 loc-2-2) (holding bear-2) ))
)
| 1 | 0.691351 | 1 | 0.691351 | game-dev | MEDIA | 0.666153 | game-dev | 0.978267 | 1 | 0.978267 |
alexkulya/pandaria_5.4.8 | 7,959 | src/server/scripts/Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp | /*
* This file is part of the Pandaria 5.4.8 Project. See THANKS file for Copyright information
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "InstanceScript.h"
#include "steam_vault.h"
class go_main_chambers_access_panel : public GameObjectScript
{
public:
go_main_chambers_access_panel() : GameObjectScript("go_main_chambers_access_panel") { }
bool OnGossipHello(Player* /*player*/, GameObject* go) override
{
InstanceScript* instance = go->GetInstanceScript();
if (!instance)
return false;
if (go->GetEntry() == GO_ACCESS_PANEL_HYDRO && (instance->GetBossState(DATA_HYDROMANCER_THESPIA) == DONE || instance->GetBossState(DATA_HYDROMANCER_THESPIA) == SPECIAL))
{
instance->SetBossState(DATA_HYDROMANCER_THESPIA, SPECIAL);
go->SetGoState(GO_STATE_ACTIVE);
}
if (go->GetEntry() == GO_ACCESS_PANEL_MEK && (instance->GetBossState(DATA_MEKGINEER_STEAMRIGGER) == DONE || instance->GetBossState(DATA_MEKGINEER_STEAMRIGGER) == SPECIAL))
{
instance->SetBossState(DATA_MEKGINEER_STEAMRIGGER, SPECIAL);
go->SetGoState(GO_STATE_ACTIVE);
}
return true;
}
};
class instance_steam_vault : public InstanceMapScript
{
public:
instance_steam_vault() : InstanceMapScript(SteamVaultScriptName, 545) { }
struct instance_steam_vault_InstanceMapScript : public InstanceScript
{
instance_steam_vault_InstanceMapScript(Map* map) : InstanceScript(map)
{
SetBossNumber(EncounterCount);
ThespiaGUID = 0;
MekgineerGUID = 0;
KalithreshGUID = 0;
MainChambersDoorGUID = 0;
MekDoor = 0;
HydroDoor = 0;
DistillerState = 0;
}
void OnCreatureCreate(Creature* creature) override
{
switch (creature->GetEntry())
{
case NPC_HYDROMANCER_THESPIA:
ThespiaGUID = creature->GetGUID();
break;
case NPC_MEKGINEER_STEAMRIGGER:
MekgineerGUID = creature->GetGUID();
break;
case NPC_WARLORD_KALITHRESH:
KalithreshGUID = creature->GetGUID();
break;
default:
break;
}
}
void OnGameObjectCreate(GameObject* go) override
{
switch (go->GetEntry())
{
case GO_MAIN_CHAMBERS_DOOR:
MainChambersDoorGUID = go->GetGUID();
break;
case GO_ACCESS_PANEL_HYDRO:
HydroDoor = go->GetGUID();
break;
case GO_ACCESS_PANEL_MEK:
MekDoor = go->GetGUID();
break;
}
}
uint64 GetData64(uint32 type) const override
{
switch (type)
{
case DATA_HYDROMANCER_THESPIA:
return ThespiaGUID;
case DATA_MEKGINEER_STEAMRIGGER:
return MekgineerGUID;
case DATA_WARLORD_KALITHRESH:
return KalithreshGUID;
case GO_ACCESS_PANEL_HYDRO:
return HydroDoor;
case GO_ACCESS_PANEL_MEK:
return MekDoor;
}
return 0;
}
void SetData(uint32 type, uint32 data) override
{
if (type == DATA_DISTILLER)
DistillerState = data;
}
uint32 GetData(uint32 type) const override
{
if (type == DATA_DISTILLER)
return DistillerState;
return 0;
}
bool SetBossState(uint32 type, EncounterState state) override
{
if (!InstanceScript::SetBossState(type, state))
return false;
switch (type)
{
case DATA_HYDROMANCER_THESPIA:
if (state == SPECIAL)
{
if (GetBossState(DATA_MEKGINEER_STEAMRIGGER) == SPECIAL)
HandleGameObject(MainChambersDoorGUID, true);
TC_LOG_DEBUG("scripts", "Instance Steamvault: Access panel used.");
}
break;
case DATA_MEKGINEER_STEAMRIGGER:
if (state == SPECIAL)
{
if (GetBossState(DATA_HYDROMANCER_THESPIA) == SPECIAL)
HandleGameObject(MainChambersDoorGUID, true);
TC_LOG_DEBUG("scripts", "Instance Steamvault: Access panel used.");
}
break;
default:
break;
}
return true;
}
std::string GetSaveData() override
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << "S V " << GetBossSaveData();
OUT_SAVE_INST_DATA_COMPLETE;
return saveStream.str();
}
void Load(char const* str) override
{
if (!str)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(str);
char dataHead1, dataHead2;
std::istringstream loadStream(str);
loadStream >> dataHead1 >> dataHead2;
if (dataHead1 == 'S' && dataHead2 == 'V')
{
for (uint32 i = 0; i < EncounterCount; ++i)
{
uint32 tmpState;
loadStream >> tmpState;
if (tmpState == IN_PROGRESS || tmpState > SPECIAL)
tmpState = NOT_STARTED;
SetBossState(i, EncounterState(tmpState));
}
}
else
OUT_LOAD_INST_DATA_FAIL;
OUT_LOAD_INST_DATA_COMPLETE;
}
protected:
uint64 ThespiaGUID;
uint64 MekgineerGUID;
uint64 KalithreshGUID;
uint64 MainChambersDoorGUID;
uint64 MekDoor;
uint64 HydroDoor;
uint8 DistillerState;
};
InstanceScript* GetInstanceScript(InstanceMap* map) const override
{
return new instance_steam_vault_InstanceMapScript(map);
}
};
void AddSC_instance_steam_vault()
{
new go_main_chambers_access_panel();
new instance_steam_vault();
}
| 1 | 0.971126 | 1 | 0.971126 | game-dev | MEDIA | 0.953826 | game-dev | 0.961132 | 1 | 0.961132 |
SkriptLang/Skript | 3,055 | src/main/java/org/skriptlang/skript/bukkit/damagesource/elements/ExprDirectEntity.java | package org.skriptlang.skript.bukkit.damagesource.elements;
import ch.njol.skript.Skript;
import ch.njol.skript.classes.Changer.ChangeMode;
import ch.njol.skript.doc.*;
import ch.njol.skript.expressions.base.SimplePropertyExpression;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.util.Kleenean;
import ch.njol.util.coll.CollectionUtils;
import org.bukkit.damage.DamageSource;
import org.bukkit.entity.Entity;
import org.bukkit.event.Event;
import org.jetbrains.annotations.Nullable;
import org.skriptlang.skript.bukkit.damagesource.DamageSourceExperimentSyntax;
import org.skriptlang.skript.bukkit.damagesource.elements.ExprSecDamageSource.DamageSourceSectionEvent;
@Name("Damage Source - Direct Entity")
@Description({
"The direct entity of a damage source.",
"The direct entity is the entity that directly caused the damage. (e.g. the arrow that was shot)",
"Attributes of a damage source cannot be changed once created, only while within the 'custom damage source' section."
})
@Example("""
set {_source} to a custom damage source:
set the damage type to magic
set the causing entity to {_player}
set the direct entity to {_arrow}
set the damage location to location(0, 0, 10)
damage all players by 5 using {_source}
""")
@Example("""
on death:
set {_direct} to the direct entity of event-damage source
""")
@Since("2.12")
@RequiredPlugins("Minecraft 1.20.4+")
@SuppressWarnings("UnstableApiUsage")
public class ExprDirectEntity extends SimplePropertyExpression<DamageSource, Entity> implements DamageSourceExperimentSyntax {
static {
registerDefault(ExprDirectEntity.class, Entity.class, "direct entity", "damagesources");
}
private boolean isEvent;
@Override
public boolean init(Expression<?>[] expressions, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) {
isEvent = getParser().isCurrentEvent(DamageSourceSectionEvent.class);
return super.init(expressions, matchedPattern, isDelayed, parseResult);
}
@Override
public @Nullable Entity convert(DamageSource damageSource) {
return damageSource.getDirectEntity();
}
@Override
public Class<?> @Nullable [] acceptChange(ChangeMode mode) {
if (!isEvent) {
Skript.error("You cannot change the attributes of a damage source outside a 'custom damage source' section.");
} else if (!getExpr().isSingle() || !getExpr().isDefault()) {
Skript.error("You can only change the attributes of the damage source being created in this section.");
} else if (mode == ChangeMode.SET || mode == ChangeMode.DELETE) {
return CollectionUtils.array(Entity.class);
}
return null;
}
@Override
public void change(Event event, Object @Nullable [] delta, ChangeMode mode) {
if (!(event instanceof DamageSourceSectionEvent sectionEvent))
return;
sectionEvent.directEntity = delta == null ? null : (Entity) delta[0];
}
@Override
public Class<Entity> getReturnType() {
return Entity.class;
}
@Override
protected String getPropertyName() {
return "direct entity";
}
}
| 1 | 0.859178 | 1 | 0.859178 | game-dev | MEDIA | 0.718496 | game-dev | 0.875746 | 1 | 0.875746 |
LiteLDev/LiteLoaderBDS | 2,221 | ScriptEngine/third-party/backend/include/NodeJs/v8/cppgc/prefinalizer.h | // Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef INCLUDE_CPPGC_PREFINALIZER_H_
#define INCLUDE_CPPGC_PREFINALIZER_H_
#include "cppgc/internal/compiler-specific.h"
#include "cppgc/internal/prefinalizer-handler.h"
#include "cppgc/liveness-broker.h"
namespace cppgc {
namespace internal {
template <typename T>
class PrefinalizerRegistration final {
public:
explicit PrefinalizerRegistration(T* self) {
static_assert(sizeof(&T::InvokePreFinalizer) > 0,
"USING_PRE_FINALIZER(T) must be defined.");
cppgc::internal::PreFinalizerRegistrationDispatcher::RegisterPrefinalizer(
{self, T::InvokePreFinalizer});
}
void* operator new(size_t, void* location) = delete;
void* operator new(size_t) = delete;
};
} // namespace internal
#define CPPGC_USING_PRE_FINALIZER(Class, PreFinalizer) \
public: \
static bool InvokePreFinalizer(const cppgc::LivenessBroker& liveness_broker, \
void* object) { \
static_assert(cppgc::IsGarbageCollectedOrMixinTypeV<Class>, \
"Only garbage collected objects can have prefinalizers"); \
Class* self = static_cast<Class*>(object); \
if (liveness_broker.IsHeapObjectAlive(self)) return false; \
self->Class::PreFinalizer(); \
return true; \
} \
\
private: \
CPPGC_NO_UNIQUE_ADDRESS cppgc::internal::PrefinalizerRegistration<Class> \
prefinalizer_dummy_{this}; \
static_assert(true, "Force semicolon.")
} // namespace cppgc
#endif // INCLUDE_CPPGC_PREFINALIZER_H_
| 1 | 0.546748 | 1 | 0.546748 | game-dev | MEDIA | 0.359784 | game-dev | 0.64437 | 1 | 0.64437 |
duaneking/BansheeEngine | 6,540 | BansheeEngine/Source/BsGUIWidget.cpp | //__________________________ Banshee Project - A modern game development toolkit _________________________________//
//_____________________________________ www.banshee-project.com __________________________________________________//
//________________________ Copyright (c) 2014 Marko Pintera. All rights reserved. ________________________________//
#include "BsGUIWidget.h"
#include "BsGUIManager.h"
#include "BsGUISkin.h"
#include "BsGUILabel.h"
#include "BsGUIMouseEvent.h"
#include "BsGUIArea.h"
#include "BsCoreApplication.h"
#include "BsCoreThreadAccessor.h"
#include "BsMaterial.h"
#include "BsPass.h"
#include "BsMesh.h"
#include "BsVector2I.h"
#include "BsOverlayManager.h"
#include "BsCamera.h"
#include "BsViewport.h"
#include "BsSceneObject.h"
#include "BsRenderWindow.h"
namespace BansheeEngine
{
GUISkin GUIWidget::DefaultSkin;
GUIWidget::GUIWidget(const HSceneObject& parent, Viewport* target)
:Component(parent), mSkin(nullptr), mWidgetIsDirty(false), mTarget(nullptr), mDepth(0)
{
setName("GUIWidget");
mLastFramePosition = SO()->getWorldPosition();
mLastFrameRotation = SO()->getWorldRotation();
mLastFrameScale = SO()->getWorldScale();
assert(target != nullptr);
mTarget = target;
mOwnerTargetResizedConn = mTarget->getTarget()->onResized.connect(std::bind(&GUIWidget::ownerTargetResized, this));
GUIManager::instance().registerWidget(this);
}
GUIWidget::~GUIWidget()
{
if(mTarget != nullptr)
{
GUIManager::instance().unregisterWidget(this);
mOwnerTargetResizedConn.disconnect();
}
// Iterate over all elements in this way because each
// GUIElement::destroy call internally unregisters the element
// from the widget, and modifies the mElements array
while(mElements.size() > 0)
{
GUIElement::destroy(mElements[0]);
}
for(auto& area : mAreas)
{
GUIArea::destroyInternal(area);
}
mElements.clear();
}
void GUIWidget::update()
{
// If the widgets parent scene object moved, we need to mark it as dirty
// as the GUIManager batching relies on object positions, so it needs to be updated.
const float diffEpsilon = 0.0001f;
Vector3 position = SO()->getWorldPosition();
Quaternion rotation = SO()->getWorldRotation();
Vector3 scale = SO()->getWorldScale();
if(!mWidgetIsDirty)
{
Vector3 posDiff = mLastFramePosition - position;
if(Math::abs(posDiff.x) > diffEpsilon || Math::abs(posDiff.y) > diffEpsilon || Math::abs(posDiff.z) > diffEpsilon)
{
mWidgetIsDirty = true;
}
else
{
Quaternion rotDiff = mLastFrameRotation - rotation;
if(Math::abs(rotDiff.x) > diffEpsilon || Math::abs(rotDiff.y) > diffEpsilon ||
Math::abs(rotDiff.z) > diffEpsilon || Math::abs(rotDiff.w) > diffEpsilon)
{
mWidgetIsDirty = true;
}
else
{
Vector3 scaleDiff = mLastFrameScale - scale;
if(Math::abs(scaleDiff.x) > diffEpsilon || Math::abs(scaleDiff.y) > diffEpsilon || Math::abs(scaleDiff.z) > diffEpsilon)
{
mWidgetIsDirty = true;
}
}
}
}
mLastFramePosition = position;
mLastFrameRotation = rotation;
mLastFrameScale = scale;
}
void GUIWidget::_updateLayout()
{
for(auto& area : mAreas)
{
area->_update();
}
}
bool GUIWidget::_mouseEvent(GUIElement* element, const GUIMouseEvent& ev)
{
return element->mouseEvent(ev);
}
bool GUIWidget::_textInputEvent(GUIElement* element, const GUITextInputEvent& ev)
{
return element->textInputEvent(ev);
}
bool GUIWidget::_commandEvent(GUIElement* element, const GUICommandEvent& ev)
{
return element->commandEvent(ev);
}
bool GUIWidget::_virtualButtonEvent(GUIElement* element, const GUIVirtualButtonEvent& ev)
{
return element->virtualButtonEvent(ev);
}
void GUIWidget::registerElement(GUIElement* elem)
{
assert(elem != nullptr);
mElements.push_back(elem);
mWidgetIsDirty = true;
}
void GUIWidget::unregisterElement(GUIElement* elem)
{
assert(elem != nullptr);
auto iterFind = std::find(begin(mElements), end(mElements), elem);
if(iterFind == mElements.end())
BS_EXCEPT(InvalidParametersException, "Cannot unregister an element that is not registered on this widget.");
mElements.erase(iterFind);
mWidgetIsDirty = true;
}
void GUIWidget::registerArea(GUIArea* area)
{
assert(area != nullptr);
mAreas.push_back(area);
mWidgetIsDirty = true;
}
void GUIWidget::unregisterArea(GUIArea* area)
{
assert(area != nullptr);
auto iterFind = std::find(begin(mAreas), end(mAreas), area);
if(iterFind == mAreas.end())
BS_EXCEPT(InvalidParametersException, "Cannot unregister an area that is not registered on this widget.");
mAreas.erase(iterFind);
mWidgetIsDirty = true;
}
void GUIWidget::setSkin(const GUISkin& skin)
{
mSkin = &skin;
for(auto& element : mElements)
element->_refreshStyle();
}
const GUISkin& GUIWidget::getSkin() const
{
if(mSkin != nullptr)
return *mSkin;
else
return DefaultSkin;
}
bool GUIWidget::isDirty(bool cleanIfDirty)
{
if(cleanIfDirty)
{
bool dirty = mWidgetIsDirty;
mWidgetIsDirty = false;
for(auto& elem : mElements)
{
if(elem->_isContentDirty())
{
dirty = true;
elem->updateRenderElements();
}
if(elem->_isMeshDirty())
{
dirty = true;
elem->_markAsClean();
}
}
if(dirty)
updateBounds();
return dirty;
}
else
{
if(mWidgetIsDirty)
return true;
for(auto& elem : mElements)
{
if(elem->_isContentDirty() || elem->_isMeshDirty())
{
return true;
}
}
return false;
}
}
bool GUIWidget::inBounds(const Vector2I& position) const
{
// Technically GUI widget bounds can be larger than the viewport, so make sure we clip to viewport first
if(!getTarget()->getArea().contains(position))
return false;
const Matrix4& worldTfrm = SO()->getWorldTfrm();
Vector3 vecPos((float)position.x, (float)position.y, 0.0f);
vecPos = worldTfrm.inverse().multiply3x4(vecPos);
Vector2I localPos(Math::roundToInt(vecPos.x), Math::roundToInt(vecPos.y));
return mBounds.contains(localPos);
}
void GUIWidget::updateBounds() const
{
if(mElements.size() > 0)
mBounds = mElements[0]->_getClippedBounds();
for(auto& elem : mElements)
{
RectI elemBounds = elem->_getClippedBounds();
mBounds.encapsulate(elemBounds);
}
}
void GUIWidget::ownerTargetResized()
{
for(auto& area : mAreas)
{
area->updateSizeBasedOnParent(getTarget()->getWidth(), getTarget()->getHeight());
}
}
void GUIWidget::ownerWindowFocusChanged()
{
}
} | 1 | 0.979498 | 1 | 0.979498 | game-dev | MEDIA | 0.756117 | game-dev,desktop-app | 0.937907 | 1 | 0.937907 |
bates64/papermario-dx | 2,539 | src/world/area_sbk/sbk_12/npc.c | #include "sbk_12.h"
#include "world/common/enemy/Pokey.inc.c"
NpcData N(NpcData_Pokey_01) = {
.id = NPC_Pokey_01,
.pos = { -190.0f, 0.0f, -130.0f },
.yaw = 90,
.territory = {
.wander = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.wanderShape = SHAPE_CYLINDER,
.centerPos = { -190, 0, -130 },
.wanderSize = { 100 },
.detectShape = SHAPE_CYLINDER,
.detectPos = { 0, 0, 0 },
.detectSize = { 1000 },
}
},
.settings = &N(NpcSettings_Pokey),
.flags = ENEMY_FLAG_IGNORE_ENTITY_COLLISION | ENEMY_FLAG_FLYING | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = POKEY_DROPS,
.animations = POKEY_ANIMS,
.aiDetectFlags = AI_DETECT_SIGHT,
};
NpcData N(NpcData_Pokey_02) = {
.id = NPC_Pokey_02,
.pos = { -40.0f, 0.0f, -200.0f },
.yaw = 90,
.territory = {
.wander = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.wanderShape = SHAPE_CYLINDER,
.centerPos = { -40, 0, -200 },
.wanderSize = { 100 },
.detectShape = SHAPE_CYLINDER,
.detectPos = { 0, 0, 0 },
.detectSize = { 1000 },
}
},
.settings = &N(NpcSettings_Pokey),
.flags = ENEMY_FLAG_IGNORE_ENTITY_COLLISION | ENEMY_FLAG_FLYING | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = POKEY_DROPS,
.animations = POKEY_ANIMS,
.aiDetectFlags = AI_DETECT_SIGHT,
};
NpcData N(NpcData_Pokey_03) = {
.id = NPC_Pokey_03,
.pos = { 195.0f, 0.0f, -255.0f },
.yaw = 270,
.territory = {
.wander = {
.isFlying = TRUE,
.moveSpeedOverride = NO_OVERRIDE_MOVEMENT_SPEED,
.wanderShape = SHAPE_CYLINDER,
.centerPos = { 195, 0, -255 },
.wanderSize = { 100 },
.detectShape = SHAPE_CYLINDER,
.detectPos = { 0, 0, 0 },
.detectSize = { 1000 },
}
},
.settings = &N(NpcSettings_Pokey),
.flags = ENEMY_FLAG_IGNORE_ENTITY_COLLISION | ENEMY_FLAG_FLYING | ENEMY_FLAG_NO_SHADOW_RAYCAST,
.drops = POKEY_DROPS,
.animations = POKEY_ANIMS,
.aiDetectFlags = AI_DETECT_SIGHT,
};
NpcGroupList N(DefaultNPCs) = {
NPC_GROUP(N(NpcData_Pokey_01), BTL_SBK_FORMATION_02, BTL_SBK_STAGE_00),
NPC_GROUP(N(NpcData_Pokey_02), BTL_SBK_FORMATION_00, BTL_SBK_STAGE_00),
NPC_GROUP(N(NpcData_Pokey_03), BTL_SBK_FORMATION_01, BTL_SBK_STAGE_00),
{}
};
| 1 | 0.940239 | 1 | 0.940239 | game-dev | MEDIA | 0.988875 | game-dev | 0.740617 | 1 | 0.740617 |
snape/RVO2 | 3,546 | src/Agent.h | /*
* Agent.h
* RVO2 Library
*
* SPDX-FileCopyrightText: 2008 University of North Carolina at Chapel Hill
* 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
*
* https://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.
*
* Please send all bug reports to <geom@cs.unc.edu>.
*
* The authors may be contacted via:
*
* Jur van den Berg, Stephen J. Guy, Jamie Snape, Ming C. Lin, Dinesh Manocha
* Dept. of Computer Science
* 201 S. Columbia St.
* Frederick P. Brooks, Jr. Computer Science Bldg.
* Chapel Hill, N.C. 27599-3175
* United States of America
*
* <https://gamma.cs.unc.edu/RVO2/>
*/
#ifndef RVO_AGENT_H_
#define RVO_AGENT_H_
/**
* @file Agent.h
* @brief Declares the Agent class.
*/
#include <cstddef>
#include <utility>
#include <vector>
#include "Line.h"
#include "Vector2.h"
namespace RVO {
class KdTree;
class Obstacle;
/**
* @brief Defines an agent in the simulation.
*/
class Agent {
private:
/**
* @brief Constructs an agent instance.
*/
Agent();
/**
* @brief Destroys this agent instance.
*/
~Agent();
/**
* @brief Computes the neighbors of this agent.
* @param[in] kdTree A pointer to the k-D trees for agents and static
* obstacles in the simulation.
*/
void computeNeighbors(const KdTree *kdTree);
/**
* @brief Computes the new velocity of this agent.
* @param[in] timeStep The time step of the simulation.
*/
void computeNewVelocity(float timeStep);
/**
* @brief Inserts an agent neighbor into the set of neighbors of this
* agent.
* @param[in] agent A pointer to the agent to be inserted.
* @param[in, out] rangeSq The squared range around this agent.
*/
void insertAgentNeighbor(const Agent *agent,
float &rangeSq); /* NOLINT(runtime/references) */
/**
* @brief Inserts a static obstacle neighbor into the set of
* neighbors of this agent.
* @param[in] obstacle The number of the static obstacle to be inserted.
* @param[in, out] rangeSq The squared range around this agent.
*/
void insertObstacleNeighbor(const Obstacle *obstacle, float rangeSq);
/**
* @brief Updates the two-dimensional position and two-dimensional
* velocity of this agent.
* @param[in] timeStep The time step of the simulation.
*/
void update(float timeStep);
/* Not implemented. */
Agent(const Agent &other);
/* Not implemented. */
Agent &operator=(const Agent &other);
std::vector<std::pair<float, const Agent *> > agentNeighbors_;
std::vector<std::pair<float, const Obstacle *> > obstacleNeighbors_;
std::vector<Line> orcaLines_;
Vector2 newVelocity_;
Vector2 position_;
Vector2 prefVelocity_;
Vector2 velocity_;
std::size_t id_;
std::size_t maxNeighbors_;
float maxSpeed_;
float neighborDist_;
float radius_;
float timeHorizon_;
float timeHorizonObst_;
friend class KdTree;
friend class RVOSimulator;
};
} /* namespace RVO */
#endif /* RVO_AGENT_H_ */
| 1 | 0.716705 | 1 | 0.716705 | game-dev | MEDIA | 0.419032 | game-dev | 0.755461 | 1 | 0.755461 |
PfAndrey/supermariohd | 2,653 | source/enemies/Goomba.cpp | #include "SuperMarioGame.hpp"
#include "Goomba.hpp"
Goomba::Goomba() {
setSize({ 32,32 });
const sf::Texture& texture = *MARIO_GAME.textureManager().get("Enemies");
m_animator.create("walk", texture, { {{0,0}, {32,32}},{{32,0}, {32,32}} }, 0.005f);
m_animator.create("squashed", texture, { 64, 0, 32, 32 });
m_animator.create("fall", texture, { 0, 32, 32, -32 });
m_animator.setSpriteOffset("squashed", 0, { 0,8 });
m_stateMachine.attachOnEnterMap<>(&m_animator, &Animator::play,
{{ State::WALKING , "walk" },
{ State::SQUASHED, "squashed"},
{ State::DIED , "fall" }
});
m_stateMachine.addTransition(Event::ENTERED_VIEW , State::DEACTIVATED, State::WALKING, [this]() { enterWalking(); });
m_stateMachine.addTransition(Event::PROJECTILE_HIT, State::WALKING, State::DIED, [this]() { enterDead(); });
m_stateMachine.addTransition(Event::STOMPED , State::WALKING, State::SQUASHED,[this]() { enterSquashed();});
m_stateMachine.start(State::DEACTIVATED);
}
void Goomba::update(int delta_time) {
Enemy::update(delta_time);
switch (m_stateMachine.getState()) {
case State::DEACTIVATED:
if (isInCamera()) {
m_stateMachine.dispatchEvent(Event::ENTERED_VIEW);
}
break;
case State::WALKING:
updatePhysics(delta_time, GRAVITY_FORCE);
updateCollision(delta_time, LogicFlags::ON_X_BOUND);
m_animator.update(delta_time);
break;
case State::DIED:
updatePhysics(delta_time, GRAVITY_FORCE);
break;
case State::SQUASHED:
m_timer += delta_time;
if (m_timer > 3000) {
removeLater();
}
break;
}
}
void Goomba::draw(sf::RenderWindow* render_window) {
m_animator.setPosition(getPosition());
m_animator.draw(render_window);
}
void Goomba::takeDamage(DamageType damageType, Character*) {
if (damageType == DamageType::HIT_FROM_ABOVE) {
m_stateMachine.dispatchEvent(Event::STOMPED);
} else {
m_stateMachine.dispatchEvent(Event::PROJECTILE_HIT);
}
}
void Goomba::touch(Character* character) {
character->takeDamage(DamageType::KICK, this);
}
bool Goomba::isAlive() const {
return (m_stateMachine.getState() == State::WALKING);
}
void Goomba::enterWalking() {
m_velocity.x = RUN_SPEED;
}
void Goomba::enterSquashed() {
m_velocity.x = 0;
addScoreToPlayer(100);
MARIO_GAME.playSound("stomp");
}
void Goomba::enterDead() {
m_velocity.x = 0;
m_velocity += 0.4f * Vector::UP;
addScoreToPlayer(100);
MARIO_GAME.playSound("kick");
} | 1 | 0.919851 | 1 | 0.919851 | game-dev | MEDIA | 0.996005 | game-dev | 0.980782 | 1 | 0.980782 |
amosgyamfi/open-swiftui-animations | 11,750 | Gists_To_Try/Claude4SonnetSwiftUIFireworks.swift | //
// Claude4iOSFireworks.swift
//
// Created by Amos Gyamfi on 23.5.2025.
//
import SwiftUI
import UIKit
// MARK: - Fireworks Emitter View
struct FireworksEmitterView: UIViewRepresentable {
@Binding var triggerFireworks: Bool
func makeUIView(context: Context) -> UIView {
let view = UIView()
view.backgroundColor = UIColor.clear
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
if triggerFireworks {
createFireworksEffect(in: uiView)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
triggerFireworks = false
}
}
}
private func createFireworksEffect(in view: UIView) {
// Random launch position
let launchX = CGFloat.random(in: view.bounds.width * 0.2...view.bounds.width * 0.8)
let launchY = view.bounds.height
let explosionY = CGFloat.random(in: view.bounds.height * 0.2...view.bounds.height * 0.6)
// Create launch trail
createLaunchTrail(in: view, startX: launchX, startY: launchY, endY: explosionY)
// Delay explosion to match launch timing
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
self.createExplosion(in: view, x: launchX, y: explosionY)
}
}
private func createLaunchTrail(in view: UIView, startX: CGFloat, startY: CGFloat, endY: CGFloat) {
let emitterLayer = CAEmitterLayer()
// Position at launch point
emitterLayer.emitterPosition = CGPoint(x: startX, y: startY)
emitterLayer.emitterShape = .point
emitterLayer.emitterMode = .outline
// Create launch particle
let launchCell = CAEmitterCell()
launchCell.name = "launch"
launchCell.birthRate = 5
launchCell.lifetime = 0.8
launchCell.velocity = 300
launchCell.velocityRange = 50
launchCell.emissionLongitude = -.pi / 2 // Upward
launchCell.emissionRange = .pi / 8
// Appearance
launchCell.scale = 0.3
launchCell.scaleRange = 0.1
launchCell.color = UIColor.white.cgColor
launchCell.redRange = 0.3
launchCell.greenRange = 0.3
launchCell.blueRange = 0.3
launchCell.alphaSpeed = -1.0
// Physics
launchCell.yAcceleration = 100 // Gravity effect
launchCell.scaleSpeed = -0.2
// Particle image (create a simple circle)
launchCell.contents = createParticleImage(size: 8, color: .white).cgImage
emitterLayer.emitterCells = [launchCell]
view.layer.addSublayer(emitterLayer)
// Animate the emitter position to simulate rocket trail
let animation = CABasicAnimation(keyPath: "emitterPosition")
animation.fromValue = CGPoint(x: startX, y: startY)
animation.toValue = CGPoint(x: startX, y: endY)
animation.duration = 0.8
animation.timingFunction = CAMediaTimingFunction(name: .easeOut)
emitterLayer.add(animation, forKey: "position")
// Remove after animation
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
emitterLayer.removeFromSuperlayer()
}
}
private func createExplosion(in view: UIView, x: CGFloat, y: CGFloat) {
let emitterLayer = CAEmitterLayer()
// Position at explosion point
emitterLayer.emitterPosition = CGPoint(x: x, y: y)
emitterLayer.emitterShape = .point
emitterLayer.emitterMode = .outline
// Create multiple types of explosion particles
var cells: [CAEmitterCell] = []
// Main explosion particles
let explosionCell = CAEmitterCell()
explosionCell.name = "explosion"
explosionCell.birthRate = 200
explosionCell.lifetime = 3.0
explosionCell.lifetimeRange = 1.0
explosionCell.velocity = 200
explosionCell.velocityRange = 100
explosionCell.emissionLongitude = 0
explosionCell.emissionRange = 2 * .pi // Full circle
// Random colors for fireworks
let colors: [UIColor] = [.red, .orange, .yellow, .green, .blue, .purple, .magenta, .cyan]
let selectedColor = colors.randomElement() ?? .red
explosionCell.color = selectedColor.cgColor
explosionCell.redRange = 0.4
explosionCell.greenRange = 0.4
explosionCell.blueRange = 0.4
explosionCell.alphaSpeed = -0.8
// Physics
explosionCell.yAcceleration = 200 // Gravity
explosionCell.scale = 0.5
explosionCell.scaleRange = 0.3
explosionCell.scaleSpeed = -0.2
explosionCell.contents = createParticleImage(size: 6, color: selectedColor).cgImage
cells.append(explosionCell)
// Sparkle particles
let sparkleCell = CAEmitterCell()
sparkleCell.name = "sparkle"
sparkleCell.birthRate = 100
sparkleCell.lifetime = 2.0
sparkleCell.lifetimeRange = 0.5
sparkleCell.velocity = 150
sparkleCell.velocityRange = 80
sparkleCell.emissionLongitude = 0
sparkleCell.emissionRange = 2 * .pi
sparkleCell.color = UIColor.white.cgColor
sparkleCell.alphaSpeed = -1.0
sparkleCell.yAcceleration = 150
sparkleCell.scale = 0.2
sparkleCell.scaleRange = 0.1
sparkleCell.scaleSpeed = -0.1
// Create sparkle image
sparkleCell.contents = createSparkleImage().cgImage
cells.append(sparkleCell)
// Trailing particles
let trailCell = CAEmitterCell()
trailCell.name = "trail"
trailCell.birthRate = 50
trailCell.lifetime = 1.5
trailCell.velocity = 100
trailCell.velocityRange = 30
trailCell.emissionLongitude = 0
trailCell.emissionRange = 2 * .pi
trailCell.color = selectedColor.cgColor
trailCell.alphaSpeed = -2.0
trailCell.yAcceleration = 100
trailCell.scale = 0.3
trailCell.scaleSpeed = -0.3
trailCell.contents = createParticleImage(size: 4, color: selectedColor).cgImage
cells.append(trailCell)
emitterLayer.emitterCells = cells
view.layer.addSublayer(emitterLayer)
// Stop emission after initial burst
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
emitterLayer.birthRate = 0
}
// Remove layer after particles fade
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
emitterLayer.removeFromSuperlayer()
}
}
private func createParticleImage(size: CGFloat, color: UIColor) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: CGSize(width: size, height: size))
return renderer.image { context in
context.cgContext.setFillColor(color.cgColor)
context.cgContext.fillEllipse(in: CGRect(origin: .zero, size: CGSize(width: size, height: size)))
}
}
private func createSparkleImage() -> UIImage {
let size: CGFloat = 8
let renderer = UIGraphicsImageRenderer(size: CGSize(width: size, height: size))
return renderer.image { context in
let cgContext = context.cgContext
cgContext.setStrokeColor(UIColor.white.cgColor)
cgContext.setLineWidth(1)
// Draw star shape
cgContext.move(to: CGPoint(x: size/2, y: 0))
cgContext.addLine(to: CGPoint(x: size/2, y: size))
cgContext.move(to: CGPoint(x: 0, y: size/2))
cgContext.addLine(to: CGPoint(x: size, y: size/2))
cgContext.move(to: CGPoint(x: size*0.2, y: size*0.2))
cgContext.addLine(to: CGPoint(x: size*0.8, y: size*0.8))
cgContext.move(to: CGPoint(x: size*0.8, y: size*0.2))
cgContext.addLine(to: CGPoint(x: size*0.2, y: size*0.8))
cgContext.strokePath()
}
}
}
// MARK: - Main SwiftUI View
struct Claude4iOSFireworks: View {
@State private var triggerFireworks = false
@State private var showInstructions = true
var body: some View {
ZStack {
// Night sky background
LinearGradient(
colors: [
Color.black,
Color.blue.opacity(0.3),
Color.purple.opacity(0.2)
],
startPoint: .top,
endPoint: .bottom
)
.ignoresSafeArea()
// Stars background
StarsView()
// Fireworks layer
FireworksEmitterView(triggerFireworks: $triggerFireworks)
.ignoresSafeArea()
// Instructions overlay
if showInstructions {
VStack {
Spacer()
VStack(spacing: 16) {
Text("🎆 Fireworks Display 🎆")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(.white)
Text("Tap anywhere to launch fireworks!")
.font(.body)
.foregroundColor(.white.opacity(0.8))
Button("Hide Instructions") {
withAnimation(.easeOut(duration: 0.5)) {
showInstructions = false
}
}
.foregroundColor(.yellow)
.padding(.top)
}
.padding(24)
.background(
RoundedRectangle(cornerRadius: 16)
.fill(.ultraThinMaterial)
.opacity(0.8)
)
.padding(.horizontal, 32)
.padding(.bottom, 50)
}
.transition(.move(edge: .bottom).combined(with: .opacity))
}
}
.onTapGesture {
triggerFireworks = true
// Hide instructions after first tap
if showInstructions {
withAnimation(.easeOut(duration: 0.5).delay(0.5)) {
showInstructions = false
}
}
}
.preferredColorScheme(.dark)
}
}
// MARK: - Stars Background View
struct StarsView: View {
@State private var animateStars = false
var body: some View {
ZStack {
ForEach(0..<100, id: \.self) { _ in
Circle()
.fill(Color.white.opacity(Double.random(in: 0.3...1.0)))
.frame(width: CGFloat.random(in: 1...3))
.position(
x: CGFloat.random(in: 0...UIScreen.main.bounds.width),
y: CGFloat.random(in: 0...UIScreen.main.bounds.height * 0.7)
)
.scaleEffect(animateStars ? 1.2 : 0.8)
.animation(
.easeInOut(duration: Double.random(in: 2...4))
.repeatForever(autoreverses: true)
.delay(Double.random(in: 0...2)),
value: animateStars
)
}
}
.onAppear {
animateStars = true
}
}
}
#Preview {
Claude4iOSFireworks()
}
| 1 | 0.666833 | 1 | 0.666833 | game-dev | MEDIA | 0.433839 | game-dev,graphics-rendering | 0.742028 | 1 | 0.742028 |
AxGord/Pony | 2,267 | src/pony/flash/starling/displayFactory/DisplayFactory.hx | package pony.flash.starling.displayFactory;
import flash.geom.Point;
import flash.geom.Rectangle;
typedef IDisplayObject = {
var alpha: Float;
var height: Float;
var name: String;
var parent: IDisplayObjectContainer;
var rotation: Float; // Degrees / Rads!!!
var scaleX: Float;
var scaleY: Float;
var stage: IDisplayObjectContainer;
var visible: Bool;
var width: Float;
var x: Float;
var y: Float;
function getBounds(targetSpace: IDisplayObject): Rectangle;
function globalToLocal(globalPoint: Point): Point;
function localToGlobal(localPoint: Point): Point;
}
typedef IDisplayObjectContainer = {
> IDisplayObject,
var numChildren: Int;
function addChild(child: IDisplayObject): IDisplayObject;
function addChildAt(child: IDisplayObject, index: Int): IDisplayObject;
function contains(child: IDisplayObject): Bool;
function getChildAt(index: Int): IDisplayObject;
function getChildByName(name: String): IDisplayObject;
function getChildIndex(child: IDisplayObject): Int;
function removeChild(child: IDisplayObject): IDisplayObject;
function removeChildAt(index: Int): IDisplayObject;
function setChildIndex(child: IDisplayObject, index: Int): Void;
function swapChildren(child1: IDisplayObject, child2: IDisplayObject): Void;
function swapChildrenAt(index1: Int, index2: Int): Void;
}
typedef IMovieClip = {
> IDisplayObject,
// TODO container?
var currentFrame: Int;
// numframes/totalframes
function play(): Void;
function stop(): Void; // Different behavior?
// function addChild(child:IDisplayObject):Void;
}
typedef ITextField = {
> IDisplayObject,
var border: Bool;
var text: String;
}
/**
* DisplayFactory
* @author Maletin
*/
class DisplayFactory {
#if starling
private static var _current: IDisplayFactory = StarlingDisplayFactory.getInstance();
#else
private static var _current: IDisplayFactory = NativeFlashDisplayFactory.getInstance();
#end
public static function createSprite(): IDisplayObjectContainer {
return _current.createSprite();
}
public static function createTextField(width: Float, height: Float, text: String): ITextField {
return _current.createTextField(width, height, text);
}
public static function createMovieClip(): IMovieClip {
return _current.createMovieClip();
}
} | 1 | 0.682133 | 1 | 0.682133 | game-dev | MEDIA | 0.527945 | game-dev,graphics-rendering | 0.877186 | 1 | 0.877186 |
latte-soft/builtinplugins | 12,720 | src/BuiltInPlugins/ManageCollaborators/Src/Components/CollaboratorSearchWidget.luau | local l_Parent_0 = script.Parent.Parent.Parent;
local v1 = require(l_Parent_0.Packages.Roact);
local v2 = require(l_Parent_0.Packages.RoactRodux);
local v3 = require(l_Parent_0.Packages.Cryo);
local v4 = require(l_Parent_0.Packages.Framework);
local l_Stylizer_0 = v4.Style.Stylizer;
local l_ContextServices_0 = v4.ContextServices;
local l_withContext_0 = l_ContextServices_0.withContext;
local l_Localization_0 = l_ContextServices_0.Localization;
local v9 = require(l_Parent_0.Src.Util.PermissionsConstants);
local v10 = require(l_Parent_0.Src.Keys.loadingInProgress);
local l_PlayKey_0 = v9.PlayKey;
local l_EditKey_0 = v9.EditKey;
local v13 = require(l_Parent_0.Src.Util.Constants);
local l_COLLABORATORTYPE_USER_0 = v13.COLLABORATORTYPE_USER;
local l_COLLABORATORTYPE_GROUP_0 = v13.COLLABORATORTYPE_GROUP;
local v16 = require(l_Parent_0.Src.Components.Thumbnails.UserHeadshotThumbnail);
local v17 = require(l_Parent_0.Src.Components.Thumbnails.GroupIconThumbnail);
local v18 = require(l_Parent_0.Src.Components.SearchBar);
local v19 = require(l_Parent_0.Src.Util.CreateFitToContent);
local v20 = require(l_Parent_0.Src.Selectors.GetUserCollaborators);
local v21 = require(l_Parent_0.Src.Selectors.GetGroupCollaborators);
local v22 = require(l_Parent_0.Src.Thunks.AddUserCollaborator);
local v23 = require(l_Parent_0.Src.Thunks.AddGroupCollaborator);
local v24 = require(l_Parent_0.Src.Thunks.SearchCollaborators);
local v25 = require(l_Parent_0.Src.Thunks.PermissionsLoader);
local v26 = require(l_Parent_0.Src.Selectors.IsGroupGame);
local v27 = require(l_Parent_0.Src.Selectors.IsGame17Plus);
local v28 = v19("Frame", "UIListLayout", {
SortOrder = Enum.SortOrder.LayoutOrder,
Padding = UDim.new(0, 32),
HorizontalAlignment = Enum.HorizontalAlignment.Center
});
local v29 = v1.PureComponent:extend("CollaboratorSearchWidget");
v29.isLoading = function(v30)
local l_SearchData_0 = v30.props.SearchData;
local l_CachedSearchResults_0 = l_SearchData_0.CachedSearchResults;
local l_SearchText_0 = l_SearchData_0.SearchText;
local v34 = true;
if l_SearchData_0.LocalUserGroups ~= v10 then
v34 = true;
if l_SearchData_0.LocalUserFriends ~= v10 then
v34 = true;
if l_CachedSearchResults_0[l_SearchText_0] ~= v10 then
v34 = false;
if l_CachedSearchResults_0[l_SearchText_0] == nil then
v34 = l_SearchText_0 ~= "";
end;
end;
end;
end;
return v34;
end;
v29.isFriend = function(v35, v36)
local l_props_0 = v35.props;
local l_ownerType_0 = l_props_0.ownerType;
local l_ownerFriends_0 = l_props_0.ownerFriends;
if l_ownerType_0 == Enum.CreatorType.User then
for _, v41 in ipairs(l_ownerFriends_0) do
if v41 == v36 then
return true;
end;
end;
end;
return false;
end;
v29.getMatches = function(v42)
local l_props_1 = v42.props;
local l_SearchData_1 = l_props_1.SearchData;
local l_UserCollaborators_0 = l_props_1.UserCollaborators;
local l_GroupCollaborators_0 = l_props_1.GroupCollaborators;
local l_CachedSearchResults_1 = l_SearchData_1.CachedSearchResults;
local l_SearchText_1 = l_SearchData_1.SearchText;
local v49 = {};
for _, v51 in ipairs(l_UserCollaborators_0) do
v49[v51] = true;
end;
local function _(v52)
return v49[v52] ~= nil;
end;
local v54 = {};
for _, v56 in ipairs(l_GroupCollaborators_0) do
v54[v56] = true;
end;
local function _(v57)
return v54[v57] ~= nil;
end;
local v59 = {
Users = {},
Groups = {}
};
if l_CachedSearchResults_1[l_SearchText_1] and l_CachedSearchResults_1[l_SearchText_1] ~= v10 then
local v60 = l_CachedSearchResults_1[l_SearchText_1][v9.UserSubjectKey];
local v61 = l_CachedSearchResults_1[l_SearchText_1][v9.GroupSubjectKey];
local v62 = {};
for _, v64 in pairs(v60) do
if not (v49[v64[v9.SubjectIdKey]] ~= nil) then
table.insert(v62, v64);
end;
end;
local v65 = {};
for _, v67 in pairs(v61) do
if not (v54[v67[v9.GroupIdKey]] ~= nil) then
table.insert(v65, v67);
end;
end;
v59.Users = v62;
v59.Groups = v65;
end;
return v59;
end;
v29.getResults = function(v68)
local l_props_2 = v68.props;
local l_SearchData_2 = l_props_2.SearchData;
local l_IsGroupGame_0 = l_props_2.IsGroupGame;
if l_SearchData_2.SearchText == "" then
return {};
else
local v72 = v68:getMatches();
local v73 = {};
local l_MaxSearchResultsPerSubjectTypeUsers_0 = v9.MaxSearchResultsPerSubjectTypeUsers;
local l_MaxSearchResultsPerSubjectTypeGroups_0 = v9.MaxSearchResultsPerSubjectTypeGroups;
local v76 = v9.MaxSearchResultsPerSubjectTypeUsers - #v72.Users;
local v77 = v9.MaxSearchResultsPerSubjectTypeGroups - #v72.Groups;
if v77 > 0 then
local v78 = false;
if v77 > 0 then
v78 = v9.MaxSearchResultsPerSubjectTypeUsers + v77;
end;
l_MaxSearchResultsPerSubjectTypeUsers_0 = v78;
end;
if v76 > 0 then
local v79 = false;
if v76 > 0 then
v79 = v9.MaxSearchResultsPerSubjectTypeGroups + v76;
end;
l_MaxSearchResultsPerSubjectTypeGroups_0 = v79;
end;
if #v72.Users > 0 then
local v80 = {};
local v81 = {};
for _, v83 in pairs(v72.Users) do
if l_MaxSearchResultsPerSubjectTypeUsers_0 >= (#v80 + #v81) + 1 then
local v84 = v83[v9.SubjectIdKey];
local v85 = {
Icon = v1.createElement(v16, {
Id = v84,
Size = UDim2.new(1, 0, 1, 0)
}),
Name = v83[v9.SubjectNameKey],
Key = {
Type = v9.UserSubjectKey,
Id = v84,
Name = v83[v9.SubjectNameKey],
IsEligible = v83[v9.IsEligibleKey],
EligibilityText = v83[v9.EligibilityTextKey]
}
};
if not v68:isFriend(v84) then
table.insert(v81, v85);
else
v85.IsFriend = true;
table.insert(v80, v85);
end;
else
break;
end;
end;
for _, v87 in v81, nil, nil do
table.insert(v80, v87);
end;
v80.LayoutOrder = 0;
v73[l_COLLABORATORTYPE_USER_0] = v80;
end;
if not (not (#v72.Groups > 0) or l_IsGroupGame_0) then
local v88 = {};
for _, v90 in pairs(v72.Groups) do
if l_MaxSearchResultsPerSubjectTypeGroups_0 >= #v88 + 1 then
table.insert(v88, {
Icon = v1.createElement(v17, {
Id = v90[v9.GroupIdKey],
Size = UDim2.new(1, 0, 1, 0)
}),
Name = v90[v9.GroupNameKey],
Key = {
Type = v9.GroupSubjectKey,
Id = v90[v9.GroupIdKey],
Name = v90[v9.GroupNameKey],
IsEligible = true
}
});
else
break;
end;
end;
v88.LayoutOrder = 0;
v73[l_COLLABORATORTYPE_GROUP_0] = v88;
end;
return v73;
end;
end;
v29.render = function(v91)
local l_props_3 = v91.props;
local l_LayoutOrder_0 = l_props_3.LayoutOrder;
local l_Writable_0 = l_props_3.Writable;
local l_UserCollaborators_1 = l_props_3.UserCollaborators;
local l_AddUserCollaborator_0 = l_props_3.AddUserCollaborator;
local l_AddGroupCollaborator_0 = l_props_3.AddGroupCollaborator;
local l_SearchCollaborators_0 = l_props_3.SearchCollaborators;
local l_IsGroupGame_1 = l_props_3.IsGroupGame;
local l_Is17PlusGame_0 = l_props_3.Is17PlusGame;
local l_Stylizer_1 = l_props_3.Stylizer;
local l_Localization_1 = l_props_3.Localization;
local v103 = v91:getResults();
local v104 = v91:isLoading();
local v105 = #l_UserCollaborators_1;
local l_game_FastInt_0 = game:GetFastInt("TeamCreateMaxCollaborators");
local v107 = l_game_FastInt_0 <= v105;
return v1.createElement(v28, {
BackgroundTransparency = 1,
LayoutOrder = l_LayoutOrder_0
}, {
Padding = v1.createElement("UIPadding", {
PaddingTop = l_Stylizer_1.searchWidget.paddingTop,
PaddingLeft = l_Stylizer_1.searchWidget.paddingHorizontal,
PaddingRight = l_Stylizer_1.searchWidget.paddingHorizontal
}),
AgeWarningFrame = l_Is17PlusGame_0 and v1.createElement("Frame", {
BackgroundTransparency = 1,
LayoutOrder = 1,
Size = UDim2.new(1, 0, 0, l_Stylizer_1.searchWidget.ageWarning.Height),
BorderSizePixel = 0
}, {
AgeWarning = v1.createElement("TextLabel", v3.Dictionary.join(l_Stylizer_1.searchWidget.ageWarning.fontStyle, {
Text = if not l_IsGroupGame_1 then l_Localization_1:getText("SearchBar", "AgeWarningUsers") else l_Localization_1:getText("SearchBar", "AgeWarningGroups"),
TextXAlignment = Enum.TextXAlignment.Left
}))
}),
Searchbar = v1.createElement(v18, {
LayoutOrder = 2,
Enabled = l_Writable_0 and not v107,
HeaderHeight = l_Stylizer_1.searchBar.headerHeight,
ItemHeight = l_Stylizer_1.searchBar.itemHeight,
ErrorText = not not v107 and l_Localization_1:getText("SearchBar", "TooManyResultsText", {
maxNumCollaborators = l_game_FastInt_0
}) or nil,
DefaultText = l_Localization_1:getText("SearchBar", not l_IsGroupGame_1 and "AddUsersGroups" or "AddUsers"),
NoResultsText = l_Localization_1:getText("SearchBar", "NoResultsText"),
LoadingMore = v104,
IsGroupGame = l_IsGroupGame_1,
onSearchRequested = function(v108)
l_SearchCollaborators_0(v108, true);
end,
onTextChanged = function(v109)
l_SearchCollaborators_0(v109, false);
end,
OnItemClicked = function(v110)
l_props_3.LoadFriends();
if not (v110.Type == v9.UserSubjectKey) or not v110.IsEligible then
if v110.Type == v9.GroupSubjectKey then
l_AddGroupCollaborator_0(v110.Id, l_PlayKey_0);
return ;
else
assert(false);
return ;
end;
elseif not v91:isFriend(v110.Id) then
l_AddUserCollaborator_0(v110.Id, v110.Name, l_PlayKey_0);
return ;
else
l_AddUserCollaborator_0(v110.Id, v110.Name, l_EditKey_0);
return ;
end;
end,
Results = v103,
Is17PlusGame = l_Is17PlusGame_0
})
});
end;
return (v2.connect(function(v111, _)
local v113, v114 = v20(v111);
local v115, v116 = v21(v111);
return {
IsGroupGame = v26(v111),
Is17PlusGame = v27(v111),
UserCollaborators = v3.Dictionary.join(v113, v114),
GroupCollaborators = v3.Dictionary.join(v115, v116),
SearchData = v111.CollaboratorSearch,
ownerType = v111.GameOwnerMetadata.creatorType,
ownerFriends = v111.GameOwnerMetadata.creatorFriends
};
end, function(v117)
return {
AddUserCollaborator = function(...)
v117(v22(...));
end,
AddGroupCollaborator = function(...)
v117(v23(...));
end,
SearchCollaborators = function(...)
v117(v24(...));
end,
LoadFriends = function()
v117(v25:LoadFriends());
end
};
end)((l_withContext_0({
Stylizer = l_Stylizer_0,
Localization = l_Localization_0,
Mouse = l_ContextServices_0.Mouse
})(v29))));
| 1 | 0.787211 | 1 | 0.787211 | game-dev | MEDIA | 0.785115 | game-dev | 0.950819 | 1 | 0.950819 |
Unity-Technologies/com.unity.services.samples.game-lobby | 10,827 | Assets/Scripts/GameLobby/NGO/SequenceSelector.cs | using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;
namespace LobbyRelaySample.ngo
{
/// <summary>
/// Handles selecting the randomized sequence of symbols to spawn, choosing a subset to be the ordered target sequence that each player needs to select.
/// This also handles selecting randomized positions for the symbols, and it sets up the target sequence animation for the instruction sequence.
/// </summary>
public class SequenceSelector : NetworkBehaviour
{
[SerializeField]
SymbolData m_SymbolData = default;
[SerializeField]
Image[] m_TargetSequenceOutput = default;
public const int symbolCount = 140;
bool m_HasReceivedTargetSequence = false;
ulong m_LocalId;
bool m_CanAnimateTargets = true;
// This is owned by the host, and each index is assigned as a NetworkVariable to each SymbolObject.
List<int> m_FullSequenceServer = new List<int>();
// This is owned by the host but needs to be available to all clients, so it's a NetworkedList here.
NetworkList<int> m_targetSequence;
// Each player's current target. Also owned by the host, indexed by client ID.
Dictionary<ulong, int> m_targetSequenceIndexPerPlayer = new Dictionary<ulong, int>();
public void Awake()
{
m_targetSequence = new NetworkList<int>();
}
public override void OnNetworkSpawn()
{
if (IsHost)
ChooseSymbols();
m_targetSequence.ResetDirty();
m_LocalId = NetworkManager.Singleton.LocalClientId;
AddClient_ServerRpc(m_LocalId);
}
private void ChooseSymbols()
{
// Choose some subset of the list of symbols to be present in this game, along with a target sequence.
int numSymbolTypes = 8;
List<int> symbolsForThisGame = SelectSymbols(m_SymbolData.m_availableSymbols.Count, numSymbolTypes);
m_targetSequence.Add(symbolsForThisGame[0]);
m_targetSequence.Add(symbolsForThisGame[1]);
m_targetSequence.Add(symbolsForThisGame[2]);
// Then, ensure that the target sequence is present in order throughout most of the full set of symbols to spawn.
int numTargetSequences =
(int)(symbolCount * 2 / 3f) /
3; // About 2/3 of the symbols will be definitely part of the target sequence.
for (; numTargetSequences >= 0; numTargetSequences--)
{
m_FullSequenceServer.Add(
m_targetSequence[
2]); // We want a List instead of a Queue or Stack for faster insertion, but we will remove indices backwards so as to not resize other entries.
m_FullSequenceServer.Add(m_targetSequence[1]);
m_FullSequenceServer.Add(m_targetSequence[0]);
}
// Then, fill in with a good mix of the remaining symbols.
for (int n = 3; n < numSymbolTypes - 1; n++)
AddHalfRemaining(n, 2);
AddHalfRemaining(numSymbolTypes - 1, 1); // 1 as the divider ensures all remaining symbols get an index.
void AddHalfRemaining(int symbolIndex, int divider)
{
int remaining = symbolCount - m_FullSequenceServer.Count;
for (int n = 0; n < remaining / divider; n++)
{
int randomIndex = UnityEngine.Random.Range(0, m_FullSequenceServer.Count);
m_FullSequenceServer.Insert(randomIndex, symbolsForThisGame[symbolIndex]);
}
}
}
[ServerRpc(RequireOwnership = false)]
private void AddClient_ServerRpc(ulong id)
{
m_targetSequenceIndexPerPlayer.Add(id, 0);
}
// Very simple random selection. Duplicates are allowed.
private static List<int> SelectSymbols(int numOptions, int targetCount)
{
List<int> list = new List<int>();
for (int n = 0; n < targetCount; n++)
list.Add(UnityEngine.Random.Range(0, numOptions));
return list;
}
public void Update()
{
// A client can't guarantee timing with the host's selection of the target sequence, so retrieve it once it's available.
if (!m_HasReceivedTargetSequence && m_targetSequence.Count > 0)
{
for (int n = 0; n < m_targetSequence.Count; n++)
m_TargetSequenceOutput[n].sprite = m_SymbolData.GetSymbolForIndex(m_targetSequence[n]);
m_HasReceivedTargetSequence = true;
ScaleTargetUi(m_LocalId, 0);
}
}
/// <summary>
/// If the index is correct, this will advance the current sequence index.
/// </summary>
/// <returns>True if the correct symbol index was chosen, false otherwise.</returns>
public bool ConfirmSymbolCorrect(ulong id, int symbolIndex)
{
int index = m_targetSequenceIndexPerPlayer[id];
if (symbolIndex != m_targetSequence[index])
return false;
if (++index >= m_targetSequence.Count)
index = 0;
m_targetSequenceIndexPerPlayer[id] = index;
ScaleTargetUi_ClientRpc(id, index);
return true;
}
[ClientRpc]
private void ScaleTargetUi_ClientRpc(ulong id, int sequenceIndex)
{
ScaleTargetUi(id, sequenceIndex);
}
private void ScaleTargetUi(ulong id, int sequenceIndex)
{
if (NetworkManager.Singleton.LocalClientId == id)
for (int i = 0; i < m_TargetSequenceOutput.Length; i++)
m_TargetSequenceOutput[i].transform.localScale =
Vector3.one * (sequenceIndex == i || !m_CanAnimateTargets ? 1 : 0.7f);
}
public int GetNextSymbol(int symbolObjectIndex)
{
return m_FullSequenceServer[symbolObjectIndex];
}
public void SetTargetsAnimatable()
{
m_CanAnimateTargets = true;
ScaleTargetUi(m_LocalId, 0);
}
/// <summary>
/// Used for the binary space partition (BSP) algorithm, which makes alternating "cuts" to subdivide rectangles while maintaining a buffer of space between them.
/// This ensures all symbols will be randomly (though not uniformly) distributed without overlapping each other.
/// </summary>
private struct RectCut
{
public Rect rect;
// The spawn region will be much taller than it is wide, so we'll do more horizontal cuts (instead of just alternating between horizontal and vertical).
public int cutIndex;
public bool isVertCut
{
get { return cutIndex % 3 == 2; }
}
public RectCut(Rect rect, int cutIndex)
{
this.rect = rect;
this.cutIndex = cutIndex;
}
public RectCut(float xMin, float xMax, float yMin, float yMax, int cutIndex)
{
this.rect = new Rect(xMin, yMin, xMax - xMin, yMax - yMin);
this.cutIndex = cutIndex;
}
}
/// <summary>
/// Selects a randomized series of spawn positions within the provided xy-bounds, or just a simple grid of positions if selection fails.
/// </summary>
/// <param name="bounds">Rectangle of space to subdivide.</param>
/// <param name="extent">The minimum space between points, to ensure that spawned symbol objects won't overlap.</param>
/// <param name="count">How many positions to choose.</param>
/// <returns>Position list in arbitrary order.</returns>
public List<Vector2> GenerateRandomSpawnPoints(Rect bounds, float extent, int count = symbolCount)
{
int numTries = 3;
List<Vector2> points = new List<Vector2>();
while (numTries > 0)
{
Queue<RectCut> rects = new Queue<RectCut>();
points.Clear();
rects.Enqueue(new RectCut(bounds,
-1)); // Start with an extra horizontal cut since the space is so tall.
// For each rect, subdivide it with an alternating cut, and then enqueue the two smaller rects for recursion until enough points are chosen or the rects are all too small.
while (rects.Count + points.Count < count && rects.Count > 0)
{
RectCut currRect = rects.Dequeue();
bool isLargeEnough = (currRect.isVertCut && currRect.rect.width > extent * 2) ||
(!currRect.isVertCut && currRect.rect.height > extent * 2);
if (!isLargeEnough)
{
points.Add(currRect.rect.center);
continue;
}
float xMin = currRect.rect.xMin,
xMax = currRect.rect.xMax,
yMin = currRect.rect.yMin,
yMax = currRect.rect.yMax;
if (currRect.isVertCut)
{
float cutPosX = Random.Range(xMin + extent, xMax - extent);
rects.Enqueue(new RectCut(xMin, cutPosX, yMin, yMax, currRect.cutIndex + 1));
rects.Enqueue(new RectCut(cutPosX, xMax, yMin, yMax, currRect.cutIndex + 1));
}
else
{
float cutPosY = Random.Range(yMin + extent, yMax - extent);
rects.Enqueue(new RectCut(xMin, xMax, yMin, cutPosY, currRect.cutIndex + 1));
rects.Enqueue(new RectCut(xMin, xMax, cutPosY, yMax, currRect.cutIndex + 1));
}
}
while (rects.Count > 0)
points.Add(rects.Dequeue().rect.center);
if (points.Count >= count)
return points;
numTries--;
}
Debug.LogError("Failed to generate symbol spawn points. Defaulting to a simple grid of points.");
points.Clear();
int numPerLine = Mathf.CeilToInt(bounds.width / (extent * 1.5f));
for (int n = 0; n < count; n++)
points.Add(new Vector2(Mathf.Lerp(bounds.xMin, bounds.xMax, (n % numPerLine) / (numPerLine - 1f)),
n / numPerLine * extent * 1.5f));
return points;
}
}
} | 1 | 0.941008 | 1 | 0.941008 | game-dev | MEDIA | 0.561371 | game-dev | 0.980785 | 1 | 0.980785 |
showlab/BYOC | 7,855 | BlendshapeToolkit/Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/Raycasters/PhysicsRaycaster.cs | using System.Collections.Generic;
using UnityEngine.UI;
namespace UnityEngine.EventSystems
{
/// <summary>
/// Simple event system using physics raycasts.
/// </summary>
[AddComponentMenu("Event/Physics Raycaster")]
[RequireComponent(typeof(Camera))]
/// <summary>
/// Raycaster for casting against 3D Physics components.
/// </summary>
public class PhysicsRaycaster : BaseRaycaster
{
/// <summary>
/// Const to use for clarity when no event mask is set
/// </summary>
protected const int kNoEventMaskSet = -1;
protected Camera m_EventCamera;
/// <summary>
/// Layer mask used to filter events. Always combined with the camera's culling mask if a camera is used.
/// </summary>
[SerializeField]
protected LayerMask m_EventMask = kNoEventMaskSet;
/// <summary>
/// The max number of intersections allowed. 0 = allocating version anything else is non alloc.
/// </summary>
[SerializeField]
protected int m_MaxRayIntersections = 0;
protected int m_LastMaxRayIntersections = 0;
#if PACKAGE_PHYSICS
RaycastHit[] m_Hits;
#endif
protected PhysicsRaycaster()
{}
public override Camera eventCamera
{
get
{
if (m_EventCamera == null)
m_EventCamera = GetComponent<Camera>();
return m_EventCamera ?? Camera.main;
}
}
/// <summary>
/// Depth used to determine the order of event processing.
/// </summary>
public virtual int depth
{
get { return (eventCamera != null) ? (int)eventCamera.depth : 0xFFFFFF; }
}
/// <summary>
/// Event mask used to determine which objects will receive events.
/// </summary>
public int finalEventMask
{
get { return (eventCamera != null) ? eventCamera.cullingMask & m_EventMask : kNoEventMaskSet; }
}
/// <summary>
/// Layer mask used to filter events. Always combined with the camera's culling mask if a camera is used.
/// </summary>
public LayerMask eventMask
{
get { return m_EventMask; }
set { m_EventMask = value; }
}
/// <summary>
/// Max number of ray intersection allowed to be found.
/// </summary>
/// <remarks>
/// A value of zero will represent using the allocating version of the raycast function where as any other value will use the non allocating version.
/// </remarks>
public int maxRayIntersections
{
get { return m_MaxRayIntersections; }
set { m_MaxRayIntersections = value; }
}
/// <summary>
/// Returns a ray going from camera through the event position and the distance between the near and far clipping planes along that ray.
/// </summary>
/// <param name="eventData">The pointer event for which we will cast a ray.</param>
/// <param name="ray">The ray to use.</param>
/// <param name="eventDisplayIndex">The display index used.</param>
/// <param name="distanceToClipPlane">The distance between the near and far clipping planes along the ray.</param>
/// <returns>True if the operation was successful. false if it was not possible to compute, such as the eventPosition being outside of the view.</returns>
protected bool ComputeRayAndDistance(PointerEventData eventData, ref Ray ray, ref int eventDisplayIndex, ref float distanceToClipPlane)
{
if (eventCamera == null)
return false;
var eventPosition = MultipleDisplayUtilities.RelativeMouseAtScaled(eventData.position);
if (eventPosition != Vector3.zero)
{
// We support multiple display and display identification based on event position.
eventDisplayIndex = (int)eventPosition.z;
// Discard events that are not part of this display so the user does not interact with multiple displays at once.
if (eventDisplayIndex != eventCamera.targetDisplay)
return false;
}
else
{
// The multiple display system is not supported on all platforms, when it is not supported the returned position
// will be all zeros so when the returned index is 0 we will default to the event data to be safe.
eventPosition = eventData.position;
}
// Cull ray casts that are outside of the view rect. (case 636595)
if (!eventCamera.pixelRect.Contains(eventPosition))
return false;
ray = eventCamera.ScreenPointToRay(eventPosition);
// compensate far plane distance - see MouseEvents.cs
float projectionDirection = ray.direction.z;
distanceToClipPlane = Mathf.Approximately(0.0f, projectionDirection)
? Mathf.Infinity
: Mathf.Abs((eventCamera.farClipPlane - eventCamera.nearClipPlane) / projectionDirection);
return true;
}
public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList)
{
#if PACKAGE_PHYSICS
Ray ray = new Ray();
int displayIndex = 0;
float distanceToClipPlane = 0;
if (!ComputeRayAndDistance(eventData, ref ray, ref displayIndex, ref distanceToClipPlane))
return;
int hitCount = 0;
if (m_MaxRayIntersections == 0)
{
if (ReflectionMethodsCache.Singleton.raycast3DAll == null)
return;
m_Hits = ReflectionMethodsCache.Singleton.raycast3DAll(ray, distanceToClipPlane, finalEventMask);
hitCount = m_Hits.Length;
}
else
{
if (ReflectionMethodsCache.Singleton.getRaycastNonAlloc == null)
return;
if (m_LastMaxRayIntersections != m_MaxRayIntersections)
{
m_Hits = new RaycastHit[m_MaxRayIntersections];
m_LastMaxRayIntersections = m_MaxRayIntersections;
}
hitCount = ReflectionMethodsCache.Singleton.getRaycastNonAlloc(ray, m_Hits, distanceToClipPlane, finalEventMask);
}
if (hitCount != 0)
{
if (hitCount > 1)
System.Array.Sort(m_Hits, 0, hitCount, RaycastHitComparer.instance);
for (int b = 0, bmax = hitCount; b < bmax; ++b)
{
var result = new RaycastResult
{
gameObject = m_Hits[b].collider.gameObject,
module = this,
distance = m_Hits[b].distance,
worldPosition = m_Hits[b].point,
worldNormal = m_Hits[b].normal,
screenPosition = eventData.position,
displayIndex = displayIndex,
index = resultAppendList.Count,
sortingLayer = 0,
sortingOrder = 0
};
resultAppendList.Add(result);
}
}
#endif
}
#if PACKAGE_PHYSICS
private class RaycastHitComparer : IComparer<RaycastHit>
{
public static RaycastHitComparer instance = new RaycastHitComparer();
public int Compare(RaycastHit x, RaycastHit y)
{
return x.distance.CompareTo(y.distance);
}
}
#endif
}
}
| 1 | 0.877949 | 1 | 0.877949 | game-dev | MEDIA | 0.896895 | game-dev | 0.98124 | 1 | 0.98124 |
qcad/qcad | 16,121 | src/scripting/ecmaapi/generated/REcmaFontList.cpp | // ***** AUTOGENERATED CODE, DO NOT EDIT *****
// ***** This class is not copyable.
#include "REcmaFontList.h"
#include "RMetaTypes.h"
#include "../REcmaHelper.h"
// forwards declarations mapped to includes
// includes for base ecma wrapper classes
void REcmaFontList::initEcma(QScriptEngine& engine, QScriptValue* proto
)
{
bool protoCreated = false;
if(proto == NULL){
proto = new QScriptValue(engine.newVariant(qVariantFromValue(
(RFontList*) 0)));
protoCreated = true;
}
QScriptValue fun;
// toString:
REcmaHelper::registerFunction(&engine, proto, toString, "toString");
// destroy:
REcmaHelper::registerFunction(&engine, proto, destroy, "destroy");
// get class name
REcmaHelper::registerFunction(&engine, proto, getClassName, "getClassName");
// conversion to all base classes (multiple inheritance):
REcmaHelper::registerFunction(&engine, proto, getBaseClasses, "getBaseClasses");
// properties:
// methods:
engine.setDefaultPrototype(
qMetaTypeId<RFontList*>(), *proto);
QScriptValue ctor = engine.newFunction(createEcma, *proto, 2);
// static methods:
REcmaHelper::registerFunction(&engine, &ctor, init, "init");
REcmaHelper::registerFunction(&engine, &ctor, initSubstitutions, "initSubstitutions");
REcmaHelper::registerFunction(&engine, &ctor, uninit, "uninit");
REcmaHelper::registerFunction(&engine, &ctor, getNames, "getNames");
REcmaHelper::registerFunction(&engine, &ctor, getSubName, "getSubName");
REcmaHelper::registerFunction(&engine, &ctor, get, "get");
REcmaHelper::registerFunction(&engine, &ctor, isCadFont, "isCadFont");
// static properties:
// enum values:
// enum conversions:
// init class:
engine.globalObject().setProperty("RFontList",
ctor, QScriptValue::SkipInEnumeration);
if( protoCreated ){
delete proto;
}
}
QScriptValue REcmaFontList::createEcma(QScriptContext* context, QScriptEngine* engine)
{
if (context->thisObject().strictlyEquals(
engine->globalObject())) {
return REcmaHelper::throwError(
QString::fromLatin1("RFontList(): Did you forget to construct with 'new'?"),
context);
}
QScriptValue result;
// constructor without variants:
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ constructor:
// non-copyable class:
RFontList
* cppResult =
new
RFontList
();
// TODO: triggers: Warning: QScriptEngine::newVariant(): changing class of non-QScriptObject not supported:
result = engine->newVariant(context->thisObject(), qVariantFromValue(cppResult));
} else
{
return REcmaHelper::throwError(
QString::fromLatin1("RFontList(): no matching constructor found."),
context);
}
return result;
}
// conversion functions for base classes:
// returns class name:
QScriptValue REcmaFontList::getClassName(QScriptContext *context, QScriptEngine *engine)
{
return qScriptValueFromValue(engine, QString("RFontList"));
}
// returns all base classes (in case of multiple inheritance):
QScriptValue REcmaFontList::getBaseClasses(QScriptContext *context, QScriptEngine *engine)
{
QStringList list;
return qScriptValueFromSequence(engine, list);
}
// properties:
// public methods:
QScriptValue
REcmaFontList::init
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaFontList::init", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaFontList::init";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'void'
RFontList::
init();
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RFontList.init().",
context);
}
//REcmaHelper::functionEnd("REcmaFontList::init", context, engine);
return result;
}
QScriptValue
REcmaFontList::initSubstitutions
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaFontList::initSubstitutions", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaFontList::initSubstitutions";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'void'
RFontList::
initSubstitutions();
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RFontList.initSubstitutions().",
context);
}
//REcmaHelper::functionEnd("REcmaFontList::initSubstitutions", context, engine);
return result;
}
QScriptValue
REcmaFontList::uninit
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaFontList::uninit", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaFontList::uninit";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'void'
RFontList::
uninit();
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RFontList.uninit().",
context);
}
//REcmaHelper::functionEnd("REcmaFontList::uninit", context, engine);
return result;
}
QScriptValue
REcmaFontList::getNames
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaFontList::getNames", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaFontList::getNames";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
0
){
// prepare arguments:
// end of arguments
// call C++ function:
// return type 'QStringList'
QStringList cppResult =
RFontList::
getNames();
// return type: QStringList
// not standard type nor reference
result = qScriptValueFromValue(engine, cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RFontList.getNames().",
context);
}
//REcmaHelper::functionEnd("REcmaFontList::getNames", context, engine);
return result;
}
QScriptValue
REcmaFontList::getSubName
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaFontList::getSubName", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaFontList::getSubName";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
1 && (
context->argument(0).isString()
) /* type: QString */
){
// prepare arguments:
// argument isStandardType
QString
a0 =
(QString)
context->argument( 0 ).
toString();
// end of arguments
// call C++ function:
// return type 'QString'
QString cppResult =
RFontList::
getSubName(a0);
// return type: QString
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RFontList.getSubName().",
context);
}
//REcmaHelper::functionEnd("REcmaFontList::getSubName", context, engine);
return result;
}
QScriptValue
REcmaFontList::get
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaFontList::get", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaFontList::get";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
1 && (
context->argument(0).isString()
) /* type: QString */
){
// prepare arguments:
// argument isStandardType
QString
a0 =
(QString)
context->argument( 0 ).
toString();
// end of arguments
// call C++ function:
// return type 'RFont *'
RFont * cppResult =
RFontList::
get(a0);
// return type: RFont *
// not standard type nor reference
result = qScriptValueFromValue(engine, cppResult);
} else
if( context->argumentCount() ==
2 && (
context->argument(0).isString()
) /* type: QString */
&& (
context->argument(1).isBool()
) /* type: bool */
){
// prepare arguments:
// argument isStandardType
QString
a0 =
(QString)
context->argument( 0 ).
toString();
// argument isStandardType
bool
a1 =
(bool)
context->argument( 1 ).
toBool();
// end of arguments
// call C++ function:
// return type 'RFont *'
RFont * cppResult =
RFontList::
get(a0
,
a1);
// return type: RFont *
// not standard type nor reference
result = qScriptValueFromValue(engine, cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RFontList.get().",
context);
}
//REcmaHelper::functionEnd("REcmaFontList::get", context, engine);
return result;
}
QScriptValue
REcmaFontList::isCadFont
(QScriptContext* context, QScriptEngine* engine)
{
//REcmaHelper::functionStart("REcmaFontList::isCadFont", context, engine);
//qDebug() << "ECMAScript WRAPPER: REcmaFontList::isCadFont";
//QCoreApplication::processEvents();
QScriptValue result = engine->undefinedValue();
if( context->argumentCount() ==
2 && (
context->argument(0).isString()
) /* type: QString */
&& (
context->argument(1).isString()
) /* type: QString */
){
// prepare arguments:
// argument isStandardType
QString
a0 =
(QString)
context->argument( 0 ).
toString();
// argument isStandardType
QString
a1 =
(QString)
context->argument( 1 ).
toString();
// end of arguments
// call C++ function:
// return type 'bool'
bool cppResult =
RFontList::
isCadFont(a0
,
a1);
// return type: bool
// standard Type
result = QScriptValue(cppResult);
} else
{
return REcmaHelper::throwError("Wrong number/types of arguments for RFontList.isCadFont().",
context);
}
//REcmaHelper::functionEnd("REcmaFontList::isCadFont", context, engine);
return result;
}
QScriptValue REcmaFontList::toString
(QScriptContext *context, QScriptEngine *engine)
{
RFontList* self = getSelf("toString", context);
QString result;
result = QString("RFontList(0x%1)").arg((unsigned long int)self, 0, 16);
return QScriptValue(result);
}
QScriptValue REcmaFontList::destroy(QScriptContext *context, QScriptEngine *engine)
{
RFontList* self = getSelf("RFontList", context);
//Q_ASSERT(self!=NULL);
if (self==NULL) {
return REcmaHelper::throwError("self is NULL", context);
}
delete self;
context->thisObject().setData(engine->nullValue());
context->thisObject().prototype().setData(engine->nullValue());
context->thisObject().setPrototype(engine->nullValue());
context->thisObject().setScriptClass(NULL);
return engine->undefinedValue();
}
RFontList* REcmaFontList::getSelf(const QString& fName, QScriptContext* context)
{
RFontList* self = NULL;
// self could be a normal object (e.g. from an UI file) or
// an ECMA shell object (made from an ECMA script):
//self = getSelfShell(fName, context);
//if (self==NULL) {
self = REcmaHelper::scriptValueTo<RFontList >(context->thisObject())
;
//}
if (self == NULL){
// avoid recursion (toString is used by the backtrace):
if (fName!="toString") {
REcmaHelper::throwError(QString("RFontList.%1(): "
"This object is not a RFontList").arg(fName),
context);
}
return NULL;
}
return self;
}
RFontList* REcmaFontList::getSelfShell(const QString& fName, QScriptContext* context)
{
RFontList* selfBase = getSelf(fName, context);
RFontList* self = dynamic_cast<RFontList*>(selfBase);
//return REcmaHelper::scriptValueTo<RFontList >(context->thisObject());
if(self == NULL){
REcmaHelper::throwError(QString("RFontList.%1(): "
"This object is not a RFontList").arg(fName),
context);
}
return self;
}
| 1 | 0.920626 | 1 | 0.920626 | game-dev | MEDIA | 0.225149 | game-dev | 0.914428 | 1 | 0.914428 |
CafeFPS/r5_flowstate | 1,318 | vscripts/titan/_titan_commands.gnut | untyped
global function TitanCommands_Init
function TitanCommands_Init()
{
if ( GetCurrentPlaylistVarInt( "titan_move_command_enabled", 0 ) == 0 )
return
AddClientCommandCallback( "PrototypeOrderTitanMove", Prototype_OrderTitanMove )
RegisterSignal( "Prototype_TitanMove" )
}
bool function Prototype_OrderTitanMove( entity player, array<string> args )
{
Assert( args.len() == 3 )
vector pos = Vector( args[0].tofloat(), args[1].tofloat(), args[2].tofloat() )
DebugDrawLine( pos, pos + Vector(0,0,500), 255, 0, 0, true, 5.0 )
entity titan = player.GetPetTitan()
if ( !IsAlive( titan ) )
return true
thread Prototype_TitanMove( player, titan, pos )
return true
}
void function Prototype_TitanMove( entity player, entity titan, vector origin )
{
titan.Signal( "Prototype_TitanMove" )
titan.EndSignal( "Prototype_TitanMove" )
titan.EndSignal( "ChangedTitanMode" )
titan.EndSignal( "OnDeath" )
local mode = player.GetPetTitanMode()
if ( mode != eNPCTitanMode.STAY ) // assuming there are only 2 modes
{
player.SetPetTitanMode( eNPCTitanMode.STAY )
titan.DisableBehavior( "Follow" )
// #if R1_VGUI_MINIMAP
// titan.Minimap_SetBossPlayerMaterial( $"vgui/HUD/threathud_titan_friendlyself_guard" )
// #endif
titan.AssaultSetOrigin( origin )
}
AssaultOrigin( titan, origin, 100 )
} | 1 | 0.807943 | 1 | 0.807943 | game-dev | MEDIA | 0.994085 | game-dev | 0.959353 | 1 | 0.959353 |
punesemu/puNES | 16,399 | src/gui/nes20db.cpp | /*
* Copyright (C) 2010-2026 Fabio Cavallo (aka FHorse)
*
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <string.h>
#include <QtCore/QMap>
#include <QtCore/QFile>
#include <QtCore/QXmlStreamReader>
#include <QtCore/QStandardPaths>
#include "nes20db.h"
#include "version.h"
#include "gui.h"
#include "info.h"
#include "memmap.h"
#include "vs_system.h"
#define NES20DBFILENAME "nes20db.xml"
typedef QMap<QString, QString> game_map;
bool search_in_xml(QFile &file);
game_map parse_game(QXmlStreamReader &xml);
bool is_game_element(const QXmlStreamReader &xml);
void add_element_data_to_map(const QString &element_name, const QString &text, game_map &map);
void add_element_data_to_map(QXmlStreamReader &xml, game_map &map);
void populate_game_info(_nes20db &game_info, game_map &map);
uint32_t to_uint(const QString &svalue, int base, int def = 0);
uint32_t to_mirroring(const QString &svalue);
_nes20db nes20db;
void nes20db_reset(void) {
::memset((void *)&nes20db, 0x00, sizeof(_nes20db));
}
BYTE nes20db_search(void) {
QStringList gdl = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
QStringList data_locations;
const QString gdf = uQString(gui_extract_base(gui_data_folder()));
const QString gaf = uQString(gui_application_folder());
bool finded = false;
nes20db_reset();
// elimino la gui_data_folder() e la gui_application_folder() dall'elenco perche' voglio che siano le ultime voci.
gdl.removeAll(gdf);
if (gdf.compare(gaf)) {
gdl.removeAll(gaf);
gdl.append(gdf);
}
foreach(const QString path, gdl) {
data_locations.append(QString("%0/%1").arg(path, NAME));
}
data_locations.append(gaf);
info.mapper.nes20db.in_use = FALSE;
foreach(const QString path, data_locations) {
QFile file(QString("%0/%1").arg(path, NES20DBFILENAME));
if (file.exists()) {
if (search_in_xml(file)) {
finded = true;
}
}
}
return (finded);
}
bool search_in_xml(QFile &file) {
bool finded = false;
// Just "rom" is the entirety of the ROM file without header, including PRG-, CHR- and Misc ROM. It's what you look
// up when being confronted with a headerless ROM file (see note 2).
// "prgram","prgnvram","chrram","chrnvram","chrrom","miscrom" tags are only present if the respective memory type
// is present.
// "sum16" is a simple sum of all bytes in a particular ROM type, truncated to 16 bits; this value can be found in
// Nintendo's leaked internal spreadsheet.
// "console type", "console region", "expansion type", "vs hardware" and "vs ppu" are just the direct values defined
// for the NES 2.0 header; I did not want to use text strings that have to be looked up.
// "mirroring" can be:
// For normal mappers:
// "H", meaning that byte 6's LSB nibble is set to 0..0
// "V", meaning that byte 6's LSB nibble is set to 0..1
// "4", meaning that byte 6's LSB nibble is set to 1..0
// For mapper 030's idiosyncratic use of the NES header's mirroring bits:
// "H", meaning that byte 6's LSB nibble is set to 0..0
// "V", meaning that byte 6's LSB nibble is set to 0..1
// "1", meaning that byte 6's LSB nibble is set to 1..0
// "4", meaning that byte 6's LSB nibble is set to 1..1
// For mapper 218's idiosyncratic use of the NES header's mirroring bits:
// "H", meaning that byte 6's LSB nibble is set to 0..0
// "V", meaning that byte 6's LSB nibble is set to 0..1
// "0", meaning that byte 6's LSB nibble is set to 1..0
// "1", meaning that byte 6's LSB nibble is set to 1..1
//
// Notes:
//
// The database should be complete for all dumped licensed and original unlicensed games, and will be continuously
// updated to include more homebrew games/hacks/translations, pirate dumps and plug-and-play consoles, as well as
// corrections. As it is created automatically from a master set of headered ROM files, I cannot process pull requests
// on the XML text data; instead, simply point out errors or omissions by posting replies to this thread.
// When comparing file hashes against the database's full "rom" hash, be sure to compute two hashes:
// one that trusts and uses an existing header's ROM size fields to know how many bytes to hash,
// one that ignores any existing header completely and just hashes the entire file sans header.
// Searching for the first hash value will fail if an otherwise complete ROM has a header with incorrect size fields.
// Searching for the second hash value will fail if the file has common trailing garbage at the end,
// such as "This file downloaded from website x". Searching for both hashes will maximize the chances of identifying
// ROM files with bad headers or trailing garbage bytes. ROM files that have simultaneously trailing garbage and
// incorrect sizes specified in the header, or no header at all and trailing garbage, cannot be identified without
// human intervention. ;)
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QXmlStreamReader xmlReader(&file);
while (!xmlReader.atEnd() && !xmlReader.hasError()) {
const QXmlStreamReader::TokenType token = xmlReader.readNext();
if (token == QXmlStreamReader::StartDocument) {
continue;
}
if (token == QXmlStreamReader::StartElement) {
if (!xmlReader.name().toString().compare("nes20db", Qt::CaseInsensitive)) {
continue;
}
if (!xmlReader.name().toString().compare("game", Qt::CaseInsensitive)) {
game_map game = parse_game(xmlReader);
if (game.count() > 0) {
populate_game_info(nes20db, game);
// Ho deciso di usare solo il crc32 total (tralasciando quello della prgrom perche' ci sono
// roms con lo stesso crc32 ma usano mapper diverse :
// Esempio :
// Angry Birds Week(byCasperdj777).nes (0x2A629F7D mapper 185) e
// Compatibility Hacks\Bird Week [m003].nes (0x2A629F7D mapper 003)
if (nes20db.rom.crc32 == info.crc32.total) {
//const QString comment = game["comment"];
const BYTE old_format = info.format;
info.mapper.nes20db.in_use = TRUE;
info.format = NES_2_0;
// visto che con il NES_2_0 non eseguo la ricerca nel
// database inizializzo queste variabili.
info.mirroring_db = DEFAULT;
info.mapper.id = nes20db.pcb.mapper;
info.mapper.submapper_nes20 = nes20db.pcb.submapper;
info.mapper.submapper = info.mapper.submapper_nes20;
wram_set_ram_size(nes20db.prgram.size ? nes20db.prgram.size : 0);
wram_set_nvram_size(nes20db.prgnvram.size ? nes20db.prgnvram.size : 0);
vram_set_ram_size(0, nes20db.chrram.size ? nes20db.chrram.size : 0);
vram_set_nvram_size(0, nes20db.chrnvram.size ? nes20db.chrnvram.size : 0);
info.mapper.battery = nes20db.pcb.battery;
info.mapper.expansion = nes20db.expansion.type;
if (old_format != UNIF_FORMAT) {
info.mapper.prgrom_size = nes20db.prgrom.size;
info.mapper.prgrom_banks_16k = (nes20db.prgrom.size / S16K) +
((nes20db.prgrom.size % S16K) ? 1 : 0);
info.mapper.chrrom_size = nes20db.chrrom.size;
info.mapper.chrrom_banks_8k = (nes20db.chrrom.size / S8K) +
((nes20db.chrrom.size % S8K) ? 1 : 0);
}
// There is no such thing as an "initial mirroring" in the NES header.
// "Initial mirroring" is a peculiar behavior of FCEUX that was carried over from
// the old Nesticle emulator from a time when mapper 4 did not distinguish between
// actual MMC3 (with software-selectable mirroring) and
// Namco 108 (with hard-wired mirroring, now assigned to mapper 206).
// For mappers with software-selectable mirroring such as mapper 45, the
// mirroring bit of the NES header has no function. It does not specify
// an "initial mirroring", and must be ignored. And as the NES 2.0 Wiki
// article states, "Bit 0 is normally relevant only if the mapper does not
// allow the mirroring type to be switched. It should be set to zero otherwise.",
// which is the reason it is set to "Horizontal" (i.e. zero) in nes20db.
// Although Nintendo's original MMC3 has the power-on register state
// undefined (and thus potentially random), mapper 45's MMC3 clone,
// based on all hardware tests, seems to power on with all registers cleared
// to $00, which in the case of $A000 means Vertical mirroring.
// Of course, since this is a homebrew ROM file that likely was never
// tested on real hardware, actual hardware behavior is beside the point.
if (nes20db.pcb.mirroring != MIRRORING_HORIZONTAL) {
info.mapper.mirroring = nes20db.pcb.mirroring;
}
switch (nes20db.console.type) {
case 0:
case 1:
case 2:
info.decimal_mode = FALSE;
info.mapper.ext_console_type = nes20db.console.type;
vs_system.ppu = nes20db.vs.ppu;
vs_system.special_mode.type = nes20db.vs.hardware;
break;
case 3:
// usato per esempio da :
// Othello (rev0).nes
info.decimal_mode = TRUE;
break;
default:
info.mapper.ext_console_type = nes20db.console.type;
info.decimal_mode = FALSE;
break;
}
switch (nes20db.console.region) {
default:
case 0:
case 2:
info.machine[DATABASE] = NTSC;
break;
case 1:
info.machine[DATABASE] = PAL;
break;
case 3:
info.machine[DATABASE] = DENDY;
break;
}
finded = true;
break;
}
}
}
}
}
if (xmlReader.hasError()) {
//QMessageBox::critical(parent, tr("Error on reading the file"), xmlReader.errorString(), QMessageBox::Ok);
}
xmlReader.clear();
file.close();
}
return (finded);
}
game_map parse_game(QXmlStreamReader &xml) {
game_map game;
if ((xml.tokenType() != QXmlStreamReader::StartElement) && is_game_element(xml)) {
return (game);
}
xml.readNext();
while (!((xml.tokenType() == QXmlStreamReader::EndElement) && is_game_element(xml))) {
if (xml.tokenType() == QXmlStreamReader::Comment) {
add_element_data_to_map("comment", xml.text().toString(), game);
} else if (xml.tokenType() == QXmlStreamReader::StartElement) {
if (!xml.name().toString().compare("prgrom", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("chrrom", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("trainer", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("miscrom", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("rom", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("prgram", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("prgnvram", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("chrram", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("chrnvram", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("pcb", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("console", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("vs", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
if (!xml.name().toString().compare("expansion", Qt::CaseInsensitive)) {
add_element_data_to_map(xml, game);
}
}
xml.readNext();
}
if (!game.contains("prgrom_size") ||
!game.contains("prgrom_crc32") ||
!game.contains("rom_size") ||
!game.contains("rom_crc32") ||
!game.contains("pcb_mapper")) {
game.clear();
}
return (game);
}
bool is_game_element(const QXmlStreamReader &xml) {
return (!xml.name().toString().compare("game", Qt::CaseInsensitive));
}
void add_element_data_to_map(const QString &element_name, const QString &text, game_map &map) {
if (text.isNull() || text.isEmpty() || !text.compare("-")) {
return;
}
map.insert(element_name.toLower(), text);
}
void add_element_data_to_map(QXmlStreamReader &xml, game_map &map) {
if (xml.tokenType() != QXmlStreamReader::StartElement) {
return;
}
QString element_name = xml.name().toString();
QXmlStreamAttributes attribs = xml.attributes();
xml.readNext();
if (xml.tokenType() != QXmlStreamReader::EndElement) {
return;
}
for (const QXmlStreamAttribute &a : attribs) {
add_element_data_to_map(QString("%0_%1").arg(element_name, a.name().toString()),
a.value().toString(), map);
}
}
void populate_game_info(_nes20db &game_info, game_map &map) {
game_info.prgrom.size = to_uint(map["prgrom_size"], 10);
game_info.prgrom.crc32 = to_uint(map["prgrom_crc32"], 16);
game_info.chrrom.size = to_uint(map["chrrom_size"], 10);
game_info.chrrom.crc32 = to_uint(map["chrrom_crc32"], 16);
game_info.trainer.size = to_uint(map["trainer_size"], 10);
game_info.trainer.crc32 = to_uint(map["trainer_crc32"], 16);
game_info.miscrom.size = to_uint(map["miscrom_size"], 10);
game_info.miscrom.crc32 = to_uint(map["miscrom_crc32"], 16);
game_info.rom.size = to_uint(map["rom_size"], 10);
game_info.rom.crc32 = to_uint(map["rom_crc32"], 16);
game_info.prgram.size = to_uint(map["prgram_size"], 10);
game_info.prgnvram.size = to_uint(map["prgnvram_size"], 10);
game_info.chrram.size = to_uint(map["chrram_size"], 10);
game_info.chrnvram.size = to_uint(map["chrnvram_size"], 10);
game_info.pcb.mapper = to_uint(map["pcb_mapper"], 10);
game_info.pcb.submapper = to_uint(map["pcb_submapper"], 10);
game_info.pcb.mirroring = to_mirroring(map["pcb_mirroring"]);
game_info.pcb.battery = to_uint(map["pcb_battery"], 10);
game_info.console.type = to_uint(map["console_type"], 10);
game_info.console.region = to_uint(map["console_region"], 10);
game_info.vs.hardware = to_uint(map["vs_hardware"], 10);
game_info.vs.ppu = to_uint(map["vs_ppu"], 10);
game_info.expansion.type = to_uint(map["expansion_type"], 10);
}
uint32_t to_uint(const QString &svalue, const int base, const int def) {
uint32_t value = 0;
bool ok = false;
value = svalue.toUInt(&ok, base);
return (ok ? value : def);
}
uint32_t to_mirroring(const QString &svalue) {
// "H", meaning that byte 6's LSB nibble is set to 0..0
// "V", meaning that byte 6's LSB nibble is set to 0..1
// "4", meaning that byte 6's LSB nibble is set to 1..0
// For mapper 030's idiosyncratic use of the NES header's mirroring bits:
// "H", meaning that byte 6's LSB nibble is set to 0..0
// "V", meaning that byte 6's LSB nibble is set to 0..1
// "1", meaning that byte 6's LSB nibble is set to 1..0
// "4", meaning that byte 6's LSB nibble is set to 1..1
// For mapper 218's idiosyncratic use of the NES header's mirroring bits:
// "H", meaning that byte 6's LSB nibble is set to 0..0
// "V", meaning that byte 6's LSB nibble is set to 0..1
// "0", meaning that byte 6's LSB nibble is set to 1..0
// "1", meaning that byte 6's LSB nibble is set to 1..1
if (!svalue.compare("H", Qt::CaseInsensitive)) {
return (MIRRORING_HORIZONTAL);
}
if (!svalue.compare("V", Qt::CaseInsensitive)) {
return (MIRRORING_VERTICAL);
}
if (!svalue.compare("4", Qt::CaseInsensitive)) {
return (MIRRORING_FOURSCR);
}
if (!svalue.compare("0", Qt::CaseInsensitive)) {
return (MIRRORING_SINGLE_SCR0);
}
if (!svalue.compare("1", Qt::CaseInsensitive)) {
return (MIRRORING_SINGLE_SCR1);
}
return (MIRRORING_HORIZONTAL);
}
| 1 | 0.950636 | 1 | 0.950636 | game-dev | MEDIA | 0.586216 | game-dev | 0.984851 | 1 | 0.984851 |
CodeNMore/New-Beginner-Java-Game-Programming-Src | 1,426 | Episode 24/TileGame/src/dev/codenmore/tilegame/gfx/GameCamera.java | package dev.codenmore.tilegame.gfx;
import dev.codenmore.tilegame.Handler;
import dev.codenmore.tilegame.entities.Entity;
import dev.codenmore.tilegame.tiles.Tile;
public class GameCamera {
private Handler handler;
private float xOffset, yOffset;
public GameCamera(Handler handler, float xOffset, float yOffset){
this.handler = handler;
this.xOffset = xOffset;
this.yOffset = yOffset;
}
public void checkBlankSpace(){
if(xOffset < 0){
xOffset = 0;
}else if(xOffset > handler.getWorld().getWidth() * Tile.TILEWIDTH - handler.getWidth()){
xOffset = handler.getWorld().getWidth() * Tile.TILEWIDTH - handler.getWidth();
}
if(yOffset < 0){
yOffset = 0;
}else if(yOffset > handler.getWorld().getHeight() * Tile.TILEHEIGHT - handler.getHeight()){
yOffset = handler.getWorld().getHeight() * Tile.TILEHEIGHT - handler.getHeight();
}
}
public void centerOnEntity(Entity e){
xOffset = e.getX() - handler.getWidth() / 2 + e.getWidth() / 2;
yOffset = e.getY() - handler.getHeight() / 2 + e.getHeight() / 2;
checkBlankSpace();
}
public void move(float xAmt, float yAmt){
xOffset += xAmt;
yOffset += yAmt;
checkBlankSpace();
}
public float getxOffset() {
return xOffset;
}
public void setxOffset(float xOffset) {
this.xOffset = xOffset;
}
public float getyOffset() {
return yOffset;
}
public void setyOffset(float yOffset) {
this.yOffset = yOffset;
}
}
| 1 | 0.905298 | 1 | 0.905298 | game-dev | MEDIA | 0.784019 | game-dev | 0.791722 | 1 | 0.791722 |
coin-or/minotaur | 4,800 | src/base/KnapCovHandler.h | //
// Minotaur -- It's only 1/2 bull
//
// (C)opyright 2008 - 2025 The Minotaur Team.
//
/**
* \file KnapCovHandler.h
* \brief Declare the KnapCovHandler class for handling knapsack cover
* constraints. It generates the cuts whenever they are needed.
* \author Serdar Yildiz, Argonne National Laboratory
*/
#ifndef MINOTAURKNAPCOVHANDLER_H
#define MINOTAURKNAPCOVHANDLER_H
#include "Handler.h"
#include "Types.h"
#include "Solution.h"
#include "Variable.h"
#include "Relaxation.h"
#include "CoverCutGenerator.h"
namespace Minotaur {
// Pointers for knapsack cover cut handler are defined.
class KnapCovHandler;
typedef KnapCovHandler *KnapCovHandlerPtr;
typedef const KnapCovHandler *ConstKnapCovHandler;
class Logger;
struct KCStats
{
UInt knaps; /// Number of knapsacks solved.
UInt cuts; /// Number of cover cuts generated.
UInt extended; /// Number of extended cover cuts generated.
UInt simple; /// Number of simple lifted cuts generated.
UInt gns; /// Number of Gu, Nemhauser, Savelsbergh lifted cover cuts
/// generated.
UInt singlectwo; /// Number of general lifted cover cuts generated by
/// using a single element for C2 (downlifting).
double time; /// Total time used to generate cuts.
UInt cutdel; /// Number of cuts marked for deletion.
};
/**
* KnapCovHandler class considers knapsack cover cuts in the problem. It
* generates the cuts and manages them.
*/
class KnapCovHandler : public Handler {
public:
/// Default constructor.
KnapCovHandler();
/// Constructor.
KnapCovHandler(EnvPtr env, ProblemPtr problem);
/// Destroy
~KnapCovHandler();
/// Does nothing.
void relaxInitFull(RelaxationPtr, SolutionPool *, bool *) {};
/// Does nothing.
void relaxInitInc(RelaxationPtr, SolutionPool *, bool *) {};
/// Does nothing.
void relaxNodeFull(NodePtr, RelaxationPtr, bool *) {};
/// Does nothing.
void relaxNodeInc(NodePtr, RelaxationPtr, bool *) {};
/// Check if solution is feasible.
/// Checks all the constraints if they are satisfied by the given
/// solution.
bool isFeasible(ConstSolutionPtr sol, RelaxationPtr relaxation,
bool &should_prune, double &inf_meas);
/**
* We need separation for this handler to generate the knapsack cover
* cuts.
* A set of knapsack cover cuts will be generated.
*/
void separate(ConstSolutionPtr, NodePtr, RelaxationPtr,
CutManager *cutman, SolutionPoolPtr, ModVector &p_mods,
ModVector &r_mods, bool *, SeparationStatus *status);
/// Does nothing.
virtual void getBranchingCandidates(RelaxationPtr, const DoubleVector &,
ModVector &, BrVarCandSet &,
BrCandVector &, bool &) {};
/// Does nothing.
virtual ModificationPtr getBrMod(BrCandPtr, DoubleVector &, RelaxationPtr,
BranchDirection)
{
return ModificationPtr();
};
/// Does nothing.
virtual Branches getBranches(BrCandPtr, DoubleVector &, RelaxationPtr,
SolutionPoolPtr)
{
return Branches();
};
/// Does nothing.
SolveStatus presolve(PreModQ *, bool *, Solution **) { return Finished; };
/// Does nothing.
//void postsolveGetX(const double *, UInt, DoubleVector *) {};
// Does nothing.
virtual bool presolveNode(RelaxationPtr, NodePtr, SolutionPoolPtr,
ModVector &, ModVector &)
{
return false;
};
// Write name.
std::string getName() const;
/// Show statistics.
void writeStats(std::ostream &) const;
/// Updates the handler statistics by using returned information form
/// cover cut generator.
// void updateStats(ConsCovCutGenStatsPtr covstats);
// Return specific statistics.
UInt KC_knaps() { return stats_->knaps; }
UInt KC_cuts() { return stats_->cuts; }
UInt KC_extended() { return stats_->extended; }
UInt KC_simple() { return stats_->simple; }
UInt KC_gns() { return stats_->gns; }
UInt KC_singlectwo() { return stats_->singlectwo; }
double KC_time() { return stats_->time; }
private:
/// Environment.
EnvPtr env_;
/// The problem for which the handler is created.
ProblemPtr minlp_;
/// Log.
LoggerPtr logger_;
/// Statistics.
KCStats *stats_;
// Number of variables in the MINLP.
size_t numvars_;
/// Tolerance for checking integrality.
double intTol_;
/// For log:
static const std::string me_;
};
} //namespace Minotaur
#endif // MINOTAURKNAPCOVHANDLER_H
| 1 | 0.977576 | 1 | 0.977576 | game-dev | MEDIA | 0.635467 | game-dev | 0.778629 | 1 | 0.778629 |
Squalr/Squally | 1,082 | Source/Scenes/Platformer/Level/Combat/Attacks/Debuffs/ManaDrain/CastManaDrain.h | #pragma once
#include "Scenes/Platformer/Level/Combat/Attacks/PlatformerAttack.h"
class WorldSound;
class CastManaDrain : public PlatformerAttack
{
public:
static CastManaDrain* create(float attackDuration, float recoverDuration, Priority priority);
bool isWorthUsing(PlatformerEntity* caster, const std::vector<PlatformerEntity*>& sameTeam, const std::vector<PlatformerEntity*>& otherTeam) override;
float getUseUtility(PlatformerEntity* caster, PlatformerEntity* target, const std::vector<PlatformerEntity*>& sameTeam, const std::vector<PlatformerEntity*>& otherTeam) override;
LocalizedString* getString() override;
std::string getAttackAnimation() override;
protected:
CastManaDrain(float attackDuration, float recoverDuration, Priority priority);
virtual ~CastManaDrain();
void initializePositions() override;
void performAttack(PlatformerEntity* owner, std::vector<PlatformerEntity*> targets) override;
void onCleanup() override;
private:
typedef PlatformerAttack super;
PlatformerAttack* cloneInternal() override;
WorldSound* castSound = nullptr;
};
| 1 | 0.619013 | 1 | 0.619013 | game-dev | MEDIA | 0.975255 | game-dev | 0.53589 | 1 | 0.53589 |
pmmp/PocketMine-MP | 5,016 | src/entity/Attribute.php | <?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\entity;
use function max;
use function min;
class Attribute{
public const MC_PREFIX = "minecraft:";
public const ABSORPTION = self::MC_PREFIX . "absorption";
public const SATURATION = self::MC_PREFIX . "player.saturation";
public const EXHAUSTION = self::MC_PREFIX . "player.exhaustion";
public const KNOCKBACK_RESISTANCE = self::MC_PREFIX . "knockback_resistance";
public const HEALTH = self::MC_PREFIX . "health";
public const MOVEMENT_SPEED = self::MC_PREFIX . "movement";
public const FOLLOW_RANGE = self::MC_PREFIX . "follow_range";
public const HUNGER = self::MC_PREFIX . "player.hunger";
public const FOOD = self::HUNGER;
public const ATTACK_DAMAGE = self::MC_PREFIX . "attack_damage";
public const EXPERIENCE_LEVEL = self::MC_PREFIX . "player.level";
public const EXPERIENCE = self::MC_PREFIX . "player.experience";
public const UNDERWATER_MOVEMENT = self::MC_PREFIX . "underwater_movement";
public const LUCK = self::MC_PREFIX . "luck";
public const FALL_DAMAGE = self::MC_PREFIX . "fall_damage";
public const HORSE_JUMP_STRENGTH = self::MC_PREFIX . "horse.jump_strength";
public const ZOMBIE_SPAWN_REINFORCEMENTS = self::MC_PREFIX . "zombie.spawn_reinforcements";
public const LAVA_MOVEMENT = self::MC_PREFIX . "lava_movement";
protected float $currentValue;
protected bool $desynchronized = true;
public function __construct(
protected string $id,
protected float $minValue,
protected float $maxValue,
protected float $defaultValue,
protected bool $shouldSend = true
){
if($minValue > $maxValue || $defaultValue > $maxValue || $defaultValue < $minValue){
throw new \InvalidArgumentException("Invalid ranges: min value: $minValue, max value: $maxValue, $defaultValue: $defaultValue");
}
$this->currentValue = $this->defaultValue;
}
public function getMinValue() : float{
return $this->minValue;
}
/**
* @return $this
*/
public function setMinValue(float $minValue){
if($minValue > ($max = $this->getMaxValue())){
throw new \InvalidArgumentException("Minimum $minValue is greater than the maximum $max");
}
if($this->minValue !== $minValue){
$this->desynchronized = true;
$this->minValue = $minValue;
}
return $this;
}
public function getMaxValue() : float{
return $this->maxValue;
}
/**
* @return $this
*/
public function setMaxValue(float $maxValue){
if($maxValue < ($min = $this->getMinValue())){
throw new \InvalidArgumentException("Maximum $maxValue is less than the minimum $min");
}
if($this->maxValue !== $maxValue){
$this->desynchronized = true;
$this->maxValue = $maxValue;
}
return $this;
}
public function getDefaultValue() : float{
return $this->defaultValue;
}
/**
* @return $this
*/
public function setDefaultValue(float $defaultValue){
if($defaultValue > $this->getMaxValue() || $defaultValue < $this->getMinValue()){
throw new \InvalidArgumentException("Default $defaultValue is outside the range " . $this->getMinValue() . " - " . $this->getMaxValue());
}
if($this->defaultValue !== $defaultValue){
$this->desynchronized = true;
$this->defaultValue = $defaultValue;
}
return $this;
}
public function resetToDefault() : void{
$this->setValue($this->getDefaultValue(), true);
}
public function getValue() : float{
return $this->currentValue;
}
/**
* @return $this
*/
public function setValue(float $value, bool $fit = false, bool $forceSend = false){
if($value > $this->getMaxValue() || $value < $this->getMinValue()){
if(!$fit){
throw new \InvalidArgumentException("Value $value is outside the range " . $this->getMinValue() . " - " . $this->getMaxValue());
}
$value = min(max($value, $this->getMinValue()), $this->getMaxValue());
}
if($this->currentValue !== $value){
$this->desynchronized = true;
$this->currentValue = $value;
}elseif($forceSend){
$this->desynchronized = true;
}
return $this;
}
public function getId() : string{
return $this->id;
}
public function isSyncable() : bool{
return $this->shouldSend;
}
public function isDesynchronized() : bool{
return $this->shouldSend && $this->desynchronized;
}
public function markSynchronized(bool $synced = true) : void{
$this->desynchronized = !$synced;
}
}
| 1 | 0.894913 | 1 | 0.894913 | game-dev | MEDIA | 0.88615 | game-dev | 0.864244 | 1 | 0.864244 |
ParadiseSS13/Paradise | 1,045 | code/modules/procedural_mapping/mapGeneratorModules/nature.dm |
//Contents exist primarily for the nature generator test type.
//Pine Trees
/datum/map_generator_module/pine_trees
spawnableAtoms = list(/obj/structure/flora/tree/pine = 30)
//Dead Trees
/datum/map_generator_module/dead_trees
spawnableAtoms = list(/obj/structure/flora/tree/dead = 10)
//Random assortment of bushes
/datum/map_generator_module/rand_bushes
spawnableAtoms = list()
/datum/map_generator_module/rand_bushes/New()
..()
spawnableAtoms = typesof(/obj/structure/flora/ausbushes)
for(var/i in spawnableAtoms)
spawnableAtoms[i] = 20
//Random assortment of rocks and rockpiles
/datum/map_generator_module/rand_rocks
spawnableAtoms = list(/obj/structure/flora/rock = 40, /obj/structure/flora/rock/pile = 20)
//Grass turfs
/datum/map_generator_module/bottom_layer/grass_turfs
spawnableTurfs = list(/turf/simulated/floor/grass = 100)
//Grass tufts with a high spawn chance
/datum/map_generator_module/dense_layer/grass_tufts
spawnableTurfs = list()
spawnableAtoms = list(/obj/structure/flora/ausbushes/grassybush = 75)
| 1 | 0.773769 | 1 | 0.773769 | game-dev | MEDIA | 0.991881 | game-dev | 0.735067 | 1 | 0.735067 |
lordofduct/spacepuppy-unity-framework-4.0 | 7,154 | Framework/com.spacepuppy.ui/Runtime/src/UI/DraggableUIElement.cs | using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using com.spacepuppy;
using com.spacepuppy.Geom;
using com.spacepuppy.Utils;
using com.spacepuppy.Events;
using com.spacepuppy.Collections;
namespace com.spacepuppy.UI
{
[RequireComponent(typeof(RectTransform))]
public class DraggableUIElement : SPUIComponent, IUIComponent, IDragHandler, IBeginDragHandler, IEndDragHandler
{
public static readonly MultitonPool<DraggableUIElement> ActivelyDraggedElements = new MultitonPool<DraggableUIElement>();
#region Fields
[SerializeField]
private bool _duplicateSelfOnDrag;
[SerializeField]
private bool _maintainOriginalParent;
[SerializeField]
private bool _resetOnEnd;
[SerializeField]
[SPEvent.Config("this (DraggableUIElement)")]
private SPEvent _onDragBegin = new SPEvent("OnDragBegin");
[SerializeField]
[SPEvent.Config("this (DraggableUIElement)")]
private SPEvent _onDragEnd = new SPEvent("OnDragEnd");
[System.NonSerialized]
protected RectTransform _surface;
[System.NonSerialized]
protected DraggableUIElement _duplicateSource;
[System.NonSerialized]
private bool _calledCancel;
[System.NonSerialized]
private System.Action<IBeforeDragStartGlobalHandler> __beforeDragFunctor;
private System.Action<IBeforeDragStartGlobalHandler> _beforeDragFunctor => __beforeDragFunctor ?? (__beforeDragFunctor = (o) => o.OnBeforeDragStart(this));
#endregion
#region CONSTRUCTOR
protected override void OnDisable()
{
ActivelyDraggedElements.RemoveReference(this);
base.OnDisable();
}
#endregion
#region Properties
public bool DuplicateSelfOnDrag
{
get => _duplicateSelfOnDrag;
set => _duplicateSelfOnDrag = value;
}
public bool MaintainOriginalParent
{
get => _maintainOriginalParent;
set => _maintainOriginalParent = value;
}
public bool ResetOnEnd
{
get => _resetOnEnd;
set => _resetOnEnd = value;
}
public SPEvent OnDragBegin => _onDragBegin;
public SPEvent OnDragEnd => _onDragEnd;
public TransformStateCache LastBeginGlobalTransformation
{
get;
set;
}
public bool IsDuplicate => !object.ReferenceEquals(_duplicateSource, null);
#endregion
#region Methods
public void CancelDrag()
{
_calledCancel = true;
this.OnEndDrag(null);
}
void IBeginDragHandler.OnBeginDrag(PointerEventData eventData)
{
this.OnBeginDrag(eventData);
}
protected virtual void OnBeginDrag(PointerEventData eventData)
{
var surface = this.GetComponentInParent<Canvas>()?.transform as RectTransform;
if (surface == null) return;
_calledCancel = false;
Messaging.Broadcast(_beforeDragFunctor);
if (_calledCancel)
{
_calledCancel = false;
return;
}
if (_duplicateSelfOnDrag)
{
var clone = Instantiate(this, this.transform.position, this.transform.rotation, _maintainOriginalParent ? this.transform.parent : surface);
clone._duplicateSource = this;
var rts = this.transform as RectTransform;
var rtc = clone.transform as RectTransform;
if (rtc && rts)
{
rtc.sizeDelta = rts.sizeDelta;
}
eventData.pointerDrag = clone.gameObject;
clone.StartDrag(surface, eventData);
}
else
{
this.StartDrag(surface, eventData);
}
_onDragBegin.ActivateTrigger(this, this);
}
void IDragHandler.OnDrag(PointerEventData eventData)
{
this.OnDrag(eventData);
}
protected virtual void OnDrag(PointerEventData eventData)
{
if (_surface == null) return;
SetPositionInParent(eventData);
}
void IEndDragHandler.OnEndDrag(PointerEventData eventData)
{
this.OnEndDrag(eventData);
}
protected void OnEndDrag(PointerEventData eventData)
{
ActivelyDraggedElements.RemoveReference(this);
if (_surface == null) return;
if (this.IsDuplicate)
{
Destroy(this.gameObject);
if (_duplicateSource) _duplicateSource._onDragEnd.ActivateTrigger(this, null);
}
else
{
if (_resetOnEnd)
{
if (!_maintainOriginalParent)
{
this.transform.SetParent(this.LastBeginGlobalTransformation.Parent, true);
this.transform.SetSiblingIndex(this.LastBeginGlobalTransformation.SiblingIndex);
}
this.LastBeginGlobalTransformation.Trans.SetToGlobal(this.transform, false);
}
_onDragEnd.ActivateTrigger(this, this);
}
}
protected void SetPositionInParent(PointerEventData data)
{
var rt = this.transform as RectTransform;
Vector3 globalMousePos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(_surface, data.position, data.pressEventCamera, out globalMousePos))
{
rt.position = globalMousePos;
rt.rotation = _surface.rotation;
}
}
protected void StartDrag(RectTransform surface, PointerEventData eventData)
{
if (surface == null) throw new System.ArgumentNullException(nameof(surface));
ActivelyDraggedElements.AddReference(this);
_surface = surface;
this.LastBeginGlobalTransformation = TransformStateCache.GetGlobal(this.transform);
if (!_maintainOriginalParent)
{
this.transform.SetParent(_surface, true);
}
SetPositionInParent(eventData);
}
#endregion
#region Special Types
public struct TransformStateCache
{
public Trans Trans;
public Transform Parent;
public int SiblingIndex;
public static TransformStateCache GetGlobal(Transform t)
{
return new TransformStateCache()
{
Trans = Trans.GetGlobal(t),
Parent = t.parent,
SiblingIndex = t.GetSiblingIndex()
};
}
}
public interface IBeforeDragStartGlobalHandler
{
void OnBeforeDragStart(DraggableUIElement element);
}
#endregion
}
}
| 1 | 0.71706 | 1 | 0.71706 | game-dev | MEDIA | 0.913305 | game-dev | 0.682285 | 1 | 0.682285 |
Joshua-F/osrs-dumps | 2,030 | script/[clientscript,script6522].cs2 | // 6522
[clientscript,script6522](int $int0, component $component1, component $component2, component $component3)
sound_synth(synth_2266, 1, 0);
~xpdrops_setup_display_hoverdisable($component1);
if_sethide(false, $component2);
if_setonrelease("script6307(calc(clientclock + 10), $component1, $component2)", $component2);
def_boolean $boolean4 = ~on_mobile;
def_int $int5 = 17;
if ($boolean4 = true) {
$int5 = scale(8, 5, $int5);
}
cc_deleteall($component3);
.cc_create($component3, ^iftype_rectangle, 0);
.cc_setsize(0, calc($int5 + 2), ^setsize_minus, ^setsize_abs);
.cc_setfill(true);
.cc_setcolour(^white);
.cc_settrans(200);
.cc_sethide(true);
def_int $int6 = enum_getoutputcount(enum_4389);
def_int $int7 = 0;
def_int $int8 = -1;
def_int $int9 = 0;
while ($int9 < $int6) {
cc_create($component3, ^iftype_text, calc($int9 + 1));
$int8 = enum(int, int, enum_4389, $int9);
if ($int0 = 2 & $int8 = 2) {
cc_sethide(true);
} else {
cc_sethide(false);
cc_setsize(0, $int5, ^setsize_minus, ^setsize_abs);
cc_setcolour(0xff981f);
cc_settextshadow(true);
cc_settextfont(p12_full);
cc_settextalign(^settextalign_centre, ^settextalign_centre, 0);
cc_setop(1, "Select");
if ($boolean4 = false) {
cc_setonmouseover("xpdrops_setup_display_dropdown_hover(true, event_com, event_comsubid, .cc_getid, 0xff981f)");
cc_setonmouseleave("xpdrops_setup_display_dropdown_hover(false, event_com, event_comsubid, .cc_getid, 0xff981f)");
}
cc_setonop("br_loadout_spellbook_op(event_op, event_comsubid, $int0, $component1, $component2, $component3)");
cc_setposition(0, calc($int7 * $int5 + 2), ^setpos_abs_centre, ^setpos_abs_top);
cc_settext(enum(int, string, enum_4208, $int8));
$int7 = calc($int7 + 1);
}
$int9 = calc($int9 + 1);
}
~thinstonebox($component3, calc($int9 + 1));
if_setsize(if_getwidth($component3), calc($int7 * $int5 + 2 + 4), ^setsize_abs, ^setsize_abs, $component3);
| 1 | 0.828569 | 1 | 0.828569 | game-dev | MEDIA | 0.235878 | game-dev | 0.615977 | 1 | 0.615977 |
aurilisdev/Electrodynamics | 1,900 | src/main/java/electrodynamics/common/inventory/container/tile/ContainerAdvancedCompressor.java | package electrodynamics.common.inventory.container.tile;
import electrodynamics.common.tile.pipelines.gas.gastransformer.compressor.GenericTileAdvancedCompressor;
import electrodynamics.registers.ElectrodynamicsMenuTypes;
import net.minecraft.world.Container;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.inventory.ContainerData;
import net.minecraft.world.inventory.SimpleContainerData;
import voltaic.common.item.subtype.SubtypeItemUpgrade;
import voltaic.prefab.inventory.container.slot.item.type.SlotGas;
import voltaic.prefab.inventory.container.slot.item.type.SlotUpgrade;
import voltaic.prefab.inventory.container.types.GenericContainerBlockEntity;
public class ContainerAdvancedCompressor extends GenericContainerBlockEntity<GenericTileAdvancedCompressor.TileAdvancedCompressor> {
public static final SubtypeItemUpgrade[] VALID_UPGRADES = new SubtypeItemUpgrade[] { SubtypeItemUpgrade.advancedspeed, SubtypeItemUpgrade.basicspeed };
public ContainerAdvancedCompressor(int id, Inventory playerinv, Container inventory, ContainerData inventorydata) {
super(ElectrodynamicsMenuTypes.CONTAINER_ADVANCEDCOMPRESSOR.get(), id, playerinv, inventory, inventorydata);
}
public ContainerAdvancedCompressor(int id, Inventory playerInv) {
this(id, playerInv, new SimpleContainer(5), new SimpleContainerData(3));
}
@Override
public void addInventorySlots(Container inv, Inventory playerinv) {
setPlayerInvOffset(47);
addSlot(new SlotGas(inv, nextIndex(), 20, 50));
addSlot(new SlotGas(inv, nextIndex(), 109, 50));
addSlot(new SlotUpgrade(inv, nextIndex(), 153, 14, VALID_UPGRADES));
addSlot(new SlotUpgrade(inv, nextIndex(), 153, 34, VALID_UPGRADES));
addSlot(new SlotUpgrade(inv, nextIndex(), 153, 54, VALID_UPGRADES));
}
}
| 1 | 0.810233 | 1 | 0.810233 | game-dev | MEDIA | 0.995337 | game-dev | 0.922186 | 1 | 0.922186 |
ExpressLRS/ExpressLRS-Configurator | 5,300 | dependencies/windows_amd64/python/Lib/site-packages/setuptools/_distutils/_collections.py | import collections
import functools
import itertools
import operator
# from jaraco.collections 3.5.1
class DictStack(list, collections.abc.Mapping):
"""
A stack of dictionaries that behaves as a view on those dictionaries,
giving preference to the last.
>>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])
>>> stack['a']
2
>>> stack['b']
2
>>> stack['c']
2
>>> len(stack)
3
>>> stack.push(dict(a=3))
>>> stack['a']
3
>>> set(stack.keys()) == set(['a', 'b', 'c'])
True
>>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)])
True
>>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2)
True
>>> d = stack.pop()
>>> stack['a']
2
>>> d = stack.pop()
>>> stack['a']
1
>>> stack.get('b', None)
>>> 'c' in stack
True
"""
def __iter__(self):
dicts = list.__iter__(self)
return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts)))
def __getitem__(self, key):
for scope in reversed(tuple(list.__iter__(self))):
if key in scope:
return scope[key]
raise KeyError(key)
push = list.append
def __contains__(self, other):
return collections.abc.Mapping.__contains__(self, other)
def __len__(self):
return len(list(iter(self)))
# from jaraco.collections 3.7
class RangeMap(dict):
"""
A dictionary-like object that uses the keys as bounds for a range.
Inclusion of the value for that range is determined by the
key_match_comparator, which defaults to less-than-or-equal.
A value is returned for a key if it is the first key that matches in
the sorted list of keys.
One may supply keyword parameters to be passed to the sort function used
to sort keys (i.e. key, reverse) as sort_params.
Let's create a map that maps 1-3 -> 'a', 4-6 -> 'b'
>>> r = RangeMap({3: 'a', 6: 'b'}) # boy, that was easy
>>> r[1], r[2], r[3], r[4], r[5], r[6]
('a', 'a', 'a', 'b', 'b', 'b')
Even float values should work so long as the comparison operator
supports it.
>>> r[4.5]
'b'
But you'll notice that the way rangemap is defined, it must be open-ended
on one side.
>>> r[0]
'a'
>>> r[-1]
'a'
One can close the open-end of the RangeMap by using undefined_value
>>> r = RangeMap({0: RangeMap.undefined_value, 3: 'a', 6: 'b'})
>>> r[0]
Traceback (most recent call last):
...
KeyError: 0
One can get the first or last elements in the range by using RangeMap.Item
>>> last_item = RangeMap.Item(-1)
>>> r[last_item]
'b'
.last_item is a shortcut for Item(-1)
>>> r[RangeMap.last_item]
'b'
Sometimes it's useful to find the bounds for a RangeMap
>>> r.bounds()
(0, 6)
RangeMap supports .get(key, default)
>>> r.get(0, 'not found')
'not found'
>>> r.get(7, 'not found')
'not found'
One often wishes to define the ranges by their left-most values,
which requires use of sort params and a key_match_comparator.
>>> r = RangeMap({1: 'a', 4: 'b'},
... sort_params=dict(reverse=True),
... key_match_comparator=operator.ge)
>>> r[1], r[2], r[3], r[4], r[5], r[6]
('a', 'a', 'a', 'b', 'b', 'b')
That wasn't nearly as easy as before, so an alternate constructor
is provided:
>>> r = RangeMap.left({1: 'a', 4: 'b', 7: RangeMap.undefined_value})
>>> r[1], r[2], r[3], r[4], r[5], r[6]
('a', 'a', 'a', 'b', 'b', 'b')
"""
def __init__(self, source, sort_params={}, key_match_comparator=operator.le):
dict.__init__(self, source)
self.sort_params = sort_params
self.match = key_match_comparator
@classmethod
def left(cls, source):
return cls(
source, sort_params=dict(reverse=True), key_match_comparator=operator.ge
)
def __getitem__(self, item):
sorted_keys = sorted(self.keys(), **self.sort_params)
if isinstance(item, RangeMap.Item):
result = self.__getitem__(sorted_keys[item])
else:
key = self._find_first_match_(sorted_keys, item)
result = dict.__getitem__(self, key)
if result is RangeMap.undefined_value:
raise KeyError(key)
return result
def get(self, key, default=None):
"""
Return the value for key if key is in the dictionary, else default.
If default is not given, it defaults to None, so that this method
never raises a KeyError.
"""
try:
return self[key]
except KeyError:
return default
def _find_first_match_(self, keys, item):
is_match = functools.partial(self.match, item)
matches = list(filter(is_match, keys))
if matches:
return matches[0]
raise KeyError(item)
def bounds(self):
sorted_keys = sorted(self.keys(), **self.sort_params)
return (sorted_keys[RangeMap.first_item], sorted_keys[RangeMap.last_item])
# some special values for the RangeMap
undefined_value = type('RangeValueUndefined', (), {})()
class Item(int):
"RangeMap Item"
first_item = Item(0)
last_item = Item(-1)
| 1 | 0.772465 | 1 | 0.772465 | game-dev | MEDIA | 0.1916 | game-dev | 0.942108 | 1 | 0.942108 |
veerbia/pearai-app | 6,652 | src/vs/editor/standalone/test/browser/standaloneLanguages.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { Color } from 'vs/base/common/color';
import { Emitter } from 'vs/base/common/event';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils';
import { LanguageId, MetadataConsts } from 'vs/editor/common/encodedTokenAttributes';
import { IState, Token } from 'vs/editor/common/languages';
import { TokenTheme } from 'vs/editor/common/languages/supports/tokenization';
import { LanguageService } from 'vs/editor/common/services/languageService';
import { ILineTokens, IToken, TokenizationSupportAdapter, TokensProvider } from 'vs/editor/standalone/browser/standaloneLanguages';
import { IStandaloneTheme, IStandaloneThemeData, IStandaloneThemeService } from 'vs/editor/standalone/common/standaloneTheme';
import { UnthemedProductIconTheme } from 'vs/platform/theme/browser/iconsStyleSheet';
import { ColorIdentifier } from 'vs/platform/theme/common/colorRegistry';
import { ColorScheme } from 'vs/platform/theme/common/theme';
import { IColorTheme, IFileIconTheme, IProductIconTheme, ITokenStyle } from 'vs/platform/theme/common/themeService';
suite('TokenizationSupport2Adapter', () => {
ensureNoDisposablesAreLeakedInTestSuite();
const languageId = 'tttt';
// const tokenMetadata = (LanguageId.PlainText << MetadataConsts.LANGUAGEID_OFFSET);
class MockTokenTheme extends TokenTheme {
private counter = 0;
constructor() {
super(null!, null!);
}
public override match(languageId: LanguageId, token: string): number {
return (
((this.counter++) << MetadataConsts.FOREGROUND_OFFSET)
| (languageId << MetadataConsts.LANGUAGEID_OFFSET)
) >>> 0;
}
}
class MockThemeService implements IStandaloneThemeService {
declare readonly _serviceBrand: undefined;
public setTheme(themeName: string): string {
throw new Error('Not implemented');
}
public setAutoDetectHighContrast(autoDetectHighContrast: boolean): void {
throw new Error('Not implemented');
}
public defineTheme(themeName: string, themeData: IStandaloneThemeData): void {
throw new Error('Not implemented');
}
public getColorTheme(): IStandaloneTheme {
return {
label: 'mock',
tokenTheme: new MockTokenTheme(),
themeName: ColorScheme.LIGHT,
type: ColorScheme.LIGHT,
getColor: (color: ColorIdentifier, useDefault?: boolean): Color => {
throw new Error('Not implemented');
},
defines: (color: ColorIdentifier): boolean => {
throw new Error('Not implemented');
},
getTokenStyleMetadata: (type: string, modifiers: string[], modelLanguage: string): ITokenStyle | undefined => {
return undefined;
},
semanticHighlighting: false,
tokenColorMap: []
};
}
setColorMapOverride(colorMapOverride: Color[] | null): void {
}
public getFileIconTheme(): IFileIconTheme {
return {
hasFileIcons: false,
hasFolderIcons: false,
hidesExplorerArrows: false
};
}
private _builtInProductIconTheme = new UnthemedProductIconTheme();
public getProductIconTheme(): IProductIconTheme {
return this._builtInProductIconTheme;
}
public readonly onDidColorThemeChange = new Emitter<IColorTheme>().event;
public readonly onDidFileIconThemeChange = new Emitter<IFileIconTheme>().event;
public readonly onDidProductIconThemeChange = new Emitter<IProductIconTheme>().event;
}
class MockState implements IState {
public static readonly INSTANCE = new MockState();
private constructor() { }
public clone(): IState {
return this;
}
public equals(other: IState): boolean {
return this === other;
}
}
function testBadTokensProvider(providerTokens: IToken[], expectedClassicTokens: Token[], expectedModernTokens: number[]): void {
class BadTokensProvider implements TokensProvider {
public getInitialState(): IState {
return MockState.INSTANCE;
}
public tokenize(line: string, state: IState): ILineTokens {
return {
tokens: providerTokens,
endState: MockState.INSTANCE
};
}
}
const disposables = new DisposableStore();
const languageService = disposables.add(new LanguageService());
disposables.add(languageService.registerLanguage({ id: languageId }));
const adapter = new TokenizationSupportAdapter(
languageId,
new BadTokensProvider(),
languageService,
new MockThemeService()
);
const actualClassicTokens = adapter.tokenize('whatever', true, MockState.INSTANCE);
assert.deepStrictEqual(actualClassicTokens.tokens, expectedClassicTokens);
const actualModernTokens = adapter.tokenizeEncoded('whatever', true, MockState.INSTANCE);
const modernTokens: number[] = [];
for (let i = 0; i < actualModernTokens.tokens.length; i++) {
modernTokens[i] = actualModernTokens.tokens[i];
}
// Add the encoded language id to the expected tokens
const encodedLanguageId = languageService.languageIdCodec.encodeLanguageId(languageId);
const tokenLanguageMetadata = (encodedLanguageId << MetadataConsts.LANGUAGEID_OFFSET);
for (let i = 1; i < expectedModernTokens.length; i += 2) {
expectedModernTokens[i] |= tokenLanguageMetadata;
}
assert.deepStrictEqual(modernTokens, expectedModernTokens);
disposables.dispose();
}
test('tokens always start at index 0', () => {
testBadTokensProvider(
[
{ startIndex: 7, scopes: 'foo' },
{ startIndex: 0, scopes: 'bar' }
],
[
new Token(0, 'foo', languageId),
new Token(0, 'bar', languageId),
],
[
0, (0 << MetadataConsts.FOREGROUND_OFFSET) | MetadataConsts.BALANCED_BRACKETS_MASK,
0, (1 << MetadataConsts.FOREGROUND_OFFSET) | MetadataConsts.BALANCED_BRACKETS_MASK
]
);
});
test('tokens always start after each other', () => {
testBadTokensProvider(
[
{ startIndex: 0, scopes: 'foo' },
{ startIndex: 5, scopes: 'bar' },
{ startIndex: 3, scopes: 'foo' },
],
[
new Token(0, 'foo', languageId),
new Token(5, 'bar', languageId),
new Token(5, 'foo', languageId),
],
[
0, (0 << MetadataConsts.FOREGROUND_OFFSET) | MetadataConsts.BALANCED_BRACKETS_MASK,
5, (1 << MetadataConsts.FOREGROUND_OFFSET) | MetadataConsts.BALANCED_BRACKETS_MASK,
5, (2 << MetadataConsts.FOREGROUND_OFFSET) | MetadataConsts.BALANCED_BRACKETS_MASK
]
);
});
});
| 1 | 0.859952 | 1 | 0.859952 | game-dev | MEDIA | 0.521897 | game-dev | 0.830783 | 1 | 0.830783 |
ianpatt/f4se | 67,962 | scripts/vanilla/WorkshopScript.psc | Scriptname WorkshopScript extends ObjectReference Conditional
{script for Workshop reference}
;import WorkShopObjectScript
;import WorkshopParentScript
WorkshopParentScript Property WorkshopParent Auto Const mandatory
{ parent quest - holds most general workshop properties }
Location Property myLocation Auto Hidden
{workshop's location (filled onInit)
this is a property so the WorkshopParent script can access it}
ObjectReference Property myMapMarker auto hidden
{workshop's map marker (filled by WorkshopParent.InitializeLocation) }
Group Optional
Faction Property SettlementOwnershipFaction auto
{ optional - if the workshop settlement has an ownership faction, set this here so the player can be added to that faction when workshop becomes player-owned }
bool Property UseOwnershipFaction = true auto
{ set to false to not use the ownership faction }
ActorBase Property CustomWorkshopNPC Auto const
{ Patch 1.4: the actor that gets created when a settlement makes a successful recruitment roll - overrides properties on WorkshopParentScript }
Message Property CustomUnownedMessage const auto
{ Patch 1.4: a custom unowned message, that overrides standard messages from WorkshopParentScript }
bool Property AllowBrahminRecruitment = true auto const
{ Patch 1.6: set to false to prevent brahmin from being randomly recruited at this workshop settlement }
endGroup
group BuildingBudget
int property MaxTriangles auto
{ if > 0, initialize WorkshopMaxTriangles to this value }
int property MaxDraws auto
{ if > 0, initialize WorkshopMaxDraws to this value }
int property CurrentTriangles auto
{ if > 0, initialize WorkshopCurrentTriangles to this value }
int property CurrentDraws auto
{ if > 0, initialize WorkshopCurrentDraws to this value }
endGroup
Group Flags
bool Property OwnedByPlayer = false Auto Conditional
{ all workshops start "unowned" - activate after location is cleared to "own"
}
bool Property StartsHostile = false Auto Conditional
{ set to true for workbench locations that start out with hostiles in control (to prevent it being counted as a valid Minuteman recruiting target)}
bool Property EnableAutomaticPlayerOwnership = true Auto
{ TRUE = workshop will automatically become usable when the location is cleared (or if there are no bosses)
FALSE = workshop won't be usable by player until SetOwnedByPlayer(true) is called on it
}
bool Property AllowUnownedFromLowHappiness = false Auto
{ TRUE = workshop can become unowned due to low happiness (<=minHappinessThreshold)
FALSE (default) = workshop can never become unowned, no matter how low the happiness (for special cases like the Castle)
}
bool Property HappinessWarning Auto Hidden Conditional
{ set to true when happiness warning given; set back to false when happiness goes above the warning level
NOTE: only applies when AllowUnownedFromLowHappiness = true }
int Property DaysSinceLastVisit Auto Hidden Conditional
{ this gets cleared when player visits, incremented by daily update }
bool Property PlayerHasVisited Auto Hidden Conditional
{ this gets set to true the first time player visits - used by ResetWorkshop to initialize data on first visit }
bool Property MinRecruitmentProhibitRandom = false Auto Conditional
{ set to TRUE to prohibit random Minutemen recruitment quests from picking this workshop
}
bool Property MinRecruitmentAllowRandomAfterPlayerOwned = true Auto Conditional
{ set to FALSE to prohibit random Minutemen quests from picking this workshop AFTER the player takes over (TRUE = random quests are allowed once owned by player)
}
bool Property AllowAttacksBeforeOwned = true auto conditional
{ set to FALSE to prevent attacks when unowned
NOTE: this always gets set to true when the player takes ownership for the first time
}
bool Property AllowAttacks = true auto conditional
{ set to FALSE to prevent ALL random attacks (e.g. the Castle)
}
bool Property RadioBeaconFirstRecruit = false auto conditional hidden
{ set to true after player first builds a radio beacon here and gets the first "quick" recruit }
bool Property ShowedWorkshopMenuExitMessage = false auto conditional hidden
{ set to true after player first exits the workshop menu here }
endGroup
int WorkshopID = -1 ; initialize to real workshop ID first time it's requested (workshopID = index of this workshop in WorkshopParent.Workshops)
Group VendorData
ObjectReference[] Property VendorContainersMisc auto hidden
{
array of Misc vendor containers, indexed by vendor level
}
ObjectReference[] Property VendorContainersArmor auto hidden
ObjectReference[] Property VendorContainersWeapons auto hidden
ObjectReference[] Property VendorContainersBar auto hidden
ObjectReference[] Property VendorContainersClinic auto hidden
ObjectReference[] Property VendorContainersClothing auto hidden
endGroup
; 1.6: optional radio override data
Group WorkshopRadioData
ObjectReference Property WorkshopRadioRef Auto Const
{ if WorkshopRadioRef exists, it will override the default WorkshopRadioRef from WorkshopParent }
float property workshopRadioInnerRadius = 9000.0 auto const
{ override workshop parent values }
float property workshopRadioOuterRadius = 20000.0 auto const
{ override workshop parent values }
Scene Property WorkshopRadioScene Auto Const
{ if WorkshopRadioRef exists, WorkshopRadioScene will be started instead of the default scene from WorkshopParent }
bool property bWorkshopRadioRefIsUnique = true auto const
{ TRUE: WorkshopRadioScene is unique to this workshop, so it should be stopped/disabled when radio is shut off (completely) }
endGroup
;******************
; moved from workshopparent
; productivity formula stuff
float minProductivity = 0.25 const
float productivityHappinessMult = 0.75 const
; happiness formula stuff
float maxHappinessNoFood = 30.0 const
float maxHappinessNoWater = 30.0 const
float maxHappinessNoShelter = 60.0 const
float happinessBonusFood = 20.0 const
float happinessBonusWater = 20.0 const
float happinessBonusBed = 10.0 const
float happinessBonusShelter = 10.0 const
float happinessBonusSafety = 20.0 const
int minHappinessChangePerUpdate = 1 const ; what's the min happiness can change in one update?
float happinessChangeMult = 0.20 const ; multiplier on happiness delta
int minHappinessThreshold = 10 Const ; if happiness drops <= to this value, player ownership is cleared
int minHappinessWarningThreshold = 15 const ; if happiness drops <= to this value, give happiness warning
int minHappinessClearWarningThreshold = 20 const ; if happiness >= this value, clear happiness warning
int happinessBonusChangePerUpdate = 2 const ; happiness bonus trends back to 0 (from positive or negative)
; production
int maxStoredFoodBase = 10 const ; stop producing when we reach this amount stored
int maxStoredFoodPerPopulation = 1 const ; increase max for each population
int maxStoredWaterBase = 5 const ; stop producing when we reach this amount stored
float maxStoredWaterPerPopulation = 0.25 const ; increase max for each population
int maxStoredScavengeBase = 100 const ; stop producing when we reach this amount stored
int maxStoredScavengePerPopulation = 5 const ; increase max for each population
float brahminProductionBoost = 0.5 ; what percent increase per brahmin
int maxProductionPerBrahmin = 10 ; each brahmin can only boost this much food (so max 10 * 0.5 = 5)
int maxBrahminFertilizerProduction = 3 ; max fertilizer production per settlement per day
int maxStoredFertilizerBase = 10 ; stop producing when we reach this amount stored
; vendor income
int minVendorIncomePopulation = 5 ; need at least this population to get any vendor income
float maxVendorIncome = 50.0 ; max daily vendor income from any settlement
float vendorIncomePopulationMult = 0.03 ; multiplier on population, added to vendor income
float vendorIncomeBaseMult = 2.0 ; multiplier on base vendor income
; radio/attracting NPC stuff
int iMaxSurplusNPCs = 5 const ; for now, max number of unassigned NPCs - if you have this many or more, no new NPCs will arrive.
float attractNPCDailyChance = 0.1 const ; for now, roll <= to this to attract an NPC each day, modified by happiness
int iMaxBonusAttractChancePopulation = 5 const ; for now, there's a bonus attract chance until the total population reaches this value
int iBaseMaxNPCs = 10 const ; base total NPCs that can be at a player's town - this is used in GetMaxWorkshopNPCs formula
float attractNPCHappinessMult = 0.5 const ; multiplier on happiness to attraction chance
; attack chance formula
float attackChanceBase = 0.02 const
float attackChanceResourceMult = 0.001 const
float attackChanceSafetyMult = 0.01 const
float attackChancePopulationMult = 0.005 const
float minDaysSinceLastAttack = 7.0 const ; minimum days before another attack can be rolled for
; damage
float damageDailyRepairBase = 5.0 const ; amount of damage repaired per day (overall)
float damageDailyPopulationMult = 0.20 const ; multiplier on population for repair: repair = population * damageDailyPopulationMult * damageDailyRepairBase
; timer IDs
int buildWorkObjectTimerID = 0 const
int dailyUpdateTimerID = 1 const
; randomized wait for next try at DailyUpdate if system is busy
float maxDailyUpdateWaitHours = 1.0
float minDailyUpdateWaitHours = 0.2
;----------------STEVE CONQUEST SYSTEM ADDITIONS----------------
;/
Activator property Conquest_MinutemenFlag Auto
Activator property Conquest_BoSFlag Auto
Activator property Conquest_RailroadFlag Auto
Activator property Conquest_InstituteFlag Auto
Keyword property LocTypeControlPointOwner Auto
Quest property ConquestMasterQuest Auto
Quest property ConquestControlPoint Auto
/;
;-----------------------------------------------------------
;/
OBSOLETE - no need to init actor value data on workshop
(this was needed for keyword data because conditions wouldn't work at all for keyword data on locations if they weren't initialized to 0)
Event OnInit()
;WorkshopParent.wsTrace(self + " initializing workshop")
myLocation = GetCurrentLocation()
; initialize keyword data on location
if myLocation && myLocation.HasKeyword(WorkshopParent.LocTypeWorkshopSettlement)
int i = 0
; reference the WorkshopRatings from the parent using a local array to reduce hits on WorkshopParent.
WorkshopDataScript:WorkshopRatingKeyword[] ratings = WorkshopParent.WorkshopRatings
while i < ratings.Length
myLocation.SetResourceData(ratings[i].resourceValue, 0.0)
i = i + 1
endWhile
endif
endEvent
/;
; utility function to return vendor container array
; create containers as necessary
ObjectReference[] function GetVendorContainersByType(int vendorType)
;WorkshopParent.wsTrace(self + " GetVendorContainersByType " + vendorType)
if vendorType == 0
if VendorContainersMisc == NONE
VendorContainersMisc = InitializeVendorChests(vendorType)
endif
return VendorContainersMisc
elseif vendorType == 1
;WorkshopParent.wsTrace(" VendorContainersArmor = NONE?" + (VendorContainersArmor == NONE) )
;WorkshopParent.wsTrace(" VendorContainersArmor.Length =" + VendorContainersArmor.Length)
if VendorContainersArmor == NONE
VendorContainersArmor = InitializeVendorChests(vendorType)
endif
return VendorContainersArmor
elseif vendorType == 2
if VendorContainersWeapons == NONE
VendorContainersWeapons = InitializeVendorChests(vendorType)
endif
return VendorContainersWeapons
elseif vendorType == 3
if VendorContainersBar == NONE
VendorContainersBar = InitializeVendorChests(vendorType)
endif
return VendorContainersBar
elseif vendorType == 4
if VendorContainersClinic == NONE
VendorContainersClinic = InitializeVendorChests(vendorType)
endif
return VendorContainersClinic
elseif vendorType == 5
if VendorContainersClothing == NONE
VendorContainersClothing = InitializeVendorChests(vendorType)
endif
return VendorContainersClothing
else
;WorkshopParent.wsTrace(self + " GetVendorContainersByType: WARNING - invalid vendorType=" + vendorType)
endif
endFunction
ObjectReference[] function InitializeVendorChests(int vendorType)
;WorkshopParent.wsTrace(self + " InitializeVendorChests: vendorType=" + vendorType)
; initialize array
int containerArraySize = WorkshopParent.VendorTopLevel + 1
ObjectReference[] vendorContainers = new ObjectReference[containerArraySize]
; create the chests
FormList vendorContainerList = WorkshopParent.WorkshopVendorContainers[vendorType]
int vendorLevel = 0
while vendorLevel <= WorkshopParent.VendorTopLevel
;WorkshopParent.wsTrace(" vendorLevel=" + vendorLevel)
; create ref for each vendor level
vendorContainers[vendorLevel] = WorkshopParent.WorkshopHoldingCellMarker.PlaceAtMe(vendorContainerList.GetAt(vendorLevel))
;WorkshopParent.wsTrace(" container=" + vendorContainers[vendorLevel])
vendorLevel += 1
endWhile
return vendorContainers
endFunction
Event OnInit()
; initialize building budget actor values if necessary
if MaxTriangles > 0
SetValue(WorkshopParent.WorkshopMaxTriangles, MaxTriangles)
endif
if MaxDraws > 0
SetValue(WorkshopParent.WorkshopMaxDraws, MaxDraws)
endif
if CurrentTriangles > 0
SetValue(WorkshopParent.WorkshopCurrentTriangles, CurrentTriangles)
endif
if CurrentDraws > 0
SetValue(WorkshopParent.WorkshopCurrentDraws, CurrentDraws)
endif
; happiness target (don't want to set a default value)
SetValue(WorkshopParent.WorkshopRatings[WorkshopParent.WorkshopRatingHappinessTarget].resourceValue, WorkshopParent.startingHappinessTarget)
EndEvent
Event OnLoad()
; for now, block activation if not "owned" by player
BlockActivation(!OwnedByPlayer)
; grab inventory from linked container if I'm a container myself
if (GetBaseObject() as Container)
; get linked container
ObjectReference linkedContainer = GetLinkedRef(WorkshopParent.WorkshopLinkContainer)
if linkedContainer
linkedContainer.RemoveAllItems(self)
endif
; get all linked containers (children)
ObjectReference[] linkedContainers = GetLinkedRefChildren(WorkshopParent.WorkshopLinkContainer)
int i = 0
while i < linkedContainers.Length
linkedContainer = linkedContainers[i]
if linkedContainer
linkedContainer.RemoveAllItems(self)
endif
i += 1
endWhile
endif
; if no location (this is not a settlement location so skipped WorkshopParent init process), get current location
if !myLocation
myLocation = GetCurrentLocation()
endif
EndEvent
Event OnUnload()
; reset days since last visit whenever you leave
DaysSinceLastVisit = 0
endEvent
; block activation until player "owns" this workbench
Event OnActivate(ObjectReference akActionRef)
;;debug.trace(self + "OnActivate")
if akActionRef == Game.GetPlayer()
CheckOwnership()
if OwnedByPlayer
; go into workshop mode
StartWorkshop()
endif
endif
EndEvent
; called by OnActivate and workbench scripts to check if player ownership should change
function CheckOwnership()
; if location is cleared, automatically count this as owned by player
if myLocation.IsCleared() && !OwnedByPlayer && EnableAutomaticPlayerOwnership
SetOwnedByPlayer(true)
; go into workshop mode
; StartWorkshop()
endif
if !OwnedByPlayer
; which message to show?
; Patch 1.4: handle custom unowned message
if CustomUnownedMessage
CustomUnownedMessage.Show()
else
int totalPopulation = GetBaseValue(WorkshopParent.WorkshopRatings[WorkshopParent.WorkshopRatingPopulation].resourceValue) as int
if totalPopulation > 0
WorkshopParent.WorkshopUnownedSettlementMessage.Show()
elseif myLocation.IsCleared() == false && EnableAutomaticPlayerOwnership
WorkshopParent.WorkshopUnownedHostileMessage.Show()
else
WorkshopParent.WorkshopUnownedMessage.Show()
endif
endif
endif
endFunction
Event OnWorkshopMode(bool aStart)
;debug.trace(self + " OnWorkshopMode " + aStart)
if aStart
if OwnedByPlayer
; make this the current workshop
WorkshopParent.SetCurrentWorkshop(self)
endif
Var[] kargs = new Var[2]
kargs[0] = NONE
kargs[1] = self
;WorkshopParent.wsTrace(" sending WorkshopEnterMenu event")
WorkshopParent.SendCustomEvent("WorkshopEnterMenu", kargs)
endif
; Dogmeat scene
if aStart && WorkshopParent.DogmeatAlias.GetRef()
WorkshopParent.WorkshopDogmeatWhileBuildingScene.Start()
else
WorkshopParent.WorkshopDogmeatWhileBuildingScene.Stop()
endif
; Companion scene
;debug.trace(self + " OnWorkshopMode " + WorkshopParent.CompanionAlias.GetRef())
if aStart && WorkshopParent.CompanionAlias.GetRef()
;debug.trace(self + " starting WorkshopParent.WorkshopCompanionWhileBuildingScene")
WorkshopParent.WorkshopCompanionWhileBuildingScene.Start()
else
WorkshopParent.WorkshopCompanionWhileBuildingScene.Stop()
endif
if !aStart
; show message if haven't before
if ShowedWorkshopMenuExitMessage == false
ShowedWorkshopMenuExitMessage = true
WorkshopParent.WorkshopExitMenuMessage.ShowAsHelpMessage("WorkshopMenuExit", 10.0, 0, 1, "NoMenu")
endif
; make sure resources stay assigned
WorkshopParent.TryToAssignResourceObjectsPUBLIC(self)
endif
; try recalcing when you enter/exit workshop mode
DailyUpdate(bRealUpdate = false)
endEvent
Event OnTimer(int aiTimerID)
;WorkshopParent.wsTrace(self + " OnTimer: timerID=" + aiTimerID)
if aiTimerID == buildWorkObjectTimerID
WorkshopParent.TryToAssignResourceObjectsPUBLIC(self)
endif
EndEvent
Event OnTimerGameTime(int aiTimerID)
if aiTimerID == dailyUpdateTimerID
if WorkshopParent.IsEditLocked() || WorkshopParent.DailyUpdateInProgress
float waitTime = utility.RandomFloat(minDailyUpdateWaitHours, maxDailyUpdateWaitHours)
WorkshopParent.wsTrace(self + " DailyUpdate: system busy, try again in " + waitTime + " game hours.")
; run another timer - system is too busy
StartTimerGameTime(waitTime, dailyUpdateTimerID)
else
DailyUpdate()
endif
endif
endEvent
function SetOwnedByPlayer(bool bIsOwned)
;WorkshopParent.wsTrace(self + " SetOwnedByPlayer(" + bIsOwned + ")")
; is state changing?
if !bIsOwned && OwnedByPlayer
;WorkshopParent.wsTrace(self + " SetOwnedByPlayer: state changing to UNOWNED")
OwnedByPlayer = bIsOwned ; do this here so workshop is updated for UpdatePlayerOwnership check
; display loss of ownership message
WorkshopParent.DisplayMessage(WorkshopParent.WorkshopLosePlayerOwnership, NONE, myLocation)
; flag as "lost control"
SetValue(WorkshopParent.WorkshopPlayerLostControl, 1.0)
; clear farm discount faction if we can get actors
ObjectReference[] WorkshopActors = WorkshopParent.GetWorkshopActors(self)
int i = 0
while i < WorkshopActors.Length
WorkshopNPCScript theActor = (WorkshopActors[i] as Actor) as WorkshopNPCScript
if theActor
theActor.RemoveFromFaction(WorkshopParent.FarmDiscountFaction)
; clear "player owned" actor value (used to condition trade items greetings)
theActor.UpdatePlayerOwnership(self)
endif
i += 1
endWhile
; remove all caravans to/from this settlement
WorkshopParent.ClearCaravansFromWorkshopPUBLIC(self)
elseif bIsOwned && !OwnedByPlayer
;WorkshopParent.wsTrace(self + " SetOwnedByPlayer: state changing to OWNED")
OwnedByPlayer = bIsOwned ; do this here so workshop is updated for UpdatePlayerOwnership check
; make sure owns a workshop flag is set first time you own one
if !WorkshopParent.PlayerOwnsAWorkshop
WorkshopParent.PlayerOwnsAWorkshop = true
endif
; make sure happiness (and happiness target) is set to minimum (so doesn't immediately become unowned again)
float currentHappiness = GetValue(WorkshopParent.WorkshopRatings[WorkshopParent.WorkshopRatingHappiness].resourceValue)
float currentHappinessTarget = GetValue(WorkshopParent.WorkshopRatings[WorkshopParent.WorkshopRatingHappinessTarget].resourceValue)
if currentHappiness < minHappinessClearWarningThreshold || currentHappinessTarget < minHappinessClearWarningThreshold
WorkshopParent.ModifyResourceData(WorkshopParent.WorkshopRatings[WorkshopParent.WorkshopRatingHappiness].resourceValue, self, minHappinessClearWarningThreshold)
WorkshopParent.ModifyResourceData(WorkshopParent.WorkshopRatings[WorkshopParent.WorkshopRatingHappinessTarget].resourceValue, self, minHappinessClearWarningThreshold)
EndIf
; display gain of ownership message
;WorkshopParent.wsTrace(self + " SetOwnedByPlayer - display message for location " + myLocation)
WorkshopParent.DisplayMessage(WorkshopParent.WorkshopGainPlayerOwnership, NONE, myLocation)
; if this is the first time player owns this, increment stat
if GetValue(WorkshopParent.WorkshopPlayerLostControl) == 0
;debug.trace("Increment Workshops Unlocked stat")
Game.IncrementStat("Workshops Unlocked")
else
; clear "lost control" flag
SetValue(WorkshopParent.WorkshopPlayerLostControl, 0.0)
EndIf
; if allowed, allow random quests from now on
if MinRecruitmentAllowRandomAfterPlayerOwned
MinRecruitmentProhibitRandom = false
EndIf
; allow attacks when unowned now
AllowAttacksBeforeOwned = true
; add player owned actor value if possible
ObjectReference[] WorkshopActors = WorkshopParent.GetWorkshopActors(self)
int i = 0
while i < WorkshopActors.Length
WorkshopNPCScript theActor = (WorkshopActors[i] as Actor) as WorkshopNPCScript
if theActor
theActor.UpdatePlayerOwnership(self)
endif
i += 1
endWhile
endif
OwnedByPlayer = bIsOwned
BlockActivation(!OwnedByPlayer)
; set player ownership value on myself
SetValue(WorkshopParent.WorkshopPlayerOwnership, (bIsOwned as float))
;WorkshopParent.SetResourceData(WorkshopParent.WorkshopPlayerOwnership, self, (bIsOwned as float))
if bIsOwned
SetActorOwner(Game.GetPlayer().GetActorBase())
; don't want this flagged as cleared so story manager doesn't skip it
myLocation.SetCleared(false)
; add player to ownership faction is there is one
if SettlementOwnershipFaction && UseOwnershipFaction
Game.GetPlayer().AddToFaction(SettlementOwnershipFaction)
endif
else
SetActorOwner(NONE)
; remove player from ownership faction is there is one
if SettlementOwnershipFaction && UseOwnershipFaction
Game.GetPlayer().RemoveFromFaction(SettlementOwnershipFaction)
endif
endif
; send custom event for this workshop
WorkshopParent.SendPlayerOwnershipChangedEvent(self)
endFunction
Event OnWorkshopObjectPlaced(ObjectReference akReference)
;WorkshopParent.wsTrace(self + " received OnWorkshopObjectPlaced event")
if WorkshopParent.BuildObjectPUBLIC(akReference, self)
; run timer for assigning resource objects
StartTimer(3.0, buildWorkObjectTimerID)
endif
endEvent
Event OnWorkshopObjectMoved(ObjectReference akReference)
;WorkshopParent.wsTrace(self + " received OnWorkshopObjectMoved event")
; for now, just tell the object it moved so it can update markers etc.
WorkshopObjectScript workshopObjectRef = akReference as WorkShopObjectScript
if workshopObjectRef
; workshopObjectRef.UpdatePosition()
; send custom event for this object
Var[] kargs = new Var[2]
kargs[0] = workshopObjectRef
kargs[1] = self
;WorkshopParent.wsTrace(" sending WorkshopObjectMoved event")
WorkshopParent.SendCustomEvent("WorkshopObjectMoved", kargs)
endif
EndEvent
Event OnWorkshopObjectDestroyed(ObjectReference akReference)
;WorkshopParent.wsTrace(self + " received OnWorkshopObjectDestroyed event")
WorkshopParent.RemoveObjectPUBLIC(akReference, self)
endEvent
Event OnWorkshopObjectRepaired(ObjectReference akReference)
;WorkshopParent.wsTrace(self + " received OnWorkshopObjectRepaired event")
WorkshopObjectActorScript workshopObjectActor = akReference as WorkshopObjectActorScript
if workshopObjectActor
;WorkshopParent.wsTrace(self + " repairing object actor " + workshopObjectActor)
; send destruction state changed event manually since actors aren't destructible objects
WorkshopObjectScript workshopObject = (akReference as WorkshopObjectScript)
workshopObject.OnDestructionStageChanged(1, 0)
endif
WorkshopObjectScript workshopObjectRef = akReference as WorkShopObjectScript
if workshopObjectRef
; workshopObjectRef.UpdatePosition()
; send custom event for this object
Var[] kargs = new Var[2]
kargs[0] = workshopObjectRef
kargs[1] = self
;WorkshopParent.wsTrace(" sending WorkshopObjectMoved event")
WorkshopParent.SendCustomEvent("WorkshopObjectRepaired", kargs)
endif
endEvent
ObjectReference function GetContainer()
if (GetBaseObject() as Container)
return self
else
return GetLinkedRef(WorkshopParent.WorkshopLinkContainer)
endif
endFunction
Event WorkshopParentScript.WorkshopDailyUpdate(WorkshopParentScript akSender, Var[] akArgs)
; calculate custom time interval for this workshop (to stagger out the update process throughout the day)
float waitTime = WorkshopParent.dailyUpdateIncrement * workshopID
;WorkshopParent.wsTrace(self + " WorkshopDailyUpdate event received with wait time " + waitTime + " hours")
StartTimerGameTime(waitTime, dailyUpdateTimerID)
EndEvent
; return max NPCs for this workshop
int function GetMaxWorkshopNPCs()
; base + player's charisma
int iMaxNPCs = iBaseMaxNPCs + (Game.GetPlayer().GetValue(WorkshopParent.Charisma) as int)
return iMaxNPCs
endFunction
; Data struct for passing data to/from DailyUpdate helper functions
struct DailyUpdateData
int totalPopulation
int robotPopulation
int brahminPopulation
int unassignedPopulation
float vendorIncome
float currentHappiness
float damageMult
float productivity
int availableBeds
int shelteredBeds
int bonusHappiness
int happinessModifier
int safety
int safetyDamage
int foodProduction
int waterProduction
int availableFood
int availableWater
int safetyPerNPC
float totalHappiness
endStruct
; process daily update
; bRealUpdate:
; TRUE = normal daily update - consume/produce resources, etc.
; FALSE = recalculate happiness etc. but don't produce/consume
bool bDailyUpdateInProgress = false
function DailyUpdate(bool bRealUpdate = true)
; ;debug.tracestack(self + " DailyUpdate " + bRealUpdate)
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
WorkshopParent.wsTrace(self + " DAILY UPDATE: bRealUpdate=" + bRealUpdate, bNormalTraceAlso = true)
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
; wait for update lock to be released
if bDailyUpdateInProgress
if bRealUpdate
while bDailyUpdateInProgress
WorkshopParent.wsTrace(self + " waiting for update lock to clear...")
utility.wait(0.5)
endWhile
else
; just bail if not a real update - no need
WorkshopParent.wsTrace(self + " update already in progress - don't try again right now")
return
endif
EndIf
bDailyUpdateInProgress = true
WorkshopParent.DailyUpdateInProgress = true
; create local pointer to WorkshopRatings array to speed things up
WorkshopDataScript:WorkshopRatingKeyword[] ratings = WorkshopParent.WorkshopRatings
DailyUpdateData updateData = new DailyUpdateData
; NOTE: GetBaseValue for these because we don't care if they can "produce" - actors that are wounded don't "produce" their population resource values
updateData.totalPopulation = GetBaseValue(ratings[WorkshopParent.WorkshopRatingPopulation].resourceValue) as int
updateData.robotPopulation = GetBaseValue(ratings[WorkshopParent.WorkshopRatingPopulationRobots].resourceValue) as int
updateData.brahminPopulation = GetBaseValue(ratings[WorkshopParent.WorkshopRatingBrahmin].resourceValue) as int
updateData.unassignedPopulation = GetBaseValue(ratings[WorkshopParent.WorkshopRatingPopulationUnassigned].resourceValue) as int
updateData.vendorIncome = GetValue(ratings[WorkshopParent.WorkshopRatingVendorIncome].resourceValue) * vendorIncomeBaseMult
updateData.currentHappiness = GetValue(ratings[WorkshopParent.WorkshopRatingHappiness].resourceValue)
updateData.damageMult = 1 - GetValue(ratings[WorkshopParent.WorkshopRatingDamageCurrent].resourceValue)/100.0
updateData.productivity = GetProductivityMultiplier(ratings)
updateData.availableBeds = GetBaseValue(ratings[WorkshopParent.WorkshopRatingBeds].resourceValue) as int
updateData.shelteredBeds = GetValue(ratings[WorkshopParent.WorkshopRatingBeds].resourceValue) as int
updateData.bonusHappiness = GetValue(ratings[WorkshopParent.WorkshopRatingBonusHappiness].resourceValue) as int
updateData.happinessModifier = GetValue(ratings[WorkshopParent.WorkshopRatingHappinessModifier].resourceValue) as int
updateData.safety = GetValue(ratings[WorkshopParent.WorkshopRatingSafety].resourceValue) as int
updateData.safetyDamage = GetValue(WorkshopParent.GetDamageRatingValue(ratings[WorkshopParent.WorkshopRatingSafety].resourceValue)) as int
updateData.totalHappiness = 0.0 ; sum of all happiness of each actor in town
;WorkshopParent.wsTrace(self + " total population=" + updateData.totalPopulation)
; REAL UPDATE ONLY
if bRealUpdate
DailyUpdateAttractNewSettlers(ratings, updateData)
EndIf
ObjectReference containerRef = GetContainer()
if !containerRef
WorkshopParent.wsTrace(self + " ERROR - no container linked to workshop " + self + " with " + WorkshopParent.WorkshopLinkContainer, 2)
bDailyUpdateInProgress = false
WorkshopParent.DailyUpdateInProgress = false
return
endif
;WorkshopParent.wsTrace(self + " happiness: " + updateData.currentHappiness + ", productivity mult=" + updateData.productivity + ", damage mult=" + updateData.damageMult)
; if this is current workshop, update actors (in case some have been wounded since last update)
if GetWorkshopID() == WorkshopParent.WorkshopCurrentWorkshopID.GetValue()
;WorkshopParent.wsTrace(self + " Current workshop - update actors' work objects")
ObjectReference[] WorkshopActors = WorkshopParent.GetWorkshopActors(self)
int i = 0
while i < WorkshopActors.Length
WorkshopParent.UpdateActorsWorkObjects(WorkshopActors[i] as WorkShopNPCScript, self)
i += 1
endWhile
endif
DailyUpdateProduceResources(ratings, updateData, containerRef, bRealUpdate)
DailyUpdateConsumeResources(ratings, updateData, containerRef, bRealUpdate)
; REAL UPDATE ONLY:
if bRealUpdate
DailyUpdateSurplusResources(ratings, updateData, containerRef)
RepairDamage()
; now recalc all workshop resources if the current workshop - we don't want to do this when unloaded or everything will be 0
RecalculateWorkshopResources()
CheckForAttack()
endif
; update trade caravan list
if updateData.totalPopulation >= WorkshopParent.TradeCaravanMinimumPopulation && GetValue(ratings[WorkshopParent.WorkshopRatingCaravan].resourceValue) > 0
WorkshopParent.TradeCaravanWorkshops.AddRef(self)
else
WorkshopParent.TradeCaravanWorkshops.RemoveRef(self)
EndIf
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
WorkshopParent.wsTrace(self + " DAILY UPDATE - DONE - bRbRealUpdate=" + bRealUpdate, bNormalTraceAlso = true)
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
; clear update lock
bDailyUpdateInProgress = false
WorkshopParent.DailyUpdateInProgress = false
endFunction
; **********************************************************************************************
; DAILY UPDATE HELPER FUNCTIONS - to reduce memory footprint of DailyUpdate process
; **********************************************************************************************
function DailyUpdateAttractNewSettlers(WorkshopDataScript:WorkshopRatingKeyword[] ratings, DailyUpdateData updateData)
; increment last visit counter each day
DaysSinceLastVisit += 1
; attract new NPCs
; if I have a radio station
int radioRating = GetValue(ratings[WorkshopParent.WorkshopRatingRadio].resourceValue) as int
if radioRating > 0 && HasKeyword(WorkshopParent.WorkshopType02) == false && updateData.unassignedPopulation < iMaxSurplusNPCs && updateData.totalPopulation < GetMaxWorkshopNPCs()
;WorkshopParent.wsTrace(self + " RADIO - unassigned population=" + updateData.unassignedPopulation)
float attractChance = attractNPCDailyChance + updateData.currentHappiness/100 * attractNPCHappinessMult
if updateData.totalPopulation < iMaxBonusAttractChancePopulation
attractChance += (iMaxBonusAttractChancePopulation - updateData.totalPopulation) * attractNPCDailyChance
endif
; roll to see if a new NPC arrives
float dieRoll = utility.RandomFloat()
;WorkshopParent.wsTrace(self + " dieRoll=" + dieRoll + ", attract NPC chance=" + attractChance)
if dieRoll <= attractChance
WorkshopNPCScript newWorkshopActor = WorkshopParent.CreateActor(self)
updateData.totalPopulation += 1
if newWorkshopActor.GetValue(WorkshopParent.WorkshopGuardPreference) == 0
; see if also generate a brahmin
; for now just roll if no brahmin here yet
if GetValue(ratings[WorkshopParent.WorkshopRatingBrahmin].resourceValue) == 0.0 && AllowBrahminRecruitment
int brahminRoll = utility.RandomInt()
;WorkshopParent.wsTrace(self + " brahminRoll=" + brahminRoll + ", attract brahmin chance=" + WorkshopParent.recruitmentBrahminChance)
if brahminRoll <= WorkshopParent.recruitmentBrahminChance
actor newBrahmin = WorkshopParent.CreateActor(self, true)
; NOTE: don't increment total population - brahmin aren't counted as population
endif
endif
endif
endif
endif
endFunction
function DailyUpdateProduceResources(WorkshopDataScript:WorkshopRatingKeyword[] ratings, DailyUpdateData updateData, ObjectReference containerRef, bool bRealUpdate)
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
WorkshopParent.wsTrace(self + " Produce resources: ")
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
; produce food and water
updateData.foodProduction = GetValue(ratings[WorkshopParent.WorkshopRatingFood].resourceValue) as int
updateData.waterProduction = GetValue(ratings[WorkshopParent.WorkshopRatingWater].resourceValue) as int
WorkshopParent.wsTrace(self + " Base food: " + updateData.foodProduction)
WorkshopParent.wsTrace(self + " Base water: " + updateData.waterProduction)
; safety check: population = base needed safety
int missingSafety = math.max(0, updateData.totalPopulation - updateData.safety) as int
WorkshopParent.SetResourceData(ratings[WorkshopParent.WorkshopRatingMissingSafety].resourceValue, self, missingSafety)
; subtract damage from food & water
updateData.foodProduction = math.max(0, updateData.foodProduction - (GetValue(WorkshopParent.GetDamageRatingValue(ratings[WorkshopParent.WorkshopRatingFood].resourceValue)) as int)) as int
updateData.waterProduction = math.max(0, updateData.waterProduction - (GetValue(WorkshopParent.GetDamageRatingValue(ratings[WorkshopParent.WorkshopRatingWater].resourceValue)) as int)) as int
; each brahmin can assist with 10 food production
if updateData.brahminPopulation > 0
int brahminMaxFoodBoost = math.min(updateData.brahminPopulation * maxProductionPerBrahmin, updateData.foodProduction) as int
int brahminFoodProduction = math.Ceiling(brahminMaxFoodBoost * brahminProductionBoost)
WorkshopParent.wsTrace(self + " Brahmin food boost: " + brahminFoodProduction)
updateData.foodProduction = updateData.foodProduction + brahminFoodProduction
endif
; MOVE THIS TO CONSUME SECTION:
; - confusing if food rating is higher than population but still red
; - consume first, then multiply the surplus by productivity
;/
; food rating is multiplied by productivity
updateData.foodProduction = math.Ceiling(updateData.foodProduction * updateData.productivity)
/;
; NOTE: water doesn't need a productivity factor since it's produced by machines - happiness is irrelevant
; for now, store this as rating for stats to use
WorkshopParent.SetResourceData(ratings[WorkshopParent.WorkshopRatingFoodActual].resourceValue, self, updateData.foodProduction)
WorkshopParent.wsTrace(self + " Actual production:")
WorkshopParent.wsTrace(self + " Food: " + updateData.foodProduction)
WorkshopParent.wsTrace(self + " Water: " + updateData.waterProduction)
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
WorkshopParent.wsTrace(self + " Consume resources and calculate happiness: ")
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
; reduce safety by current damage (food and water already got that treatment in the Production phase)
updateData.safety = math.Max(updateData.safety - updateData.safetyDamage, 0) as int
updateData.safetyPerNPC = 0
if updateData.totalPopulation > 0
updateData.safetyperNPC = math.ceiling(updateData.safety/updateData.totalPopulation)
endif
updateData.availableFood = containerRef.GetItemCount(WorkshopParent.WorkshopConsumeFood)
updateData.availableWater = containerRef.GetItemCount(WorkshopParent.WorkshopConsumeWater)
WorkshopParent.wsTrace(self + " Starting stats:")
WorkshopParent.wsTrace(self + " population=" + updateData.totalPopulation)
WorkshopParent.wsTrace(self + " food=" + updateData.availableFood)
WorkshopParent.wsTrace(self + " water=" + updateData.availableWater)
WorkshopParent.wsTrace(self + " beds=" + updateData.availableBeds + " (" + updateData.shelteredBeds + " sheltered)")
WorkshopParent.wsTrace(self + " bonus happiness=" + updateData.bonusHappiness)
WorkshopParent.wsTrace(self + " total safety=" + updateData.safety)
WorkshopParent.wsTrace(self + " safety per NPC=" + updateData.safetyPerNPC)
WorkshopParent.wsTrace(self + " unassignedPopulation=" + updateData.unassignedPopulation)
; get local food and water totals (including current production)
updateData.availableFood = containerRef.GetItemCount(WorkshopParent.WorkshopConsumeFood) + updateData.foodProduction
updateData.availableWater = containerRef.GetItemCount(WorkshopParent.WorkshopConsumeWater) + updateData.waterProduction
WorkshopParent.wsTrace(self + " After production:")
WorkshopParent.wsTrace(self + " food=" + updateData.availableFood)
WorkshopParent.wsTrace(self + " water=" + updateData.availableWater)
; how much food & water is needed? (robots don't need either)
int neededFood = updateData.totalPopulation - updateData.robotPopulation - updateData.availableFood
int neededWater = updateData.totalPopulation - updateData.robotPopulation - updateData.availableWater
; add in food and water from linked workshops if needed
if neededFood > 0 || neededWater > 0
WorkshopParent.wsTrace(self + " Resource shortage - try to get from linked workshops:")
WorkshopParent.wsTrace(self + " food=" + neededFood)
WorkshopParent.wsTrace(self + " water=" + neededWater)
WorkshopParent.TransferResourcesFromLinkedWorkshops(self, neededFood, neededWater)
endif
; now, get again (now including any transfers from linked workshops)
updateData.availableFood = containerRef.GetItemCount(WorkshopParent.WorkshopConsumeFood) + updateData.foodProduction
updateData.availableWater = containerRef.GetItemCount(WorkshopParent.WorkshopConsumeWater) + updateData.waterProduction
WorkshopParent.wsTrace(self + " Final stats after transfers:")
WorkshopParent.wsTrace(self + " food=" + updateData.availableFood)
WorkshopParent.wsTrace(self + " water=" + updateData.availableWater)
; for simplicity, brahmin use food & water first
; KMK 5/4/15 - remove brahmin food/water use
;/
if updateData.brahminPopulation > 0
; if current production is available, use that first
if updateData.availableFood > 0
updateData.availableFood = updateData.availableFood - 1
if updateData.foodProduction > 0
updateData.foodProduction = updateData.foodProduction - 1
elseif bRealUpdate
containerRef.RemoveItem(WorkshopParent.WorkshopConsumeFood, 1)
endif
EndIf
if updateData.availableWater > 0
updateData.availableWater = updateData.availableWater - 1
; if current production is available, use that first
if updateData.waterProduction > 0
updateData.waterProduction = updateData.waterProduction - 1
elseif bRealUpdate
containerRef.RemoveItem(WorkshopParent.WorkshopConsumeWater, 1)
endif
EndIf
EndIf
/;
endFunction
function DailyUpdateConsumeResources(WorkshopDataScript:WorkshopRatingKeyword[] ratings, DailyUpdateData updateData, ObjectReference containerRef, bool bRealUpdate)
; don't need to do any of this if no population
if updateData.totalPopulation == 0
return
endif
; variables used to track happiness for each actor
float ActorHappiness
bool ActorBed
bool ActorShelter
bool ActorFood
bool ActorWater
; track how much is missing (contributing to unhappiness)
int missingFood
int missingWater
int missingBeds
int missingShelter
int missingSafety
; calculate happiness (but not for robots)
int i = 0
while i < updateData.totalPopulation - updateData.robotPopulation
; clear variables
ActorHappiness = 0
ActorFood = false
ActorWater = false
ActorBed = false
ActorShelter = false
; we found an actor assigned to this workshop
WorkshopParent.wsTrace(self + " CalculateHappiness: actor " + i)
; do I have food?
if updateData.availableFood > 0
; if so, +20
ActorFood = true
updateData.availableFood = updateData.availableFood - 1
; if current production is available, use that first
if updateData.foodProduction > 0
updateData.foodProduction = updateData.foodProduction - 1
elseif bRealUpdate
containerRef.RemoveItem(WorkshopParent.WorkshopConsumeFood, 1)
endif
ActorHappiness += happinessBonusFood
WorkshopParent.wsTrace(self + " +FOOD - happiness=" + ActorHappiness)
else
missingFood += 1
endif
; do I have water?
if updateData.availableWater > 0
; if so, +20
ActorWater = true
updateData.availableWater = updateData.availableWater - 1
; if current production is available, use that first
if updateData.waterProduction > 0
updateData.waterProduction = updateData.waterProduction - 1
elseif bRealUpdate
containerRef.RemoveItem(WorkshopParent.WorkshopConsumeWater, 1)
endif
ActorHappiness += happinessBonusWater
WorkshopParent.wsTrace(self + " +WATER - happiness=" + ActorHappiness)
else
missingWater += 1
endif
; bed?
; if so, +10
if updateData.availableBeds > 0
ActorBed = true
updateData.availableBeds = updateData.availableBeds - 1
ActorHappiness += happinessBonusBed
WorkshopParent.wsTrace(self + " +BED - happiness=" + ActorHappiness)
else
missingBeds += 1
endif
; shelter?
if updateData.shelteredBeds > 0
ActorShelter = true
updateData.shelteredBeds = updateData.shelteredBeds - 1
ActorHappiness += happinessBonusShelter
WorkshopParent.wsTrace(self + " +SHELTER - happiness=" + ActorHappiness)
endif
; safety
if updateData.safetyperNPC > 0
ActorHappiness += happinessBonusSafety
endif
; now update happiness based on current flags
ActorHappiness = CheckActorHappiness(ActorHappiness, ActorFood, ActorWater, ActorBed, ActorShelter)
WorkshopParent.wsTrace(self + " Final actor happiness=" + ActorHappiness)
; sum happiness
updateData.totalHappiness = updateData.totalHappiness + ActorHappiness
i += 1
endWhile
; add happiness from robots - always 50
updateData.totalHappiness = updateData.totalHappiness + ( 50 * updateData.robotPopulation)
; always update missing beds stat - this isn't handled by code
WorkshopParent.SetResourceData(ratings[WorkshopParent.WorkshopRatingMissingBeds].resourceValue, self, missingBeds)
; record missing food/water/etc.
; NEW - now that code calculates missing food/water/safety, only need to do this on real update
if bRealUpdate
WorkshopParent.SetResourceData(ratings[WorkshopParent.WorkshopRatingMissingFood].resourceValue, self, missingFood)
WorkshopParent.SetResourceData(ratings[WorkshopParent.WorkshopRatingMissingWater].resourceValue, self, missingWater)
endif
; add "bonus happiness" and any happiness modifiers
updateData.totalHappiness = updateData.totalHappiness + updateData.bonusHappiness
; calculate happiness
WorkshopParent.wsTrace(self + " CalculateHappiness: totalHappiness=" + updateData.totalHappiness + ", totalActors=" + updateData.totalPopulation + ", happiness modifier=" + updateData.happinessModifier)
; add happiness modifier here - it isn't dependent on population
updateData.totalHappiness = math.max(updateData.totalHappiness/updateData.totalPopulation + updateData.happinessModifier, 0)
; don't let happiness exceed 100
updateData.totalHappiness = math.min(updateData.totalHappiness, 100)
WorkshopParent.wsTrace(self + " CalculateHappiness: Happiness Target=" + updateData.totalHappiness)
; for now, record this as a rating
WorkshopParent.SetResourceData(ratings[WorkshopParent.WorkshopRatingHappinessTarget].resourceValue, self, updateData.totalHappiness)
; REAL UPDATE ONLY:
if bRealUpdate
float deltaHappinessFloat = (updateData.totalHappiness - updateData.currentHappiness) * happinessChangeMult
; WorkshopParent.wsTrace(self + " CalculateHappiness: delta happiness (float)=" + deltaHappinessFloat)
int deltaHappiness
if deltaHappinessFloat < 0
deltaHappiness = math.floor(deltaHappinessFloat) ; how much does happiness want to change?
else
deltaHappiness = math.ceiling(deltaHappinessFloat) ; how much does happiness want to change?
endif
; WorkshopParent.wsTrace(self + " CalculateHappiness: delta happiness (int)=" + deltaHappiness)
if deltaHappiness != 0 && math.abs(deltaHappiness) < minHappinessChangePerUpdate
; increase delta to the min
deltaHappiness = minHappinessChangePerUpdate * (deltaHappiness/math.abs(deltaHappiness)) as int
endif
WorkshopParent.wsTrace(self + " CalculateHappiness: happiness change=" + deltaHappiness)
; update happiness rating on workshop's location
WorkshopParent.ModifyResourceData(ratings[WorkshopParent.WorkshopRatingHappiness].resourceValue, self, deltaHappiness)
; what is happiness now?
float finalHappiness = GetValue(ratings[WorkshopParent.WorkshopRatingHappiness].resourceValue)
WorkshopParent.wsTrace(self + " CalculateHappiness: final happiness=" + finalHappiness)
; achievement
if finalHappiness >= WorkshopParent.HappinessAchievementValue
;debug.Trace(self + " HAPPINESS ACHIEVEMENT UNLOCKED!!!!")
Game.AddAchievement(WorkshopParent.HappinessAchievementID)
endif
; if happiness is below threshold, no longer player-owned
if OwnedByPlayer && AllowUnownedFromLowHappiness
; issue warning?
if finalHappiness <= minHappinessWarningThreshold && HappinessWarning == false
HappinessWarning = true
; always show warning first
WorkshopParent.DisplayMessage(WorkshopParent.WorkshopUnhappinessWarning, NONE, myLocation)
elseif finalHappiness <= minHappinessThreshold
SetOwnedByPlayer(false)
endif
; clear warning if above threshold
if finalHappiness > minHappinessClearWarningThreshold && HappinessWarning == true
HappinessWarning = false
endif
endif
; happiness modifier tends toward 0 over time
if updateData.happinessModifier != 0
float modifierSign = -1 * (updateData.happinessModifier/math.abs(updateData.happinessModifier))
WorkshopParent.wsTrace(self + " CalculateHappiness: modifierSign=" + modifierSign)
int deltaHappinessModifier
float deltaHappinessModifierFloat = math.abs(updateData.happinessModifier) * modifierSign * happinessChangeMult
WorkshopParent.wsTrace(self + " CalculateHappiness: deltaHappinessModifierFloat=" + deltaHappinessModifierFloat)
if deltaHappinessModifierFloat > 0
deltaHappinessModifier = math.floor(deltaHappinessModifierFloat) ; how much does happiness modifier want to change?
else
deltaHappinessModifier = math.ceiling(deltaHappinessModifierFloat) ; how much does happiness modifier want to change?
EndIf
WorkshopParent.wsTrace(self + " CalculateHappiness: deltaHappinessModifier=" + deltaHappinessModifier)
if math.abs(deltaHappinessModifier) < happinessBonusChangePerUpdate
deltaHappinessModifier = (modifierSign * happinessBonusChangePerUpdate) as int
endif
WorkshopParent.wsTrace(self + " CalculateHappiness: FINAL deltaHappinessModifier=" + deltaHappinessModifier)
if deltaHappinessModifier > math.abs(updateData.happinessModifier)
WorkshopParent.SetHappinessModifier(self, 0)
else
WorkshopParent.ModifyHappinessModifier(self, deltaHappinessModifier)
endif
endif
EndIf
endFunction
function DailyUpdateSurplusResources(WorkshopDataScript:WorkshopRatingKeyword[] ratings, DailyUpdateData updateData, ObjectReference containerRef)
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
WorkshopParent.wsTrace(self + " Add surplus to workshop container: ")
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
; add surplus (if any) to container
; check for max stored resources
int currentStoredFood = containerRef.GetItemCount(WorkshopParent.WorkshopConsumeFood)
int currentStoredWater = containerRef.GetItemCount(WorkshopParent.WorkshopConsumeWater)
int currentStoredScavenge = containerRef.GetItemCount(WorkshopParent.WorkshopConsumeScavenge)
int currentStoredFertilizer = containerRef.GetItemCount(WorkshopParent.WorkshopProduceFertilizer)
WorkshopParent.wsTrace(self + " Check stored resources: food=" + currentStoredFood + ", water=" + currentStoredWater + ", scavenge=" + currentStoredScavenge)
bool bAllowFoodProduction = true
if currentStoredFood > maxStoredFoodBase + maxStoredFoodPerPopulation * updateData.totalPopulation
bAllowFoodProduction = false
endif
bool bAllowWaterProduction = true
if currentStoredWater > maxStoredWaterBase + math.floor(maxStoredWaterPerPopulation * updateData.totalPopulation)
bAllowWaterProduction = false
endif
bool bAllowScavengeProduction = true
if currentStoredScavenge > maxStoredScavengeBase + maxStoredScavengePerPopulation * updateData.totalPopulation
bAllowScavengeProduction = false
endif
bool bAllowFertilizerProduction = true
if currentStoredFertilizer > maxStoredFertilizerBase
bAllowFertilizerProduction = false
endif
maxBrahminFertilizerProduction
WorkshopParent.wsTrace(self + " Allow production? food: " + bAllowFoodProduction + ", water: " + bAllowWaterProduction + ", scavenge: " + bAllowScavengeProduction)
; add to workshop container
if updateData.foodProduction > 0 && bAllowFoodProduction
; MOVED FROM PRODUCTION SECTION:
; - previously, multiplied all food production by productivity
; - but, it was confusing if base food rating was higher than population but still red
; - NOW: consume first, then multiply the surplus by productivity
; food rating is multiplied by productivity
updateData.foodProduction = math.Floor(updateData.foodProduction * updateData.productivity)
WorkshopParent.wsTrace(self + " FOOD SURPLUS: +" + updateData.foodProduction)
if updateData.foodProduction > 0
WorkshopParent.ProduceFood(self, updateData.foodProduction)
endif
endif
if updateData.waterProduction > 0 && bAllowWaterProduction
WorkshopParent.wsTrace(self + " WATER SURPLUS: +" + updateData.waterProduction)
containerRef.AddItem(WorkshopParent.WorkshopProduceWater, updateData.waterProduction)
endif
if updateData.brahminPopulation > 0 && bAllowFertilizerProduction
int fertilizerProduction = Math.Min(updateData.brahminPopulation, maxBrahminFertilizerProduction) as int
WorkshopParent.wsTrace(self + " FERTILIZER PRODUCTION: +" + fertilizerProduction)
containerRef.AddItem(WorkshopParent.WorkshopProduceFertilizer, fertilizerProduction)
endif
; scavenging by unassigned population, minus wounded population (not quite accurate but good enough)
int scavengePopulation = (updateData.unassignedPopulation - GetValue(ratings[WorkshopParent.WorkshopRatingDamagePopulation].resourceValue)) as int
; add in general scavenging rating
int scavengeProductionGeneral = GetValue(ratings[WorkshopParent.WorkshopRatingScavengeGeneral].resourceValue) as int
; scavenging is multiplied by productivity (happiness) and damage (wounded people)
int scavengeAmount = math.Ceiling(scavengePopulation * updateData.productivity * updateData.damageMult + scavengeProductionGeneral*updateData.productivity)
WorkshopParent.wsTrace(self + " scavenge population: " + scavengePopulation + " unassigned, " + scavengeProductionGeneral + " dedicated scavengers")
if scavengeAmount > 0 && bAllowScavengeProduction
WorkshopParent.wsTrace(self + " SCAVENGING: +" + scavengeAmount)
containerRef.AddItem(WorkshopParent.WorkshopProduceScavenge, scavengeAmount)
endif
if updateData.vendorIncome > 0
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
WorkshopParent.wsTrace(self + " Vendor income: ")
WorkshopParent.wsTrace(self + "------------------------------------------------------------------------------ ")
WorkshopParent.wsTrace(self + " Productivity mult: +" + updateData.productivity, bNormalTraceAlso = showVendorTraces)
int vendorIncomeFinal = 0
; get linked population with productivity excluded
float linkedPopulation = WorkshopParent.GetLinkedPopulation(self, false)
WorkshopParent.wsTrace(self + " Linked population: +" + linkedPopulation, bNormalTraceAlso = showVendorTraces)
float vendorPopulation = linkedPopulation + updateData.totalPopulation
WorkshopParent.wsTrace(self + " Total population: +" + vendorPopulation, bNormalTraceAlso = showVendorTraces)
; only get income if population >= minimum
if vendorPopulation >= minVendorIncomePopulation
; get productivity-adjusted linked population
linkedPopulation = WorkshopParent.GetLinkedPopulation(self, true)
WorkshopParent.wsTrace(self + " Linked population (productivity adjusted): +" + linkedPopulation, bNormalTraceAlso = showVendorTraces)
; our population also gets productivity factor
vendorPopulation = updateData.totalPopulation * updateData.productivity + linkedPopulation
WorkshopParent.wsTrace(self + " Total vendor population: " + vendorPopulation, bNormalTraceAlso = showVendorTraces)
WorkshopParent.wsTrace(self + " Base income: +" + updateData.vendorIncome, bNormalTraceAlso = showVendorTraces)
float incomeBonus = updateData.vendorIncome * vendorIncomePopulationMult * vendorPopulation
WorkshopParent.wsTrace(self + " Population bonus: +" + incomeBonus, bNormalTraceAlso = showVendorTraces)
updateData.vendorIncome = updateData.vendorIncome + incomeBonus
; vendor income is multiplied by productivity (happiness)
vendorIncomeFinal = math.Ceiling(updateData.vendorIncome)
; don't go above max allowed
vendorIncomeFinal = math.Min(vendorIncomeFinal, maxVendorIncome) as int
; add to workshop container
if vendorIncomeFinal >= 1.0
containerRef.AddItem(WorkshopParent.WorkshopProduceVendorIncome, vendorIncomeFinal)
endif
endif
WorkshopParent.wsTrace(self + " VENDOR INCOME: " + vendorIncomeFinal, bNormalTraceAlso = showVendorTraces)
EndIf
endFunction
; ***********************************************
; END DAILY UPDATE HELPER FUNCTIONS
; ***********************************************
; TEMP:
bool showVendorTraces = true
function RepairDamage()
WorkshopParent.wsTrace(" Repair damage: " + self)
; create local pointer to WorkshopRatings array to speed things up
WorkshopDataScript:WorkshopRatingKeyword[] ratings = WorkshopParent.WorkshopRatings
; repair damage to each resource
RepairDamageToResource(ratings[WorkshopParent.WorkshopRatingFood].resourceValue)
RepairDamageToResource(ratings[WorkshopParent.WorkshopRatingWater].resourceValue)
RepairDamageToResource(ratings[WorkshopParent.WorkshopRatingSafety].resourceValue)
RepairDamageToResource(ratings[WorkshopParent.WorkshopRatingPower].resourceValue)
RepairDamageToResource(ratings[WorkshopParent.WorkshopRatingPopulation].resourceValue)
; repair damage (this is an overall rating that won't exactly match each resource rating)
float currentDamage = GetValue(ratings[WorkshopParent.WorkshopRatingDamageCurrent].resourceValue)
if currentDamage > 0
; update current damage rating
WorkshopParent.UpdateCurrentDamage(self)
endif
endFunction
function RepairDamageToResource(ActorValue resourceValue)
; get corresponding damage actor value
ActorValue damageRating = WorkshopParent.GetDamageRatingValue(resourceValue)
; create local pointer to WorkshopRatings array to speed things up
WorkshopDataScript:WorkshopRatingKeyword[] ratings = WorkshopParent.WorkshopRatings
bool bPopulationDamage = ( damageRating == ratings[WorkshopParent.WorkshopRatingDamagePopulation].resourceValue )
; get current damage - population is a special case
float currentDamage
if bPopulationDamage
currentDamage = WorkshopParent.GetPopulationDamage(self)
else
currentDamage = GetValue(damageRating)
endif
WorkshopParent.wsTrace(self + " RepairDamageToResource: damageRating=" + damageRating + " bPopulationDamage=" + bPopulationDamage)
int currentWorkshopID = WorkshopParent.WorkshopCurrentWorkshopID.GetValueInt()
if currentDamage > 0
; amount repaired
WorkshopParent.wsTrace(self + " RepairDamageToResource: " + currentDamage + " for " + " resourceValue=" + resourceValue)
; scale this by population (uninjured) - unless this is population
float repairAmount = 1
bool bHealedActor = false ; set to true if we find an actor to heal
if damageRating != ratings[WorkshopParent.WorkshopRatingDamagePopulation].resourceValue
repairAmount = CalculateRepairAmount(ratings)
repairAmount = math.Max(repairAmount, 1.0)
WorkshopParent.wstrace(" repair amount=" + repairAmount)
else
; if this is population, try to heal an actor:
; are any of this workshop's NPC assigned to caravans?
Location[] linkedLocations = myLocation.GetAllLinkedLocations(WorkshopParent.WorkshopCaravanKeyword)
if linkedLocations.Length > 0
; there is at least 1 actor - find them
; loop through caravan actors
int index = 0
while (index < WorkshopParent.CaravanActorAliases.GetCount())
; check this actor - is he owned by this workshop?
WorkShopNPCScript caravanActor = WorkshopParent.CaravanActorAliases.GetAt(index) as WorkshopNPCScript
if caravanActor && caravanActor.GetWorkshopID() == workshopID && caravanActor.IsWounded()
; is this actor wounded? if so heal and exit
bHealedActor = true
WorkshopParent.WoundActor(caravanActor, false)
return
endif
index += 1
endwhile
endif
if !bHealedActor
; if this is the current workshop, we can try to heal one of the actors (otherwise we don't have them)
if workshopID == currentWorkshopID
int i = 0
ObjectReference[] WorkshopActors = WorkshopParent.GetWorkshopActors(self)
while i < WorkshopActors.Length && !bHealedActor
WorkShopNPCScript theActor = WorkshopActors[i] as WorkShopNPCScript
if theActor && theActor.IsWounded()
bHealedActor = true
WorkshopParent.WoundActor(theActor, false)
endif
i += 1
endWhile
endif
endif
endif
if !bHealedActor
; if we healed an actor, keyword data already modified
repairAmount = math.min(repairAmount, currentDamage)
WorkshopParent.ModifyResourceData(damageRating, self, repairAmount*-1.0)
WorkshopParent.wsTrace(" workshopID=" + workshopID + ", currentWorkshopID=" + currentWorkshopID)
; if this is the current workshop, find an object to repair (otherwise we don't have them)
if workshopID == currentWorkshopID && damageRating != ratings[WorkshopParent.WorkshopRatingDamagePopulation].resourceValue
WorkshopParent.wsTrace(" Current workshop - find item(s) to repair " + repairAmount + " damage...")
int i = 0
; want only damaged objects that produce this resource
ObjectReference[] ResourceObjects = GetWorkshopResourceObjects(akAV = resourceValue, aiOption = 1)
while i < ResourceObjects.Length && repairAmount > 0
WorkShopObjectScript theObject = ResourceObjects[i] as WorkShopObjectScript
float damage = theObject.GetResourceDamage(resourceValue)
WorkshopParent.wstrace(" " + theObject + "=" + damage + " damage")
if damage > 0
float modDamage = math.min(repairAmount, damage)*-1.0
if theObject.ModifyResourceDamage(resourceValue, modDamage)
repairAmount += modDamage
endif
endif
i += 1
endWhile
endif
endif
endif
endFunction
; NOTE: pass in ratings array to speed things up since this is often part of an iteration
float function CalculateRepairAmount(WorkshopDataScript:WorkshopRatingKeyword[] ratings)
; RESOURCE CHANGE: now GetValue(population) is the unwounded population; GetBaseValue() is total population
float uninjuredPopulation = GetValue(ratings[WorkshopParent.WorkshopRatingPopulation].resourceValue)
float productivityMult = GetProductivityMultiplier(ratings)
float amountRepaired = math.Ceiling(uninjuredPopulation * damageDailyPopulationMult * damageDailyRepairBase * productivityMult)
;WorkshopParent.wstrace(" CalculateRepairAmount " + self + ": uninjured population=" + uninjuredPopulation + ", productivityMult=" + productivityMult + ": amount repaired=" + amountRepaired)
return amountRepaired
endFunction
function CheckForAttack(bool bForceAttack = false)
; bForceAttack = true - don't roll, automatically trigger attack
WorkshopParent.wsTrace("------------------------------------------------------------------------------ ")
WorkshopParent.wsTrace(" Check for attack: " + self)
WorkshopParent.wsTrace("------------------------------------------------------------------------------ ")
; create local pointer to WorkshopRatings array to speed things up
WorkshopDataScript:WorkshopRatingKeyword[] ratings = WorkshopParent.WorkshopRatings
; PREVIOUS ATTACKS:
; increment days since last attack
WorkshopParent.ModifyResourceData(ratings[WorkshopParent.WorkshopRatingLastAttackDaysSince].resourceValue, self, 1.0)
; attacks allowed at all?
if AllowAttacks == false
WorkshopParent.wsTrace(" attacks not allowed - no attack roll for " + self)
return
EndIf
; don't attack unowned workshop if flag unless allowed
if AllowAttacksBeforeOwned == false && OwnedByPlayer == false && bForceAttack == false
WorkshopParent.wsTrace(" attacks on unowned workshop not allowed - no attack roll for " + self)
return
endif
; NEW ATTACK:
ObjectReference containerRef = GetContainer()
if !containerRef
WorkshopParent.wsTrace(self + " ERROR - no container linked to workshop " + self + " with " + WorkshopParent.WorkshopLinkContainer, 2)
return
endif
int totalPopulation = GetBaseValue(ratings[WorkshopParent.WorkshopRatingPopulation].resourceValue) as int
int safety = GetValue(ratings[WorkshopParent.WorkshopRatingSafety].resourceValue) as int
int safetyPerNPC = 0
if totalPopulation > 0
safetyperNPC = math.ceiling(safety/totalPopulation)
elseif bForceAttack
safetyperNPC = safety
else
; no population - no attack
WorkshopParent.wsTrace(" 0 population - no attack roll")
return
endif
int daysSinceLastAttack = GetValue(ratings[WorkshopParent.WorkshopRatingLastAttackDaysSince].resourceValue) as int
if minDaysSinceLastAttack > daysSinceLastAttack && !bForceAttack
; attack happened recently - no new attack
WorkshopParent.wsTrace(" " + daysSinceLastAttack + " days since last attack - no attack roll")
return
endif
int foodRating = GetTotalFoodRating(ratings)
int waterRating = GetTotalWaterRating(ratings)
WorkshopParent.wsTrace(" Starting stats:")
WorkshopParent.wsTrace(" population=" + totalPopulation)
WorkshopParent.wsTrace(" food rating=" + foodRating)
WorkshopParent.wsTrace(" water rating=" + waterRating)
WorkshopParent.wsTrace(" total safety=" + safety)
WorkshopParent.wsTrace(" safety per NPC=" + safetyPerNPC)
; chance of attack:
; base chance + (food/water rating) - safety - total population
WorkshopParent.wsTrace(" Attack chance:")
WorkshopParent.wsTrace(" base chance=" + attackChanceBase)
WorkshopParent.wsTrace(" resources=+" + attackChanceResourceMult * (foodRating + waterRating))
WorkshopParent.wsTrace(" safety=-" + attackChanceSafetyMult*safety)
WorkshopParent.wsTrace(" population=-" + attackChancePopulationMult * totalPopulation)
float attackChance = attackChanceBase + attackChanceResourceMult * (foodRating + waterRating) - attackChanceSafetyMult*safety - attackChancePopulationMult * totalPopulation
if attackChance < attackChanceBase
attackChance = attackChanceBase
endif
WorkshopParent.wsTrace(" TOTAL=" + attackChance)
float attackRoll = Utility.RandomFloat()
WorkshopParent.wsTrace(" Attack roll = " + attackRoll)
if attackRoll <= attackChance || bForceAttack
int attackStrength = WorkshopParent.CalculateAttackStrength(foodRating, waterRating)
WorkshopParent.TriggerAttack(self, attackStrength)
endif
endFunction
; helper function to calculate total food = food production + inventory
int function GetTotalFoodRating(WorkshopDataScript:WorkshopRatingKeyword[] ratings)
int foodRating = GetValue(ratings[WorkshopParent.WorkshopRatingFood].resourceValue) as int
foodRating = foodRating + GetContainer().GetItemCount(WorkshopParent.WorkshopConsumeFood)
;WorkshopParent.wstrace(self + " GetTotalFoodRating=" + foodRating)
return foodRating
endFunction
; helper function to calculate total water = water production + inventory
int function GetTotalWaterRating(WorkshopDataScript:WorkshopRatingKeyword[] ratings)
int waterRating = GetValue(ratings[WorkshopParent.WorkshopRatingWater].resourceValue) as int
waterRating = waterRating + GetContainer().GetItemCount(WorkshopParent.WorkshopConsumeWater)
;WorkshopParent.wstrace(self + " GetTotalWaterRating=" + waterRating)
return waterRating
endFunction
; helper function - add modValue to the specified actor's happiness
; holds the rules for how happiness can go up based on the actor's various ratings (food, water, shelter, etc.)
float function CheckActorHappiness(float currentHappiness, bool bFood, bool bWater, bool bBed, bool bShelter)
; check rules
if !bWater && currentHappiness > maxHappinessNoWater
; max happiness with no water is maxHappinessNoWater
currentHappiness = maxHappinessNoWater
endif
if !bFood && currentHappiness > maxHappinessNoFood
; max happiness with no food is maxHappinessNoFood
currentHappiness = maxHappinessNoFood
endif
if !bShelter && currentHappiness > maxHappinessNoShelter
; max happiness with no shelter is maxHappinessNoShelter
currentHappiness = maxHappinessNoShelter
endif
return currentHappiness
endFunction
; get productivity multiplier for this workshop
float function GetProductivityMultiplier(WorkshopDataScript:WorkshopRatingKeyword[] ratings)
float currentHappiness = GetValue(ratings[WorkshopParent.WorkshopRatingHappiness].resourceValue)
return minProductivity + (currentHappiness/100) * (1 - minProductivity)
endFunction
int function GetWorkshopID()
if workshopID < 0
InitWorkshopID(WorkshopParent.GetWorkshopID(self))
endif
return workshopID
endFunction
function InitWorkshopID(int newWorkshopID)
if workshopID < 0
workshopID = newWorkshopID
endif
endFunction
; helper function to recalc
; we don't normally want to do this when unloaded or everything will be 0
; TRUE = we did recalc; FALSE = we didn't
bool function RecalculateWorkshopResources(bool bOnlyIfLocationLoaded = true)
if bOnlyIfLocationLoaded == false || myLocation.IsLoaded()
;WorkshopParent.wstrace(self + " RecalculateWorkshopResources=TRUE")
RecalculateResources()
return true
else
;WorkshopParent.wstrace(self + " RecalculateWorkshopResources=FALSE")
return false
endif
endFunction
| 1 | 0.557523 | 1 | 0.557523 | game-dev | MEDIA | 0.983092 | game-dev | 0.904416 | 1 | 0.904416 |
libsdl-org/sdlwiki | 1,990 | SDL3/SDL_PushEvent.md | # SDL_PushEvent
Add an event to the event queue.
## Header File
Defined in [<SDL3/SDL_events.h>](https://github.com/libsdl-org/SDL/blob/main/include/SDL3/SDL_events.h)
## Syntax
```c
bool SDL_PushEvent(SDL_Event *event);
```
## Function Parameters
| | | |
| ------------------------ | --------- | ---------------------------------------------------- |
| [SDL_Event](SDL_Event) * | **event** | the [SDL_Event](SDL_Event) to be added to the queue. |
## Return Value
(bool) Returns true on success, false if the event was filtered or on
failure; call [SDL_GetError](SDL_GetError)() for more information. A common
reason for error is the event queue being full.
## Remarks
The event queue can actually be used as a two way communication channel.
Not only can events be read from the queue, but the user can also push
their own events onto it. `event` is a pointer to the event structure you
wish to push onto the queue. The event is copied into the queue, and the
caller may dispose of the memory pointed to after
[SDL_PushEvent](SDL_PushEvent)() returns.
Note: Pushing device input events onto the queue doesn't modify the state
of the device within SDL.
Note: Events pushed onto the queue with [SDL_PushEvent](SDL_PushEvent)()
get passed through the event filter but events added with
[SDL_PeepEvents](SDL_PeepEvents)() do not.
For pushing application-specific events, please use
[SDL_RegisterEvents](SDL_RegisterEvents)() to get an event type that does
not conflict with other code that also wants its own custom event types.
## Thread Safety
It is safe to call this function from any thread.
## Version
This function is available since SDL 3.2.0.
## See Also
- [SDL_PeepEvents](SDL_PeepEvents)
- [SDL_PollEvent](SDL_PollEvent)
- [SDL_RegisterEvents](SDL_RegisterEvents)
----
[CategoryAPI](CategoryAPI), [CategoryAPIFunction](CategoryAPIFunction), [CategoryEvents](CategoryEvents)
| 1 | 0.72544 | 1 | 0.72544 | game-dev | MEDIA | 0.932612 | game-dev | 0.551315 | 1 | 0.551315 |
Die4Ever/deus-ex-randomizer | 1,827 | src/Augmentations/DeusEx/Classes/AugEMP.uc | #compileif injections
class DXRAugEMP injects AugEMP;
function UpdateBalance()
{
local int i;
if(class'MenuChoice_BalanceAugs'.static.IsEnabled()) {
LevelValues[0] = 0.7;
LevelValues[1] = 0.4;
LevelValues[2] = 0.2;
LevelValues[3] = 0;
} else {
LevelValues[0] = 0.75;
LevelValues[1] = 0.5;
LevelValues[2] = 0.25;
LevelValues[3] = 0;
}
for(i=0; i<ArrayCount(LevelValues); i++) {
default.LevelValues[i] = LevelValues[i];
}
// DXRando: AugEMP makes you immune to Scramble Grenades
Description = "Nanoscale EMP generators partially protect individual nanites and reduce bioelectrical drain by canceling incoming pulses. ";
if(class'MenuChoice_BalanceEtc'.static.IsEnabled()) {
Description = Description $ "All levels make you immune to Scramble Grenades."
$ "|n|nTECH ONE: Damage from EMP and electric attacks is reduced slightly."
$ "|n|nTECH TWO: Damage from EMP and electric attacks is reduced moderately."
$ "|n|nTECH THREE: Damage from EMP and electric attacks is reduced significantly."
$ "|n|nTECH FOUR: An agent is nearly invulnerable to damage from EMP and electric attacks.";
} else {
Description = Description $ "|n|nTECH ONE: Damage from EMP attacks is reduced slightly."
$ "|n|nTECH TWO: Damage from EMP attacks is reduced moderately."
$ "|n|nTECH THREE: Damage from EMP attacks is reduced significantly."
$ "|n|nTECH FOUR: An agent is nearly invulnerable to damage from EMP attacks.";
}
default.Description = Description;
}
defaultproperties
{
bAutomatic=true
AutoLength=1
AutoEnergyMult=1
LevelValues(0)=0.7
LevelValues(1)=0.4
LevelValues(2)=0.2
LevelValues(3)=0
}
| 1 | 0.833706 | 1 | 0.833706 | game-dev | MEDIA | 0.882514 | game-dev | 0.584416 | 1 | 0.584416 |
oiuv/mud | 1,382 | clone/misc/part.c | // part.c 身体某部位
#include <ansi.h>
inherit ITEM;
inherit F_FOOD;
inherit F_CUTABLE;
inherit F_SILENTDEST;
void eat_effect();
int is_body_part() { return 1; }
void create()
{
set_name(RED "残肢" NOR, ({"body part"}));
set_weight(50);
if (clonep())
set_default_object(__FILE__);
else
{
set("unit", "块");
set("value", 0);
set("food_supply", 15);
set("food_remaining", 4);
}
}
string long() { return ::long() + extra_desc(); }
int set_from(object owner)
{
apply_effect((: eat_effect :));
switch (name())
{
case "眼珠":
case "耳朵":
case "鼻子":
case "舌头":
set("food_supply", 10);
set("food_remaining", 1);
break;
case "手掌":
case "人脚":
set("food_supply", 15);
set("food_remaining", 2);
break;
case "手臂":
case "人腿":
set("food_supply", 20);
set("food_remaining", 5);
break;
default:
set("food_supply", 5);
set("food_remaining", 2);
}
return 1;
}
int finish_eat()
{
object ob;
if (name() != "手臂" && name() != "人腿")
return 0;
ob = new ("/clone/misc/bone");
ob->move(environment());
return 0;
}
void eat_effect()
{
object me;
me = this_player();
me->add("combat/eatman", 1);
if (me->query("shen") > -1000)
me->set("shen", -1000);
}
| 1 | 0.748352 | 1 | 0.748352 | game-dev | MEDIA | 0.617757 | game-dev | 0.863332 | 1 | 0.863332 |
dontpanic92/OpenPAL3 | 2,796 | yaobow/shared/src/scripting/sce/commands/role_path_to.rs | use crate::openpal3::directors::SceneManagerExtensions;
use crate::openpal3::scene::RoleController;
use crate::scripting::sce::{SceCommand, SceState};
use crosscom::ComRc;
use imgui::Ui;
use radiance::comdef::ISceneManager;
use radiance::math::Vec3;
#[derive(Debug, Clone)]
pub struct SceCommandRolePathTo {
role_id: i32,
nav_x: f32,
nav_z: f32,
run: i32,
}
impl SceCommand for SceCommandRolePathTo {
fn initialize(&mut self, scene_manager: ComRc<ISceneManager>, state: &mut SceState) {
let _role = scene_manager.resolve_role_mut_do(state, self.role_id, |_e, r| {
if self.run == 1 {
r.get().run();
} else {
r.get().walk();
}
});
}
fn update(
&mut self,
scene_manager: ComRc<ISceneManager>,
_ui: &Ui,
state: &mut SceState,
delta_sec: f32,
) -> bool {
const WALK_SPEED: f32 = 80.;
const RUN_SPEED: f32 = 175.;
let speed = if self.run == 1 { RUN_SPEED } else { WALK_SPEED };
let role = scene_manager.get_resolved_role(state, self.role_id);
if role.is_none() {
return true;
}
let role_controller = RoleController::get_role_controller(role.unwrap()).unwrap();
let to = {
let scene = scene_manager.scn_scene().unwrap().get();
scene.nav_coord_to_scene_coord(
role_controller.get().nav_layer(),
self.nav_x,
self.nav_z,
)
};
let role = scene_manager
.get_resolved_role(state, self.role_id)
.unwrap();
let position = role.transform().borrow().position();
// TODO: WHY?
if position.x.is_nan() {
return true;
}
let step = speed * delta_sec;
let remain = Vec3::sub(&to, &position);
let completed = remain.norm() < step;
let new_position = if completed {
to
} else {
Vec3::add(
&position,
&Vec3::scalar_mul(step, &Vec3::normalized(&remain)),
)
};
let mut look_at = Vec3::new(to.x, position.y, to.z);
if self.run == 2 {
look_at = Vec3::add(&position, &Vec3::sub(&position, &to));
}
role.transform()
.borrow_mut()
.look_at(&look_at)
.set_position(&new_position);
if completed {
role_controller.get().idle();
}
completed
}
}
impl SceCommandRolePathTo {
pub fn new(role_id: i32, nav_x: i32, nav_z: i32, run: i32) -> Self {
Self {
role_id,
nav_x: nav_x as f32,
nav_z: nav_z as f32,
run,
}
}
}
| 1 | 0.893873 | 1 | 0.893873 | game-dev | MEDIA | 0.684582 | game-dev | 0.917006 | 1 | 0.917006 |
google/swiftshader | 4,482 | third_party/llvm-10.0/llvm/lib/Support/IntervalMap.cpp | //===- lib/Support/IntervalMap.cpp - A sorted interval map ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the few non-templated functions in IntervalMap.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/IntervalMap.h"
namespace llvm {
namespace IntervalMapImpl {
void Path::replaceRoot(void *Root, unsigned Size, IdxPair Offsets) {
assert(!path.empty() && "Can't replace missing root");
path.front() = Entry(Root, Size, Offsets.first);
path.insert(path.begin() + 1, Entry(subtree(0), Offsets.second));
}
NodeRef Path::getLeftSibling(unsigned Level) const {
// The root has no siblings.
if (Level == 0)
return NodeRef();
// Go up the tree until we can go left.
unsigned l = Level - 1;
while (l && path[l].offset == 0)
--l;
// We can't go left.
if (path[l].offset == 0)
return NodeRef();
// NR is the subtree containing our left sibling.
NodeRef NR = path[l].subtree(path[l].offset - 1);
// Keep right all the way down.
for (++l; l != Level; ++l)
NR = NR.subtree(NR.size() - 1);
return NR;
}
void Path::moveLeft(unsigned Level) {
assert(Level != 0 && "Cannot move the root node");
// Go up the tree until we can go left.
unsigned l = 0;
if (valid()) {
l = Level - 1;
while (path[l].offset == 0) {
assert(l != 0 && "Cannot move beyond begin()");
--l;
}
} else if (height() < Level)
// end() may have created a height=0 path.
path.resize(Level + 1, Entry(nullptr, 0, 0));
// NR is the subtree containing our left sibling.
--path[l].offset;
NodeRef NR = subtree(l);
// Get the rightmost node in the subtree.
for (++l; l != Level; ++l) {
path[l] = Entry(NR, NR.size() - 1);
NR = NR.subtree(NR.size() - 1);
}
path[l] = Entry(NR, NR.size() - 1);
}
NodeRef Path::getRightSibling(unsigned Level) const {
// The root has no siblings.
if (Level == 0)
return NodeRef();
// Go up the tree until we can go right.
unsigned l = Level - 1;
while (l && atLastEntry(l))
--l;
// We can't go right.
if (atLastEntry(l))
return NodeRef();
// NR is the subtree containing our right sibling.
NodeRef NR = path[l].subtree(path[l].offset + 1);
// Keep left all the way down.
for (++l; l != Level; ++l)
NR = NR.subtree(0);
return NR;
}
void Path::moveRight(unsigned Level) {
assert(Level != 0 && "Cannot move the root node");
// Go up the tree until we can go right.
unsigned l = Level - 1;
while (l && atLastEntry(l))
--l;
// NR is the subtree containing our right sibling. If we hit end(), we have
// offset(0) == node(0).size().
if (++path[l].offset == path[l].size)
return;
NodeRef NR = subtree(l);
for (++l; l != Level; ++l) {
path[l] = Entry(NR, 0);
NR = NR.subtree(0);
}
path[l] = Entry(NR, 0);
}
IdxPair distribute(unsigned Nodes, unsigned Elements, unsigned Capacity,
const unsigned *CurSize, unsigned NewSize[],
unsigned Position, bool Grow) {
assert(Elements + Grow <= Nodes * Capacity && "Not enough room for elements");
assert(Position <= Elements && "Invalid position");
if (!Nodes)
return IdxPair();
// Trivial algorithm: left-leaning even distribution.
const unsigned PerNode = (Elements + Grow) / Nodes;
const unsigned Extra = (Elements + Grow) % Nodes;
IdxPair PosPair = IdxPair(Nodes, 0);
unsigned Sum = 0;
for (unsigned n = 0; n != Nodes; ++n) {
Sum += NewSize[n] = PerNode + (n < Extra);
if (PosPair.first == Nodes && Sum > Position)
PosPair = IdxPair(n, Position - (Sum - NewSize[n]));
}
assert(Sum == Elements + Grow && "Bad distribution sum");
// Subtract the Grow element that was added.
if (Grow) {
assert(PosPair.first < Nodes && "Bad algebra");
assert(NewSize[PosPair.first] && "Too few elements to need Grow");
--NewSize[PosPair.first];
}
#ifndef NDEBUG
Sum = 0;
for (unsigned n = 0; n != Nodes; ++n) {
assert(NewSize[n] <= Capacity && "Overallocated node");
Sum += NewSize[n];
}
assert(Sum == Elements && "Bad distribution sum");
#endif
return PosPair;
}
} // namespace IntervalMapImpl
} // namespace llvm
| 1 | 0.981946 | 1 | 0.981946 | game-dev | MEDIA | 0.275466 | game-dev | 0.998096 | 1 | 0.998096 |
gflze/CSGO-ZE-Configs | 1,735 | stripper/ze_jiba_journey_v4_3.cfg | ;don't kill zms with humans, as it can bug the score
modify:
{
match:
{
"classname" "logic_compare"
"targetname" "counter_human_compare"
}
delete:
{
"OnEqualTo" "nukeEnable51"
}
insert:
{
"OnEqualTo" "playerRunScriptCodeforeach(k,_ in{SetHealth=0}){if(self.GetTeam()==3&&self.GetHealth()>0)EntFireByHandle(self, k,(0).tostring(),0,null,null)}51"
}
}
;kill humans if zms get lvl 2 bridge trigger, to prevent delaying
modify:
{
match:
{
"classname" "func_button"
"targetname" "button_bridge_bomb20"
}
delete:
{
"OnPressed" "button_test_spawnTestActivator0-1"
}
insert:
{
"OnPressed" "button_test_spawnTestActivator01"
}
}
modify:
{
match:
{
"classname" "func_button"
"targetname" "button_bridge_bomb21"
}
delete:
{
"OnPressed" "button_test_spawnTestActivator0-1"
}
insert:
{
"OnPressed" "button_test_spawnTestActivator01"
}
}
modify:
{
match:
{
"classname" "func_button"
"targetname" "button_bridge_bomb23"
}
delete:
{
"OnPressed" "button_test_spawnTestActivator0-1"
}
insert:
{
"OnPressed" "button_test_spawnTestActivator01"
}
}
modify:
{
match:
{
"classname" "filter_activator_team"
"targetname" "button_test_spawn"
}
insert:
{
"OnFail" "cmdCommandsay <<ZOMBIES ACTIVATED A LEVER, SLAYING ALL HUMANS>>01"
"OnFail" "cmdCommandsay <<ZOMBIES ACTIVATED A LEVER, SLAYING ALL HUMANS>>11"
"OnFail" "cmdCommandsay <<ZOMBIES ACTIVATED A LEVER, SLAYING ALL HUMANS>>21"
"OnFail" "cmdCommandsay <<ZOMBIES ACTIVATED A LEVER, SLAYING ALL HUMANS>>31"
"OnFail" "playerRunScriptCodeforeach(k,_ in{SetHealth=0}){if(self.GetTeam()==3&&self.GetHealth()>0)EntFireByHandle(self, k,(0).tostring(),0,null,null)}51"
}
} | 1 | 0.897239 | 1 | 0.897239 | game-dev | MEDIA | 0.968618 | game-dev | 0.809393 | 1 | 0.809393 |
newhoryzon/farmers-delight-fabric | 7,424 | src/main/java/com/nhoryzon/mc/farmersdelight/item/enumeration/Foods.java | package com.nhoryzon.mc.farmersdelight.item.enumeration;
import com.nhoryzon.mc.farmersdelight.item.ConsumableItem;
import com.nhoryzon.mc.farmersdelight.registry.EffectsRegistry;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.item.FoodComponent;
import java.util.function.Supplier;
public enum Foods {
// Raw Crops
CABBAGE(2, .4f),
TOMATO(1, .3f),
ONION(2, .4f),
// Drinks (mostly for effects)
APPLE_CIDER(0, 0, () -> new StatusEffectInstance(StatusEffects.ABSORPTION, ConsumableItem.SHORT_DURATION, 0), 1.f, false, false, true),
// Basic Foods
FRIED_EGG(4, .4f),
TOMATO_SAUCE(4, .4f),
WHEAT_DOUGH(2, .3f, () -> new StatusEffectInstance(StatusEffects.HUNGER, ConsumableItem.BRIEF_DURATION, 0), .3f),
RAW_PASTA(2, .3f, () -> new StatusEffectInstance(StatusEffects.HUNGER, ConsumableItem.BRIEF_DURATION, 0), .3f),
PIE_CRUST(2, .2f),
PUMPKIN_SLICE(3, .3f),
CABBAGE_LEAF(1, .4f),
MINCED_BEEF(2, .3f, true),
BEEF_PATTY(4, .8f, true),
CHICKEN_CUTS(1, .3f, () -> new StatusEffectInstance(StatusEffects.HUNGER, ConsumableItem.BRIEF_DURATION, 0), .3f, true),
COOKED_CHICKEN_CUTS(3, .6f, true),
BACON(2, .3f, true),
COOKED_BACON(4, .8f, true),
COD_SLICE(1, .1f),
COOKED_COD_SLICE(3, .5f),
SALMON_SLICE(1, .1f),
COOKED_SALMON_SLICE(3, .8f),
MUTTON_CHOP(1, .3f, true),
COOKED_MUTTON_CHOP(3, .8f, true),
HAM(5, .3f),
SMOKED_HAM(10, .8f),
// Sweets
POPSICLE(3, .2f, null, .0f, false, true, true),
COOKIES(2, .1f, null, .0f, false, true, false),
CAKE_SLICE(2, .1f, () -> new StatusEffectInstance(StatusEffects.SPEED, 400, 0), 1.f, false, true, false),
PIE_SLICE(3, .3f, () -> new StatusEffectInstance(StatusEffects.SPEED, ConsumableItem.BRIEF_DURATION, 0), 1.f, false, true, false),
FRUIT_SALAD(6, .6f, () -> new StatusEffectInstance(StatusEffects.REGENERATION, 100, 0), 1.f),
GLOW_BERRY_CUSTARD(7, .6f, () -> new StatusEffectInstance(StatusEffects.GLOWING, 100, 0), 1.f),
// Handheld Foods
MIXED_SALAD(6, .6f, () -> new StatusEffectInstance(StatusEffects.REGENERATION, 100, 0), 1.f),
NETHER_SALAD(5, .4f, () -> new StatusEffectInstance(StatusEffects.NAUSEA, 240, 0), .3f),
BARBECUE_STICK(8, .9f),
EGG_SANDWICH(8, .8f),
CHICKEN_SANDWICH(10, .8f),
HAMBURGER(11, .8f),
BACON_SANDWICH(10, .8f),
MUTTON_WRAP(11, .8f),
DUMPLINGS(8, .8f),
STUFFED_POTATO(10, .7f),
CABBAGE_ROLLS(6, .5f),
SALMON_ROLL(7, .6f),
COD_ROLL(7, .6f),
KELP_ROLL(12, .6f),
KELP_ROLL_SLICE(6, .5f),
// Bowl Foods
COOKED_RICE(6, .4f, () -> new StatusEffectInstance(EffectsRegistry.COMFORT.get(), ConsumableItem.BRIEF_DURATION, 0), 1.f),
BONE_BROTH(8, .7f, () -> new StatusEffectInstance(EffectsRegistry.COMFORT.get(), ConsumableItem.SHORT_DURATION, 0), 1.f),
BEEF_STEW(12, .8f, () -> new StatusEffectInstance(EffectsRegistry.COMFORT.get(), ConsumableItem.MEDIUM_DURATION, 0), 1.f),
VEGETABLE_SOUP(12, .8f, () -> new StatusEffectInstance(EffectsRegistry.COMFORT.get(), ConsumableItem.MEDIUM_DURATION, 0), 1.f),
FISH_STEW(12, .8f, () -> new StatusEffectInstance(EffectsRegistry.COMFORT.get(), ConsumableItem.MEDIUM_DURATION, 0), 1.f),
CHICKEN_SOUP(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.COMFORT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
FRIED_RICE(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
PUMPKIN_SOUP(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.COMFORT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
BAKED_COD_STEW(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.COMFORT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
NOODLE_SOUP(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.COMFORT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
// Plated Foods
BACON_AND_EGGS(10, .6f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.SHORT_DURATION, 0), 12.f),
RATATOUILLE(10, .6f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.SHORT_DURATION, 0), 1.f),
STEAK_AND_POTATOES(12, .8f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.MEDIUM_DURATION, 0), 1.f),
PASTA_WITH_MEATBALLS(12, .8f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.MEDIUM_DURATION, 0), 1.f),
PASTA_WITH_MUTTON_CHOP(12, .8f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.MEDIUM_DURATION, 0), 1.f),
MUSHROOM_RICE(12, .8f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.MEDIUM_DURATION, 0), 1.f),
ROASTED_MUTTON_CHOPS(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
VEGETABLE_NOODLES(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
SQUID_INK_PASTA(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
GRILLED_SALMON(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.MEDIUM_DURATION, 0), 1.f),
// Feast Portions
ROAST_CHICKEN(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
STUFFED_PUMPKIN(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
HONEY_GLAZED_HAM(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
SHEPHERDS_PIE(14, .75f, () -> new StatusEffectInstance(EffectsRegistry.NOURISHMENT.get(), ConsumableItem.LONG_DURATION, 0), 1.f),
DOG_FOOD(4, .2f, true);
private final Supplier<FoodComponent> food;
Foods(int hunger, float saturation) {
this(hunger, saturation, null, .0f, false, false, false);
}
Foods(int hunger, float saturation, boolean isMeat) {
this(hunger, saturation, null, .0f, isMeat, false, false);
}
Foods(int hunger, float saturation, Supplier<StatusEffectInstance> effect, float effectChance) {
this(hunger, saturation, effect, effectChance, false, false, false);
}
Foods(int hunger, float saturation, Supplier<StatusEffectInstance> effect, float effectChance, boolean isMeat) {
this(hunger, saturation, effect, effectChance, isMeat, false, false);
}
Foods(int hunger, float saturation, Supplier<StatusEffectInstance> effect, float effectChance, boolean isMeat, boolean isFastToEat, boolean alwaysEdible) {
food = () -> {
FoodComponent.Builder builder = new FoodComponent.Builder();
builder.hunger(hunger).saturationModifier(saturation);
if (effect != null) {
builder.statusEffect(effect.get(), effectChance);
}
if (isMeat) {
builder.meat();
}
if (isFastToEat) {
builder.snack();
}
if (alwaysEdible) {
builder.alwaysEdible();
}
return builder.build();
};
}
public FoodComponent get() {
return food.get();
}
} | 1 | 0.769839 | 1 | 0.769839 | game-dev | MEDIA | 0.803456 | game-dev | 0.668016 | 1 | 0.668016 |
schmooblidon/meleelight | 1,783 | src/characters/fox/moves/CLIFFJUMPQUICK.js |
import FALL from "characters/shared/moves/FALL";
import {player} from "main/main";
import {Vec2D} from "main/util/Vec2D";
import {airDrift, fastfall} from "physics/actionStateShortcuts";
import {activeStage} from "stages/activeStage";
export default {
name : "CLIFFJUMPQUICK",
offset : [[-70.8428,-14.38776],[-71.49446,-14.32052],[-72.19153,-14.1652],[-72.85054,-13.88868],[-73.38803,-13.45787],[-73.72054,-12.83965],[-73.76461,-12.00094],[-73.50131,-10.89611],[-73.00593,-9.5458],[-72.33633,-8.01628],[-71.55035,-6.37383],[-70.70587,-4.6847],[-69.86075,-3.01518],[-69.07284,-1.43152]],
canBeGrabbed : true,
init : function(p,input){
player[p].actionState = "CLIFFJUMPQUICK";
player[p].timer = 0;
player[p].phys.intangibleTimer = 14;
this.main(p,input);
},
main : function(p,input){
player[p].timer++;
if (!this.interrupt(p,input)){
const onLedge = player[p].phys.onLedge;
if(onLedge === -1){
this.canGrabLedge = false;
return;
}
const l = activeStage.ledge[onLedge];
const x = activeStage[l[0]][l[1]][l[2]].x;
const y = activeStage[l[0]][l[1]][l[2]].y;
if (player[p].timer < 15){
player[p].phys.pos = new Vec2D(x+(this.offset[player[p].timer-1][0]+68.4)*player[p].phys.face,y+this.offset[player[p].timer-1][1]);
}
if (player[p].timer === 15){
player[p].phys.cVel = new Vec2D(1.1*player[p].phys.face,4);
}
if (player[p].timer > 15){
airDrift(p,input);
fastfall(p,input);
}
}
},
interrupt : function(p,input){
if (player[p].timer > 51){
player[p].phys.onLedge = -1;
player[p].phys.ledgeRegrabCount = false;
FALL.init(p,input);
return true;
}
else {
return false;
}
}
};
| 1 | 0.824074 | 1 | 0.824074 | game-dev | MEDIA | 0.870194 | game-dev | 0.979292 | 1 | 0.979292 |
amzeratul/halley | 7,521 | src/tools/editor/src/scene/undo_stack.cpp | #include "undo_stack.h"
#include "scene_editor_window.h"
using namespace Halley;
UndoStack::UndoStack()
: maxSize(50)
, accepting(true)
{
}
void UndoStack::pushAdded(bool wasModified, gsl::span<const EntityChangeOperation> changes)
{
if (!accepting) {
return;
}
Vector<EntityChangeOperation> forwardPatches;
Vector<EntityChangeOperation> backPatches;
forwardPatches.reserve(changes.size());
backPatches.reserve(changes.size());
for (auto& change: changes) {
forwardPatches.emplace_back(change.clone());
backPatches.emplace_back(change.clone());
}
addToStack(Action(Type::EntityAdded, std::move(forwardPatches)), Action(Type::EntityRemoved, std::move(backPatches)), wasModified);
}
void UndoStack::pushRemoved(bool wasModified, gsl::span<const String> entityIds, gsl::span<const std::pair<String, int>> parents, gsl::span<const EntityData> datas)
{
if (!accepting) {
return;
}
Vector<EntityChangeOperation> forwardPatches;
Vector<EntityChangeOperation> backPatches;
forwardPatches.reserve(entityIds.size());
backPatches.reserve(entityIds.size());
for (size_t i = 0; i < entityIds.size(); ++i) {
forwardPatches.emplace_back(EntityChangeOperation{ {}, entityIds[i] });
backPatches.emplace_back(EntityChangeOperation{ std::make_unique<EntityData>(datas[i]), entityIds[i], parents[i].first, parents[i].second });
}
sortPatches(backPatches);
addToStack(Action(Type::EntityRemoved, std::move(forwardPatches)), Action(Type::EntityAdded, std::move(backPatches)), wasModified);
}
void UndoStack::pushMoved(bool wasModified, gsl::span<const EntityChangeOperation> curState, gsl::span<const EntityChangeOperation> previousState)
{
if (!accepting) {
return;
}
if (curState != previousState) {
Vector<EntityChangeOperation> forwardPatches;
Vector<EntityChangeOperation> backPatches;
for (auto& e: curState) {
forwardPatches.push_back(e.clone());
}
for (auto& e: previousState) {
backPatches.push_back(e.clone());
}
sortPatches(forwardPatches);
sortPatches(backPatches);
addToStack(Action(Type::EntityMoved, std::move(forwardPatches)), Action(Type::EntityMoved, std::move(backPatches)), wasModified);
}
}
bool UndoStack::pushModified(bool wasModified, gsl::span<const String> entityIds, gsl::span<const EntityData*> before, gsl::span<const EntityData*> after)
{
Expects(entityIds.size() == before.size());
Expects(entityIds.size() == after.size());
if (!accepting) {
return true;
}
Vector<EntityChangeOperation> forwardPatches;
Vector<EntityChangeOperation> backPatches;
forwardPatches.reserve(entityIds.size());
backPatches.reserve(entityIds.size());
bool hasAnyChange = false;
for (size_t i = 0; i < entityIds.size(); ++i) {
EntityDataDelta::Options options;
options.shallow = true;
options.preserveComponentOrder = true;
auto forward = std::make_unique<EntityDataDelta>(*before[i], *after[i], options);
auto back = std::make_unique<EntityDataDelta>(*after[i], *before[i], options);
hasAnyChange = hasAnyChange || forward->hasChange();
forwardPatches.emplace_back(EntityChangeOperation{ std::move(forward), entityIds[i] });
backPatches.emplace_back(EntityChangeOperation{ std::move(back), entityIds[i] });
}
if (hasAnyChange) {
addToStack(Action(Type::EntityModified, std::move(forwardPatches)), Action(Type::EntityModified, std::move(backPatches)), wasModified);
return true;
} else {
return false;
}
}
bool UndoStack::pushReplaced(bool wasModified, const String& entityId, const EntityData& before, const EntityData& after)
{
if (accepting) {
auto forward = EntityDataDelta(after);
auto back = EntityDataDelta(before);
addToStack(Action(Type::EntityReplaced, std::move(forward), entityId), Action(Type::EntityReplaced, std::move(back), entityId), wasModified);
return true;
}
return true;
}
void UndoStack::undo(SceneEditorWindow& sceneEditorWindow)
{
if (canUndo()) {
runAction(stack[--stackPos]->back, sceneEditorWindow);
}
}
void UndoStack::redo(SceneEditorWindow& sceneEditorWindow)
{
if (canRedo()) {
runAction(stack[stackPos++]->forward, sceneEditorWindow);
}
}
void UndoStack::onSave()
{
// When saving, reset everyone's clear flag, unless they're the action that will lead back here
for (size_t i = 0; i < stack.size(); ++i) {
auto& a = stack[i];
a->back.clearModified = i == stackPos;
a->forward.clearModified = i + 1 == stackPos;
}
}
bool UndoStack::canUndo() const
{
return stackPos > 0;
}
bool UndoStack::canRedo() const
{
return stackPos < stack.size();
}
UndoStack::Action::Action(Type type, EntityDataDelta delta, String entityId, String parent, int childIndex)
: type(type)
{
auto& a = patches.emplace_back();
a.data = std::make_unique<EntityDataDelta>(std::move(delta));
a.entityId = std::move(entityId);
a.parent = std::move(parent);
a.childIndex = childIndex;
}
UndoStack::Action::Action(Type type, Vector<EntityChangeOperation> patches)
: type(type)
, patches(std::move(patches))
{
}
bool UndoStack::ActionPair::isCompatibleWith(const Action& newForward) const
{
if (forward.type != newForward.type || forward.patches.size() != newForward.patches.size()) {
return false;
}
// Check patch compatibility
for (size_t i = 0; i < forward.patches.size(); ++i) {
if (!arePatchesCompatible(forward.patches[i], newForward.patches[i], forward.type)) {
return false;
}
}
return true;
}
bool UndoStack::ActionPair::arePatchesCompatible(const EntityChangeOperation& a, const EntityChangeOperation& b, Type type) const
{
if (a.entityId != b.entityId) {
return false;
}
if (type == Type::EntityModified) {
return dynamic_cast<const EntityDataDelta&>(*a.data).modifiesTheSameAs(dynamic_cast<const EntityDataDelta&>(*b.data));
}
return true;
}
void UndoStack::addToStack(Action forward, Action back, bool wasModified)
{
// Discard redo timeline that is no longer valid
const bool hadRedo = stack.size() > stackPos;
if (hadRedo) {
stack.resize(stackPos);
}
if (!hadRedo && !stack.empty() && stack.back()->isCompatibleWith(forward)) {
// User is doing more of the same action, combine them instead
stack.back()->forward = std::move(forward);
} else {
// Insert new action into stack
stack.emplace_back(std::make_unique<ActionPair>(std::move(forward), std::move(back)));
stack.back()->back.clearModified = !wasModified;
if (stack.size() > maxSize) {
stack.erase(stack.begin());
}
stackPos = stack.size();
}
}
void UndoStack::runAction(const Action& action, SceneEditorWindow& sceneEditorWindow)
{
accepting = false;
switch (action.type) {
case Type::EntityAdded:
sceneEditorWindow.addEntities(action.patches);
break;
case Type::EntityRemoved:
sceneEditorWindow.removeEntities(action.patches);
break;
case Type::EntityMoved:
sceneEditorWindow.moveEntities(action.patches);
break;
case Type::EntityModified:
sceneEditorWindow.modifyEntities(action.patches);
break;
case Type::EntityReplaced:
sceneEditorWindow.replaceEntities(action.patches);
break;
}
if (action.clearModified) {
sceneEditorWindow.clearModifiedFlag();
}
accepting = true;
}
void UndoStack::sortPatches(Vector<EntityChangeOperation>& patches)
{
// Sort back patches by parentId/childIdx, that way we ensure that entities are added from top to bottom on every parent
std::sort(patches.begin(), patches.end(), [&] (const EntityChangeOperation& a, const EntityChangeOperation& b)
{
if (a.parent != b.parent) {
return a.parent < b.parent;
}
return a.childIndex < b.childIndex;
});
}
| 1 | 0.796093 | 1 | 0.796093 | game-dev | MEDIA | 0.695671 | game-dev | 0.926173 | 1 | 0.926173 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.