hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
eafdc0cd3b09175715bccfd215d2b98bf55d4ad1
233,040
cpp
C++
game/SceneObjectFactory.cpp
Sheph/TriggerTime
9265dee6a178e43bf7365e3aa2f7f2ca22df074f
[ "BSD-2-Clause" ]
24
2019-02-24T14:48:16.000Z
2022-03-21T21:37:26.000Z
game/SceneObjectFactory.cpp
Sheph/TriggerTime
9265dee6a178e43bf7365e3aa2f7f2ca22df074f
[ "BSD-2-Clause" ]
3
2019-02-25T20:45:09.000Z
2019-02-28T18:05:45.000Z
game/SceneObjectFactory.cpp
Sheph/TriggerTime
9265dee6a178e43bf7365e3aa2f7f2ca22df074f
[ "BSD-2-Clause" ]
7
2019-02-28T11:33:15.000Z
2022-01-26T20:11:45.000Z
/* * Copyright (c) 2014, Stanislav Vorobiov * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "SceneObjectFactory.h" #include "Settings.h" #include "AssetManager.h" #include "PlayerComponent.h" #include "ShroomCannonComponent.h" #include "ShroomGuardianComponent.h" #include "MissileComponent.h" #include "ExplosionComponent.h" #include "BlasterShotComponent.h" #include "CollisionDieComponent.h" #include "CollisionSparksComponent.h" #include "CollisionDamageComponent.h" #include "CollisionSensorComponent.h" #include "RenderQuadComponent.h" #include "RenderTerrainComponent.h" #include "RenderBackgroundComponent.h" #include "RenderDottedCircleComponent.h" #include "RenderPolygonsComponent.h" #include "AnimationComponent.h" #include "ShroomSnakeComponent.h" #include "TetrobotComponent.h" #include "RenderBeamComponent.h" #include "LaserComponent.h" #include "TetrocrabComponent.h" #include "PhysicsBodyComponent.h" #include "PhysicsRopeComponent.h" #include "RenderHealthbarComponent.h" #include "SpawnerComponent.h" #include "FireballComponent.h" #include "ScorpComponent.h" #include "TeleportComponent.h" #include "BloodComponent.h" #include "InvulnerabilityComponent.h" #include "WeaponStationComponent.h" #include "RenderTrailComponent.h" #include "BuckshotComponent.h" #include "BarrelComponent.h" #include "ConeLight.h" #include "TurretComponent.h" #include "GoalComponent.h" #include "PyrobotComponent.h" #include "PlaceholderComponent.h" #include "TimebombComponent.h" #include "BossSkullComponent.h" #include "SpiderComponent.h" #include "BabySpiderComponent.h" #include "SpiderNestComponent.h" #include "WeaponGGComponent.h" #include "WeaponShotgunComponent.h" #include "WeaponPistolComponent.h" #include "WeaponMachineGunComponent.h" #include "WeaponRLauncherComponent.h" #include "WeaponLGunComponent.h" #include "WeaponPlasmaGunComponent.h" #include "WeaponSeekerComponent.h" #include "BossQueenComponent.h" #include "CollisionCancelComponent.h" #include "BulletComponent.h" #include "EnforcerComponent.h" #include "SentryComponent.h" #include "GorgerComponent.h" #include "RocketComponent.h" #include "ProxMineComponent.h" #include "LaserSightComponent.h" #include "RoboArmComponent.h" #include "CrateComponent.h" #include "OrboComponent.h" #include "WarderComponent.h" #include "PlasmaComponent.h" #include "KeeperComponent.h" #include "DudeComponent.h" #include "HealthStationComponent.h" #include "SummonComponent.h" #include "BossCoreProtectorComponent.h" #include "ToxicSplashComponent.h" #include "ToxicCloudComponent.h" #include "AcidWormComponent.h" #include "WeaponAcidballComponent.h" #include "AcidballComponent.h" #include "CentipedeComponent.h" #include "WeaponSpitterComponent.h" #include "SpitComponent.h" #include "BeetleComponent.h" #include "BoatComponent.h" #include "PowerGenComponent.h" #include "TentaclePulseComponent.h" #include "TentacleSwingComponent.h" #include "TentacleSquidComponent.h" #include "BossSquidComponent.h" #include "MechComponent.h" #include "HomerComponent.h" #include "SeekerComponent.h" #include "BossChopperComponent.h" #include "CreatureComponent.h" #include "GasCloudComponent.h" #include "OctopusComponent.h" #include "WalkerComponent.h" #include "SnakeComponent.h" #include "BossBuddyComponent.h" #include "QuadPulseComponent.h" #include "BuddySideComponent.h" #include "BuddyTongueComponent.h" #include "NapalmComponent.h" #include "BossNatanComponent.h" #include "PowerBeamComponent.h" #include "Tetrobot2Component.h" #include "WeaponHeaterComponent.h" #include "WeaponAimComponent.h" #include "GuardianComponent.h" #include "SawerComponent.h" #include "CollisionBuzzSawComponent.h" #include "PuzzleHintComponent.h" #include "BossBeholderComponent.h" #include "WeaponEShieldComponent.h" #include "Const.h" #include "Utils.h" #include "af/Utils.h" #include <boost/make_shared.hpp> #include <cmath> namespace af { SceneObjectFactory sceneObjectFactory; template <> Single<SceneObjectFactory>* Single<SceneObjectFactory>::single = NULL; SceneObjectFactory::SceneObjectFactory() { } SceneObjectFactory::~SceneObjectFactory() { } bool SceneObjectFactory::init() { return true; } void SceneObjectFactory::shutdown() { } void SceneObjectFactory::setupGarbage(const SceneObjectPtr& obj, bool cancelCollisions) { if (cancelCollisions) { SceneObjectTypes types; types.set(SceneObjectTypePlayer); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeAlly); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); CollisionCancelComponentPtr c = boost::make_shared<CollisionCancelComponent>(); c->setFilter(types); obj->addComponent(c); } } SceneObjectPtr SceneObjectFactory::createDummy() { b2BodyDef bodyDef; bodyDef.type = b2_kinematicBody; RUBEBodyPtr body = boost::make_shared<RUBEBody>("", bodyDef); ComponentPtr component = boost::make_shared<PhysicsBodyComponent>(body); SceneObjectPtr obj = boost::make_shared<SceneObject>(); obj->setBodyDef(body->bodyDef()); obj->addComponent(component); return obj; } SceneObjectPtr SceneObjectFactory::createPlayer() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("player.json"); asset->root()->setType(SceneObjectTypePlayer); /* * We control the damping manually for the player. */ asset->root()->setLinearDamping(0.0f); asset->root()->setAngularDamping(0.0f); asset->root()->setMaxLife(settings.player.maxLife); asset->root()->setLife(settings.player.maxLife); RenderQuadComponentPtr torsoRc = asset->root()->findComponentByName<RenderQuadComponent>("torso"); RenderQuadComponentPtr legsRc = asset->root()->findComponentByName<RenderQuadComponent>("legs"); AnimationComponentPtr torsoAc = boost::make_shared<AnimationComponent>(torsoRc->drawable()); AnimationComponentPtr legsAc = boost::make_shared<AnimationComponent>(legsRc->drawable()); torsoAc->addAnimation(AnimationDefault, "player_torso_def"); torsoAc->addAnimation(PlayerComponent::AnimationIdle, "player_torso_idle"); torsoAc->addAnimation(PlayerComponent::AnimationWalk, "player_torso_walk"); torsoAc->addAnimation(PlayerComponent::AnimationHelmetDefault, "player_torso_helmet_def"); torsoAc->addAnimation(PlayerComponent::AnimationHelmetIdle, "player_torso_helmet_idle"); torsoAc->addAnimation(PlayerComponent::AnimationHelmetWalk, "player_torso_helmet_walk"); torsoAc->addAnimation(PlayerComponent::AnimationNogunDefault, "player_torso_nogun_def"); torsoAc->addAnimation(PlayerComponent::AnimationNogunIdle, "player_torso_nogun_idle"); torsoAc->addAnimation(PlayerComponent::AnimationNogunWalk, "player_torso_nogun_walk"); torsoAc->addAnimation(PlayerComponent::AnimationNobackpackDefault, "player_torso_nobp_def"); torsoAc->addAnimation(PlayerComponent::AnimationNobackpackIdle, "player_torso_nobp_idle"); torsoAc->addAnimation(PlayerComponent::AnimationNobackpackWalk, "player_torso_nobp_walk"); torsoAc->addAnimation(PlayerComponent::AnimationNobackpackChainsawDefault, "player_torso_nobp_chainsaw_def"); torsoAc->addAnimation(PlayerComponent::AnimationNobackpackChainsawIdle, "player_torso_nobp_chainsaw_idle"); torsoAc->addAnimation(PlayerComponent::AnimationNobackpackChainsawWalk, "player_torso_nobp_chainsaw_walk"); torsoAc->addAnimation(PlayerComponent::AnimationNobackpackChainsawAttack, "player_torso_nobp_chainsaw_attack"); torsoAc->addAnimation(PlayerComponent::AnimationChainsawDefault, "player_torso_chainsaw_def"); torsoAc->addAnimation(PlayerComponent::AnimationChainsawIdle, "player_torso_chainsaw_idle"); torsoAc->addAnimation(PlayerComponent::AnimationChainsawWalk, "player_torso_chainsaw_walk"); torsoAc->addAnimation(PlayerComponent::AnimationChainsawAttack, "player_torso_chainsaw_attack"); legsAc->addAnimation(AnimationDefault, "player_legs_def"); legsAc->addAnimation(PlayerComponent::AnimationWalk, "player_legs_walk"); torsoAc->startAnimation(PlayerComponent::AnimationIdle); legsAc->startAnimation(AnimationDefault); asset->root()->addComponent(torsoAc); asset->root()->addComponent(legsAc); PlayerComponentPtr pc(new PlayerComponent( asset->world()->image("missile")->pos(), normalizeAngle(asset->world()->image("missile")->angle() + b2_pi / 2.0f), asset->world()->image("missile")->height() / 2.0f, asset->world()->image("exhaust1")->pos(), normalizeAngle(asset->world()->image("exhaust1")->angle()), asset->world()->image("exhaust2")->pos(), normalizeAngle(asset->world()->image("exhaust2")->angle()), torsoRc, torsoAc, legsRc, legsAc, asset->root()->findComponent<LightComponent>()->getLight<Light>("flashlight"))); pc->setMaxStamina(settings.player.maxStamina); pc->setStamina(settings.player.maxStamina); asset->root()->addComponent(pc); { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.player.damageImpulseThreshold); SceneObjectTypes types; types.set(SceneObjectTypeTerrain); types.set(SceneObjectTypeRock); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); component->setFilter(types); component->setDamageSound(audio.createSound("player_hit.ogg")); asset->root()->addComponent(component); } if (settings.player.laserSight) { RenderTrailComponentPtr rtc = boost::make_shared<RenderTrailComponent>(asset->world()->image("sight")->pos(), normalizeAngle(asset->world()->image("sight")->angle() + b2_pi / 2.0f), assetManager.getDrawable("trail1.png", Texture::WrapModeRepeat, Texture::WrapModeClamp), zOrderMarker); rtc->setColor(Color(1.0f, 0.0f, 0.0f, 0.4f)); rtc->setColor2(Color(1.0f, 0.0f, 0.0f, 0.05f)); rtc->setWidth1(0.3f); rtc->setWidth2(0.3f); rtc->setLength(0.0f); ComponentPtr component = boost::make_shared<LaserSightComponent>(pc, rtc); asset->root()->addComponent(rtc); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBackground(const std::string& image, float width, float height, const b2Vec2& velocity, int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); obj->setLinearVelocity(velocity); { ComponentPtr component = boost::make_shared<RenderBackgroundComponent>( assetManager.getDrawable(image), width, height, zOrder); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createShroomCannonRed1() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("shroom_cannon_red1.json"); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setLife(settings.shroomCannon.life); DrawablePtr drawable = asset->root()->findComponent<RenderQuadComponent>()->drawable(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(drawable); ac->addAnimation(AnimationDefault, "shroom_cannon_red1_def"); ac->addAnimation(ShroomCannonComponent::AnimationAttack, "shroom_cannon_red1_attack"); ac->addAnimation(ShroomCannonComponent::AnimationReload, "shroom_cannon_red1_reload"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); ShroomCannonComponentPtr thinkComponent = boost::make_shared<ShroomCannonComponent>(ac, asset->world()->image("missile")->pos()); asset->root()->addComponent(thinkComponent); { CollisionSensorComponentPtr component = boost::make_shared<CollisionSensorComponent>(); component->setListener(thinkComponent); asset->root()->addComponent(component); } { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setFilter(SceneObjectTypeRock); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createShroomCannonRed1Missile(float damage) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("shroom_cannon_red1_missile.json"); asset->root()->setType(SceneObjectTypeEnemyMissile); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<MissileComponent>(cdc, damage); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createExplosion1(int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("explosion1.p", b2Vec2(0.0f, 0.0f), 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { ExplosionComponentPtr component = boost::make_shared<ExplosionComponent>(pec, 15.0f, 128); component->setLight(25.0f, 1.0f, false, 0.9f); component->setShake(2.0f); component->setSound(audio.createSound("explosion1.ogg")); component->setColor(Color(1.0f, 0.7f, 0.7f)); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createExplosion2(int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("explosion2.p", b2Vec2(0.0f, 0.0f), 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { ExplosionComponentPtr component = boost::make_shared<ExplosionComponent>(pec); component->setLight(0.6f, 0.3f, true, 1.0f); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createExplosion3(int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("explosion3.p", b2Vec2(0.0f, 0.0f), 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { ExplosionComponentPtr component = boost::make_shared<ExplosionComponent>(pec, 9.0f, 64); component->setLight(10.0f, 1.0f, false, 0.7f); component->setShake(0.5f); component->setSound(audio.createSound("explosion3.ogg")); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createExplosion4(int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("explosion4.p", b2Vec2(0.0f, 0.0f), 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { ExplosionComponentPtr component = boost::make_shared<ExplosionComponent>(pec, 7.0f, 64); component->setLight(10.0f, 1.0f, true, 0.8f); component->setShake(0.5f); component->setSound(audio.createSound("explosion4.ogg")); component->setColor(Color(0.0f, 1.0f, 0.0f)); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createExplosion5(int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("explosion5.p", b2Vec2(0.0f, 0.0f), 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { ExplosionComponentPtr component = boost::make_shared<ExplosionComponent>(pec, 7.5f, 64); component->setLight(10.0f, 1.0f, true, 0.75f); component->setShake(0.5f); component->setSound(audio.createSound("explosion3.ogg")); component->setColor(Color(1.0f, 1.0f, 1.0f)); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createExplosion6(int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("explosion6.p", b2Vec2(0.0f, 0.0f), 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { ExplosionComponentPtr component = boost::make_shared<ExplosionComponent>(pec, 11.0f, 96); component->setLight(12.0f, 1.0f, false, 1.0f); component->setShake(1.5f); component->setSound(audio.createSound("explosion5.ogg")); component->setColor(Color(0.0f, 1.0f, 1.0f)); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createBlasterShot(SceneObjectType type, float damage, bool twisted, float velocity) { static std::vector<float> tmp; SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("bullet1.json"); Color* colors = &settings.blasterShot.enemy[0]; switch (type) { case SceneObjectTypePlayerMissile: colors = &settings.blasterShot.player[0]; break; case SceneObjectTypeAllyMissile: colors = &settings.blasterShot.ally[0]; break; case SceneObjectTypeEnemyMissile: case SceneObjectTypeNeutralMissile: break; default: assert(false); break; } asset->root()->findComponent<RenderQuadComponent>()->setColor(colors[0]); asset->root()->findComponent<LightComponent>()->lights().front()->setColor(colors[1]); ParticleEffectComponentPtr pec = asset->root()->findComponent<ParticleEffectComponent>(); pec->setTimeFactor(2); for (ParticleEffectComponent::Emmiters::iterator it = pec->emmiters().begin(); it != pec->emmiters().end(); ++it) { tmp.push_back(0.0f); tmp.push_back(1.0f); (*it)->entry().tint.setTimeline(tmp); tmp.clear(); tmp.push_back(colors[2].rgba[0]); tmp.push_back(colors[2].rgba[1]); tmp.push_back(colors[2].rgba[2]); tmp.push_back(colors[3].rgba[0]); tmp.push_back(colors[3].rgba[1]); tmp.push_back(colors[3].rgba[2]); (*it)->entry().tint.setColors(tmp); tmp.clear(); (*it)->entry().duration.setLow((*it)->entry().duration.lowMin() * (20.0f / velocity)); (*it)->entry().emission.setHigh((*it)->entry().emission.highMin() * (velocity / 20.0f)); (*it)->entry().life.setHigh((*it)->entry().life.highMin() * (20.0f / velocity)); } pec->resetEmit(); asset->root()->setType(type); b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; if (type == SceneObjectTypeEnemyMissile) { filter.maskBits &= ~(collisionBitEnemy | collisionBitEnemyBuilding); } else if (type != SceneObjectTypeNeutralMissile) { filter.maskBits &= ~(collisionBitPlayer | collisionBitAlly); } asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<BlasterShotComponent>(cdc, pec, damage, twisted); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createShroomGuardianRed1() { return createShroomGuardianRed(settings.shroomGuardian.life, settings.shroomGuardian.turnSpeed, Color(1.0f, 1.0f, 1.0f, 1.0f)); } SceneObjectPtr SceneObjectFactory::createShroomGuardianRed2() { return createShroomGuardianRed(settings.shroomGuardian2.life, settings.shroomGuardian2.turnSpeed, Color(1.0f, 0.0f, 0.0f, 1.0f)); } SceneObjectPtr SceneObjectFactory::createJake() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("jake.json"); asset->root()->setType(SceneObjectTypeAlly); RenderQuadComponentPtr legsRc = asset->root()->findComponentByName<RenderQuadComponent>("legs"); AnimationComponentPtr legsAc = boost::make_shared<AnimationComponent>(legsRc->drawable()); legsAc->addAnimation(AnimationDefault, "player_def"); legsAc->addAnimation(DudeComponent::AnimationWalk, "player_walk"); legsAc->startAnimation(AnimationDefault); asset->root()->addComponent(legsAc); ComponentPtr component = boost::make_shared<DudeComponent>(legsRc, legsAc); asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createShroomSnake() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("shroom_snake.json"); asset->root()->setLife(settings.shroomSnake.life); std::vector<SInt32> cookies; for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); cookies.push_back(asset->object(i)->cookie()); } for (int i = 0; i < asset->numObjects(); ++i) { CollisionCookieFilterPtr collisionFilter = boost::make_shared<CollisionCookieFilter>(); for (size_t j = 0; j < cookies.size(); ++j) { if (cookies[j] != asset->object(i)->cookie()) { collisionFilter->add(cookies[j]); } } asset->object(i)->setCollisionFilter(collisionFilter); } AnimationComponentPtr ac; Animation attack; { DrawablePtr drawable = asset->root()->findComponent<RenderQuadComponent>()->drawable(); ac = boost::make_shared<AnimationComponent>(drawable); ac->addAnimation(AnimationDefault, "shroom_snake_def"); ac->addAnimation(ShroomSnakeComponent::AnimationBite, "shroom_snake_bite"); ac->addAnimation(ShroomSnakeComponent::AnimationAttack, "shroom_snake_attack"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); } ShroomSnakeComponentPtr thinkComponent; { assert(settings.shroomSnake.attackAngles.size() == static_cast<size_t>(attack.numFrames())); thinkComponent = boost::make_shared<ShroomSnakeComponent>( asset->object("upper_lip"), asset->object("upper_lip")->pos() - asset->root()->pos(), asset->object("lower_lip"), asset->object("lower_lip")->pos() - asset->root()->pos(), ac, settings.shroomSnake.defAngle, settings.shroomSnake.attackAngles); asset->root()->addComponent(thinkComponent); } { CollisionSensorComponentPtr component = boost::make_shared<CollisionSensorComponent>(); component->setListener(thinkComponent); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createRope(float length) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("rope_hook.json"); asset->root()->setType(SceneObjectTypeDeadbody); float segmentSize = 1.0f; SceneObjectPtr root = asset->root(); int numSegments = std::ceil(length / segmentSize); std::vector<SceneObject*> objects; objects.reserve(numSegments + 1); objects.push_back(root.get()); if (numSegments > 1) { for (int i = 1; i < numSegments; ++i) { b2Vec2 pos(-segmentSize * i, 0.0f); asset = assetManager.getSceneObjectAsset(((i % 2) == 0) ? "rope_segment1.json" : "rope_segment2.json"); asset->root()->setType(SceneObjectTypeDeadbody); asset->root()->setPos(pos); root->addObject(asset->root()); objects.push_back(asset->root().get()); } } PhysicsRopeComponentPtr component = boost::make_shared<PhysicsRopeComponent>(objects, segmentSize); root->addComponent(component); return root; } SceneObjectPtr SceneObjectFactory::createBlocker(float width, float height) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); obj->setType(SceneObjectTypeBlocker); RUBEBodyPtr body = boost::make_shared<RUBEBody>("", b2BodyDef()); RUBEPolygonFixturePtr fixture = boost::make_shared<RUBEPolygonFixture>(""); fixture->fixtureDef().friction = 0.0f; fixture->fixtureDef().filter.categoryBits = collisionBitGeneral; fixture->fixtureDef().filter.maskBits = collisionBitPlayer; fixture->shape().SetAsBox(width / 2.0f, height / 2.0f); body->addFixture(fixture); ComponentPtr component = boost::make_shared<PhysicsBodyComponent>(body); obj->addComponent(component); return obj; } SceneObjectPtr SceneObjectFactory::createTetrobot() { return createTetrobot2(); } SceneObjectPtr SceneObjectFactory::createTetrobotGibbed() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("tetrobot_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createTetrobot2() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("tetrobot2.json"); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setMaxLife(settings.tetrobot2.life); asset->root()->setLife(settings.tetrobot2.life); RenderQuadComponentPtr rc = asset->root()->findComponent<RenderQuadComponent>(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(rc->drawable()); ac->addAnimation(AnimationDefault, "tetrobot2_def"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); Tetrobot2ComponentPtr component = boost::make_shared<Tetrobot2Component>(); WeaponHeaterComponentPtr weapon = boost::make_shared<WeaponHeaterComponent>(SceneObjectTypeEnemyMissile); weapon->setDamage(settings.tetrobot2.shootDamage); weapon->setLength(settings.tetrobot2.shootLength); weapon->setImpulse(settings.tetrobot2.shootImpulse); weapon->setDuration(settings.tetrobot2.shootDuration); weapon->setInterval(0.0f); weapon->setPos(asset->world()->image("missile")->pos()); weapon->setAngle(asset->world()->image("missile")->angle()); component->setWeapon(weapon); asset->root()->addComponent(weapon); WeaponAimComponentPtr aimWeapon = boost::make_shared<WeaponAimComponent>(SceneObjectTypeEnemyMissile); aimWeapon->setLength(settings.tetrobot2.shootLength); aimWeapon->setPos(asset->world()->image("missile")->pos()); aimWeapon->setAngle(asset->world()->image("missile")->angle()); component->setAimWeapon(aimWeapon); asset->root()->addComponent(aimWeapon); asset->root()->addComponent(component); { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.tetrobot2.damageImpulseThreshold); component->setMultiplier(settings.tetrobot2.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypeTerrain); types.set(SceneObjectTypeRock); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); component->setFilter(types); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createTetrobot2Gibbed() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("tetrobot2_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); } return asset->root(); } ComponentPtr SceneObjectFactory::createLaser(const b2Vec2& pos, float angle, float length, float damage, int zOrder) { RenderBeamComponentPtr rbc = boost::make_shared<RenderBeamComponent>(pos, angle, 0.5f, assetManager.getDrawable("healthbar_life.png", Texture::WrapModeRepeat, Texture::WrapModeClamp), zOrder); return boost::make_shared<LaserComponent>(pos, angle, length, damage, rbc); } SceneObjectPtr SceneObjectFactory::createTetrocrabInternal(const std::string& assetPath, const Color& color, int idx, float life, float walkSpeed, float walkAccel, float turnSpeed) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset(assetPath); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setMaterial(MaterialFlesh); asset->root()->setLife(life); DrawablePtr drawable = asset->root()->findComponent<RenderQuadComponent>()->drawable(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(drawable); std::ostringstream os; os << "tetrocrab" << idx; ac->addAnimation(AnimationDefault, os.str() + "_def", 5.0f / walkSpeed); ac->addAnimation(TetrocrabComponent::AnimationBite, os.str() + "_bite", 5.0f / walkSpeed); ac->startAnimation(AnimationDefault); ac->setPaused(true); asset->root()->addComponent(ac); TetrocrabComponentPtr thinkComponent = boost::make_shared<TetrocrabComponent>(idx, ac, walkSpeed, walkAccel, turnSpeed); asset->root()->addComponent(thinkComponent); { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.tetrocrab.damageImpulseThreshold); component->setMultiplier(settings.tetrocrab.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypeTerrain); types.set(SceneObjectTypeRock); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); component->setFilter(types); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createTetrocrab() { return createTetrocrab3(); } SceneObjectPtr SceneObjectFactory::createTetrocrab2() { return createTetrocrab4(); } SceneObjectPtr SceneObjectFactory::createTetrocrab3() { return createTetrocrabInternal("tetrocrab3.json", Color(1.0f, 1.0f, 0.0f, 1.0f), 1, settings.tetrocrab3.life, settings.tetrocrab3.walkSpeed, 2.0f, settings.tetrocrab3.turnSpeed); } SceneObjectPtr SceneObjectFactory::createTetrocrab4() { return createTetrocrabInternal("tetrocrab3.json", Color(0.0f, 1.0f, 0.0f, 1.0f), 2, settings.tetrocrab4.life, settings.tetrocrab3.walkSpeed, 2.0f, settings.tetrocrab3.turnSpeed); } SceneObjectPtr SceneObjectFactory::createTetrocrabGibbed(int i) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset((i == 1) ? "tetrocrab1_gibbed.json" : "tetrocrab2_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); asset->object(i)->setMaterial(MaterialFlesh); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createSpawner1() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("spawner1.json"); asset->root()->setType(SceneObjectTypeEnemyBuilding); asset->root()->setMaxLife(1); asset->root()->setLife(1); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 7.0f), 0, 10.0f, 1.5f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } { SpawnerComponentPtr component = boost::make_shared<SpawnerComponent>(b2Vec2_zero, 8.0f); asset->root()->addComponent(component); } return asset->root(); } AnimationComponentPtr SceneObjectFactory::createLightningAnimation() { AnimationComponentPtr component = boost::make_shared<AnimationComponent>( assetManager.getDrawable("lightning/0.png", Texture::WrapModeRepeat, Texture::WrapModeClamp)); component->addAnimation(AnimationDefault, "lightning"); return component; } SceneObjectPtr SceneObjectFactory::createScorpInternal(const Color& color, const std::string& nameBase, float life, float walkSpeed) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("scorp.json"); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setLife(life); asset->root()->findComponent<RenderQuadComponent>()->setColor(color); DrawablePtr drawable = asset->root()->findComponent<RenderQuadComponent>()->drawable(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(drawable); ac->addAnimation(AnimationDefault, nameBase + "_def"); ac->addAnimation(ScorpComponent::AnimationWalk, nameBase + "_walk", (5.0f / walkSpeed)); ac->addAnimation(ScorpComponent::AnimationAttack, nameBase + "_attack"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); ScorpComponentPtr thinkComponent = boost::make_shared<ScorpComponent>(ac, walkSpeed); asset->root()->addComponent(thinkComponent); { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.scorp.damageImpulseThreshold); component->setMultiplier(settings.scorp.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypeTerrain); types.set(SceneObjectTypeRock); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); component->setFilter(types); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createScorp() { return createScorp3(); } SceneObjectPtr SceneObjectFactory::createScorp2() { return createScorp4(); } SceneObjectPtr SceneObjectFactory::createScorp3() { return createScorpInternal(Color(1.0f, 1.0f, 1.0f, 1.0f), "scorp", settings.scorp3.life, settings.scorp3.walkSpeed); } SceneObjectPtr SceneObjectFactory::createScorp4() { return createScorpInternal(Color(1.0f, 1.0f, 1.0f, 1.0f), "scorp2", settings.scorp4.life, settings.scorp3.walkSpeed); } SceneObjectPtr SceneObjectFactory::createFireball(SceneObjectType type, float damage) { assert((type == SceneObjectTypePlayerMissile) || (type == SceneObjectTypeEnemyMissile) || (type == SceneObjectTypeAllyMissile) || (type == SceneObjectTypeNeutralMissile)); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("fireball.json"); asset->root()->setType(type); b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; if (type == SceneObjectTypeEnemyMissile) { filter.maskBits &= ~(collisionBitEnemy | collisionBitEnemyBuilding); } else if (type != SceneObjectTypeNeutralMissile) { filter.maskBits &= ~(collisionBitPlayer | collisionBitAlly); } asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); asset->root()->addComponent(cdc); DrawablePtr drawable = asset->root()->findComponent<RenderQuadComponent>()->drawable(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(drawable); ac->addAnimation(AnimationDefault, "fireball_def"); ac->addAnimation(FireballComponent::AnimationBoom, "fireball_boom"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); { ComponentPtr component = boost::make_shared<FireballComponent>(cdc, ac, damage); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createTeleport1() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("teleport1.json"); { ComponentPtr component = boost::make_shared<TeleportComponent>(asset->object("ring")); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createPowerupHealth(float timeout, float amount) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("powerup_health.json"); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); cdc->setAllowSensor(true); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<PowerupHealthComponent>(cdc, timeout, settings.powerupHealth.radius, settings.powerupHealth.color, amount); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createPowerupGem(float timeout) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("powerup_gem.json"); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); cdc->setAllowSensor(true); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<PowerupGemComponent>(cdc, timeout, settings.powerupGem.radius, settings.powerupGem.color); asset->root()->addComponent(component); } DrawablePtr drawable = asset->root()->findComponent<RenderQuadComponent>()->drawable(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(drawable); ac->addAnimation(AnimationDefault, "powerup_gem_def"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); return asset->root(); } SceneObjectPtr SceneObjectFactory::createPowerupInventory(InventoryItem item) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset(Inventory::getAssetPath(item)); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); cdc->setAllowSensor(true); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<PowerupInventoryComponent>(item, cdc, settings.powerupInventory.radius, settings.powerupInventory.color); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createPowerupHelmet() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("powerup_helmet.json"); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); cdc->setAllowSensor(true); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<PowerupHelmetComponent>(cdc, settings.powerupHelmet.radius, settings.powerupHelmet.color); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createPowerupAmmo(WeaponType type) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset(WeaponComponent::getAmmoAssetPath(type)); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); cdc->setAllowSensor(true); asset->root()->addComponent(cdc); float amount = 0; switch (type) { case WeaponTypeProxMine: amount = settings.powerupAmmo.proxmineAmount[0]; break; case WeaponTypeRLauncher: amount = settings.powerupAmmo.rlauncherAmount[0]; break; case WeaponTypeMachineGun: amount = settings.powerupAmmo.mgunAmount[0]; break; case WeaponTypePlasmaGun: amount = settings.powerupAmmo.plasmagunAmount[0]; break; case WeaponTypeShotgun: amount = settings.powerupAmmo.shotgunAmount[0]; break; case WeaponTypeEShield: amount = settings.powerupAmmo.eshieldAmount[0]; break; default: assert(false); break; } { ComponentPtr component = boost::make_shared<PowerupAmmoComponent>(type, amount, cdc, settings.powerupAmmo.radius, settings.powerupAmmo.color); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createPowerupWeapon(WeaponType type, float amount) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("powerup_weapon.json"); asset->root()->findComponentByName<RenderQuadComponent>("weapon")->drawable()->setImage( WeaponComponent::getImage(type)); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); cdc->setAllowSensor(true); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<PowerupWeaponComponent>(type, amount, cdc, settings.powerupWeapon.radius, settings.powerupWeapon.color); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createPowerupBackpack() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("powerup_backpack.json"); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); cdc->setAllowSensor(true); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<PowerupBackpackComponent>(cdc, settings.powerupBackpack.radius, settings.powerupBackpack.color); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createPowerupEarpiece() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("powerup_earpiece.json"); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); cdc->setAllowSensor(true); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<PowerupEarpieceComponent>(cdc, settings.powerupEarpiece.radius, settings.powerupEarpiece.color); asset->root()->addComponent(component); } return asset->root(); } AnimationComponentPtr SceneObjectFactory::createArrowAnimation() { AnimationComponentPtr component = boost::make_shared<AnimationComponent>( assetManager.getDrawable("common2/arrow_0.png")); component->addAnimation(AnimationDefault, "arrow"); return component; } SceneObjectPtr SceneObjectFactory::createBlood1(float height, int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); DrawablePtr drawable = assetManager.getDrawable("common2/blood_0.png"); float width = height * drawable->image().aspect(); RenderQuadComponentPtr rc = boost::make_shared<RenderQuadComponent>(b2Vec2_zero, -b2_pi / 2.0f, width, height, drawable, zOrder); obj->addComponent(rc); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(drawable); ac->addAnimation(AnimationDefault, "blood"); ac->startAnimation(AnimationDefault); obj->addComponent(ac); BloodComponentPtr bc = boost::make_shared<BloodComponent>(ac); obj->addComponent(bc); return obj; } ComponentPtr SceneObjectFactory::createInvulnerability(float radius, float duration, int zOrder) { DrawablePtr drawable = assetManager.getDrawable("factory4/shield_0.png"); float height = radius * 2.0f; float width = height * drawable->image().aspect(); RenderQuadComponentPtr rc = boost::make_shared<RenderQuadComponent>(b2Vec2_zero, -b2_pi / 2.0f, width, height, drawable, zOrder); rc->setColor(Color(1.0f, 1.0f, 1.0f, 0.5f)); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(drawable); ac->addAnimation(AnimationDefault, "shield"); ac->startAnimation(AnimationDefault); return boost::make_shared<InvulnerabilityComponent>(rc, ac, duration); } SceneObjectPtr SceneObjectFactory::createBloodStain1(float height, int zOrder, bool deadbody) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); if (deadbody) { makeDeadbody(obj, height / 8.0f); } else { obj->setFreezable(true); obj->setFreezeRadius(height); } std::ostringstream os; os << "common2/blood_" << (rand() % 6) << ".png"; DrawablePtr drawable = assetManager.getDrawable(os.str()); float width = height * drawable->image().aspect(); RenderQuadComponentPtr rc = boost::make_shared<RenderQuadComponent>(b2Vec2_zero, -b2_pi / 2.0f, width, height, drawable, zOrder); obj->addComponent(rc); return obj; } SceneObjectPtr SceneObjectFactory::createBloodStain2(float height, int zOrder, bool deadbody) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); if (deadbody) { makeDeadbody(obj, height / 8.0f); } else { obj->setFreezable(true); obj->setFreezeRadius(height); } DrawablePtr drawable = assetManager.getDrawable("factory1/blood2.png"); float width = height * drawable->image().aspect(); RenderQuadComponentPtr rc = boost::make_shared<RenderQuadComponent>(b2Vec2_zero, -b2_pi / 2.0f, width, height, drawable, zOrder); obj->addComponent(rc); return obj; } SceneObjectPtr SceneObjectFactory::createWeaponStation(WeaponType weaponType, float minAmmo) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("weapon_station.json"); asset->root()->findComponentByName<RenderQuadComponent>("weapon")->drawable()->setImage( WeaponComponent::getImage(weaponType)); WeaponStationComponentPtr thinkComponent = boost::make_shared<WeaponStationComponent>(weaponType, minAmmo); asset->root()->addComponent(thinkComponent); { CollisionSensorComponentPtr component = boost::make_shared<CollisionSensorComponent>(); component->setListener(thinkComponent); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBuckshot(SceneObjectType type, float damage) { assert((type == SceneObjectTypePlayerMissile) || (type == SceneObjectTypeEnemyMissile) || (type == SceneObjectTypeAllyMissile) || (type == SceneObjectTypeNeutralMissile)); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("buckshot.json"); asset->root()->setType(type); b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; if (type == SceneObjectTypeEnemyMissile) { filter.maskBits &= ~(collisionBitEnemy | collisionBitEnemyBuilding); } else if (type != SceneObjectTypeNeutralMissile) { filter.maskBits &= ~(collisionBitPlayer | collisionBitAlly); } asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); asset->root()->addComponent(cdc); ConeLightPtr light = asset->root()->findComponent<LightComponent>()->getLight<ConeLight>("cone_light"); RenderQuadComponentPtr rc = asset->root()->findComponentByName<RenderQuadComponent>("root"); RenderTrailComponentPtr rtc = boost::make_shared<RenderTrailComponent>(b2Vec2_zero, b2_pi, assetManager.getDrawable("fire1.png", Texture::WrapModeRepeat, Texture::WrapModeClamp), rc->zOrder() - 1); rtc->setColor(Color(1.0f, 1.0f, 1.0f, rc->color().rgba[3])); rtc->setColor2(Color(1.0f, 1.0f, 1.0f, 0.0f)); asset->root()->addComponent(rtc); { ComponentPtr component = boost::make_shared<BuckshotComponent>(cdc, rc, rtc, light, damage, 0.3f, 0.8f, 10.0f); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBarrel1() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("barrel1.json"); asset->root()->setType(SceneObjectTypeGizmo); asset->root()->setLife(settings.barrel1.life); asset->root()->setMaxLife(settings.barrel1.life); asset->root()->setBlastDamageMultiplier(settings.barrel1.blastDamageMultiplier); { BarrelComponentPtr component = boost::make_shared<BarrelComponent>(); component->setExplosive(settings.barrel1.explosionImpulse, settings.barrel1.explosionDamage); asset->root()->addComponent(component); } { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.barrel1.damageImpulseThreshold); component->setMultiplier(settings.barrel1.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypePlayer); types.set(SceneObjectTypeAlly); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); component->setFilter(types); component->setDamageSound(audio.createSound("metal_hit1.ogg")); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBarrel1Gibbed() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("barrel1_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeGizmo); makeDebris(asset->object(i)); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBarrel2() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("barrel2.json"); asset->root()->setType(SceneObjectTypeGizmo); asset->root()->setLife(settings.barrel2.life); asset->root()->setMaxLife(settings.barrel2.life); { BarrelComponentPtr component = boost::make_shared<BarrelComponent>(); asset->root()->addComponent(component); } { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.barrel2.damageImpulseThreshold); component->setMultiplier(settings.barrel2.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypePlayer); types.set(SceneObjectTypeAlly); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); component->setFilter(types); component->setDamageSound(audio.createSound("metal_hit1.ogg")); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBarrel2Gibbed() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("barrel2_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeGizmo); makeDebris(asset->object(i)); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBarrel3() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("barrel3.json"); asset->root()->setType(SceneObjectTypeGizmo); asset->root()->setLife(settings.barrel3.life); asset->root()->setMaxLife(settings.barrel3.life); { BarrelComponentPtr component = boost::make_shared<BarrelComponent>(); component->setToxic(settings.barrel3.toxicDamage, settings.barrel3.toxicDamageTimeout); asset->root()->addComponent(component); } { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.barrel3.damageImpulseThreshold); component->setMultiplier(settings.barrel3.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypePlayer); types.set(SceneObjectTypeAlly); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); component->setFilter(types); component->setDamageSound(audio.createSound("metal_hit1.ogg")); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBarrel3Gibbed() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("barrel3_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeGizmo); makeDebris(asset->object(i)); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createTurret1() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("turret1.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemyBuilding); } asset->root()->setLife(settings.turret1.life); asset->root()->setMaxLife(settings.turret1.life); SceneObjectPtr tower; std::vector<b2Transform> shotPoses; { tower = asset->object("tower"); for (int i = 0; i < asset->world()->numImages(); ++i) { const RUBEImagePtr& image = asset->world()->image(i); if (image->name() == "missile") { shotPoses.push_back(b2Transform(image->pos(), b2Rot(image->angle() + b2_pi / 2.0f))); } } CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.turret1.damageImpulseThreshold); component->setMultiplier(settings.turret1.damageMultiplier); component->setFilter(SceneObjectTypes(SceneObjectTypeGizmo) | SceneObjectTypeRock); tower->addComponent(component); } { ComponentPtr component = boost::make_shared<TurretComponent>(tower, shotPoses); asset->root()->addComponent(component); } tower->setBlastDamageMultiplier(settings.turret1.blastDamageMultiplier); return asset->root(); } ComponentPtr SceneObjectFactory::createGoal(const SceneObjectPtr& forObject) { PhysicsBodyComponentPtr c = forObject->findComponent<PhysicsBodyComponent>(); b2Vec2 ext = c->computeAABB(b2Transform(b2Vec2_zero, b2Rot(0))).GetExtents(); float radius = b2Max(ext.x, ext.y) + 0.3f; return createGoal(radius, b2Vec2_zero); } ComponentPtr SceneObjectFactory::createGoal(float radius, const b2Vec2& offset) { RenderDottedCircleComponentPtr dcc = boost::make_shared<RenderDottedCircleComponent>(offset, 0.3f, assetManager.getDrawable("common2/dot.png"), zOrderMarker); dcc->setColor(Color(0.17f, 0.7f, 0.17f, 0.8f)); dcc->setRadius(radius); dcc->setDotVelocity(5.0f, radius); dcc->setDotDistance(0.5f, radius); return boost::make_shared<GoalComponent>(dcc); } SceneObjectPtr SceneObjectFactory::createShroomGuardianRed(float life, float turnSpeed, const Color& color) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("shroom_guardian_red1.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); asset->object(i)->findComponent<RenderQuadComponent>()->setColor(color); } asset->root()->setLife(life); asset->root()->setMaxLife(life); { ShroomGuardianComponentPtr component = boost::make_shared<ShroomGuardianComponent>(); component->setTurnSpeed(turnSpeed); asset->root()->addComponent(component); } { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 2.0f), 0, 3.0f, 0.5f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createPyrobot() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("pyrobot.json"); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setMaterial(MaterialBulletProof); asset->root()->setLife(settings.pyrobot.life); asset->root()->setMaxLife(settings.pyrobot.life); DrawablePtr drawable = asset->root()->findComponent<RenderQuadComponent>()->drawable(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(drawable); ac->addAnimation(AnimationDefault, "pyrobot_def"); ac->addAnimation(PyrobotComponent::AnimationWalk, "pyrobot_walk"); ac->addAnimation(PyrobotComponent::AnimationAttack, "pyrobot_attack"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); std::vector<b2Transform> weaponXfs; for (int i = 0; i < asset->world()->numImages(); ++i) { const RUBEImagePtr& image = asset->world()->image(i); if (image->name() == "missile") { weaponXfs.push_back(b2Transform(image->pos(), b2Rot(image->angle() + b2_pi / 2.0f))); } } PyrobotComponentPtr thinkComponent = boost::make_shared<PyrobotComponent>(ac, weaponXfs[0], weaponXfs[1]); asset->root()->addComponent(thinkComponent); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 4.0f), 0, 5.0f, 1.0f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createKeyl() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("keyl.json"); asset->root()->setType(SceneObjectTypeAlly); RenderQuadComponentPtr legsRc = asset->root()->findComponentByName<RenderQuadComponent>("legs"); RenderQuadComponentPtr torsoRc = asset->root()->findComponentByName<RenderQuadComponent>("torso"); AnimationComponentPtr legsAc = boost::make_shared<AnimationComponent>(legsRc->drawable()); AnimationComponentPtr torsoAc = boost::make_shared<AnimationComponent>(torsoRc->drawable()); legsAc->addAnimation(AnimationDefault, "kyle_legs_def"); legsAc->addAnimation(DudeComponent::AnimationWalk, "kyle_legs_walk"); torsoAc->addAnimation(AnimationDefault, "kyle_torso_def"); torsoAc->addAnimation(DudeComponent::AnimationWalk, "kyle_torso_walk"); legsAc->startAnimation(AnimationDefault); torsoAc->startAnimationRandomTime(AnimationDefault); asset->root()->addComponent(legsAc); asset->root()->addComponent(torsoAc); DudeComponentPtr component = boost::make_shared<DudeComponent>(legsRc, legsAc, torsoAc); component->setLegsAngle(-b2_pi / 2); asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createLaserBlocker(const Color& color, float width, float length, int zOrder, UInt32 maskBits) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); obj->setType(SceneObjectTypeBlocker); b2BodyDef bodyDef; bodyDef.type = b2_kinematicBody; RUBEBodyPtr body = boost::make_shared<RUBEBody>("", bodyDef); RUBEPolygonFixturePtr fixture = boost::make_shared<RUBEPolygonFixture>(""); fixture->fixtureDef().friction = 0.0f; fixture->fixtureDef().filter.categoryBits = collisionBitGeneral; fixture->fixtureDef().filter.maskBits = maskBits; fixture->shape().SetAsBox(length / 2.0f, width / 2.0f, b2Vec2(length / 2.0f, 0.0f), 0.0f); body->addFixture(fixture); ComponentPtr component = boost::make_shared<PhysicsBodyComponent>(body); obj->addComponent(component); { RenderBeamComponentPtr component = boost::make_shared<RenderBeamComponent>(b2Vec2_zero, 0.0f, width, assetManager.getDrawable("laser1.png", Texture::WrapModeRepeat, Texture::WrapModeClamp), zOrder); component->setLength(length); Color tmp = color; tmp.rgba[3] = 0.4f; component->setColor(tmp); obj->addComponent(component); } { Color tmp = color; tmp.rgba[3] = 1.0f; LineLightPtr light = boost::make_shared<LineLight>(); light->setAngle(b2_pi / 2); light->setColor(tmp); light->setXray(true); light->setDistance(width); light->setBothWays(true); light->setPos(b2Vec2(length / 2, 0.0f)); light->setLength(length / 2); LightComponentPtr component = boost::make_shared<LightComponent>(); component->attachLight(light); obj->addComponent(component); } obj->setBodyDef(body->bodyDef()); return obj; } SceneObjectPtr SceneObjectFactory::createCircleSensor(float radius, UInt32 maskBits) { b2BodyDef bodyDef; bodyDef.type = b2_kinematicBody; RUBEBodyPtr body = boost::make_shared<RUBEBody>("", bodyDef); RUBECircleFixturePtr fixture = boost::make_shared<RUBECircleFixture>(""); fixture->fixtureDef().isSensor = true; fixture->fixtureDef().filter.categoryBits = collisionBitGeneral; fixture->fixtureDef().filter.maskBits = maskBits; fixture->shape().m_p = b2Vec2_zero; fixture->shape().m_radius = radius; body->addFixture(fixture); SceneObjectPtr obj = boost::make_shared<SceneObject>(); { ComponentPtr component = boost::make_shared<PhysicsBodyComponent>(body); obj->addComponent(component); } { ComponentPtr component = boost::make_shared<CollisionSensorComponent>(); obj->addComponent(component); } obj->setBodyDef(body->bodyDef()); return obj; } ComponentPtr SceneObjectFactory::createCircle(float radius, int numSectors, const Color& color, int zOrder) { std::vector<Points> polygons; polygons.push_back(Points()); polygons.back().resize(numSectors); for (int i = 0; i < numSectors; ++i) { float a = i * 2 * b2_pi / numSectors; polygons.back()[i] = radius * b2Vec2(cosf(a), sinf(a)); } RenderPolygonsComponentPtr component = boost::make_shared<RenderPolygonsComponent>(polygons, assetManager.getImage("dialog_bg.png"), 1.0f, 1.0f, zOrder); component->setColor(color); return component; } ComponentPtr SceneObjectFactory::createPlaceholder(InventoryItem item, float height, float radius, int numSectors, int imageZOrder, int circleZOrder) { return createPlaceholder(item, height, radius, numSectors, imageZOrder, circleZOrder, "", false, 0.0f); } ComponentPtr SceneObjectFactory::createPlaceholder(InventoryItem item, float height, float radius, int numSectors, int imageZOrder, int circleZOrder, const std::string& image, bool imageFlip, float alpha) { return boost::make_shared<PlaceholderComponent>(item, createPlaceholderSensor((image.empty() ? Inventory::getPlaceholderImageName(item) : image), (image.empty() ? false : imageFlip), height, radius, numSectors, imageZOrder, circleZOrder, collisionBitPlayer | collisionBitVehicle, alpha)); } ComponentPtr SceneObjectFactory::createRockPlaceholder(float height, float radius, int numSectors, int imageZOrder, int circleZOrder, const std::string& image, bool imageFlip, float alpha) { return boost::make_shared<PlaceholderComponent>(InventoryItemDynomite, createPlaceholderSensor(image, imageFlip, height, radius, numSectors, imageZOrder, circleZOrder, collisionBitRock, alpha)); } ComponentPtr SceneObjectFactory::createVehiclePlaceholder(float radius, int numSectors, int zOrder, float alpha) { Color color = settings.placeholder.color; if (alpha > 0.0f) { color.rgba[3] = alpha; } SceneObjectPtr sensor = createCircleSensor(radius, collisionBitPlayer | collisionBitVehicle); sensor->addComponent(createCircle(radius, numSectors, color, zOrder)); RenderDottedCircleComponentPtr dcc = boost::make_shared<RenderDottedCircleComponent>(b2Vec2_zero, 0.3f, assetManager.getDrawable("common2/dot.png"), zOrder); dcc->setColor(color); dcc->setRadius(radius); dcc->setDotVelocity(5.0f, radius); dcc->setDotDistance(0.5f, radius); sensor->addComponent(dcc); return boost::make_shared<PlaceholderComponent>(InventoryItemDynomite, sensor); } ComponentPtr SceneObjectFactory::createAllyPlaceholder(InventoryItem item, float height, float radius, int numSectors, int imageZOrder, int circleZOrder, const std::string& image, bool imageFlip, float alpha) { SceneObjectPtr sensor = createPlaceholderSensor((image.empty() ? Inventory::getPlaceholderImageName(item) : image), (image.empty() ? false : imageFlip), height, radius, numSectors, imageZOrder, circleZOrder, collisionBitAlly, alpha); sensor->script_setBodyType(b2_dynamicBody); sensor->setSleepingAllowed(false); return boost::make_shared<PlaceholderComponent>(item, sensor); } SceneObjectPtr SceneObjectFactory::createPlaceholderSensor(const std::string& image, bool imageFlip, float height, float radius, int numSectors, int imageZOrder, int circleZOrder, UInt32 maskBits, float alpha) { Color color = settings.placeholder.color; if (alpha > 0.0f) { color.rgba[3] = alpha; } SceneObjectPtr sensor = createCircleSensor(radius, maskBits); sensor->addComponent(createCircle(radius, numSectors, color, circleZOrder)); DrawablePtr drawable = assetManager.getDrawable(image); float width = height * drawable->image().aspect(); RenderQuadComponentPtr rc = boost::make_shared<RenderQuadComponent>(b2Vec2_zero, -b2_pi / 2.0f, width, height, drawable, imageZOrder); rc->setColor(color); rc->setFlip(imageFlip); sensor->addComponent(rc); RenderDottedCircleComponentPtr dcc = boost::make_shared<RenderDottedCircleComponent>(b2Vec2_zero, 0.3f, assetManager.getDrawable("common2/dot.png"), circleZOrder); dcc->setColor(color); dcc->setRadius(radius); dcc->setDotVelocity(5.0f, radius); dcc->setDotDistance(0.5f, radius); sensor->addComponent(dcc); return sensor; } ComponentPtr SceneObjectFactory::createTimebomb(InventoryItem item, float height, int imageZOrder, int circleZOrder) { static const float radius = 13.0f; static const float numSectors = 30.0f; SceneObjectPtr obj = boost::make_shared<SceneObject>(); obj->addComponent(createCircle(radius, numSectors, settings.timebomb.color, circleZOrder)); DrawablePtr drawable = assetManager.getDrawable(Inventory::getImageName(item)); float width = height * drawable->image().aspect(); RenderQuadComponentPtr rc = boost::make_shared<RenderQuadComponent>(b2Vec2_zero, -b2_pi / 2.0f, width, height, drawable, imageZOrder); obj->addComponent(rc); RenderDottedCircleComponentPtr dcc = boost::make_shared<RenderDottedCircleComponent>(b2Vec2_zero, 0.3f, assetManager.getDrawable("common2/dot.png"), circleZOrder); dcc->setColor(settings.timebomb.color); dcc->setRadius(radius); dcc->setDotVelocity(5.0f, radius); dcc->setDotDistance(0.5f, radius); obj->addComponent(dcc); return boost::make_shared<TimebombComponent>(obj, height); } SceneObjectPtr SceneObjectFactory::createBossSkull() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("boss_skull.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemyBuilding); asset->object(i)->setPropagateDamage(false); } asset->root()->setLife(settings.bossSkull.life); asset->root()->setMaxLife(settings.bossSkull.life); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 3.0f), 0, 8.0f, 2.0f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } std::vector<BossSkullGunComponentPtr> guns; /* * Setup front guns. */ const char* frontGunNames[] = { "gun_front_left", "gun_front_right" }; const char* frontGunJointNames[] = { "gun_front_left_joint", "gun_front_right_joint" }; for (size_t i = 0; i < sizeof(frontGunNames)/sizeof(frontGunNames[0]); ++i) { SceneObjectPtr obj = asset->object(frontGunNames[i]); std::vector<WeaponComponentPtr> weapons; for (int j = 0; j < asset->world()->body(frontGunNames[i])->numImages(); ++j) { const RUBEImagePtr& image = asset->world()->body(frontGunNames[i])->image(j); if (image->name() != "missile") { continue; } WeaponBlasterComponentPtr weapon = boost::make_shared<WeaponBlasterComponent>(true, SceneObjectTypeEnemyMissile); weapon->setTransform(b2Transform(image->pos(), b2Rot(image->angle() + b2_pi / 2.0f))); weapon->setDamage(settings.bossSkull.gunFrontShootDamage); weapon->setVelocity(settings.bossSkull.gunFrontShootVelocity); weapon->setTurns(1); weapon->setShotsPerTurn(1); weapon->setLoopDelay(settings.bossSkull.gunFrontShootDelay); weapon->setHaveSound(false); if (weapons.empty()) { weapon->setHaveSound(true); } weapons.push_back(weapon); } BossSkullGunComponentPtr c = boost::make_shared<BossSkullGunComponent>(weapons, settings.bossSkull.gunFrontTurnSpeed, settings.bossSkull.gunFrontShootAngle, settings.bossSkull.gunFrontShootRadius, frontGunJointNames[i]); obj->addComponent(c); guns.push_back(c); } /* * Setup back guns. */ const char* backGunNames[] = { "gun_back_left", "gun_back_right" }; const char* backGunJointNames[] = { "gun_back_left_joint", "gun_back_right_joint" }; for (size_t i = 0; i < sizeof(backGunNames)/sizeof(backGunNames[0]); ++i) { SceneObjectPtr obj = asset->object(backGunNames[i]); std::vector<WeaponComponentPtr> weapons; for (int j = 0; j < asset->world()->body(backGunNames[i])->numImages(); ++j) { const RUBEImagePtr& image = asset->world()->body(backGunNames[i])->image(j); if (image->name() != "missile") { continue; } WeaponBlasterComponentPtr weapon = boost::make_shared<WeaponBlasterComponent>(false, SceneObjectTypeEnemyMissile); weapon->setTransform(b2Transform(image->pos(), b2Rot(image->angle() + b2_pi / 2.0f))); weapon->setDamage(settings.bossSkull.gunBackShootDamage); weapon->setVelocity(settings.bossSkull.gunBackShootVelocity); weapon->setTurns(1); weapon->setShotsPerTurn(1); weapon->setLoopDelay(settings.bossSkull.gunBackShootDelay); weapon->setHaveSound(false); if (weapons.empty()) { weapon->setHaveSound(true); } weapons.push_back(weapon); } BossSkullGunComponentPtr c = boost::make_shared<BossSkullGunComponent>(weapons, settings.bossSkull.gunBackTurnSpeed, settings.bossSkull.gunBackShootAngle, settings.bossSkull.gunBackShootRadius, backGunJointNames[i]); obj->addComponent(c); guns.push_back(c); } /* * Setup mid guns. */ std::vector<BossSkullGunComponentPtr> flamethrowers; const char* midGunNames[] = { "gun_mid_left", "gun_mid_right" }; const char* midGunJointNames[] = { "gun_mid_left_joint", "gun_mid_right_joint" }; for (size_t i = 0; i < sizeof(midGunNames)/sizeof(midGunNames[0]); ++i) { SceneObjectPtr obj = asset->object(midGunNames[i]); std::vector<WeaponComponentPtr> weapons; for (int j = 0; j < asset->world()->body(midGunNames[i])->numImages(); ++j) { const RUBEImagePtr& image = asset->world()->body(midGunNames[i])->image(j); if (image->name() != "missile") { continue; } WeaponFlamethrowerComponentPtr weapon = boost::make_shared<WeaponFlamethrowerComponent>(SceneObjectTypeEnemyMissile); weapon->setTransform(b2Transform(image->pos(), b2Rot(image->angle() + b2_pi / 2.0f))); weapon->setDamage(settings.bossSkull.gunMidDamage); weapon->setHaveSound(false); if (weapons.empty()) { weapon->setHaveSound(true); } weapons.push_back(weapon); } BossSkullGunComponentPtr c = boost::make_shared<BossSkullGunComponent>(weapons, settings.bossSkull.gunMidTurnSpeed, settings.bossSkull.gunMidShootAngle, settings.bossSkull.gunMidShootRadius, midGunJointNames[i]); obj->addComponent(c); guns.push_back(c); flamethrowers.push_back(c); } BossSkullComponentPtr c = boost::make_shared<BossSkullComponent>(guns, flamethrowers); asset->root()->addComponent(c); asset->root()->setBlastDamageMultiplier(settings.bossSkull.blastDamageMultiplier); return asset->root(); } SceneObjectPtr SceneObjectFactory::createSpider() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("spider.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); } RenderQuadComponentPtr torsoRc = asset->root()->findComponentByName<RenderQuadComponent>("torso"); AnimationComponentPtr torsoAc = boost::make_shared<AnimationComponent>(torsoRc->drawable()); torsoAc->addAnimation(AnimationDefault, "bigspider_def"); torsoAc->addAnimation(SpiderComponent::AnimationAttack, "bigspider_attack"); torsoAc->startAnimation(AnimationDefault); asset->root()->addComponent(torsoAc); SceneObjectPtr legs[] = { asset->object("leg_front1_top"), asset->object("leg_front1_bottom"), asset->object("leg_front2_top"), asset->object("leg_front2_bottom"), asset->object("leg_back1_top"), asset->object("leg_back1_bottom"), asset->object("leg_back2_top"), asset->object("leg_back2_bottom") }; b2Vec2 legTips[] = { asset->world()->body("leg_front1_top")->image("tip")->pos(), asset->world()->body("leg_front1_bottom")->image("tip")->pos(), asset->world()->body("leg_front2_top")->image("tip")->pos(), asset->world()->body("leg_front2_bottom")->image("tip")->pos(), asset->world()->body("leg_back1_top")->image("tip")->pos(), asset->world()->body("leg_back1_bottom")->image("tip")->pos(), asset->world()->body("leg_back2_top")->image("tip")->pos(), asset->world()->body("leg_back2_bottom")->image("tip")->pos() }; SpiderComponentPtr c = boost::make_shared<SpiderComponent>(legs, legTips, asset->rootBody()->image("tip")->pos(), torsoAc); asset->root()->addComponent(c); return asset->root(); } SceneObjectPtr SceneObjectFactory::createBabySpider1() { return createBabySpider(1.0f, settings.babySpider1.life, settings.babySpider1.walkSpeed, settings.babySpider1.biteDamage, false); } SceneObjectPtr SceneObjectFactory::createBabySpider2() { return createBabySpider(0.7f, settings.babySpider2.life, settings.babySpider2.walkSpeed, settings.babySpider2.biteDamage, true); } SceneObjectPtr SceneObjectFactory::createBabySpider(float scale, float life, float walkSpeed, float biteDamage, bool isSmall) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("baby_spider.json"); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setMaterial(MaterialFlesh); asset->root()->setLife(life); asset->root()->setFireDamageMultiplier(settings.babySpider.fireDamageMultiplier); RenderQuadComponentPtr rc = asset->root()->findComponent<RenderQuadComponent>(); rc->setHeight(rc->height() * scale); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(rc->drawable()); if (isSmall) { ac->addAnimation(AnimationDefault, "spider2_def", 10.0f / walkSpeed); ac->addAnimation(BabySpiderComponent::AnimationDie, "spider2_die"); } else { ac->addAnimation(AnimationDefault, "spider_def", 10.0f / walkSpeed); ac->addAnimation(BabySpiderComponent::AnimationDie, "spider_die"); } ac->startAnimation(AnimationDefault); ac->setPaused(true); asset->root()->addComponent(ac); BabySpiderComponentPtr thinkComponent = boost::make_shared<BabySpiderComponent>(ac, rc, walkSpeed, biteDamage); asset->root()->addComponent(thinkComponent); { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.babySpider.damageImpulseThreshold); component->setMultiplier(settings.babySpider.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypeTerrain); types.set(SceneObjectTypeRock); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); component->setFilter(types); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createSpiderNest(float probabilities[1], bool dead) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("spider_nest.json"); asset->root()->setType(SceneObjectTypeEnemyBuilding); asset->root()->setMaterial(MaterialFlesh); asset->root()->setLife(settings.spiderNest.life); RenderQuadComponentPtr rc = asset->root()->findComponent<RenderQuadComponent>(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(rc->drawable()); ac->addAnimation(AnimationDefault, "spidernest_def"); ac->addAnimation(SpiderNestComponent::AnimationDie, "spidernest_die"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); b2Transform spawn[3]; int j = 0; for (int i = 0; i < asset->rootBody()->numImages(); ++i) { const RUBEImagePtr& image = asset->rootBody()->image(i); if (image->name() != "spawn") { continue; } if (j < 3) { spawn[j++] = b2Transform(image->pos(), b2Rot(image->angle() + b2_pi / 2.0f)); } } SpiderNestComponentPtr thinkComponent = boost::make_shared<SpiderNestComponent>(ac, spawn, settings.spiderNest.radius, probabilities); if (dead) { thinkComponent->setDead(); } asset->root()->addComponent(thinkComponent); { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.spiderNest.damageImpulseThreshold); component->setMultiplier(settings.spiderNest.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypeTerrain); types.set(SceneObjectTypeRock); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); component->setFilter(types); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createWeaponTrap(WeaponType weaponType, SceneObjectType objectType) { b2BodyDef bodyDef; bodyDef.type = b2_kinematicBody; RUBEBodyPtr body = boost::make_shared<RUBEBody>("", bodyDef); ComponentPtr component = boost::make_shared<PhysicsBodyComponent>(body); SceneObjectPtr obj = boost::make_shared<SceneObject>(); obj->setBodyDef(body->bodyDef()); obj->addComponent(component); WeaponComponentPtr weapon; switch (weaponType) { case WeaponTypeGG: weapon = boost::make_shared<WeaponGGComponent>(objectType); break; case WeaponTypeBlaster: weapon = boost::make_shared<WeaponBlasterComponent>(false, objectType); break; case WeaponTypeShotgun: weapon = boost::make_shared<WeaponShotgunComponent>(false, objectType); break; case WeaponTypeRLauncher: weapon = boost::make_shared<WeaponRLauncherComponent>(objectType); break; case WeaponTypeFireball: weapon = boost::make_shared<WeaponFireballComponent>(objectType); break; case WeaponTypeFlamethrower: weapon = boost::make_shared<WeaponFlamethrowerComponent>(objectType); break; case WeaponTypePistol: weapon = boost::make_shared<WeaponPistolComponent>(objectType); break; case WeaponTypeLGun: weapon = boost::make_shared<WeaponLGunComponent>(objectType); break; default: assert(false); break; } obj->addComponent(weapon); return obj; } SceneObjectPtr SceneObjectFactory::createBossQueen() { SceneObjectTypes types; types.set(SceneObjectTypePlayer); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("boss_queen.json"); asset->root()->setLife(settings.bossQueen.life); asset->root()->setMaxLife(settings.bossQueen.life); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 1.0f), 0, 12.0f, 2.0f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } asset->root()->setMaterial(MaterialFlesh); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); asset->object(i)->setCollisionImpulseMultiplier(0.0f); asset->object(i)->setPropagateDamage(false); if (asset->object(i)->name() == "front_leg") { CollisionCancelComponentPtr c = boost::make_shared<CollisionCancelComponent>(); c->setFilter(types); c->setDamage(settings.bossQueen.legDamage); asset->object(i)->addComponent(c); } } RenderQuadComponentPtr headRc = asset->root()->findComponentByName<RenderQuadComponent>("head"); AnimationComponentPtr headAc = boost::make_shared<AnimationComponent>(headRc->drawable()); headAc->addAnimation(AnimationDefault, "queen_def"); headAc->addAnimation(BossQueenComponent::AnimationAttack, "queen_attack"); headAc->startAnimation(AnimationDefault); asset->root()->addComponent(headAc); SceneObjectPtr legs[] = { asset->object("leg1_top"), asset->object("leg1_bottom"), asset->object("leg2_top"), asset->object("leg2_bottom"), asset->object("leg3_top"), asset->object("leg3_bottom"), asset->object("leg4_top"), asset->object("leg4_bottom") }; for (size_t i = 0; i < 4; ++i) { CollisionCancelComponentPtr c = boost::make_shared<CollisionCancelComponent>(); c->setFilter(types); c->setDamage(settings.bossQueen.legDamage); legs[i]->addComponent(c); } b2Vec2 legTips[] = { asset->world()->body("leg1_top")->image("tip")->pos(), asset->world()->body("leg1_bottom")->image("tip")->pos(), asset->world()->body("leg2_top")->image("tip")->pos(), asset->world()->body("leg2_bottom")->image("tip")->pos(), asset->world()->body("leg3_top")->image("tip")->pos(), asset->world()->body("leg3_bottom")->image("tip")->pos(), asset->world()->body("leg4_top")->image("tip")->pos(), asset->world()->body("leg4_bottom")->image("tip")->pos() }; b2Vec2 cover[] = { asset->rootBody()->image("leg1_top_cover")->pos(), asset->rootBody()->image("leg1_bottom_cover")->pos(), asset->rootBody()->image("leg2_top_cover")->pos(), asset->rootBody()->image("leg2_bottom_cover")->pos() }; Points spawn; for (int i = 0; i < asset->rootBody()->numImages(); ++i) { const RUBEImagePtr& image = asset->rootBody()->image(i); if (image->name() == "spawn") { spawn.push_back(image->pos()); } } b2Vec2 dead[] = { asset->rootBody()->image("leg1_top_dead")->pos(), asset->rootBody()->image("leg1_bottom_dead")->pos(), asset->rootBody()->image("leg2_top_dead")->pos(), asset->rootBody()->image("leg2_bottom_dead")->pos() }; BossQueenComponentPtr c = boost::make_shared<BossQueenComponent>(legs, legTips, asset->rootBody()->image("tip")->pos(), cover, spawn, dead, headAc); asset->root()->addComponent(c); return asset->root(); } SceneObjectPtr SceneObjectFactory::createEnforcer(float life, float shootInterval, const Color& color, b2Vec2& missilePos, float& missileAngle, float& missileFlashDistance) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("enforcer.json"); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setMaterial(MaterialFlesh); asset->root()->setLife(life); asset->root()->setMaxLife(life); RenderQuadComponentPtr torsoRc = asset->root()->findComponentByName<RenderQuadComponent>("torso"); RenderQuadComponentPtr torsoMaskRc = asset->root()->findComponentByName<RenderQuadComponent>("torso_mask"); RenderQuadComponentPtr legsRc = asset->root()->findComponentByName<RenderQuadComponent>("legs"); torsoMaskRc->setColor(color); AnimationComponentPtr torsoAc = boost::make_shared<AnimationComponent>(torsoRc->drawable()); AnimationComponentPtr torsoMaskAc = boost::make_shared<AnimationComponent>(torsoMaskRc->drawable()); AnimationComponentPtr legsAc = boost::make_shared<AnimationComponent>(legsRc->drawable()); torsoAc->addAnimation(AnimationDefault, "enforcer_torso_def"); torsoMaskAc->addAnimation(AnimationDefault, "enforcer_torso_mask_def"); legsAc->addAnimation(AnimationDefault, "enforcer_legs_def"); torsoAc->addAnimation(EnforcerComponent::AnimationDie, "enforcer_torso_die"); torsoMaskAc->addAnimation(EnforcerComponent::AnimationDie, "enforcer_torso_mask_die"); torsoAc->startAnimation(AnimationDefault); torsoMaskAc->startAnimation(AnimationDefault); legsAc->startAnimation(AnimationDefault); torsoAc->setPaused(true); torsoMaskAc->setPaused(true); legsAc->setPaused(true); asset->root()->addComponent(torsoAc); asset->root()->addComponent(torsoMaskAc); asset->root()->addComponent(legsAc); { EnforcerComponentPtr component = boost::make_shared<EnforcerComponent>(torsoRc, torsoMaskRc, legsRc, torsoAc, torsoMaskAc, legsAc, shootInterval); missilePos = asset->rootBody()->image("missile")->pos(); missileAngle = normalizeAngle(asset->rootBody()->image("missile")->angle() + b2_pi / 2.0f); missileFlashDistance = asset->rootBody()->image("missile")->height() / 2.0f; asset->root()->addComponent(component); } { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.enforcer.damageImpulseThreshold); component->setMultiplier(settings.enforcer.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypeTerrain); types.set(SceneObjectTypeRock); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); component->setFilter(types); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createEnforcer1() { b2Vec2 missilePos; float missileAngle; float missileFlashDistance; SceneObjectPtr obj = createEnforcer(settings.enforcer1.life, settings.enforcer1.shootInterval, settings.enforcer1.color, missilePos, missileAngle, missileFlashDistance); EnforcerComponentPtr component = obj->findComponent<EnforcerComponent>(); WeaponPistolComponentPtr pistol = boost::make_shared<WeaponPistolComponent>(SceneObjectTypeEnemyMissile); pistol->setDamage(settings.enforcer1.shootDamage); pistol->setVelocity(settings.enforcer1.shootVelocity); pistol->setInterval(settings.enforcer1.shootInterval); pistol->setPos(missilePos); pistol->setAngle(missileAngle); pistol->setFlashDistance(missileFlashDistance); component->setWeapon(pistol); obj->addComponent(pistol); return obj; } SceneObjectPtr SceneObjectFactory::createEnforcer2() { b2Vec2 missilePos; float missileAngle; float missileFlashDistance; SceneObjectPtr obj = createEnforcer(settings.enforcer2.life, settings.enforcer2.shootDelay, settings.enforcer2.color, missilePos, missileAngle, missileFlashDistance); EnforcerComponentPtr component = obj->findComponent<EnforcerComponent>(); WeaponBlasterComponentPtr blaster = boost::make_shared<WeaponBlasterComponent>(true, SceneObjectTypeEnemyMissile); blaster->setDamage(settings.enforcer2.shootDamage); blaster->setVelocity(settings.enforcer2.shootVelocity); blaster->setTurns(3); blaster->setShotsPerTurn(3); blaster->setTurnInterval(settings.enforcer2.shootTurnInterval); blaster->setLoopDelay(settings.enforcer2.shootDelay); blaster->setPos(missilePos + angle2vec(missileAngle, missileFlashDistance)); blaster->setAngle(missileAngle); blaster->setTweakPos(true); component->setWeapon(blaster); obj->addComponent(blaster); return obj; } SceneObjectPtr SceneObjectFactory::createEnforcer3() { b2Vec2 missilePos; float missileAngle; float missileFlashDistance; SceneObjectPtr obj = createEnforcer(settings.enforcer1.life, settings.enforcer1.shootInterval, settings.enforcer3.color, missilePos, missileAngle, missileFlashDistance); EnforcerComponentPtr component = obj->findComponent<EnforcerComponent>(); WeaponPistolComponentPtr pistol = boost::make_shared<WeaponPistolComponent>(SceneObjectTypeEnemyMissile); pistol->setDamage(settings.enforcer1.shootDamage); pistol->setVelocity(settings.enforcer1.shootVelocity); pistol->setInterval(settings.enforcer1.shootInterval); pistol->setPos(missilePos); pistol->setAngle(missileAngle); pistol->setFlashDistance(missileFlashDistance); component->setWeapon(pistol); obj->addComponent(pistol); return obj; } SceneObjectPtr SceneObjectFactory::createBullet(SceneObjectType type, float height, float damage) { assert((type == SceneObjectTypePlayerMissile) || (type == SceneObjectTypeEnemyMissile) || (type == SceneObjectTypeAllyMissile) || (type == SceneObjectTypeNeutralMissile)); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("bullet2.json"); asset->root()->setType(type); b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; if (type == SceneObjectTypeEnemyMissile) { filter.maskBits &= ~(collisionBitEnemy | collisionBitEnemyBuilding); } else if (type != SceneObjectTypeNeutralMissile) { filter.maskBits &= ~(collisionBitPlayer | collisionBitAlly); } asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); asset->root()->addComponent(cdc); LineLightPtr light = asset->root()->findComponent<LightComponent>()->getLight<LineLight>("light"); RenderTrailComponentPtr rtc = boost::make_shared<RenderTrailComponent>(b2Vec2_zero, b2_pi, assetManager.getDrawable("trail1.png", Texture::WrapModeRepeat, Texture::WrapModeClamp), asset->rootBody()->image("light")->zOrder()); switch (type) { case SceneObjectTypePlayerMissile: light->setColor(settings.bullet.player[0]); rtc->setColor2(settings.bullet.player[1]); break; case SceneObjectTypeAllyMissile: light->setColor(settings.bullet.ally[0]); rtc->setColor2(settings.bullet.ally[1]); break; case SceneObjectTypeEnemyMissile: case SceneObjectTypeNeutralMissile: light->setColor(settings.bullet.enemy[0]); rtc->setColor2(settings.bullet.enemy[1]); break; default: assert(false); break; } rtc->setColor(light->color()); rtc->setWidth1(height); rtc->setWidth2(height); asset->root()->addComponent(rtc); { ComponentPtr component = boost::make_shared<BulletComponent>(cdc, rtc, light, damage); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createSentry1(bool folded) { SceneObjectPtr obj = createSentry(true, folded, settings.sentry1.life, settings.sentry1.shootDamage, settings.sentry1.shootTurnDuration, settings.sentry1.shootLoopDelay, "sentry1"); return obj; } SceneObjectPtr SceneObjectFactory::createSentry2(bool folded) { SceneObjectPtr obj = createSentry(false, folded, settings.sentry2.life, settings.sentry2.shootDamage, settings.sentry2.shootTurnDuration, settings.sentry2.shootLoopDelay, "sentry2"); return obj; } SceneObjectPtr SceneObjectFactory::createSentryGibbed(int i) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset((i == 1) ? "sentry_gibbed.json" : "sentry2_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemyBuilding); makeDebris(asset->object(i)); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createGorger1() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("gorger.json"); asset->root()->setType(SceneObjectTypeEnemyBuilding); asset->root()->setMaterial(MaterialFlesh); asset->root()->setLife(settings.gorger.life); asset->root()->setMaxLife(settings.gorger.life); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 4.0f), 0, 6.0f, 1.0f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } DrawablePtr drawable = asset->root()->findComponent<RenderQuadComponent>()->drawable(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(drawable); ac->addAnimation(AnimationDefault, "gorger_def"); ac->addAnimation(GorgerComponent::AnimationAngry, "gorger_angry"); ac->addAnimation(GorgerComponent::AnimationWalk, "gorger_walk"); ac->addAnimation(GorgerComponent::AnimationMelee, "gorger_melee"); ac->addAnimation(GorgerComponent::AnimationPreShoot, "gorger_preshoot"); ac->addAnimation(GorgerComponent::AnimationPostShoot, "gorger_postshoot"); ac->addAnimation(GorgerComponent::AnimationShoot, "gorger_shoot"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); { GorgerComponentPtr component = boost::make_shared<GorgerComponent>(ac, asset->rootBody()->image("melee")->pos(), asset->rootBody()->image("melee")->height() / 2.0f); for (int i = 0; i < 2; ++i) { std::ostringstream os; os << "missile" << (i + 1); WeaponRLauncherComponentPtr rlauncher = boost::make_shared<WeaponRLauncherComponent>(SceneObjectTypeEnemyMissile); rlauncher->setExplosionImpulse(settings.gorger.shootExplosionImpulse); rlauncher->setExplosionDamage(settings.gorger.shootExplosionDamage); rlauncher->setVelocity(settings.gorger.shootVelocity); rlauncher->setInterval(0.1f); rlauncher->setPos(asset->rootBody()->image(os.str())->pos()); rlauncher->setAngle(normalizeAngle(asset->rootBody()->image(os.str())->angle() + b2_pi / 2.0f)); component->setWeapon(i, rlauncher); asset->root()->addComponent(rlauncher); } asset->root()->addComponent(component); } asset->root()->setBlastDamageMultiplier(settings.gorger.blastDamageMultiplier); return asset->root(); } SceneObjectPtr SceneObjectFactory::createRocket(SceneObjectType type, float explosionImpulse, float explosionDamage) { assert((type == SceneObjectTypePlayerMissile) || (type == SceneObjectTypeEnemyMissile) || (type == SceneObjectTypeAllyMissile) || (type == SceneObjectTypeNeutralMissile)); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("rocket.json"); asset->root()->setType(type); b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; SceneObjectTypes damageTypes; if (type == SceneObjectTypeEnemyMissile) { filter.maskBits &= ~(collisionBitEnemy | collisionBitEnemyBuilding); damageTypes.set(SceneObjectTypePlayer); damageTypes.set(SceneObjectTypeAlly); } else if (type != SceneObjectTypeNeutralMissile) { filter.maskBits &= ~(collisionBitPlayer | collisionBitAlly); damageTypes.set(SceneObjectTypeEnemy); damageTypes.set(SceneObjectTypeEnemyBuilding); } else { damageTypes.set(SceneObjectTypePlayer); damageTypes.set(SceneObjectTypeAlly); damageTypes.set(SceneObjectTypeEnemy); damageTypes.set(SceneObjectTypeEnemyBuilding); } asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<RocketComponent>(cdc, asset->root()->findComponent<ParticleEffectComponent>(), explosionImpulse, explosionDamage, damageTypes); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createGorgerGibbed() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("gorger_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemyBuilding); makeDebris(asset->object(i)); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createProxMine(SceneObjectType type) { assert((type == SceneObjectTypePlayerMissile) || (type == SceneObjectTypeEnemyMissile) || (type == SceneObjectTypeAllyMissile) || (type == SceneObjectTypeNeutralMissile)); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("proxmine.json"); asset->root()->setType(type); b2Filter filter = asset->rootBody()->fixture<RUBEFixture>("sensor")->fixtureDef().filter; SceneObjectTypes damageTypes; if (type == SceneObjectTypeEnemyMissile) { filter.maskBits = collisionBitPlayer | collisionBitAlly; damageTypes.set(SceneObjectTypePlayer); damageTypes.set(SceneObjectTypeAlly); } else if (type != SceneObjectTypeNeutralMissile) { filter.maskBits = collisionBitEnemy | collisionBitEnemyBuilding | collisionBitEnemyRock; damageTypes.set(SceneObjectTypeEnemy); damageTypes.set(SceneObjectTypeEnemyBuilding); } else { filter.maskBits = collisionBitPlayer | collisionBitAlly | collisionBitEnemy | collisionBitEnemyBuilding | collisionBitEnemyRock; damageTypes.set(SceneObjectTypePlayer); damageTypes.set(SceneObjectTypeAlly); damageTypes.set(SceneObjectTypeEnemy); damageTypes.set(SceneObjectTypeEnemyBuilding); } asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); ProxMineComponentPtr thinkComponent = boost::make_shared<ProxMineComponent>(damageTypes); asset->root()->addComponent(thinkComponent); { CollisionSensorComponentPtr component = boost::make_shared<CollisionSensorComponent>(); component->setListener(thinkComponent); asset->root()->addComponent(component); } asset->root()->becomeDeadbody(); return asset->root(); } SceneObjectPtr SceneObjectFactory::createRoboArm() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("roboarm.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeRock); } RoboArmComponentPtr c = boost::make_shared<RoboArmComponent>(asset->object("tip"), asset->object("clamp_high"), asset->object("clamp_low"), "joint_high", "joint_low", asset->rootBody()->image("min")->pos().Length()); asset->root()->addComponent(c); return asset->root(); } SceneObjectPtr SceneObjectFactory::createCrate(int i, float powerupProbabilities[PowerupTypeMax + 1], float ammoProbabilities[WeaponTypeMax + 1]) { std::ostringstream os; os << "crate" << i << ".json"; SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset(os.str()); asset->root()->setType(SceneObjectTypeGizmo); asset->root()->setLife(settings.crate1.life); asset->root()->setMaxLife(settings.crate1.life); { CrateComponentPtr component = boost::make_shared<CrateComponent>(i, powerupProbabilities, ammoProbabilities); asset->root()->addComponent(component); } { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.crate1.damageImpulseThreshold); component->setMultiplier(settings.crate1.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypePlayer); types.set(SceneObjectTypeAlly); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeTerrain); types.set(SceneObjectTypeRock); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); component->setFilter(types); component->setDamageSound(audio.createSound("wood_hit1.ogg")); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createCrateGibbed(int i) { std::ostringstream os; os << "crate" << i << "_gibbed.json"; SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset(os.str()); for (int j = 0; j < asset->numObjects(); ++j) { asset->object(j)->setType(SceneObjectTypeGizmo); makeDebris(asset->object(j)); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createSentry(bool enemy, bool folded, float life, float shootDamage, float shootTurnDuration, float shootLoopDelay, const std::string& base) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("sentry.json"); for (int i = 0; i < asset->numObjects(); ++i) { if (enemy) { asset->object(i)->setType(SceneObjectTypeEnemyBuilding); } else { asset->object(i)->setType(SceneObjectTypeAlly); } } asset->root()->setLife(life); asset->root()->setMaxLife(life); RenderQuadComponentPtr torsoRc = asset->object("torso")->findComponentByName<RenderQuadComponent>("torso"); RenderQuadComponentPtr legsRc = asset->root()->findComponentByName<RenderQuadComponent>("legs"); AnimationComponentPtr torsoAc = boost::make_shared<AnimationComponent>(torsoRc->drawable()); AnimationComponentPtr legsAc = boost::make_shared<AnimationComponent>(legsRc->drawable()); torsoAc->addAnimation(AnimationDefault, base + "_torso_def"); legsAc->addAnimation(AnimationDefault, base + "_legs_def"); torsoAc->addAnimation(SentryComponent::AnimationUnfold, base + "_torso_unfold"); legsAc->addAnimation(SentryComponent::AnimationUnfold, base + "_legs_unfold"); legsAc->addAnimation(SentryComponent::AnimationWalk, base + "_legs_walk"); asset->root()->addComponent(torsoAc); asset->root()->addComponent(legsAc); { SentryComponentPtr component = boost::make_shared<SentryComponent>(asset->object("torso"), torsoRc, legsRc, torsoAc, legsAc, folded); component->setShootDelay(shootLoopDelay * 1.5f); WeaponMachineGunComponentPtr mgun = boost::make_shared<WeaponMachineGunComponent>(enemy ? SceneObjectTypeEnemyMissile : SceneObjectTypeAllyMissile); mgun->setDamage(shootDamage); mgun->setVelocity(settings.sentry.shootVelocity); mgun->setSpreadAngle(settings.sentry.shootSpreadAngle); mgun->setTurnInterval(settings.sentry.shootTurnInterval); mgun->setTurnDuration(shootTurnDuration); mgun->setLoopDelay(shootLoopDelay); mgun->setPos(asset->world()->body("torso")->image("missile")->pos()); mgun->setAngle(normalizeAngle(asset->world()->body("torso")->image("missile")->angle() + b2_pi / 2.0f)); mgun->setFlashDistance(asset->world()->body("torso")->image("missile")->height() / 2.0f); mgun->setTweakPos(true); component->setWeapon(mgun); asset->root()->addComponent(component); asset->object("torso")->addComponent(mgun); } if (!enemy) { b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; filter.categoryBits = collisionBitAlly; asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createOrbo() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("orbo.json"); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setLife(settings.orbo.life); asset->root()->setMaxLife(settings.orbo.life); RenderQuadComponentPtr rc = asset->root()->findComponent<RenderQuadComponent>(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(rc->drawable()); ac->addAnimation(AnimationDefault, "orbo_def"); ac->addAnimation(OrboComponent::AnimationExtend, "orbo_extend"); ac->addAnimation(OrboComponent::AnimationRetract, "orbo_retract"); ac->startAnimation(AnimationDefault); ac->setPaused(true); asset->root()->addComponent(ac); OrboComponentPtr thinkComponent = boost::make_shared<OrboComponent>(ac); for (int i = 0; i < 2; ++i) { std::ostringstream os; os << "missile" << (i + 1); WeaponMachineGunComponentPtr mgun = boost::make_shared<WeaponMachineGunComponent>(SceneObjectTypeEnemyMissile); mgun->setDamage(settings.orbo.shootDamage); mgun->setVelocity(settings.orbo.shootVelocity); mgun->setSpreadAngle(settings.orbo.shootSpreadAngle); mgun->setTurnInterval(settings.orbo.shootTurnInterval); mgun->setTurnDuration(settings.orbo.shootTurnDuration); mgun->setLoopDelay(settings.orbo.shootLoopDelay); mgun->setPos(asset->rootBody()->image(os.str())->pos()); mgun->setAngle(normalizeAngle(asset->rootBody()->image(os.str())->angle() + b2_pi / 2.0f)); mgun->setFlashDistance(asset->rootBody()->image(os.str())->height() / 2.0f); if (i != 0) { mgun->setHaveSound(false); } thinkComponent->setWeapon(i, mgun); asset->root()->addComponent(mgun); } asset->root()->addComponent(thinkComponent); return asset->root(); } SceneObjectPtr SceneObjectFactory::createOrboGibbed() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("orbo_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); makeDebris(asset->object(i)); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createWarder() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("warder.json"); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setMaterial(MaterialFlesh); asset->root()->setLife(settings.warder.life); asset->root()->setMaxLife(settings.warder.life); RenderQuadComponentPtr rc = asset->root()->findComponent<RenderQuadComponent>(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(rc->drawable()); ac->addAnimation(AnimationDefault, "warder_def"); ac->addAnimation(WarderComponent::AnimationWalk, "warder_walk"); ac->addAnimation(WarderComponent::AnimationMelee1, "warder_melee1"); ac->addAnimation(WarderComponent::AnimationMelee2, "warder_melee2"); ac->addAnimation(WarderComponent::AnimationMelee3, "warder_melee3"); ac->addAnimation(WarderComponent::AnimationShoot, "warder_shoot"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); b2Vec2 meleePos[3] = { asset->rootBody()->image("melee1")->pos(), asset->rootBody()->image("melee2")->pos(), asset->rootBody()->image("melee3")->pos() }; float meleeRadius[3] = { asset->rootBody()->image("melee1")->height() / 2.0f, asset->rootBody()->image("melee2")->height() / 2.0f, asset->rootBody()->image("melee3")->height() / 2.0f }; WarderComponentPtr thinkComponent = boost::make_shared<WarderComponent>(ac, meleePos, meleeRadius); WeaponLGunComponentPtr lgun = boost::make_shared<WeaponLGunComponent>(SceneObjectTypeEnemyMissile); lgun->setDamage(settings.warder.shootDamage); lgun->setLength(settings.warder.shootLength); lgun->setImpulse(settings.warder.shootImpulse); lgun->setPos(asset->rootBody()->image("missile")->pos()); lgun->setAngle(normalizeAngle(asset->rootBody()->image("missile")->angle() + b2_pi / 2.0f)); lgun->setFlashDistance(asset->rootBody()->image("missile")->height() / 2.0f); thinkComponent->setWeapon(lgun); asset->root()->addComponent(lgun); asset->root()->addComponent(thinkComponent); return asset->root(); } SceneObjectPtr SceneObjectFactory::createWarderGibbed() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("warder_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); makeDebris(asset->object(i)); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createPlasma(SceneObjectType type, float damage) { assert((type == SceneObjectTypePlayerMissile) || (type == SceneObjectTypeEnemyMissile) || (type == SceneObjectTypeAllyMissile) || (type == SceneObjectTypeNeutralMissile)); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("plasma.json"); asset->root()->setType(type); b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; if (type == SceneObjectTypeEnemyMissile) { filter.maskBits &= ~(collisionBitEnemy | collisionBitEnemyBuilding); } else if (type != SceneObjectTypeNeutralMissile) { filter.maskBits &= ~(collisionBitPlayer | collisionBitAlly); } asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<PlasmaComponent>(cdc, asset->root()->findComponent<ParticleEffectComponent>(), damage); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createKeeper(bool folded) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("keeper.json"); asset->root()->setType(SceneObjectTypeEnemyBuilding); asset->root()->setLife(settings.keeper.life); asset->root()->setMaxLife(settings.keeper.life); DrawablePtr drawable = asset->root()->findComponent<RenderQuadComponent>()->drawable(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(drawable); { std::string pathBase = settings.keeper.badImages ? "badkeeper" : "keeper"; ac->addAnimation(AnimationDefault, pathBase + "_def"); ac->addAnimation(KeeperComponent::AnimationAngry, pathBase + "_angry"); ac->addAnimation(KeeperComponent::AnimationWalk, pathBase + "_walk"); ac->addAnimation(KeeperComponent::AnimationMelee, pathBase + "_melee"); ac->addAnimation(KeeperComponent::AnimationGun, pathBase + "_gun"); ac->addAnimation(KeeperComponent::AnimationPrePlasma, pathBase + "_preplasma"); ac->addAnimation(KeeperComponent::AnimationPostPlasma, pathBase + "_postplasma"); ac->addAnimation(KeeperComponent::AnimationPlasma, pathBase + "_plasma"); ac->addAnimation(KeeperComponent::AnimationMissile, pathBase + "_missile"); ac->addAnimation(KeeperComponent::AnimationCrawlOut, pathBase + "_crawlout"); ac->addAnimation(KeeperComponent::AnimationDeath, pathBase + "_death"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); } { KeeperComponentPtr component = boost::make_shared<KeeperComponent>(ac, asset->rootBody()->image("melee")->pos(), asset->rootBody()->image("melee")->height() / 2.0f, folded); WeaponMachineGunComponentPtr mgun = boost::make_shared<WeaponMachineGunComponent>(SceneObjectTypeEnemyMissile); mgun->setDamage(settings.keeper.gunDamage); mgun->setVelocity(settings.keeper.gunVelocity); mgun->setSpreadAngle(settings.keeper.gunAngle); mgun->setLoopDelay(settings.keeper.gunInterval); mgun->setPos(asset->rootBody()->image("gun")->pos()); mgun->setAngle(normalizeAngle(asset->rootBody()->image("gun")->angle() + b2_pi / 2.0f)); mgun->setTweakPos(true); mgun->setFlashQuad(false); component->setWeaponGun(mgun); asset->root()->addComponent(mgun); WeaponPlasmaGunComponentPtr pgun = boost::make_shared<WeaponPlasmaGunComponent>(SceneObjectTypeEnemyMissile); pgun->setDamage(settings.keeper.plasmaDamage); pgun->setVelocity(settings.keeper.plasmaVelocity); pgun->setSpreadAngle(settings.keeper.plasmaAngle); pgun->setNumShots(5); pgun->setInterval(0.0f); pgun->setPos(asset->rootBody()->image("plasma")->pos()); pgun->setAngle(normalizeAngle(asset->rootBody()->image("plasma")->angle() + b2_pi / 2.0f)); component->setWeaponPlasma(pgun); asset->root()->addComponent(pgun); WeaponRLauncherComponentPtr rlauncher = boost::make_shared<WeaponRLauncherComponent>(SceneObjectTypeEnemyMissile); rlauncher->setExplosionImpulse(settings.keeper.missileImpulse); rlauncher->setExplosionDamage(settings.keeper.missileDamage); rlauncher->setVelocity(settings.keeper.missileVelocity); rlauncher->setInterval(0.1f); rlauncher->setPos(asset->rootBody()->image("missile")->pos()); rlauncher->setAngle(normalizeAngle(asset->rootBody()->image("missile")->angle() + b2_pi / 2.0f)); component->setWeaponMissile(rlauncher); asset->root()->addComponent(rlauncher); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createHealthStation(float amount) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("health_station.json"); amount *= settings.player.maxLife / settings.healthStation.life; asset->root()->setLife(amount); asset->root()->setMaxLife(amount); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 4.5f), 0, 7.0f, 1.25f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } HealthStationComponentPtr thinkComponent = boost::make_shared<HealthStationComponent>(); asset->root()->addComponent(thinkComponent); { CollisionSensorComponentPtr component = boost::make_shared<CollisionSensorComponent>(); component->setListener(thinkComponent); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createRodBundle() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("rod_bundle.json"); asset->root()->setMaxLife(settings.rodBundle.life); asset->root()->setType(SceneObjectTypeEnemyBuilding); return asset->root(); } SceneObjectPtr SceneObjectFactory::createSummon1(bool haveSound, int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("teleport1.p", b2Vec2_zero, 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { SummonComponentPtr component = boost::make_shared<SummonComponent>(pec, Color(0.33f, 0.66f, 1.0f, 1.0f), 11.0f, 2.0f, 2.0f, haveSound); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createSummon2(bool haveSound, int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("teleport2.p", b2Vec2_zero, 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { SummonComponentPtr component = boost::make_shared<SummonComponent>(pec, Color(0.33f, 0.66f, 1.0f, 1.0f), 15.0f, 2.0f, 2.0f, haveSound); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createBossCoreProtector() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("boss_coreprotector.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); asset->object(i)->setCollisionImpulseMultiplier(0.0f); SceneObjectTypes types; types.set(SceneObjectTypePlayer); CollisionCancelComponentPtr c = boost::make_shared<CollisionCancelComponent>(); c->setFilter(types); c->setDamage(settings.bossCoreProtector.meleeDamage); c->setDamageSound(audio.createSound("player_hit.ogg")); c->setRoll(settings.bossCoreProtector.meleeRollAngle); c->setCoreProtectorMelee(); asset->object(i)->addComponent(c); } SceneObjectPtr arm[] = { asset->object("arm3_upper"), asset->object("arm3_lower"), }; b2Vec2 armTip[] = { asset->world()->body("arm3_upper")->image("tip")->pos(), asset->world()->body("arm3_lower")->image("tip")->pos(), }; b2Vec2 armElbow[] = { asset->world()->body("arm3_upper")->image("elbow")->pos(), asset->world()->body("arm3_lower")->image("elbow")->pos(), }; b2Vec2 armInitPos[] = { asset->rootBody()->image("init_upper")->pos(), asset->rootBody()->image("init_lower")->pos() }; b2Vec2 armAimPos[] = { asset->rootBody()->image("aim_upper")->pos(), asset->rootBody()->image("aim_lower")->pos() }; b2Vec2 armWeaponPos[] = { asset->rootBody()->image("weapon_upper")->pos(), asset->rootBody()->image("weapon_lower")->pos() }; b2Vec2 armAngryPos[][2] = { { asset->rootBody()->image("angry_upper1")->pos(), asset->rootBody()->image("angry_lower1")->pos() }, { asset->rootBody()->image("angry_upper2")->pos(), asset->rootBody()->image("angry_lower2")->pos() } }; b2Vec2 armDiePos[][2] = { { asset->rootBody()->image("die_upper1")->pos(), asset->rootBody()->image("die_lower1")->pos() }, { asset->rootBody()->image("die_upper2")->pos(), asset->rootBody()->image("die_lower2")->pos() } }; WeaponLGunComponentPtr lgun = boost::make_shared<WeaponLGunComponent>(SceneObjectTypeEnemyMissile); lgun->setDamage(settings.bossCoreProtector.shootDamage); lgun->setLength(settings.bossCoreProtector.shootLength); lgun->setImpulse(settings.bossCoreProtector.shootImpulse); lgun->setPos(asset->world()->body("head")->image("missile")->pos()); lgun->setAngle(normalizeAngle(asset->world()->body("head")->image("missile")->angle() + b2_pi / 2.0f)); lgun->setFlashDistance(asset->world()->body("head")->image("missile")->height() / 2.0f); asset->object("head")->addComponent(lgun); BossCoreProtectorComponentPtr c = boost::make_shared<BossCoreProtectorComponent>(asset->object("head"), arm, armTip, armElbow, armInitPos, armAimPos, armWeaponPos, armAngryPos, armDiePos); c->setWeapon(lgun); asset->root()->addComponent(c); return asset->root(); } SceneObjectPtr SceneObjectFactory::createToxicSplash1(int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("toxic1.p", b2Vec2(0.0f, 0.0f), 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { ToxicSplashComponentPtr component = boost::make_shared<ToxicSplashComponent>(pec); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createToxicSplash2(int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("toxic3.p", b2Vec2(0.0f, 0.0f), 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { ToxicSplashComponentPtr component = boost::make_shared<ToxicSplashComponent>(pec); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createToxicCloud1(float damage, float damageTimeout, int zOrder) { SceneObjectPtr obj = boost::make_shared<SceneObject>(); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("toxic2.p", b2Vec2(0.0f, 0.0f), 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { ToxicCloudComponentPtr component = boost::make_shared<ToxicCloudComponent>(pec, 12.0f, 4.0f, 4.0f, damage, damageTimeout, 8.0f); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createMissileHit1(const SceneObjectPtr& obj, const b2Vec2& pos) { return createMissileHit1(obj->material(), pos); } SceneObjectPtr SceneObjectFactory::createMissileHit1(Material material, const b2Vec2& pos) { SceneObjectPtr hit; if (material == MaterialFlesh) { hit = sceneObjectFactory.createBlood1(1.5f, zOrderExplosion); hit->setPos(pos); hit->setAngle(getRandom(0.0f, 2.0f * b2_pi)); } else { hit = sceneObjectFactory.createExplosion2(zOrderExplosion); hit->setPos(pos); } return hit; } SceneObjectPtr SceneObjectFactory::createAcidWorm1(bool folded, bool foldable, float unfoldRadius) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("acidworm.json"); asset->root()->setLife(settings.acidworm.life); asset->root()->setMaxLife(settings.acidworm.life); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); asset->object(i)->setMaterial(MaterialFlesh); } RenderQuadComponentPtr headRc = asset->object("head")->findComponentByName<RenderQuadComponent>("head"); AnimationComponentPtr headAc = boost::make_shared<AnimationComponent>(headRc->drawable()); headAc->addAnimation(AnimationDefault, "acidworm_def"); headAc->addAnimation(AcidWormComponent::AnimationAttack, "acidworm_attack"); headAc->startAnimation(AnimationDefault); asset->object("head")->addComponent(headAc); { WeaponAcidballComponentPtr weapon = boost::make_shared<WeaponAcidballComponent>(SceneObjectTypeEnemyMissile); weapon->setExplosionTimeout(settings.acidworm.explosionTimeout); weapon->setExplosionImpulse(settings.acidworm.explosionImpulse); weapon->setExplosionDamage(settings.acidworm.explosionDamage); weapon->setToxicDamage(settings.acidworm.toxicDamage); weapon->setToxicDamageTimeout(settings.acidworm.toxicDamageTimeout); weapon->setVelocity(settings.acidworm.shootVelocity); weapon->setPos(asset->world()->body("head")->image("missile")->pos()); weapon->setAngle(normalizeAngle(asset->world()->body("head")->image("missile")->angle() + b2_pi / 2.0f)); weapon->setAcidWormOwner(); asset->object("head")->addComponent(weapon); AcidWormComponentPtr component = boost::make_shared<AcidWormComponent>(asset->object("head"), asset->object("part5"), folded, foldable, unfoldRadius, headAc); component->setWeapon(weapon); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createAcidball(SceneObjectType type) { assert((type == SceneObjectTypePlayerMissile) || (type == SceneObjectTypeEnemyMissile) || (type == SceneObjectTypeAllyMissile) || (type == SceneObjectTypeNeutralMissile)); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("acidball.json"); asset->root()->setType(type); b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; SceneObjectTypes damageTypes; if (type == SceneObjectTypeEnemyMissile) { filter.maskBits &= ~(collisionBitEnemy | collisionBitEnemyBuilding); damageTypes.set(SceneObjectTypePlayer); damageTypes.set(SceneObjectTypeAlly); } else if (type != SceneObjectTypeNeutralMissile) { filter.maskBits &= ~(collisionBitPlayer | collisionBitAlly); damageTypes.set(SceneObjectTypeEnemy); damageTypes.set(SceneObjectTypeEnemyBuilding); } else { damageTypes.set(SceneObjectTypePlayer); damageTypes.set(SceneObjectTypeAlly); damageTypes.set(SceneObjectTypeEnemy); damageTypes.set(SceneObjectTypeEnemyBuilding); } asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); asset->root()->addComponent(cdc); { AcidballComponentPtr component = boost::make_shared<AcidballComponent>(cdc); component->setExplosionDamageTypes(damageTypes); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createCentipede1() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("centipede.json"); asset->root()->setLife(settings.centipede.life); asset->root()->setMaxLife(settings.centipede.life); asset->root()->setBlastDamageMultiplier(1.0f / 5.0f); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); asset->object(i)->setMaterial(MaterialFlesh); asset->object(i)->setBlastDamageMultiplier(1.0f / 5.0f); } std::vector<AnimationComponentPtr> acs; for (int i = 1; i <= 9; ++i) { std::ostringstream os; os << "part" << i; SceneObjectPtr part = asset->object(os.str()); { RenderQuadComponentPtr rc = part->findComponentByName<RenderQuadComponent>("upperleg"); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(rc->drawable()); acs.push_back(ac); if ((i % 2) == 0) { ac->addAnimation(AnimationDefault, "centipede_upperleg1"); } else { ac->addAnimation(AnimationDefault, "centipede_upperleg2"); } ac->startAnimation(AnimationDefault); ac->setPaused(true); part->addComponent(ac); } { RenderQuadComponentPtr rc = part->findComponentByName<RenderQuadComponent>("lowerleg"); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(rc->drawable()); acs.push_back(ac); if ((i % 2) != 0) { ac->addAnimation(AnimationDefault, "centipede_lowerleg1"); } else { ac->addAnimation(AnimationDefault, "centipede_lowerleg2"); } ac->startAnimation(AnimationDefault); ac->setPaused(true); part->addComponent(ac); } } RenderQuadComponentPtr headRc = asset->root()->findComponentByName<RenderQuadComponent>("part"); AnimationComponentPtr headAc = boost::make_shared<AnimationComponent>(headRc->drawable()); headAc->addAnimation(AnimationDefault, "centipede_def"); headAc->addAnimation(CentipedeComponent::AnimationAttack, "centipede_attack"); headAc->startAnimation(AnimationDefault); asset->root()->addComponent(headAc); { WeaponSpitterComponentPtr weapon = boost::make_shared<WeaponSpitterComponent>(SceneObjectTypeEnemyMissile); weapon->setDamage(settings.centipede.spitDamage); weapon->setVelocity(settings.centipede.spitVelocity); weapon->setSpreadAngle(settings.centipede.spitAngle); weapon->setMinShots(settings.centipede.spitMinShots); weapon->setMaxShots(settings.centipede.spitMaxShots); weapon->setTotalShots(settings.centipede.spitTotalShots); weapon->setShotInterval(settings.centipede.spitInterval); weapon->setInterval(0.0f); weapon->setMinColor(Color(0.0f, 1.0f, 0.0f, 0.5f)); weapon->setMaxColor(Color(0.5f, 1.0f, 0.0f, 0.7f)); weapon->setMinHeight(0.5f); weapon->setMaxHeight(1.0f); weapon->setPos(asset->rootBody()->image("missile")->pos()); weapon->setAngle(normalizeAngle(asset->rootBody()->image("missile")->angle() + b2_pi / 2.0f)); asset->root()->addComponent(weapon); CentipedeComponentPtr component = boost::make_shared<CentipedeComponent>(acs, headAc); component->setWeapon(weapon); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createSpit(int i, SceneObjectType type, float damage, float height, const Color& color) { assert((type == SceneObjectTypePlayerMissile) || (type == SceneObjectTypeEnemyMissile) || (type == SceneObjectTypeAllyMissile) || (type == SceneObjectTypeNeutralMissile)); std::ostringstream os; os << "spit" << i << ".json"; SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset(os.str()); asset->root()->setType(type); b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; if (type == SceneObjectTypeEnemyMissile) { filter.maskBits &= ~(collisionBitEnemy | collisionBitEnemyBuilding); } else if (type != SceneObjectTypeNeutralMissile) { filter.maskBits &= ~(collisionBitPlayer | collisionBitAlly); } asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); Color tmpColor = color; tmpColor.rgba[3] = 1.0f; int j = 1; LightComponentPtr lc = asset->root()->findComponent<LightComponent>(); float factor = 0.0f; while (true) { os.str(""); os << "image" << j; RenderQuadComponentPtr rc = asset->root()->findComponentByName<RenderQuadComponent>(os.str()); if (!rc) { break; } rc->setColor(tmpColor); if (j == 1) { factor = height / rc->height(); } rc->setHeight(factor * rc->height()); rc->setPos(factor * rc->pos()); os.str(""); os << "light" << j++; PointLightPtr light = lc->getLight<PointLight>(os.str()); light->setColor(color); light->setPos(factor * light->pos()); light->setDistance(factor * light->distance()); } CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<SpitComponent>(cdc, damage); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBeetle1(bool shoot, bool split) { b2Vec2 missilePos; float missileAngle; Color color; float scale; if (shoot && split) { color = Color(0.0f, 1.0f, 0.0f); scale = 1.2f; } else if (shoot) { color = Color(0.19f, 0.68f, 0.37f); scale = 1.0f; } else if (split) { color = Color(1.0f, 1.0f, 0.0f); scale = 1.2f; } else { color = Color(0.68f, 0.68f, 0.37f); scale = 1.0f; } SceneObjectPtr obj = createBeetle(scale, settings.beetle1.walkSpeed, color, missilePos, missileAngle); obj->setLife(settings.beetle1.life); { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.beetle1.damageImpulseThreshold); component->setMultiplier(settings.beetle1.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypeTerrain); types.set(SceneObjectTypeRock); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); component->setFilter(types); obj->addComponent(component); } BeetleComponentPtr c = obj->findComponent<BeetleComponent>(); if (shoot) { WeaponSpitterComponentPtr weapon = boost::make_shared<WeaponSpitterComponent>(SceneObjectTypeEnemyMissile); weapon->setDamage(settings.beetle1.spitDamage); weapon->setVelocity(settings.beetle1.spitVelocity); weapon->setSpreadAngle(settings.beetle1.spitAngle); weapon->setMinShots(3); weapon->setMaxShots(3); weapon->setTotalShots(3); weapon->setShotInterval(0.0f); weapon->setInterval(0.0f); weapon->setMinColor(Color(0.0f, 1.0f, 0.0f, 1.0f)); weapon->setMaxColor(Color(0.0f, 1.0f, 0.0f, 1.0f)); weapon->setMinHeight(0.9f); weapon->setMaxHeight(0.9f); weapon->setPos(missilePos); weapon->setAngle(normalizeAngle(missileAngle + b2_pi / 2.0f)); weapon->setSpreadRandom(false); weapon->setI(2); obj->addComponent(weapon); c->setWeapon(weapon); } c->setSplit(split); return obj; } SceneObjectPtr SceneObjectFactory::createBeetle2() { b2Vec2 missilePos; float missileAngle; SceneObjectPtr obj = createBeetle(0.7f, settings.beetle2.walkSpeed, Color(1.0f, 0.0f, 0.0f), missilePos, missileAngle); obj->setLife(settings.beetle2.life); { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.beetle2.damageImpulseThreshold); component->setMultiplier(settings.beetle2.damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypeTerrain); types.set(SceneObjectTypeRock); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); component->setFilter(types); obj->addComponent(component); } BeetleComponentPtr c = obj->findComponent<BeetleComponent>(); c->setKamikaze(true); return obj; } SceneObjectPtr SceneObjectFactory::createBeetle(float scale, float walkSpeed, const Color& color, b2Vec2& missilePos, float& missileAngle) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("beetle.json"); missilePos = asset->rootBody()->image("missile")->pos(); missileAngle = asset->rootBody()->image("missile")->angle(); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setMaterial(MaterialFlesh); RenderQuadComponentPtr torsoRc = asset->root()->findComponentByName<RenderQuadComponent>("torso"); RenderQuadComponentPtr torsoMaskRc = asset->root()->findComponentByName<RenderQuadComponent>("torso_mask"); torsoRc->setHeight(torsoRc->height() * scale); torsoMaskRc->setHeight(torsoMaskRc->height() * scale); torsoMaskRc->setColor(color); AnimationComponentPtr torsoAc = boost::make_shared<AnimationComponent>(torsoRc->drawable()); AnimationComponentPtr torsoMaskAc = boost::make_shared<AnimationComponent>(torsoMaskRc->drawable()); torsoAc->addAnimation(AnimationDefault, "beetle_def", 10.0f / walkSpeed); torsoMaskAc->addAnimation(AnimationDefault, "beetle_mask_def", 10.0f / walkSpeed); torsoAc->addAnimation(BeetleComponent::AnimationDie, "beetle_die"); torsoMaskAc->addAnimation(BeetleComponent::AnimationDie, "beetle_mask_die"); torsoAc->startAnimation(AnimationDefault); torsoMaskAc->startAnimation(AnimationDefault); torsoAc->setPaused(true); torsoMaskAc->setPaused(true); asset->root()->addComponent(torsoAc); asset->root()->addComponent(torsoMaskAc); BeetleComponentPtr thinkComponent = boost::make_shared<BeetleComponent>(torsoAc, torsoMaskAc, torsoRc, torsoMaskRc); asset->root()->addComponent(thinkComponent); return asset->root(); } SceneObjectPtr SceneObjectFactory::createBeetle1Gibbed(bool shoot, const Color& color) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("beetle_gibbed.json"); float factor = shoot ? 1.2f : 1.0f; for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); asset->object(i)->setMaterial(MaterialFlesh); RenderQuadComponentPtr rc = asset->object(i)->findComponent<RenderQuadComponent>(); rc->setHeight(factor * rc->height()); rc->setPos(factor * rc->pos()); if ((asset->object(i) == asset->root()) || (asset->object(i)->name() == "tint_gib")) { rc->setColor(color); } } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBoat() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("boat.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeVehicle); } BoatComponentPtr c = boost::make_shared<BoatComponent>(asset->object("gun"), "gun_joint"); WeaponLGunComponentPtr lgun = boost::make_shared<WeaponLGunComponent>(SceneObjectTypePlayerMissile); lgun->setDamage(settings.boat.shootDamage); lgun->setLength(settings.boat.shootLength); lgun->setImpulse(settings.boat.shootImpulse); lgun->setPos(asset->world()->body("gun")->image("missile")->pos()); lgun->setAngle(normalizeAngle(asset->world()->body("gun")->image("missile")->angle() + b2_pi / 2.0f)); lgun->setFlashDistance(asset->world()->body("gun")->image("missile")->height() / 2.0f); lgun->setI(1); c->setWeapon(lgun); asset->object("gun")->addComponent(lgun); asset->root()->addComponent(c); return asset->root(); } ComponentPtr SceneObjectFactory::script_createQuad(const std::string& image, float height, int zOrder) { DrawablePtr drawable = assetManager.getDrawable(image); float width = height * drawable->image().aspect(); return boost::make_shared<RenderQuadComponent>(b2Vec2_zero, 0.0f, width, height, drawable, zOrder); } SceneObjectPtr SceneObjectFactory::createPowerGen(bool rusted) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("powergen.json"); asset->root()->setMaxLife(settings.powerGen1.life); asset->root()->setLife(settings.powerGen1.life); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 3.5f), 0, 8.0f, 1.2f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } asset->root()->setType(SceneObjectTypeEnemyBuilding); RenderQuadComponentPtr rc = asset->root()->findComponentByName<RenderQuadComponent>("root"); rc->drawable()->setImage(assetManager.getImage(rusted ? "prison1/powergen1.png" : "prison1/powergen2.png")); RenderQuadComponentPtr lampRc = asset->root()->findComponentByName<RenderQuadComponent>("lamp"); LightComponentPtr lc = asset->root()->findComponent<LightComponent>(); LightPtr fireLight[] = { lc->getLight<Light>("light1"), lc->getLight<Light>("light2"), lc->getLight<Light>("light3") }; PowerGenComponentPtr c = boost::make_shared<PowerGenComponent>(rc, lampRc, lc->getLight<Light>("lamp_light"), fireLight); asset->root()->addComponent(c); return asset->root(); } SceneObjectPtr SceneObjectFactory::createPowerGen2(bool rusted) { SceneObjectPtr obj = createPowerGen(rusted); obj->setMaxLife(settings.powerGen2.life); obj->setLife(settings.powerGen2.life); return obj; } SceneObjectPtr SceneObjectFactory::createBossSquid() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("boss_squid.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemyBuilding); asset->object(i)->setMaterial(MaterialFlesh); asset->object(i)->setPropagateDamage(false); } asset->object("blocker")->setType(SceneObjectTypeBlocker); asset->root()->setLife(settings.bossSquid.life); asset->root()->setMaxLife(settings.bossSquid.life); SceneObjectPtr mouth[] = { asset->object("mouth_top_left"), asset->object("mouth_top_right"), asset->object("mouth_bottom_left"), asset->object("mouth_bottom_right") }; SceneObjectPtr leg[] = { asset->object("leg_top_right"), asset->object("leg_bottom_right"), asset->object("leg_top_left"), asset->object("leg_bottom_left") }; SceneObjectPtr tentacle[] = { asset->object("tentacle_right1"), asset->object("tentacle_right2"), asset->object("tentacle_top1"), asset->object("tentacle_top2"), asset->object("tentacle_left1"), asset->object("tentacle_left2"), asset->object("tentacle_bottom1"), asset->object("tentacle_bottom2") }; for (int i = 0; i < 4; ++i) { mouth[i]->addComponent(boost::make_shared<TentaclePulseComponent>( 15, getRandom(0.2f, 0.4f), getRandom(3.0f, 3.5f), getRandom(0.2f, 0.3f), getRandom(0.2f, 0.3f))); float t = getRandom(1.0f, 1.5f); float f = getRandom(800.0f, 1000.0f); TentacleSwingComponentPtr c = boost::make_shared<TentacleSwingComponent>( t, EaseInOutQuad, f, t, EaseInOutQuad, -f); c->setBone(0); mouth[i]->addComponent(c); } for (int i = 0; i < 4; ++i) { leg[i]->addComponent(boost::make_shared<TentaclePulseComponent>( 15, getRandom(0.2f, 0.4f), getRandom(4.0f, 4.5f), getRandom(0.2f, 0.3f), getRandom(0.2f, 0.3f))); float t = getRandom(1.2f, 1.7f); float f = getRandom(4000.0f, 6000.0f); TentacleSwingComponentPtr c = boost::make_shared<TentacleSwingComponent>( t, EaseInOutQuad, f, t, EaseInOutQuad, -f); c->setBone(0); leg[i]->addComponent(c); } for (int i = 0; i < 8; ++i) { float t = getRandom(1.0f, 1.5f); float f = getRandom(20000.0f, 30000.0f); TentacleSwingComponentPtr c = boost::make_shared<TentacleSwingComponent>( t, EaseInOutQuad, f, t, EaseInOutQuad, -f); c->setBone(0); tentacle[i]->addComponent(c); { RUBEBodyPtr tipBody = asset->world()->body(tentacle[i]->name() + "_tip"); WeaponSpitterComponentPtr weapon = boost::make_shared<WeaponSpitterComponent>(SceneObjectTypeEnemyMissile); if ((i % 2) == 0) { weapon->setDamage(settings.bossSquid.attack1Damage); weapon->setVelocity(settings.bossSquid.attack1Velocity); weapon->setSpreadAngle(settings.bossSquid.attack1Angle); weapon->setMinShots(settings.bossSquid.attack1MinShots); weapon->setMaxShots(settings.bossSquid.attack1MaxShots); weapon->setTotalShots(settings.bossSquid.attack1TotalShots); weapon->setShotInterval(settings.bossSquid.attack1Interval); weapon->setInterval(0.0f); weapon->setMinColor(Color(0.0f, 1.0f, 0.0f, 0.5f)); weapon->setMaxColor(Color(0.5f, 1.0f, 0.0f, 0.7f)); weapon->setMinHeight(0.5f); weapon->setMaxHeight(1.0f); weapon->setSound(audio.createSound("squid_attack1.ogg")); } else { weapon->setDamage(settings.bossSquid.attack2Damage); weapon->setVelocity(settings.bossSquid.attack2Velocity); weapon->setSpreadAngle(settings.bossSquid.attack2Angle); weapon->setMinShots(3); weapon->setMaxShots(3); weapon->setTotalShots(3); weapon->setShotInterval(0.0f); weapon->setInterval(0.0f); weapon->setMinColor(Color(0.0f, 1.0f, 0.0f, 1.0f)); weapon->setMaxColor(Color(0.0f, 1.0f, 0.0f, 1.0f)); weapon->setMinHeight(0.9f); weapon->setMaxHeight(0.9f); weapon->setSpreadRandom(false); weapon->setI(2); weapon->setSound(audio.createSound("beetle_attack.ogg")); } weapon->setPos(tipBody->image("missile")->pos()); weapon->setAngle(tipBody->image("missile")->angle()); weapon->setUseFreeze(false); asset->object(tentacle[i]->name() + "_tip")->addComponent(weapon); TentacleSquidComponentPtr component = boost::make_shared<TentacleSquidComponent>((i % 2) == 0); component->setWeapon(weapon); tentacle[i]->addComponent(component); } } SceneObjectPtr legControl[] = { asset->object("leg_top_right_control"), asset->object("leg_bottom_right_control"), asset->object("leg_top_left_control"), asset->object("leg_bottom_left_control") }; SceneObjectPtr eyeControl[] = { asset->object("eye_right_control"), asset->object("eye_top_control"), asset->object("eye_left_control"), asset->object("eye_bottom_control") }; SceneObjectPtr mouthControl[] = { asset->object("mouth_top_right_control"), asset->object("mouth_bottom_right_control"), asset->object("mouth_top_left_control"), asset->object("mouth_bottom_left_control") }; Points explosionPos; for (int i = 0; i < asset->rootBody()->numImages(); ++i) { const RUBEImagePtr& image = asset->rootBody()->image(i); if (image->name() != "explosion") { continue; } explosionPos.push_back(image->pos()); } BossSquidComponentPtr c = boost::make_shared<BossSquidComponent>(tentacle, legControl, eyeControl, mouthControl, leg, mouth, explosionPos); asset->root()->addComponent(c); return asset->root(); } SceneObjectPtr SceneObjectFactory::createBossSquidEye() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("boss_squid_eye.json"); RenderTentacleComponentPtr tc = asset->root()->findComponent<RenderTentacleComponent>(); tc->objects().back()->setLife(settings.bossSquid.eyeLife); tc->objects().back()->setMaxLife(settings.bossSquid.eyeLife); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemyBuilding); asset->object(i)->setMaterial(MaterialFlesh); asset->object(i)->setPropagateDamage(false); } float t = getRandom(1.2f, 1.5f); float f = getRandom(7000.0f, 8000.0f); float duration = getRandom(0.0f, t * 2.0f); TentacleSwingComponentPtr c = boost::make_shared<TentacleSwingComponent>( t, EaseInOutQuad, f, t, EaseInOutQuad, -f); c->setBone(3); c->setTweenTime(duration); asset->root()->addComponent(c); c = boost::make_shared<TentacleSwingComponent>( t, EaseInOutQuad, -f * 3, t, EaseInOutQuad, f * 3); c->setBone(1); c->setTweenTime(duration); asset->root()->addComponent(c); return asset->root(); } SceneObjectPtr SceneObjectFactory::createMech() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("mech.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeAlly); } asset->root()->setLife(settings.mech.life); asset->root()->setMaxLife(settings.mech.life); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 4.0f), 0, 6.0f, 1.0f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; filter.categoryBits = collisionBitAlly; asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); RenderQuadComponentPtr torsoRc = asset->object("torso")->findComponentByName<RenderQuadComponent>("torso"); RenderQuadComponentPtr legsRc = asset->root()->findComponentByName<RenderQuadComponent>("legs"); AnimationComponentPtr torsoAc = boost::make_shared<AnimationComponent>(torsoRc->drawable()); AnimationComponentPtr legsAc = boost::make_shared<AnimationComponent>(legsRc->drawable()); torsoAc->addAnimation(AnimationDefault, "mech_torso_def"); legsAc->addAnimation(AnimationDefault, "mech_legs_def", 10.0f / settings.mech.walkSpeed); torsoAc->addAnimation(MechComponent::AnimationMelee2, "mech_torso_melee2"); torsoAc->addAnimation(MechComponent::AnimationPreGun, "mech_torso_pregun"); torsoAc->addAnimation(MechComponent::AnimationGun, "mech_torso_gun"); torsoAc->addAnimation(MechComponent::AnimationPostGun, "mech_torso_postgun"); torsoAc->startAnimation(AnimationDefault); legsAc->startAnimation(AnimationDefault); legsAc->setPaused(true); asset->root()->addComponent(torsoAc); asset->root()->addComponent(legsAc); Points melee2Points; std::ostringstream os; while (true) { os.str(""); os << "melee2_" << melee2Points.size(); RUBEImagePtr image = asset->world()->image(os.str()); if (!image) { break; } melee2Points.push_back(image->pos()); } { float melee2Duration = assetManager.getAnimation("mech_torso_melee2").duration() / assetManager.getAnimation("mech_torso_melee2").numFrames(); MechComponentPtr component = boost::make_shared<MechComponent>(asset->object("torso"), torsoRc, legsRc, torsoAc, legsAc, melee2Points, melee2Duration, asset->object("torso")->findComponent<LightComponent>()->getLights("fire")); WeaponMachineGunComponentPtr mgun = boost::make_shared<WeaponMachineGunComponent>(SceneObjectTypePlayerMissile); mgun->setDamage(settings.mech.attackDamage); mgun->setVelocity(settings.mech.attackVelocity); mgun->setSpreadAngle(settings.mech.attackSpreadAngle); mgun->setLoopDelay(settings.mech.attackInterval); mgun->setPos(asset->world()->image("gun")->pos()); mgun->setAngle(asset->world()->image("gun")->angle()); mgun->setTweakPos(true); mgun->setBulletHeight(0.2f); mgun->setTriggerCrosshair(true); mgun->setFlashQuad(false); component->setWeapon(mgun); asset->object("torso")->addComponent(mgun); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createHomer() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("homer.json"); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setMaterial(MaterialFlesh); asset->root()->setLife(settings.homer.life); asset->root()->setMaxLife(settings.homer.life); RenderQuadComponentPtr rc = asset->root()->findComponent<RenderQuadComponent>(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(rc->drawable()); ac->addAnimation(AnimationDefault, "homer_def"); ac->addAnimation(HomerComponent::AnimationPreGun, "homer_pregun"); ac->addAnimation(HomerComponent::AnimationPostGun, "homer_postgun"); ac->addAnimation(HomerComponent::AnimationGun, "homer_gun"); ac->addAnimation(HomerComponent::AnimationPreMissile, "homer_premissile"); ac->addAnimation(HomerComponent::AnimationPostMissile, "homer_postmissile"); ac->addAnimation(HomerComponent::AnimationMissile, "homer_missile"); ac->addAnimation(HomerComponent::AnimationMelee, "homer_melee"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); HomerComponentPtr component = boost::make_shared<HomerComponent>(ac, asset->rootBody()->image("melee")->pos(), asset->rootBody()->image("melee")->height() / 2.0f); WeaponPlasmaGunComponentPtr pgun = boost::make_shared<WeaponPlasmaGunComponent>(SceneObjectTypeEnemyMissile); pgun->setDamage(settings.homer.gunDamage); pgun->setVelocity(settings.homer.gunVelocity); pgun->setSpreadAngle(settings.homer.gunAngle); pgun->setNumShots(1); pgun->setInterval(settings.homer.gunInterval); pgun->setPos(asset->world()->image("gun")->pos()); pgun->setAngle(asset->world()->image("gun")->angle()); component->setWeaponGun(pgun); asset->root()->addComponent(pgun); WeaponSeekerComponentPtr seeker = boost::make_shared<WeaponSeekerComponent>(SceneObjectTypeEnemyMissile); seeker->setExplosionImpulse(settings.homer.missileImpulse); seeker->setExplosionDamage(settings.homer.missileDamage); seeker->setVelocity(settings.homer.missileVelocity); seeker->setInterval(0.1f); seeker->setSeekVelocity(settings.homer.missileSeekVelocity); seeker->setPos(asset->world()->image("missile")->pos()); seeker->setAngle(asset->world()->image("missile")->angle()); component->setWeaponMissile(seeker); asset->root()->addComponent(seeker); asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createSeeker(SceneObjectType type, float explosionImpulse, float explosionDamage) { assert((type == SceneObjectTypePlayerMissile) || (type == SceneObjectTypeEnemyMissile) || (type == SceneObjectTypeAllyMissile) || (type == SceneObjectTypeNeutralMissile)); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("seeker.json"); asset->root()->setType(type); b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; SceneObjectTypes damageTypes; if (type == SceneObjectTypeEnemyMissile) { filter.maskBits &= ~(collisionBitEnemy | collisionBitEnemyBuilding); damageTypes.set(SceneObjectTypePlayer); damageTypes.set(SceneObjectTypeAlly); } else if (type != SceneObjectTypeNeutralMissile) { filter.maskBits &= ~(collisionBitPlayer | collisionBitAlly); damageTypes.set(SceneObjectTypeEnemy); damageTypes.set(SceneObjectTypeEnemyBuilding); } else { damageTypes.set(SceneObjectTypePlayer); damageTypes.set(SceneObjectTypeAlly); damageTypes.set(SceneObjectTypeEnemy); damageTypes.set(SceneObjectTypeEnemyBuilding); } asset->root()->findComponent<PhysicsBodyComponent>()->setFilterOverride(filter); CollisionDieComponentPtr cdc = boost::make_shared<CollisionDieComponent>(); asset->root()->addComponent(cdc); { ComponentPtr component = boost::make_shared<SeekerComponent>(cdc, asset->root()->findComponent<ParticleEffectComponent>(), explosionImpulse, explosionDamage, damageTypes); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createHomerGibbed() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("homer_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); makeDebris(asset->object(i)); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createEShield(SceneObjectType type) { assert((type == SceneObjectTypePlayerMissile) || (type == SceneObjectTypeEnemyMissile) || (type == SceneObjectTypeAllyMissile) || (type == SceneObjectTypeNeutralMissile)); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("eshield.json"); asset->root()->setType(SceneObjectTypeShield); asset->root()->setGlassy(true); SceneObjectTypes types; if (type == SceneObjectTypeEnemyMissile) { types.set(SceneObjectTypePlayerMissile); types.set(SceneObjectTypeAllyMissile); types.set(SceneObjectTypeNeutralMissile); } else if (type != SceneObjectTypeNeutralMissile) { types.set(SceneObjectTypeEnemyMissile); types.set(SceneObjectTypeNeutralMissile); } else { types.set(SceneObjectTypePlayerMissile); types.set(SceneObjectTypeAllyMissile); types.set(SceneObjectTypeEnemyMissile); } CollisionTypeFilterPtr cf = boost::make_shared<CollisionTypeFilter>(); cf->setTypes(types); asset->root()->setCollisionFilter(cf); return asset->root(); } SceneObjectPtr SceneObjectFactory::createFakeMissile(SceneObjectType type) { assert((type == SceneObjectTypePlayerMissile) || (type == SceneObjectTypeEnemyMissile) || (type == SceneObjectTypeAllyMissile) || (type == SceneObjectTypeNeutralMissile)); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("fake_missile.json"); asset->root()->setType(type); b2Filter filter = asset->rootBody()->fixture(0)->fixtureDef().filter; if (type == SceneObjectTypeEnemyMissile) { filter.maskBits &= ~(collisionBitEnemy | collisionBitEnemyBuilding); } else if (type != SceneObjectTypeNeutralMissile) { filter.maskBits &= ~(collisionBitPlayer | collisionBitAlly); } PhysicsBodyComponentPtr c = asset->root()->findComponent<PhysicsBodyComponent>(); c->setFilterOverride(filter); return asset->root(); } SceneObjectPtr SceneObjectFactory::createScientist() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("scientist.json"); asset->root()->setType(SceneObjectTypeAlly); RenderQuadComponentPtr legsRc = asset->root()->findComponentByName<RenderQuadComponent>("legs"); RenderQuadComponentPtr torsoRc = asset->root()->findComponentByName<RenderQuadComponent>("torso"); AnimationComponentPtr legsAc = boost::make_shared<AnimationComponent>(legsRc->drawable()); AnimationComponentPtr torsoAc = boost::make_shared<AnimationComponent>(torsoRc->drawable()); legsAc->addAnimation(AnimationDefault, "scientist_legs_def"); legsAc->addAnimation(DudeComponent::AnimationWalk, "scientist_legs_walk"); torsoAc->addAnimation(AnimationDefault, "scientist_torso_def"); torsoAc->addAnimation(DudeComponent::AnimationWalk, "scientist_torso_walk"); legsAc->startAnimation(AnimationDefault); torsoAc->startAnimationRandomTime(AnimationDefault); asset->root()->addComponent(legsAc); asset->root()->addComponent(torsoAc); DudeComponentPtr component = boost::make_shared<DudeComponent>(legsRc, legsAc, torsoAc); component->setLegsAngle(-b2_pi / 2); asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createBossChopper() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("boss_chopper.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); } asset->root()->setLife(settings.bossChopper.life); asset->root()->setMaxLife(settings.bossChopper.life); asset->root()->setBlastDamageMultiplier(settings.bossChopper.blastDamageMultiplier); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 5.0f), 0, 12.0f, 2.0f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } std::vector<WeaponComponentPtr> guns; for (int i = 0; i < asset->rootBody()->numImages(); ++i) { const RUBEImagePtr& image = asset->rootBody()->image(i); if (image->name() != "gun") { continue; } WeaponMachineGunComponentPtr weapon = boost::make_shared<WeaponMachineGunComponent>(SceneObjectTypeEnemyMissile); weapon->setDamage(settings.bossChopper.gunDamage); weapon->setVelocity(settings.bossChopper.gunVelocity); weapon->setSpreadAngle(settings.bossChopper.gunAngle); weapon->setLoopDelay(settings.bossChopper.gunInterval); weapon->setPos(image->pos()); weapon->setAngle(image->angle()); weapon->setHaveSound(false); weapon->setBulletHeight(0.2f); if (guns.empty()) { weapon->setHaveSound(true); } guns.push_back(weapon); asset->root()->addComponent(weapon); } Points explosionPos; for (int i = 0; i < asset->rootBody()->numImages(); ++i) { const RUBEImagePtr& image = asset->rootBody()->image(i); if (image->name() != "boom") { continue; } explosionPos.push_back(image->pos()); } BossChopperComponentPtr component = boost::make_shared<BossChopperComponent>(explosionPos); component->setWeaponGuns(guns); WeaponSeekerComponentPtr seeker = boost::make_shared<WeaponSeekerComponent>(SceneObjectTypeEnemyMissile); seeker->setExplosionImpulse(settings.bossChopper.missileImpulse); seeker->setExplosionDamage(settings.bossChopper.missileDamage); seeker->setVelocity(settings.bossChopper.missileVelocity); seeker->setInterval(0.1f); seeker->setSeekVelocity(settings.bossChopper.missileSeekVelocity); seeker->setPos(asset->world()->image("missile")->pos()); seeker->setAngle(asset->world()->image("missile")->angle()); component->setWeaponMissile(seeker); asset->root()->addComponent(seeker); asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createCreature(int i) { assert((i >= 1) && (i <= static_cast<int>(settings.creature.size()))); std::ostringstream os; os << "creature" << i << ".json"; SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset(os.str()); asset->root()->setLife(settings.creature[i - 1].life); asset->root()->setMaxLife(settings.creature[i - 1].life); for (int j = 0; j < asset->numObjects(); ++j) { asset->object(j)->setType(SceneObjectTypeEnemyBuilding); asset->object(j)->setMaterial(MaterialFlesh); { CollisionDamageComponentPtr component = boost::make_shared<CollisionDamageComponent>(); component->setImpulseThreshold(settings.creature[i - 1].damageImpulseThreshold); component->setMultiplier(settings.creature[i - 1].damageMultiplier); SceneObjectTypes types; types.set(SceneObjectTypePlayer); types.set(SceneObjectTypeAlly); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeTerrain); types.set(SceneObjectTypeRock); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); component->setFilter(types); asset->object(j)->addComponent(component); } } { CreatureComponentPtr component = boost::make_shared<CreatureComponent>(i); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createGasCloud1(float delay, int zOrder) { return createGasCloud1Inner(settings.gasCloud1.propagationDelay, settings.gasCloud1.propagationDelay - delay, zOrder); } SceneObjectPtr SceneObjectFactory::createGasCloud1Inner(float delay, float offset, int zOrder) { SceneObjectPtr obj = createCircleSensor(5.0f, collisionBitPlayer); ParticleEffectComponentPtr pec = assetManager.getParticleEffect("gas1.p", b2Vec2(0.0f, 0.0f), 0.0f); pec->setZOrder(zOrder); pec->resetEmit(); obj->addComponent(pec); { GasCloudComponentPtr thinkComponent = boost::make_shared<GasCloudComponent>(pec, delay, offset); obj->addComponent(thinkComponent); CollisionSensorComponentPtr component = boost::make_shared<CollisionSensorComponent>(); component->setListener(thinkComponent); obj->addComponent(component); } return obj; } SceneObjectPtr SceneObjectFactory::createOctopus() { SceneObjectTypes types; types.set(SceneObjectTypePlayer); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("octopus.json"); asset->root()->setLife(settings.octopus.life); asset->root()->setMaxLife(settings.octopus.life); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemyBuilding); asset->object(i)->setMaterial(MaterialFlesh); asset->object(i)->setPropagateDamage(false); CollisionCancelComponentPtr c = boost::make_shared<CollisionCancelComponent>(); c->setFilter(types); if (asset->object(i) == asset->root()) { c->setDamage(settings.octopus.hitDamage); c->setDamageSound(audio.createSound("player_hit.ogg")); c->setRoll(deg2rad(2.0f)); } asset->object(i)->addComponent(c); } std::vector<WeaponComponentPtr> weapons; for (int i = 0; i < asset->world()->numImages(); ++i) { const RUBEImagePtr& image = asset->world()->image(i); if (image->name() == "missile") { WeaponSpitterComponentPtr weapon = boost::make_shared<WeaponSpitterComponent>(SceneObjectTypeEnemyMissile); weapon->setDamage(settings.octopus.spitDamage); weapon->setVelocity(settings.octopus.spitVelocity); weapon->setSpreadAngle(0.0f); weapon->setMinShots(1); weapon->setMaxShots(1); weapon->setTotalShots(1); weapon->setShotInterval(0.0f); weapon->setInterval(0.0f); weapon->setMinColor(Color(0.0f, 1.0f, 0.0f, 1.0f)); weapon->setMaxColor(Color(0.0f, 1.0f, 0.0f, 1.0f)); weapon->setMinHeight(1.1f); weapon->setMaxHeight(1.1f); weapon->setSpreadRandom(false); weapon->setI(2); weapon->setSound(audio.createSound("beetle_attack.ogg")); weapon->setPos(image->pos()); weapon->setAngle(image->angle()); weapon->setUseFreeze(false); weapon->setHaveSound(weapons.empty()); asset->root()->addComponent(weapon); weapons.push_back(weapon); } } { OctopusComponentPtr component = boost::make_shared<OctopusComponent>(); component->setWeapons(weapons); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createWalker() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("walker.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemyBuilding); asset->object(i)->setPropagateDamage(false); } asset->object("blocker")->setType(SceneObjectTypeBlocker); asset->object("heart")->setMaxLife(settings.walker.life); asset->object("heart")->setLife(settings.walker.life); asset->object("heart")->setMaterial(MaterialFlesh); SceneObjectPtr legs[] = { asset->object("leg1"), asset->object("leg2"), asset->object("leg3"), asset->object("leg4"), }; b2Vec2 legTips[] = { asset->world()->body("leg1")->image("tip")->pos(), asset->world()->body("leg2")->image("tip")->pos(), asset->world()->body("leg3")->image("tip")->pos(), asset->world()->body("leg4")->image("tip")->pos(), }; WalkerComponentPtr component = boost::make_shared<WalkerComponent>(asset->object("heart"), legs, legTips); for (int i = 0; i < 4; ++i) { std::ostringstream os; os << "missile" << (i + 1); const RUBEImagePtr& image = asset->world()->image(os.str()); WeaponSeekerComponentPtr seeker = boost::make_shared<WeaponSeekerComponent>(SceneObjectTypeEnemyMissile); seeker->setExplosionImpulse(settings.walker.missileImpulse); seeker->setExplosionDamage(settings.walker.missileDamage); seeker->setVelocity(settings.walker.missileVelocity); seeker->setInterval(0.1f); seeker->setSeekVelocity(settings.walker.missileSeekVelocity); seeker->setTweakPos(false); seeker->setUseFilter(true); seeker->setPos(image->pos()); seeker->setAngle(image->angle()); component->setWeapon(i, seeker); asset->root()->addComponent(seeker); WeaponSpitterComponentPtr weapon = boost::make_shared<WeaponSpitterComponent>(SceneObjectTypeEnemyMissile); weapon->setDamage(settings.walker.spitDamage); weapon->setVelocity(settings.walker.spitVelocity); weapon->setSpreadAngle(settings.walker.spitAngle); weapon->setMinShots(settings.walker.spitMinShots); weapon->setMaxShots(settings.walker.spitMaxShots); weapon->setTotalShots(settings.walker.spitTotalShots); weapon->setShotInterval(settings.walker.spitInterval); weapon->setInterval(settings.walker.spitDelay); weapon->setMinColor(Color(0.0f, 1.0f, 0.0f, 0.5f)); weapon->setMaxColor(Color(0.5f, 1.0f, 0.0f, 0.7f)); weapon->setMinHeight(0.7f); weapon->setMaxHeight(1.2f); weapon->setPos(image->pos()); weapon->setAngle(image->angle()); weapon->setUseFilter(true); weapon->setUseFreeze(false); weapon->setTweakPos(false); component->setExposedWeapon(i, weapon); asset->root()->addComponent(weapon); } asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createSnake() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("snake.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemyBuilding); asset->object(i)->setPropagateDamage(false); } asset->object("eye")->setMaterial(MaterialFlesh); asset->object("eye")->setMaxLife(settings.snake.life); asset->object("eye")->setLife(settings.snake.life); asset->object("eye")->setBlastDamageMultiplier(2.0f); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 3.0f), 0, 8.0f, 1.5f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->object("eye")->addComponent(component); } { SnakeComponentPtr thinkComponent = boost::make_shared<SnakeComponent>(asset->object("eye"), asset->object("tentacle_base")->findComponent<RenderTentacleComponent>()); asset->root()->addComponent(thinkComponent); CollisionSensorComponentPtr component = boost::make_shared<CollisionSensorComponent>(); component->setListener(thinkComponent); WeaponAcidballComponentPtr missileWeapon = boost::make_shared<WeaponAcidballComponent>(SceneObjectTypeEnemyMissile); missileWeapon->setExplosionTimeout(settings.snake.missileExplosionTimeout); missileWeapon->setExplosionImpulse(settings.snake.missileExplosionImpulse); missileWeapon->setExplosionDamage(settings.snake.missileExplosionDamage); missileWeapon->setToxicDamage(settings.snake.missileToxicDamage); missileWeapon->setToxicDamageTimeout(settings.snake.missileToxicDamageTimeout); missileWeapon->setVelocity(settings.snake.missileVelocity); missileWeapon->setInterval(settings.snake.missileInterval); missileWeapon->setPos(asset->world()->image("missile")->pos()); missileWeapon->setAngle(asset->world()->image("missile")->angle()); missileWeapon->setUseFilter(true); missileWeapon->setUseFreeze(false); asset->root()->addComponent(missileWeapon); std::vector<SceneObjectPtr> tmp = asset->root()->getObjects("fang"); for (std::vector<SceneObjectPtr>::const_iterator it = tmp.begin(); it != tmp.end(); ++it) { missileWeapon->addToFilter((*it)->cookie()); } thinkComponent->setWeaponMissile(missileWeapon); WeaponLGunComponentPtr gun = boost::make_shared<WeaponLGunComponent>(SceneObjectTypeEnemyMissile); gun->setDamage(settings.snake.gunDamage); gun->setLength(settings.snake.gunLength); gun->setImpulse(settings.snake.gunImpulse); gun->setPos(asset->world()->image("gun")->pos()); gun->setAngle(asset->world()->image("gun")->angle()); thinkComponent->setWeaponGun(gun); asset->root()->addComponent(gun); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBossBuddy() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("boss_buddy.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); asset->object(i)->setPropagateDamage(false); asset->object(i)->setCollisionImpulseMultiplier(0.0f); asset->object(i)->setMaterial(MaterialFlesh); } asset->object("brain")->setMaxLife(settings.bossBuddy.life); asset->object("brain")->setLife(settings.bossBuddy.life); BuddySideComponent::Layer layers[3][8] = { { BuddySideComponent::Layer(asset->object("head1"), asset->object("upperElbow1"), asset->object("lowerElbow1"), asset->object("upperArm1"), asset->object("lowerArm1")), BuddySideComponent::Layer(asset->object("head1_1"), asset->object("upperElbow1_1"), asset->object("lowerElbow1_1"), asset->object("upperArm1_1"), asset->object("lowerArm1_1")), BuddySideComponent::Layer(asset->object("head1_2"), asset->object("upperElbow1_2"), asset->object("lowerElbow1_2"), asset->object("upperArm1_2"), asset->object("lowerArm1_2")), BuddySideComponent::Layer(asset->object("head1_3"), asset->object("upperElbow1_3"), asset->object("lowerElbow1_3"), asset->object("upperArm1_3"), asset->object("lowerArm1_3")), BuddySideComponent::Layer(asset->object("head1_4"), asset->object("upperElbow1_4"), asset->object("lowerElbow1_4"), asset->object("upperArm1_4"), asset->object("lowerArm1_4")), BuddySideComponent::Layer(asset->object("head1_5"), asset->object("upperElbow1_5"), asset->object("lowerElbow1_5"), asset->object("upperArm1_5"), asset->object("lowerArm1_5"), asset->object("upperElbow1_5s"), asset->object("lowerElbow1_5s"), asset->object("upperArm1_5s"), asset->object("lowerArm1_5s")), BuddySideComponent::Layer(asset->object("head1_6"), asset->object("upperElbow1_6"), asset->object("lowerElbow1_6"), asset->object("upperArm1_6"), asset->object("lowerArm1_6"), asset->object("upperElbow1_6s"), asset->object("lowerElbow1_6s"), asset->object("upperArm1_6s"), asset->object("lowerArm1_6s")), BuddySideComponent::Layer(asset->object("head1_7"), asset->object("upperElbow1_7"), asset->object("lowerElbow1_7"), asset->object("upperArm1_7"), asset->object("lowerArm1_7"), asset->object("upperElbow1_7s"), asset->object("lowerElbow1_7s"), asset->object("upperArm1_7s"), asset->object("lowerArm1_7s")), }, { BuddySideComponent::Layer(asset->object("head2"), asset->object("upperElbow2"), asset->object("lowerElbow2"), asset->object("upperArm2"), asset->object("lowerArm2")), BuddySideComponent::Layer(asset->object("head2_1"), asset->object("upperElbow2_1"), asset->object("lowerElbow2_1"), asset->object("upperArm2_1"), asset->object("lowerArm2_1")), BuddySideComponent::Layer(asset->object("head2_2"), asset->object("upperElbow2_2"), asset->object("lowerElbow2_2"), asset->object("upperArm2_2"), asset->object("lowerArm2_2")), BuddySideComponent::Layer(asset->object("head2_3"), asset->object("upperElbow2_3"), asset->object("lowerElbow2_3"), asset->object("upperArm2_3"), asset->object("lowerArm2_3")), BuddySideComponent::Layer(asset->object("head2_4"), asset->object("upperElbow2_4"), asset->object("lowerElbow2_4"), asset->object("upperArm2_4"), asset->object("lowerArm2_4")), BuddySideComponent::Layer(asset->object("head2_5"), asset->object("upperElbow2_5"), asset->object("lowerElbow2_5"), asset->object("upperArm2_5"), asset->object("lowerArm2_5"), asset->object("upperElbow2_5s"), asset->object("lowerElbow2_5s"), asset->object("upperArm2_5s"), asset->object("lowerArm2_5s")), BuddySideComponent::Layer(asset->object("head2_6"), asset->object("upperElbow2_6"), asset->object("lowerElbow2_6"), asset->object("upperArm2_6"), asset->object("lowerArm2_6"), asset->object("upperElbow2_6s"), asset->object("lowerElbow2_6s"), asset->object("upperArm2_6s"), asset->object("lowerArm2_6s")), BuddySideComponent::Layer(asset->object("head2_7"), asset->object("upperElbow2_7"), asset->object("lowerElbow2_7"), asset->object("upperArm2_7"), asset->object("lowerArm2_7"), asset->object("upperElbow2_7s"), asset->object("lowerElbow2_7s"), asset->object("upperArm2_7s"), asset->object("lowerArm2_7s")), }, { BuddySideComponent::Layer(asset->object("head3"), asset->object("upperElbow3"), asset->object("lowerElbow3"), asset->object("upperArm3"), asset->object("lowerArm3")), BuddySideComponent::Layer(asset->object("head3_1"), asset->object("upperElbow3_1"), asset->object("lowerElbow3_1"), asset->object("upperArm3_1"), asset->object("lowerArm3_1")), BuddySideComponent::Layer(asset->object("head3_2"), asset->object("upperElbow3_2"), asset->object("lowerElbow3_2"), asset->object("upperArm3_2"), asset->object("lowerArm3_2")), BuddySideComponent::Layer(asset->object("head3_3"), asset->object("upperElbow3_3"), asset->object("lowerElbow3_3"), asset->object("upperArm3_3"), asset->object("lowerArm3_3")), BuddySideComponent::Layer(asset->object("head3_4"), asset->object("upperElbow3_4"), asset->object("lowerElbow3_4"), asset->object("upperArm3_4"), asset->object("lowerArm3_4")), BuddySideComponent::Layer(asset->object("head3_5"), asset->object("upperElbow3_5"), asset->object("lowerElbow3_5"), asset->object("upperArm3_5"), asset->object("lowerArm3_5"), asset->object("upperElbow3_5s"), asset->object("lowerElbow3_5s"), asset->object("upperArm3_5s"), asset->object("lowerArm3_5s")), BuddySideComponent::Layer(asset->object("head3_6"), asset->object("upperElbow3_6"), asset->object("lowerElbow3_6"), asset->object("upperArm3_6"), asset->object("lowerArm3_6"), asset->object("upperElbow3_6s"), asset->object("lowerElbow3_6s"), asset->object("upperArm3_6s"), asset->object("lowerArm3_6s")), BuddySideComponent::Layer(asset->object("head3_7"), asset->object("upperElbow3_7"), asset->object("lowerElbow3_7"), asset->object("upperArm3_7"), asset->object("lowerArm3_7"), asset->object("upperElbow3_7s"), asset->object("lowerElbow3_7s"), asset->object("upperArm3_7s"), asset->object("lowerArm3_7s")), }}; for (int n = 0; n < 3; ++n) { for (int i = 5; i <= 7; ++i) { SceneObjectTypes types; types.set(SceneObjectTypePlayer); for (int j = 0; j < 2; ++j) { CollisionCancelComponentPtr c = boost::make_shared<CollisionCancelComponent>(); c->setFilter(types); c->setDamage(settings.bossBuddy.sideMeleeDamage); c->setDamageSound(audio.createSound("buddy_hit.ogg")); c->setRoll(deg2rad(2.0f)); layers[n][i].elbowS[j]->addComponent(c); c = boost::make_shared<CollisionCancelComponent>(); c->setFilter(types); c->setDamage(settings.bossBuddy.sideMeleeDamage); c->setDamageSound(audio.createSound("buddy_hit.ogg")); c->setRoll(deg2rad(2.0f)); layers[n][i].armS[j]->addComponent(c); } } for (int i = 0; i < 8; ++i) { RenderQuadComponentPtr rc = layers[n][i].head->findComponent<RenderQuadComponent>(); QuadPulseComponentPtr pc = boost::make_shared<QuadPulseComponent>(rc, b2Vec2_zero, 1.0f, EaseInOutQuad, 0.95f, 1.0f, EaseInOutQuad, 1.05f); layers[n][i].head->addComponent(pc); } } SceneObjectPtr center[5] = { asset->object("root"), asset->object("root_1"), asset->object("root_2"), asset->object("root_3"), asset->object("root_4") }; for (int i = 0; i < 5; ++i) { std::vector<RenderQuadComponentPtr> rcs = center[i]->findComponents<RenderQuadComponent>("body"); for (std::vector<RenderQuadComponentPtr>::const_iterator it = rcs.begin(); it != rcs.end(); ++it) { QuadPulseComponentPtr pc = boost::make_shared<QuadPulseComponent>(*it, (*it)->pos(), 1.0f, EaseInOutQuad, 0.95f, 1.0f, EaseInOutQuad, 1.05f); center[i]->addComponent(pc); } } SceneObjectPtr tentacles[3] = { asset->object("tentacle_base1"), asset->object("tentacle_base2"), asset->object("tentacle_base3") }; for (int i = 0; i < 3; ++i) { tentacles[i]->addComponent(boost::make_shared<TentaclePulseComponent>( 15, getRandom(0.15f, 0.3f), getRandom(6.0f, 7.5f), getRandom(0.6f, 0.8f), getRandom(0.6f, 0.8f))); } BuddySideComponentPtr c1 = boost::make_shared<BuddySideComponent>(1, layers[0]); asset->object("head1")->addComponent(c1); BuddySideComponentPtr c2 = boost::make_shared<BuddySideComponent>(2, layers[1]); asset->object("head2")->addComponent(c2); BuddySideComponentPtr c3 = boost::make_shared<BuddySideComponent>(3, layers[2]); asset->object("head3")->addComponent(c3); BuddySideComponentPtr sides[3] = {c1, c2, c3}; SceneObjectPtr pipes[2] = { asset->object("pipe0"), asset->object("pipe1") }; b2Transform eyeletXf[2] = { b2Transform(asset->world()->body("pipe0")->image("eyelet")->pos(), b2Rot(asset->world()->body("pipe0")->image("eyelet")->angle())), b2Transform(asset->world()->body("pipe1")->image("eyelet")->pos(), b2Rot(asset->world()->body("pipe1")->image("eyelet")->angle())) }; SceneObjectPtr jaws[2] = { asset->object("jaw0"), asset->object("jaw1") }; SceneObjectPtr skull[2] = { asset->object("skull0"), asset->object("skull1") }; BossBuddyComponentPtr thinkComponent(new BossBuddyComponent(sides, asset->object("head0"), asset->object("head0s"), b2Transform(asset->world()->image("tongue")->pos(), b2Rot(asset->world()->image("tongue")->angle())), pipes, eyeletXf, asset->object("brain"), asset->object("root_3"), asset->object("root3s"), b2Transform(asset->world()->image("napalm")->pos(), b2Rot(asset->world()->image("napalm")->angle())), jaws, skull, asset->object("gun0"))); for (int i = 0; i < 2; ++i) { std::ostringstream os; os << "gun" << (i + 1); const RUBEImagePtr& image = asset->world()->body(os.str())->image("missile"); WeaponPlasmaGunComponentPtr weapon = boost::make_shared<WeaponPlasmaGunComponent>(SceneObjectTypeEnemyMissile); weapon->setDamage(settings.bossBuddy.plasmaDamage); weapon->setVelocity(settings.bossBuddy.plasmaVelocity); weapon->setSpreadAngle(settings.bossBuddy.plasmaAngle); weapon->setNumShots(3); weapon->setInterval(settings.bossBuddy.plasmaInterval); weapon->setPos(image->pos()); weapon->setAngle(image->angle()); weapon->setUseFreeze(false); weapon->setHaveSound(i == 0); thinkComponent->setSideWeapon(i, weapon); asset->object(os.str())->addComponent(weapon); WeaponRLauncherComponentPtr altWeapon = boost::make_shared<WeaponRLauncherComponent>(SceneObjectTypeEnemyMissile); altWeapon->setExplosionImpulse(settings.bossBuddy.missileExplosionImpulse); altWeapon->setExplosionDamage(settings.bossBuddy.missileExplosionDamage); altWeapon->setVelocity(settings.bossBuddy.missileVelocity); altWeapon->setInterval(0.1f); altWeapon->setPos(image->pos()); altWeapon->setAngle(image->angle()); altWeapon->setUseFreeze(false); thinkComponent->setSideAltWeapon(i, altWeapon); asset->object(os.str())->addComponent(altWeapon); } WeaponSeekerComponentPtr seeker = boost::make_shared<WeaponSeekerComponent>(SceneObjectTypeEnemyMissile); seeker->setExplosionImpulse(settings.bossBuddy.seekerImpulse); seeker->setExplosionDamage(settings.bossBuddy.seekerDamage); seeker->setVelocity(settings.bossBuddy.seekerVelocity); seeker->setInterval(0.1f); seeker->setSeekVelocity(settings.bossBuddy.seekerSeekVelocity); seeker->setPos(asset->world()->body("gun0")->image("missile")->pos()); seeker->setAngle(asset->world()->body("gun0")->image("missile")->angle()); thinkComponent->setFrontWeapon(seeker); asset->object("gun0")->addComponent(seeker); asset->root()->addComponent(thinkComponent); { CollisionSensorComponentPtr component = boost::make_shared<CollisionSensorComponent>(); component->setListener(thinkComponent); asset->object("pipe0")->addComponent(component); } { CollisionSensorComponentPtr component = boost::make_shared<CollisionSensorComponent>(); component->setListener(thinkComponent); asset->object("pipe1")->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBuddyTongue() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("boss_buddy_tongue.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeDeadbody); asset->object(i)->setPropagateDamage(false); asset->object(i)->setCollisionImpulseMultiplier(0.0f); asset->object(i)->setMaterial(MaterialFlesh); } asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setMaxLife(settings.bossBuddy.tongueLife); asset->root()->setLife(settings.bossBuddy.tongueLife); BuddyTongueComponentPtr thinkComponent = boost::make_shared<BuddyTongueComponent>( b2Transform(asset->world()->image("eyelet")->pos(), b2Rot(asset->world()->image("eyelet")->angle()))); WeaponSpitterComponentPtr weapon = boost::make_shared<WeaponSpitterComponent>(SceneObjectTypeEnemyMissile); weapon->setDamage(settings.bossBuddy.tongueAttackDamage); weapon->setVelocity(settings.bossBuddy.tongueAttackVelocity); weapon->setSpreadAngle(settings.bossBuddy.tongueAttackAngle); weapon->setMinShots(settings.bossBuddy.tongueAttackMinShots); weapon->setMaxShots(settings.bossBuddy.tongueAttackMaxShots); weapon->setTotalShots(settings.bossBuddy.tongueAttackTotalShots); weapon->setShotInterval(0.04f); weapon->setInterval(settings.bossBuddy.tongueAttackInterval); weapon->setMinColor(Color(0.0f, 1.0f, 0.0f, 0.5f)); weapon->setMaxColor(Color(0.5f, 1.0f, 0.0f, 0.7f)); weapon->setMinHeight(0.7f); weapon->setMaxHeight(1.2f); weapon->setPos(asset->world()->image("missile")->pos()); weapon->setAngle(asset->world()->image("missile")->angle()); weapon->setUseFreeze(false); weapon->setTweakPos(false); weapon->setSound(audio.createSound("squid_attack1.ogg")); thinkComponent->setWeapon(weapon); asset->root()->addComponent(weapon); asset->root()->addComponent(thinkComponent); { CollisionSensorComponentPtr component = boost::make_shared<CollisionSensorComponent>(); component->setListener(thinkComponent); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createNapalm(float damage, bool haveSound) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("napalm.json"); { NapalmComponentPtr component = boost::make_shared<NapalmComponent>( asset->root()->findComponent<ParticleEffectComponent>(), damage, haveSound); component->setAutoTarget(true); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createNapalm2(float damage, bool haveSound) { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("napalm2.json"); { NapalmComponentPtr component = boost::make_shared<NapalmComponent>( asset->root()->findComponent<ParticleEffectComponent>(), damage, haveSound); component->setAutoTarget(true); asset->root()->addComponent(component); } return asset->root(); } SceneObjectPtr SceneObjectFactory::createBossNatan() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("boss_natan.json"); asset->root()->setType(SceneObjectTypeEnemy); asset->root()->setMaterial(MaterialFlesh); asset->root()->setMaxLife(settings.bossNatan.life); asset->root()->setLife(asset->root()->maxLife() * (2.0f / 3.0f)); RenderQuadComponentPtr rc = asset->root()->findComponent<RenderQuadComponent>(); AnimationComponentPtr ac = boost::make_shared<AnimationComponent>(rc->drawable()); ac->addAnimation(AnimationDefault, "natan_def"); ac->addAnimation(BossNatanComponent::AnimationMelee, "natan_melee"); ac->addAnimation(BossNatanComponent::AnimationPreShoot, "natan_preshoot"); ac->addAnimation(BossNatanComponent::AnimationPreShoot2, "natan_preshoot2"); ac->addAnimation(BossNatanComponent::AnimationPostShoot, "natan_postshoot"); ac->addAnimation(BossNatanComponent::AnimationShoot, "natan_shoot"); ac->addAnimation(BossNatanComponent::AnimationSyringe, "natan_syringe"); ac->addAnimation(BossNatanComponent::AnimationRam, "natan_ram"); ac->addAnimation(BossNatanComponent::AnimationPowerup, "natan_powerup"); ac->addAnimation(BossNatanComponent::AnimationDie, "natan_die"); ac->addAnimation(BossNatanComponent::AnimationDead, "natan_dead"); ac->startAnimation(AnimationDefault); asset->root()->addComponent(ac); std::vector<ParticleEffectComponentPtr> cs = asset->root()->findComponents<ParticleEffectComponent>(); assert(cs.size() == 2); ParticleEffectComponentPtr pec[] = { cs[0], cs[1] }; BossNatanComponentPtr component = boost::make_shared<BossNatanComponent>(ac, pec, asset->rootBody()->image("melee")->pos(), asset->rootBody()->image("melee")->height() / 2.0f); WeaponPlasmaGunComponentPtr weapon = boost::make_shared<WeaponPlasmaGunComponent>(SceneObjectTypeEnemyMissile); weapon->setDamage(settings.bossNatan.plasmaDamage); weapon->setVelocity(settings.bossNatan.plasmaVelocity); weapon->setSpreadAngle(settings.bossNatan.plasmaAngle); weapon->setNumShots(3); weapon->setInterval(settings.bossNatan.plasmaInterval); weapon->setPos(asset->world()->image("missile")->pos()); weapon->setAngle(asset->world()->image("missile")->angle()); weapon->setUseFreeze(false); weapon->setHaveSound(true); component->setWeapon(0, weapon); asset->root()->addComponent(weapon); WeaponSpitterComponentPtr weapon2 = boost::make_shared<WeaponSpitterComponent>(SceneObjectTypeEnemyMissile); weapon2->setDamage(settings.bossNatan.spitDamage); weapon2->setVelocity(settings.bossNatan.spitVelocity); weapon2->setSpreadAngle(settings.bossNatan.spitAngle); weapon2->setMinShots(3); weapon2->setMaxShots(3); weapon2->setTotalShots(3); weapon2->setShotInterval(0.0f); weapon2->setInterval(settings.bossNatan.spitInterval); weapon2->setMinColor(Color(0.0f, 1.0f, 0.0f, 1.0f)); weapon2->setMaxColor(Color(0.0f, 1.0f, 0.0f, 1.0f)); weapon2->setMinHeight(1.1f); weapon2->setMaxHeight(1.1f); weapon2->setSpreadRandom(false); weapon2->setI(2); weapon2->setSound(audio.createSound("beetle_attack.ogg")); weapon2->setPos(asset->world()->image("missile")->pos()); weapon2->setAngle(asset->world()->image("missile")->angle()); weapon2->setUseFreeze(false); weapon2->setHaveSound(true); component->setWeapon(1, weapon2); asset->root()->addComponent(weapon2); WeaponBlasterComponentPtr weapon3 = boost::make_shared<WeaponBlasterComponent>(true, SceneObjectTypeEnemyMissile); weapon3->setDamage(settings.bossNatan.blasterDamage); weapon3->setVelocity(settings.bossNatan.blasterVelocity); weapon3->setTurns(1); weapon3->setShotsPerTurn(3); weapon3->setLoopDelay(settings.bossNatan.blasterInterval); weapon3->setPos(asset->world()->image("missile")->pos()); weapon3->setAngle(asset->world()->image("missile")->angle()); weapon3->setUseFreeze(false); component->setWeapon(2, weapon3); asset->root()->addComponent(weapon3); asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createPowerBeam(float radius, float length) { SceneObjectPtr obj = createDummy(); PowerBeamComponentPtr component = boost::make_shared<PowerBeamComponent>(radius, length); obj->addComponent(component); return obj; } SceneObjectPtr SceneObjectFactory::createGuardian() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("guardian.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); asset->object(i)->setPropagateDamage(false); } asset->root()->setMaxLife(settings.guardian.life); asset->root()->setLife(settings.guardian.life); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 2.5f), 0, 4.0f, 0.8f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } GuardianComponentPtr component = boost::make_shared<GuardianComponent>(settings.guardian.jumpVelocity, settings.guardian.shootMinTimeout, settings.guardian.shootMaxTimeout, settings.guardian.jumpTimeout); WeaponBlasterComponentPtr blaster = boost::make_shared<WeaponBlasterComponent>(false, SceneObjectTypeEnemyMissile); blaster->setDamage(settings.guardian.shootDamage); blaster->setVelocity(settings.guardian.shootVelocity); blaster->setTurns(4); blaster->setShotsPerTurn(1); blaster->setTurnInterval(0.1f); blaster->setLoopDelay(0.5f); blaster->setPos(asset->world()->image("missile")->pos()); blaster->setAngle(asset->world()->image("missile")->angle()); component->setWeapon(blaster); asset->root()->addComponent(blaster); asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createGuardian2() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("guardian.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); asset->object(i)->setPropagateDamage(false); if (asset->object(i)->name() == "bone1") { asset->object(i)->findComponent<RenderQuadComponent>()->drawable()->setImage( assetManager.getImage("common1/guardian2_bone1.png")); } else if (asset->object(i)->name() == "bone2") { asset->object(i)->findComponent<RenderQuadComponent>()->drawable()->setImage( assetManager.getImage("common1/guardian2_bone2.png")); } } asset->root()->findComponent<RenderQuadComponent>()->drawable()->setImage( assetManager.getImage("common1/guardian2_head.png")); asset->root()->setMaxLife(settings.guardian2.life); asset->root()->setLife(settings.guardian2.life); { RenderHealthbarComponentPtr component = boost::make_shared<RenderHealthbarComponent>(b2Vec2(0.0f, 2.5f), 0, 4.0f, 0.8f, zOrderMarker + 1); component->setColor(Color(1.0f, 1.0f, 1.0f, 0.6f)); asset->root()->addComponent(component); } GuardianComponentPtr component = boost::make_shared<GuardianComponent>(settings.guardian2.jumpVelocity, settings.guardian2.shootMinTimeout, settings.guardian2.shootMaxTimeout, settings.guardian2.jumpTimeout); WeaponBlasterComponentPtr blaster = boost::make_shared<WeaponBlasterComponent>(true, SceneObjectTypeEnemyMissile); blaster->setDamage(settings.guardian.shootDamage); blaster->setVelocity(settings.guardian.shootVelocity); blaster->setTurns(4); blaster->setShotsPerTurn(2); blaster->setTurnInterval(0.1f); blaster->setLoopDelay(0.5f); blaster->setPos(asset->world()->image("missile")->pos()); blaster->setAngle(asset->world()->image("missile")->angle()); component->setWeapon(blaster); asset->root()->addComponent(blaster); asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createMilitary1() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("military1.json"); asset->root()->setType(SceneObjectTypeAlly); RenderQuadComponentPtr legsRc = asset->root()->findComponentByName<RenderQuadComponent>("legs"); RenderQuadComponentPtr torsoRc = asset->root()->findComponentByName<RenderQuadComponent>("torso"); AnimationComponentPtr legsAc = boost::make_shared<AnimationComponent>(legsRc->drawable()); AnimationComponentPtr torsoAc = boost::make_shared<AnimationComponent>(torsoRc->drawable()); legsAc->addAnimation(AnimationDefault, "military_legs_def"); legsAc->addAnimation(DudeComponent::AnimationWalk, "military_legs_walk"); torsoAc->addAnimation(AnimationDefault, "military_torso_nogun_def"); torsoAc->addAnimation(DudeComponent::AnimationWalk, "military_torso_nogun_walk"); torsoAc->addAnimation(DudeComponent::AnimationGunDefault, "military_torso_def"); torsoAc->addAnimation(DudeComponent::AnimationGunWalk, "military_torso_walk"); legsAc->startAnimation(AnimationDefault); torsoAc->startAnimationRandomTime(DudeComponent::AnimationGunDefault); asset->root()->addComponent(legsAc); asset->root()->addComponent(torsoAc); DudeComponentPtr component = boost::make_shared<DudeComponent>(legsRc, legsAc, torsoAc); component->setLegsAngle(-b2_pi / 2); component->setHaveGun(true); asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createSarge1() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("sarge1.json"); asset->root()->setType(SceneObjectTypeAlly); RenderQuadComponentPtr legsRc = asset->root()->findComponentByName<RenderQuadComponent>("legs"); RenderQuadComponentPtr torsoRc = asset->root()->findComponentByName<RenderQuadComponent>("torso"); AnimationComponentPtr legsAc = boost::make_shared<AnimationComponent>(legsRc->drawable()); AnimationComponentPtr torsoAc = boost::make_shared<AnimationComponent>(torsoRc->drawable()); legsAc->addAnimation(AnimationDefault, "sarge_legs_def"); legsAc->addAnimation(DudeComponent::AnimationWalk, "sarge_legs_walk"); torsoAc->addAnimation(AnimationDefault, "sarge_torso_def"); torsoAc->addAnimation(DudeComponent::AnimationWalk, "sarge_torso_walk"); legsAc->startAnimation(AnimationDefault); torsoAc->startAnimationRandomTime(AnimationDefault); asset->root()->addComponent(legsAc); asset->root()->addComponent(torsoAc); DudeComponentPtr component = boost::make_shared<DudeComponent>(legsRc, legsAc, torsoAc); component->setLegsAngle(-b2_pi / 2); asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createSawer(float length, bool fixed) { float segmentSize = 1.0f; SceneObjectPtr root; int numSegments = std::ceil(length / segmentSize); std::vector<SceneObjectPtr> objs; std::vector<RUBECircleFixturePtr> fixtures; for (int i = 0; i < numSegments; ++i) { b2Vec2 pos(segmentSize * i, 0.0f); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("sawer_segment.json"); asset->root()->setType(SceneObjectTypeDeadbody); asset->root()->setPos(pos); if (root) { root->addObject(asset->root()); } else { root = asset->root(); } objs.push_back(asset->root()); fixtures.push_back(asset->rootBody()->fixture<RUBECircleFixture>("root")); } if (fixed) { root->script_setBodyType(b2_kinematicBody); } SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("sawer_head.json"); asset->root()->setType(SceneObjectTypeDeadbody); asset->root()->setPos(b2Vec2(segmentSize * numSegments, 0.0f)); root->addObject(asset->root()); RenderQuadComponentPtr rc = asset->root()->findComponent<RenderQuadComponent>(); RenderTentacleComponentPtr tc = boost::make_shared<RenderTentacleComponent>(objs, fixtures, assetManager.getDrawable("pipe9.png", Texture::WrapModeRepeat, Texture::WrapModeClamp), rc->zOrder() + 1, 25, 0.0f, 0.2f); tc->resetTimeline1(2); tc->resetTimeline2(2); tc->set1At(0, 0.0f, 0.8f); tc->set1At(1, 1.0f, 0.8f); tc->set2At(0, 0.0f, 0.8f); tc->set2At(1, 1.0f, 0.8f); root->addComponent(tc); { SawerComponentPtr component = boost::make_shared<SawerComponent>(tc, asset->root()); root->addComponent(component); } return root; } SceneObjectPtr SceneObjectFactory::createSawerSaw() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("sawer_saw.json"); asset->root()->setType(SceneObjectTypeEnemy); CollisionBuzzSawComponentPtr component = boost::make_shared<CollisionBuzzSawComponent>(); asset->root()->addComponent(component); return asset->root(); } SceneObjectPtr SceneObjectFactory::createSawerSawGibbed() { SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("sawer_saw_gibbed.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemy); } return asset->root(); } void SceneObjectFactory::makeDeadbody(const SceneObjectPtr& obj, float radius) { b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.linearDamping = 3.0f; bodyDef.angularDamping = 3.0f; RUBEBodyPtr body = boost::make_shared<RUBEBody>("", bodyDef); RUBECircleFixturePtr fixture = boost::make_shared<RUBECircleFixture>(""); fixture->fixtureDef().filter.categoryBits = collisionBitEnemy; fixture->fixtureDef().density = 1.0f; fixture->shape().m_p = b2Vec2_zero; fixture->shape().m_radius = radius; body->addFixture(fixture); { ComponentPtr component = boost::make_shared<PhysicsBodyComponent>(body); obj->addComponent(component); } obj->setBodyDef(body->bodyDef()); obj->becomeDeadbody(); } bool SceneObjectFactory::makeDebris(const SceneObjectPtr& obj) { PhysicsBodyComponentPtr pc = obj->findComponent<PhysicsBodyComponent>(); if (!pc || (pc->rubeBody()->numFixtures() < 1) || pc->rubeBody()->fixture(0)->fixtureDef().isSensor) { return false; } obj->setType(SceneObjectTypeGarbage); obj->setCollisionImpulseMultiplier(0.0f); if (obj->body()) { pc->setFilterCategoryBits(collisionBitGarbage); pc->setFilterMaskBits(0xFFFF); pc->setFilterGroupIndex(collisionGroupMissile); } else { b2Filter filter; filter.categoryBits = collisionBitGarbage; filter.groupIndex = collisionGroupMissile; pc->setFilterOverride(filter); } SceneObjectTypes types; types.set(SceneObjectTypePlayer); types.set(SceneObjectTypeEnemy); types.set(SceneObjectTypeEnemyBuilding); types.set(SceneObjectTypeAlly); types.set(SceneObjectTypeGizmo); types.set(SceneObjectTypeVehicle); types.set(SceneObjectTypeRock); CollisionCancelComponentPtr c = boost::make_shared<CollisionCancelComponent>(); c->setFilter(types); c->setNoStatic(true); obj->addComponent(c); std::vector<RenderQuadComponentPtr> tmp = obj->findComponents<RenderQuadComponent>(); for (std::vector<RenderQuadComponentPtr>::const_iterator it = tmp.begin(); it != tmp.end(); ++it) { (*it)->setZOrder(-92); } return true; } SceneObjectPtr SceneObjectFactory::createPuzzleHint() { SceneObjectPtr obj = boost::make_shared<SceneObject>(); obj->setFreezable(true); obj->setFreezeRadius(settings.puzzleHint.radius * 2.0f); /* RenderDottedCircleComponentPtr dcc = boost::make_shared<RenderDottedCircleComponent>(b2Vec2_zero, 0.3f, assetManager.getDrawable("common2/dot.png"), zOrderMarker + 1); dcc->setColor(settings.puzzleHint.color); dcc->setRadius(settings.puzzleHint.radius); dcc->setDotVelocity(5.0f, settings.puzzleHint.radius); dcc->setDotDistance(0.5f, settings.puzzleHint.radius); obj->addComponent(boost::make_shared<GoalComponent>(dcc));*/ DrawablePtr drawable = assetManager.getDrawable("common1/hint_arrow.png"); float height = settings.puzzleHint.height; float width = height * drawable->image().aspect(); RenderQuadComponentPtr rc = boost::make_shared<RenderQuadComponent>(b2Vec2(0.0f, height * 0.5f), 0.0f, width, height, drawable, zOrderMarker + 2); obj->addComponent(rc); obj->addComponent(boost::make_shared<PuzzleHintComponent>(rc)); return obj; } SceneObjectPtr SceneObjectFactory::createBossBeholder() { SceneObjectTypes types; types.set(SceneObjectTypePlayer); SceneObjectAssetPtr asset = assetManager.getSceneObjectAsset("boss_beholder.json"); for (int i = 0; i < asset->numObjects(); ++i) { asset->object(i)->setType(SceneObjectTypeEnemyBuilding); asset->object(i)->setMaterial(MaterialFlesh); asset->object(i)->setPropagateDamage(false); if (asset->object(i)->name() == "leg") { CollisionCancelComponentPtr c = boost::make_shared<CollisionCancelComponent>(); c->setFilter(types); c->setDamage(settings.bossBeholder.legDamage); c->setDamageSound(audio.createSound("player_hit.ogg")); c->setRoll(deg2rad(2.0f)); asset->object(i)->addComponent(c); } } asset->root()->setMaxLife(settings.bossBeholder.life); asset->root()->setLife(settings.bossBeholder.life); RenderQuadComponentPtr rc = asset->root()->findComponentByName<RenderQuadComponent>("root"); QuadPulseComponentPtr pc = boost::make_shared<QuadPulseComponent>(rc, b2Vec2_zero, 0.5f, EaseInOutQuad, 0.98f, 0.5f, EaseInOutQuad, 1.02f); pc->setT(0.0f); asset->root()->addComponent(pc); LightComponentPtr lc = asset->root()->findComponent<LightComponent>(); LightPtr fireLight[] = { lc->getLight<Light>("light1"), lc->getLight<Light>("light2"), lc->getLight<Light>("light3"), lc->getLight<Light>("light4"), lc->getLight<Light>("light5"), lc->getLight<Light>("light6") }; BossBeholderComponentPtr component = boost::make_shared<BossBeholderComponent>(asset->object("legs"), asset->object("guns"), lc->getLight<Light>("light"), fireLight); for (int i = 0; i < 8; ++i) { std::ostringstream os; os << "gun" << (i + 1); const RUBEImagePtr& image = asset->world()->body(os.str())->image("missile"); WeaponFireballComponentPtr weapon = boost::make_shared<WeaponFireballComponent>(SceneObjectTypeEnemyMissile); weapon->setDamage(settings.bossBeholder.fireballDamage); weapon->setVelocity(settings.bossBeholder.fireballVelocity); weapon->setInterval(0.0f); weapon->setPos(image->pos()); weapon->setAngle(image->angle()); weapon->setUseFreeze(false); weapon->setHaveSound(i == 0); weapon->setHitHaveSound(false); component->setGunWeapon(i, weapon); asset->object(os.str())->addComponent(weapon); WeaponHeaterComponentPtr heaterWeapon = boost::make_shared<WeaponHeaterComponent>(SceneObjectTypeEnemyMissile); heaterWeapon->setDamage(settings.bossBeholder.laserDamage); heaterWeapon->setLength(100.0f); heaterWeapon->setImpulse(settings.bossBeholder.laserImpulse); heaterWeapon->setDuration(0.8f); heaterWeapon->setInterval(0.0f); heaterWeapon->setMinWidth(0.8f); heaterWeapon->setMaxWidth(1.8f); heaterWeapon->setHaveSound(false); heaterWeapon->setPos(asset->world()->image("missile")->pos()); heaterWeapon->setAngle(asset->world()->image("missile")->angle()); component->setLaserWeapon(i, heaterWeapon); asset->object(os.str())->addComponent(heaterWeapon); WeaponAimComponentPtr aimWeapon = boost::make_shared<WeaponAimComponent>(SceneObjectTypeEnemyMissile); aimWeapon->setLength(100.0f); aimWeapon->setPos(asset->world()->image("missile")->pos()); aimWeapon->setAngle(asset->world()->image("missile")->angle()); component->setAimWeapon(i, aimWeapon); asset->object(os.str())->addComponent(aimWeapon); } WeaponEShieldComponentPtr shield0 = boost::make_shared<WeaponEShieldComponent>(SceneObjectTypeEnemyMissile); shield0->setAngle(0.0f); shield0->setHaveSound(true); component->setShieldWeapon(0, shield0); asset->root()->addComponent(shield0); WeaponEShieldComponentPtr shield1 = boost::make_shared<WeaponEShieldComponent>(SceneObjectTypeEnemyMissile); shield1->setAngle(b2_pi * 2.0f / 3.0f); shield1->setHaveSound(false); component->setShieldWeapon(1, shield1); asset->root()->addComponent(shield1); WeaponEShieldComponentPtr shield2 = boost::make_shared<WeaponEShieldComponent>(SceneObjectTypeEnemyMissile); shield2->setAngle(b2_pi * 4.0f / 3.0f); shield2->setHaveSound(false); component->setShieldWeapon(2, shield2); asset->root()->addComponent(shield2); shield0->setDistance(2.5f); shield1->setDistance(2.5f); shield2->setDistance(2.5f); asset->root()->addComponent(component); return asset->root(); } }
36.595477
213
0.62539
[ "object", "shape", "vector" ]
eaff5d44a2f2c25a2c4af663659eaa8e2165e740
20,091
cpp
C++
src/CADAssembler/CADCreoParametricCommonFunctions/CommonFunctions.cpp
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
src/CADAssembler/CADCreoParametricCommonFunctions/CommonFunctions.cpp
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
src/CADAssembler/CADCreoParametricCommonFunctions/CommonFunctions.cpp
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
#include <CommonFunctions.h> #include <ToolKitPassThroughFunctions.h> #include <cc_CommonFunctions.h> #include <string> namespace isis { /** std::ostream& operator <<(std::ostream & out, const bool & value) { out << Bool_string(value); return out; } std::string Bool_string( bool in_Bool ) { if ( in_Bool ) return "TRUE"; else return "FALSE"; } **/ // This function is necessary because the working directory buffer (e.g. setCreoWorkingDirectory_buffer // in the setCreoWorkingDirectory function) must be persisted between calls to isis_ProDirectoryChange. // This is because after the initial call to isis_ProDirectoryChange, isis_ProDirectoryChange appears to // access the address of the buffer used in the previous call. Therefore, the same address must be used // between calls, or at least, the previously used buffer address must still be valid. // // This function is not thread safe. void setCreoWorkingDirectory ( const MultiFormatString &in_MultiFormatString ) throw (isis::application_exception) { isis_LOG(lg, isis_FILE, isis_INFO) << "setCreoWorkingDirectory: " << in_MultiFormatString; static wchar_t *setCreoWorkingDirectory_buffer = NULL; if ( !setCreoWorkingDirectory_buffer) setCreoWorkingDirectory_buffer = new wchar_t[PRO_PATH_SIZE]; wcscpy_s( setCreoWorkingDirectory_buffer, PRO_PATH_SIZE, (const wchar_t*)in_MultiFormatString); isis::isis_ProDirectoryChange( setCreoWorkingDirectory_buffer ); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// std::string CombineCreoModelNameAndSuffix ( const std::string &in_ModelName, ProMdlType in_ModelType ) throw (isis::application_exception) { if ( in_ModelName.size() == 0 ) { std::stringstream errorString; errorString << "exception: Function" + std::string(__FUNCTION__) + " was passed a null string for in_ModelName."; throw isis::application_exception(errorString.str()); } std::string tempString; switch (in_ModelType) { case PRO_PART: tempString = in_ModelName + ".prt"; break; case PRO_ASSEMBLY: tempString = in_ModelName + ".asm"; break; default: std::stringstream errorString; errorString << "exception: Function" + std::string(__FUNCTION__) + " was passed in_ModelType that was not PRO_PART or PRO_ASSEMBLY, in_ModelType: " << in_ModelType; throw isis::application_exception(errorString.str()); } return tempString; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void ComputeBoundingBox( e_ComputeBoundingBoxMethod in_ComputeBoundingBoxMethod, ProSolid in_p_solid, isis_CADCommon::Point_3D &out_BoundingBox_Point_1, isis_CADCommon::Point_3D &out_BoundingBox_Point_2, double out_Dimensions_xyz[3] ) throw (isis::application_exception) { Pro3dPnt r_outline_points[2]; if ( in_ComputeBoundingBoxMethod == CAD_PRO_SOLID_OUTLINE_COMPUTE ) { ProMatrix transf= {{1,0.0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}; ProSolidOutlExclTypes excludes[] = { PRO_OUTL_EXC_DATUM_PLANE, PRO_OUTL_EXC_DATUM_POINT, PRO_OUTL_EXC_DATUM_CSYS, PRO_OUTL_EXC_DATUM_AXES, PRO_OUTL_EXC_FACETS, PRO_OUTL_EXC_ALL_CRVS }; isis_ProSolidOutlineCompute( in_p_solid, transf, excludes, 6, r_outline_points); } else { isis::isis_ProSolidOutlineGet( in_p_solid, r_outline_points); } out_BoundingBox_Point_1.x = r_outline_points[0][0]; out_BoundingBox_Point_1.y = r_outline_points[0][1]; out_BoundingBox_Point_1.z = r_outline_points[0][2]; out_BoundingBox_Point_2.x = r_outline_points[1][0]; out_BoundingBox_Point_2.y = r_outline_points[1][1]; out_BoundingBox_Point_2.z = r_outline_points[1][2]; out_Dimensions_xyz[0] = abs(r_outline_points[1][0] - r_outline_points[0][0]); out_Dimensions_xyz[1] = abs(r_outline_points[1][1] - r_outline_points[0][1]); out_Dimensions_xyz[2] = abs(r_outline_points[1][2] - r_outline_points[0][2]); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::string CAD_SimplifiedRep_InclusionStatus_string( e_CAD_SimplifiedRep_InclusionStatus in_SimplifiedRep_InclusionStatus_enum) throw (isis::application_exception) { switch (in_SimplifiedRep_InclusionStatus_enum ) { case CAD_SIMPLIFIED_REP_INCLUDE: return "CAD_SIMPLIFIED_REP_INCLUDE"; break; case CAD_SIMPLIFIED_REP_EXCLUDE: return "CAD_SIMPLIFIED_REP_EXCLUDE"; break; default: char temp_char_array[64]; string temp_string = "Function CAD_SimplifiedRep_InclusionStatus_string was passed " + std::string(itoa(in_SimplifiedRep_InclusionStatus_enum, temp_char_array, 10)) + " which is an erroneous type. Allowed enum values are CAD_SIMPLIFIED_REP_INCLUDE and CAD_SIMPLIFIED_REP_EXCLUDE."; throw isis::application_exception(temp_string.c_str()); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::map<int, CAD_SimplifiedRepData> FeatureID_to_SimplifiedRepData_map_temp; ProError SimplifiedRep_Action ( ProSimprepitem *item, ProError err, ProSolid owner) { //std::cout << std::endl << "-----------------+ SimplifiedRep_Action, owner: " << owner; //std::cout << std::endl << "-----------------+ SimplifiedRep_Action, item->item_path.feat_id: " << item->item_path.feat_id; //std::cout << std::endl << "-----------------+ SimplifiedRep_Action, item->action.type: " << item->action.type; //std::cout << std::endl << "-----------------+ SimplifiedRep_Action, item->item_path.path_size: " << item->item_path.path_size; //std::cout << std::endl << "-----------------+ SimplifiedRep_Action, item->item_path.comp_path[i]: "; //for ( int i = 0; i < item->item_path.path_size ; ++ i ) // std::cout << std::endl << "-----------------+ " << item->item_path.comp_path[i]; //std::cout << std::endl; // This function is only intended to be called for an assembly where the simplified rep exists in the assembly. // No deeper hierarchies, other than one assembly, are supported. // Therefore, item_path.comp_path[0 ] should contain the feature ID of the .prt/.asm which is either include or exclude from the // representation. if ( item->item_path.path_size != 1 ) { // It would be safer to throw an exception here, but at this point I am not // sure about all the perturbations of simplified reps. The goal is to // determine if a .prt or .asm was include or exclude. If the simplified // rep is doing other things, then allow this function to continue // would be appropriate. return PRO_TK_NO_ERROR; } // Note: item->item_path.feat_id would be set to -1. This means the tem->item_path defines the list of feature IDs to the .prt/.asm. // For our case the path only has one feature ID. int feature_ID = item->item_path.comp_path[0]; CAD_SimplifiedRepData cAD_SimplifiedRepData_temp; cAD_SimplifiedRepData_temp.featureID = feature_ID; if ( item->action.type == PRO_SIMPREP_EXCLUDE ) cAD_SimplifiedRepData_temp.inclusionStatus = CAD_SIMPLIFIED_REP_EXCLUDE; else cAD_SimplifiedRepData_temp.inclusionStatus = CAD_SIMPLIFIED_REP_INCLUDE; FeatureID_to_SimplifiedRepData_map_temp[feature_ID] = cAD_SimplifiedRepData_temp; return PRO_TK_NO_ERROR; } /* class SimplifiedRep_Action { public: //ProError operator() (){ return PRO_TK_NO_ERROR; }; ProError operator() ( ProSimprepitem *item, ProError err, ProSolid owner) { std::cout << std::endl << "-----------------+ SimplifiedRep_Action, owner: " << owner; std::cout << std::endl << "-----------------+ SimplifiedRep_Action, item->item_path.feat_id: " << item->item_path.feat_id; std::cout << std::endl << "-----------------+ SimplifiedRep_Action, item->action.type: " << item->action.type; std::cout << std::endl << "-----------------+ SimplifiedRep_Action, item->item_path.path_size: " << item->item_path.path_size; std::cout << std::endl << "-----------------+ SimplifiedRep_Action, item->item_path.comp_path[i]: "; for ( int i = 0; i < item->item_path.path_size ; ++ i ) std::cout << std::endl << "-----------------+ " << item->item_path.comp_path[i]; std::cout << std::endl; return PRO_TK_NO_ERROR; } }; */ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void AssemblySimplifiedRep_RetrieveModelInclusionStatus ( ProMdl &in_Owner, ProSimprep &in_SimplifiedRep, std::map<int, CAD_SimplifiedRepData> &out_FeatureID_to_SimplifiedRepData_map ) throw (isis::application_exception) { // Erase the global map FeatureID_to_SimplifiedRepData_map_temp.erase(FeatureID_to_SimplifiedRepData_map_temp.begin(),FeatureID_to_SimplifiedRepData_map_temp.end()); ProSimprepdata *simpRepData; //ProError SimplifiedRep_Action(); isis_ProSimprepdataGet( &in_SimplifiedRep, &simpRepData); isis_ProSimprepdataitemsVisit (simpRepData, NULL, (ProFunction)SimplifiedRep_Action, (ProAppData) in_Owner); /* This did not work, tried to use a functor SimplifiedRep_Action simplifiedRep_Action_obj; ProSimprepitem *item_dummy = NULL; ProError err_dummy; ProSolid owner_dummy; isis_ProSimprepdataitemsVisit ( simpRepData, NULL, (ProFunction)simplifiedRep_Action_obj(item_dummy,err_dummy,owner_dummy ), (ProAppData) in_Owner); */ out_FeatureID_to_SimplifiedRepData_map = FeatureID_to_SimplifiedRepData_map_temp; FeatureID_to_SimplifiedRepData_map_temp.erase(FeatureID_to_SimplifiedRepData_map_temp.begin(),FeatureID_to_SimplifiedRepData_map_temp.end()); isis_ProSimprepdataFree( &simpRepData); } ProAsmcomp getProAsmcomp(const CADAssembledFeature &in_CADAssembledFeature ) { ProAsmcomp ProAsmcomp_temp; ProAsmcomp_temp.type = FeatureGeometryType_enum(in_CADAssembledFeature.type); ProAsmcomp_temp.id = in_CADAssembledFeature.id; ProAsmcomp_temp.owner = in_CADAssembledFeature.owner; return ProAsmcomp_temp; } CADAssembledFeature getCADAssembledFeature( const ProAsmcomp &in_ProAsmcomp ) { CADAssembledFeature CADAssembledFeature_temp; CADAssembledFeature_temp.type = CADFeatureGeometryType_enum(in_ProAsmcomp.type); CADAssembledFeature_temp.id = in_ProAsmcomp.id; CADAssembledFeature_temp.owner = in_ProAsmcomp.owner; return CADAssembledFeature_temp; } /////////////////////////////////////////////////////////////////////////////////////////////////// void RetrieveUnits( //cad::CadFactoryAbstract &in_Factory, ProMdl in_Model, CADModelUnits &out_CADModelUnits ) throw(isis::application_exception) { isis::cad::CadFactoryAbstract_global *cadFactoryAbstract_global_ptr = isis::cad::CadFactoryAbstract_global::instance(); isis::cad::CadFactoryAbstract::ptr cAD_Factory_ptr = cadFactoryAbstract_global_ptr->getCadFactoryAbstract_ptr(); std::string unitsString; ProUnitsystem unitSystem; //ProUnititem unit, forceUnit, timeUnit, lengthUnit; ProUnititem massUnit, forceUnit, timeUnit, lengthUnit, temperatureUnit, angleUnit; //ProLine massUnitsLabel; //ProUnitsystemType type; isis::isis_ProMdlPrincipalunitsystemGet (in_Model, &unitSystem); // PRO_UNITTYPE_LENGTH L // PRO_UNITTYPE_MASS M // PRO_UNITTYPE_FORCE F // PRO_UNITTYPE_TIME T // PRO_UNITTYPE_TEMPERATURE D isis::isis_ProUnitsystemUnitGet (&unitSystem, PRO_UNITTYPE_LENGTH, &lengthUnit); MultiFormatString distanceUnit_multiformat( lengthUnit.name); out_CADModelUnits.distanceUnit = CADUnitsDistance_enum( distanceUnit_multiformat ); ComputeUnitNames_Distance( out_CADModelUnits.distanceUnit , out_CADModelUnits.distanceUnit_ShortName, out_CADModelUnits.distanceUnit_LongName ); bool derived = false; try { isis::isis_ProUnitsystemUnitGet (&unitSystem, PRO_UNITTYPE_MASS, &massUnit); //ConvertCreoUnitToGMEUnit_Mass( massUnit.name, out_MassUnit_ShortName, out_MassUnit_LongName ); } catch(...) { out_CADModelUnits.massUnit_LongName = "Derived"; derived = true; } if ( !derived ) { //modelOperations.convertCADUnitToGMEUnit_Mass(massUnit.name, out_CADModelUnits.massUnit_ShortName,out_CADModelUnits.massUnit_LongName ); MultiFormatString massUnit_multiformat( massUnit.name); out_CADModelUnits.massUnit = CADUnitsMass_enum( massUnit_multiformat ); ComputeUnitNames_Mass( out_CADModelUnits.massUnit , out_CADModelUnits.massUnit_ShortName, out_CADModelUnits.massUnit_LongName ); } derived = false; try { isis::isis_ProUnitsystemUnitGet (&unitSystem, PRO_UNITTYPE_FORCE, &forceUnit); //ConvertCreoUnitToGMEUnit_Force( forceUnit.name, out_ForceUnit_ShortName, out_ForceUnit_LongName ); } catch(...) { out_CADModelUnits.forceUnit_ShortName = "Derived"; out_CADModelUnits.forceUnit_LongName = "Derived"; derived = true; } if ( !derived ) { //modelOperations.convertCADUnitToGMEUnit_Force( forceUnit.name, out_CADModelUnits.forceUnit_ShortName, out_CADModelUnits.forceUnit_LongName ); MultiFormatString forceUnit_multiformat( forceUnit.name); out_CADModelUnits.forceUnit = CADUnitsForce_enum( forceUnit_multiformat ); ComputeUnitNames_Force( out_CADModelUnits.forceUnit , out_CADModelUnits.forceUnit_ShortName, out_CADModelUnits.forceUnit_LongName ); } isis::isis_ProUnitsystemUnitGet (&unitSystem, PRO_UNITTYPE_TEMPERATURE , &temperatureUnit); //ConvertCreoUnitToGMEUnit_Temperature( temperatureUint.name, out_TemperatureUnit_ShortName, out_TemperatureUnit_LongName ); //modelOperations.convertCADUnitToGMEUnit_Temperature(temperatureUnit.name, out_CADModelUnits.temperatureUnit_ShortName, out_CADModelUnits.temperatureUnit_LongName ); MultiFormatString temperatureUnit_multiformat( temperatureUnit.name); out_CADModelUnits.temperatureUnit = CADUnitsTemperature_enum( temperatureUnit_multiformat ); ComputeUnitNames_Temperature( out_CADModelUnits.temperatureUnit , out_CADModelUnits.temperatureUnit_ShortName, out_CADModelUnits.temperatureUnit_LongName ); isis::isis_ProUnitsystemUnitGet (&unitSystem, PRO_UNITTYPE_TIME, &timeUnit); //ConvertCreoUnitToGMEUnit_Time( timeUnit.name, out_TimeUnit_ShortName, out_TimeUnit_LongName ); //modelOperations.convertCADUnitToGMEUnit_Time( timeUnit.name, out_CADModelUnits.timeUnit_ShortName, out_CADModelUnits.timeUnit_LongName ); MultiFormatString timeUnit_multiformat( timeUnit.name); out_CADModelUnits.timeUnit = CADUnitsTime_enum( timeUnit_multiformat ); ComputeUnitNames_Time( out_CADModelUnits.timeUnit , out_CADModelUnits.timeUnit_ShortName, out_CADModelUnits.timeUnit_LongName ); isis::isis_ProUnitsystemUnitGet(&unitSystem, PRO_UNITTYPE_ANGLE, &angleUnit); // FIXME Creo reports rad, but it seems deg is used everywhere // MultiFormatString angleUnit_multiformat(angleUnit.name); MultiFormatString angleUnit_multiformat("deg"); out_CADModelUnits.angleUnit = CADUnitsAngle_enum(angleUnit_multiformat); ComputeUnitNames_Angle(out_CADModelUnits.angleUnit, out_CADModelUnits.angleUnit_ShortName, out_CADModelUnits.angleUnit_LongName); } /////////////////////////////////////////////////////////////////////////////////////// void RetrieveUnits_withDescriptiveErrorMsg( const std::string &in_ComponentInstanceID, const isis::CADComponentData &in_CADComponentData, CADModelUnits &out_CADModelUnits ) throw(isis::application_exception) { try { RetrieveUnits( in_CADComponentData.cADModel_hdl, out_CADModelUnits ); } catch(const isis::application_exception &exc) { std::stringstream errorString; errorString << "Error retrieving model units:" << std::endl << " ComponentInstanceID: " << in_ComponentInstanceID << std::endl << " ModelName: " << in_CADComponentData.name << std::endl << " Error: " << exc.what(); throw isis::application_exception(errorString.str()); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////// void RetrieveDatumPointCoordinates( //cad::CadFactoryAbstract &in_Factory, const std::string &in_AssemblyComponentID, const std::string &in_PartComponentID, const std::map<string, isis::CADComponentData> &in_CADComponentData_map, const MultiFormatString &in_DatumName, CADPoint &out_CADPoint) throw (isis::application_exception) { //wchar_t datum_name[PRO_NAME_SIZE ]; //ProStringToWstring(datum_name, (char *)in_DatumName.c_str() ); isis::cad::CadFactoryAbstract_global *cadFactoryAbstract_global_ptr = isis::cad::CadFactoryAbstract_global::instance(); isis::cad::CadFactoryAbstract::ptr cAD_Factory_ptr = cadFactoryAbstract_global_ptr->getCadFactoryAbstract_ptr(); std::map<std::string, isis::CADComponentData>::const_iterator itr_part; itr_part = in_CADComponentData_map.find(in_PartComponentID); if ( itr_part == in_CADComponentData_map.end()) { std::stringstream errorString; errorString << "Function - " << __FUNCTION__ << ", was passed an in_PartComponentID that is not in in_CADComponentData_map. in_PartComponentID: " << in_PartComponentID; throw isis::application_exception(errorString); } ProModelitem datum_point; //isis::isis_ProModelitemByNameInit_WithDescriptiveErrorMsg ( // in_PartComponentID, in_CADComponentData_map[in_PartComponentID].name, ProMdlType_enum(in_CADComponentData_map[in_PartComponentID].modelType), // in_CADComponentData_map[in_PartComponentID].cADModel_hdl, PRO_POINT, (wchar_t*)(const wchar_t*)in_DatumName, &datum_point); isis::isis_ProModelitemByNameInit_WithDescriptiveErrorMsg ( in_PartComponentID, itr_part->second.name, ProMdlType_enum( itr_part->second.modelType), itr_part->second.cADModel_hdl, PRO_POINT, (wchar_t*)(const wchar_t*)in_DatumName, &datum_point); ProPoint point; isis::isis_ProPointInit ( (ProSolid) datum_point.owner, // ProSolid owner_handle, datum_point.id, &point); ProVector part_xyz_point; isis::isis_ProPointCoordGet (point, part_xyz_point); double transformationMatrix[4][4]; //RetrieveTranformationMatrix_Assembly_to_Child ( in_AssemblyComponentID, // in_CADComponentData_map[in_PartComponentID].componentPaths, // in_CADComponentData_map, // PRO_B_TRUE, // bottom up // transformationMatrix); isis::cad::IModelOperations& modelOperations = cAD_Factory_ptr->getModelOperations(); // modelOperations.retrieveTranformationMatrix_Assembly_to_Child( in_AssemblyComponentID, // in_CADComponentData_map[in_PartComponentID].componentPaths, // in_CADComponentData_map, // true, // bottom up // transformationMatrix); modelOperations.retrieveTranformationMatrix_Assembly_to_Child( in_AssemblyComponentID, in_PartComponentID, in_CADComponentData_map, true, // bottom up transformationMatrix); ProVector from_assembly_xyz_point; isis::isis_ProPntTrfEval( part_xyz_point, transformationMatrix, from_assembly_xyz_point); out_CADPoint.x = from_assembly_xyz_point[0]; out_CADPoint.y = from_assembly_xyz_point[1]; out_CADPoint.z = from_assembly_xyz_point[2]; } } // END namespace isis
40.424547
171
0.692499
[ "cad", "model" ]
d805c312500d8b2877ac9d09e26c8b5500666de3
46,969
cpp
C++
Engine/Code/engine.cpp
ChronoByte/AGP-Engine
9889eabf27ca0346de45b9e91047440ee71a9eb2
[ "MIT" ]
null
null
null
Engine/Code/engine.cpp
ChronoByte/AGP-Engine
9889eabf27ca0346de45b9e91047440ee71a9eb2
[ "MIT" ]
null
null
null
Engine/Code/engine.cpp
ChronoByte/AGP-Engine
9889eabf27ca0346de45b9e91047440ee71a9eb2
[ "MIT" ]
null
null
null
// // engine.cpp : Put all your graphics stuff in this file. This is kind of the graphics module. // In here, you should type all your OpenGL commands, and you can also type code to handle // input platform events (e.g to move the camera or react to certain shortcuts), writing some // graphics related GUI options, and so on. // #include "engine.h" #include <imgui.h> #include <stb_image.h> #include <stb_image_write.h> #include<time.h> GLuint CreateProgramFromSource(String programSource, const char* shaderName) { GLchar infoLogBuffer[1024] = {}; GLsizei infoLogBufferSize = sizeof(infoLogBuffer); GLsizei infoLogSize; GLint success; char versionString[] = "#version 430\n"; char shaderNameDefine[128]; sprintf(shaderNameDefine, "#define %s\n", shaderName); char vertexShaderDefine[] = "#define VERTEX\n"; char fragmentShaderDefine[] = "#define FRAGMENT\n"; const GLchar* vertexShaderSource[] = { versionString, shaderNameDefine, vertexShaderDefine, programSource.str }; const GLint vertexShaderLengths[] = { (GLint) strlen(versionString), (GLint) strlen(shaderNameDefine), (GLint) strlen(vertexShaderDefine), (GLint) programSource.len }; const GLchar* fragmentShaderSource[] = { versionString, shaderNameDefine, fragmentShaderDefine, programSource.str }; const GLint fragmentShaderLengths[] = { (GLint) strlen(versionString), (GLint) strlen(shaderNameDefine), (GLint) strlen(fragmentShaderDefine), (GLint) programSource.len }; GLuint vshader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vshader, ARRAY_COUNT(vertexShaderSource), vertexShaderSource, vertexShaderLengths); glCompileShader(vshader); glGetShaderiv(vshader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vshader, infoLogBufferSize, &infoLogSize, infoLogBuffer); ELOG("glCompileShader() failed with vertex shader %s\nReported message:\n%s\n", shaderName, infoLogBuffer); } GLuint fshader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fshader, ARRAY_COUNT(fragmentShaderSource), fragmentShaderSource, fragmentShaderLengths); glCompileShader(fshader); glGetShaderiv(fshader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fshader, infoLogBufferSize, &infoLogSize, infoLogBuffer); ELOG("glCompileShader() failed with fragment shader %s\nReported message:\n%s\n", shaderName, infoLogBuffer); } GLuint programHandle = glCreateProgram(); glAttachShader(programHandle, vshader); glAttachShader(programHandle, fshader); glLinkProgram(programHandle); glGetProgramiv(programHandle, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(programHandle, infoLogBufferSize, &infoLogSize, infoLogBuffer); ELOG("glLinkProgram() failed with program %s\nReported message:\n%s\n", shaderName, infoLogBuffer); } glUseProgram(0); glDetachShader(programHandle, vshader); glDetachShader(programHandle, fshader); glDeleteShader(vshader); glDeleteShader(fshader); return programHandle; } u32 LoadProgram(App* app, const char* filepath, const char* programName) { String programSource = ReadTextFile(filepath); Program program = {}; program.handle = CreateProgramFromSource(programSource, programName); program.filepath = filepath; program.programName = programName; program.lastWriteTimestamp = GetFileLastWriteTimestamp(filepath); app->programs.push_back(program); return app->programs.size() - 1; } Image LoadImage(const char* filename) { Image img = {}; stbi_set_flip_vertically_on_load(true); img.pixels = stbi_load(filename, &img.size.x, &img.size.y, &img.nchannels, 0); if (img.pixels) { img.stride = img.size.x * img.nchannels; } else { ELOG("Could not open file %s", filename); } return img; } void FreeImage(Image image) { stbi_image_free(image.pixels); } GLuint CreateTexture2DFromImage(Image image) { GLenum internalFormat = GL_RGB8; GLenum dataFormat = GL_RGB; GLenum dataType = GL_UNSIGNED_BYTE; switch (image.nchannels) { case 3: dataFormat = GL_RGB; internalFormat = GL_RGB8; break; case 4: dataFormat = GL_RGBA; internalFormat = GL_RGBA8; break; default: ELOG("LoadTexture2D() - Unsupported number of channels"); } GLuint texHandle; glGenTextures(1, &texHandle); glBindTexture(GL_TEXTURE_2D, texHandle); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, image.size.x, image.size.y, 0, dataFormat, dataType, image.pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); return texHandle; } u32 LoadTexture2D(App* app, const char* filepath) { for (u32 texIdx = 0; texIdx < app->textures.size(); ++texIdx) if (app->textures[texIdx].filepath == filepath) return texIdx; Image image = LoadImage(filepath); if (image.pixels) { Texture tex = {}; tex.handle = CreateTexture2DFromImage(image); tex.filepath = filepath; u32 texIdx = app->textures.size(); app->textures.push_back(tex); FreeImage(image); return texIdx; } else { return UINT32_MAX; } } void Init(App* app) { // TODO: Initialize your resources here! // - vertex buffers // - element/index buffers // - vaos // - programs (and retrieve uniform indices) // - textures // OpenGL information ------------------ app->info.version = (const char*)glGetString(GL_VERSION); app->info.renderer = (const char*)glGetString(GL_RENDERER); app->info.vendor = (const char*)glGetString(GL_VENDOR); app->info.shadingLanguageVersion = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION); GLint num_extensions; glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions); for (int i = 0; i < num_extensions; ++i) { app->info.extensions.push_back((const char*)glGetStringi(GL_EXTENSIONS, GLuint(i))); } //--------------------- TEXTURED QUAD ---------------------- // // Vertex Buffer glGenBuffers(1, &app->embeddedVertices); glBindBuffer(GL_ARRAY_BUFFER, app->embeddedVertices); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); // Index Buffer glGenBuffers(1, &app->embeddedElements); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, app->embeddedElements); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // VAO glGenVertexArrays(1, &app->vao); glBindVertexArray(app->vao); glBindBuffer(GL_ARRAY_BUFFER, app->embeddedVertices); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexV3V2), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(VertexV3V2), (void*)12); glEnableVertexAttribArray(1); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, app->embeddedElements); glBindVertexArray(0); // Program app->finalPassShaderIdx = LoadProgram(app, "shaders.glsl", "FINAL_PASS_SHADER"); Program& finalPassShader = app->programs[app->finalPassShaderIdx]; glUseProgram(finalPassShader.handle); glUniform1i(glGetUniformLocation(finalPassShader.handle, "sceneTexture"), 0); glUniform1i(glGetUniformLocation(finalPassShader.handle, "bloomBlurTexture"), 1); glUseProgram(0); app->geometryPassShaderID = LoadProgram(app, "shaders.glsl", "GEOMETRY_PASS_SHADER"); Program& geometryPassShader = app->programs[app->geometryPassShaderID]; app->programGPassUniformTexture = glGetUniformLocation(geometryPassShader.handle, "uTexture"); { int attributeCount; glGetProgramiv(geometryPassShader.handle, GL_ACTIVE_ATTRIBUTES, &attributeCount); GLchar attributeName[64]; GLsizei attributeNameLength; GLint attributeSize; GLenum attributeType; for (int i = 0; i < attributeCount; ++i) { glGetActiveAttrib(geometryPassShader.handle, i, 64, &attributeNameLength, &attributeSize, &attributeType, attributeName); GLint attributeLocation = glGetAttribLocation(geometryPassShader.handle, attributeName); geometryPassShader.vertexInputLayout.attributes.push_back({ (u8)attributeLocation,(u8)attributeSize }); } } app->shadingPassShaderID = LoadProgram(app, "shaders.glsl", "SHADING_PASS_SHADER"); Program& shadingPassShader = app->programs[app->shadingPassShaderID]; app->programShadingPassUniformTexturePosition = glGetUniformLocation(shadingPassShader.handle, "gPosition"); app->programShadingPassUniformTextureNormals = glGetUniformLocation(shadingPassShader.handle, "gNormal"); app->programShadingPassUniformTextureAlbedo = glGetUniformLocation(shadingPassShader.handle, "gAlbedoSpec"); app->programShadingPassUniformTextureDepth = glGetUniformLocation(shadingPassShader.handle, "gDepth"); { int attributeCount; glGetProgramiv(shadingPassShader.handle, GL_ACTIVE_ATTRIBUTES, &attributeCount); GLchar attributeName[64]; GLsizei attributeNameLength; GLint attributeSize; GLenum attributeType; for (int i = 0; i < attributeCount; ++i) { glGetActiveAttrib(shadingPassShader.handle, i, 64, &attributeNameLength, &attributeSize, &attributeType, attributeName); GLint attributeLocation = glGetAttribLocation(shadingPassShader.handle, attributeName); shadingPassShader.vertexInputLayout.attributes.push_back({ (u8)attributeLocation,(u8)attributeSize }); } } app->lightsShaderID = LoadProgram(app, "shaders.glsl", "LIGHTS_SHADER"); Program& lightsShader = app->programs[app->lightsShaderID]; app->programLightsUniformColor = glGetUniformLocation(lightsShader.handle, "lightColor"); app->programLightsUniformWorldMatrix = glGetUniformLocation(lightsShader.handle, "uWorldViewProjectionMatrix"); { int attributeCount; glGetProgramiv(lightsShader.handle, GL_ACTIVE_ATTRIBUTES, &attributeCount); GLchar attributeName[64]; GLsizei attributeNameLength; GLint attributeSize; GLenum attributeType; for (int i = 0; i < attributeCount; ++i) { glGetActiveAttrib(lightsShader.handle, i, 64, &attributeNameLength, &attributeSize, &attributeType, attributeName); GLint attributeLocation = glGetAttribLocation(lightsShader.handle, attributeName); lightsShader.vertexInputLayout.attributes.push_back({ (u8)attributeLocation,(u8)attributeSize }); } } app->blurShaderID = LoadProgram(app, "shaders.glsl", "BLUR_SHADER"); Program& blurShader = app->programs[app->blurShaderID]; glUseProgram(blurShader.handle); glUniform1i(glGetUniformLocation(blurShader.handle, "image"), 0); // Attributes Program ---------- { int attributeCount; glGetProgramiv(blurShader.handle, GL_ACTIVE_ATTRIBUTES, &attributeCount); GLchar attributeName[64]; GLsizei attributeNameLength; GLint attributeSize; GLenum attributeType; for (int i = 0; i < attributeCount; ++i) { glGetActiveAttrib(blurShader.handle, i, 64, &attributeNameLength, &attributeSize, &attributeType, attributeName); GLint attributeLocation = glGetAttribLocation(blurShader.handle, attributeName); blurShader.vertexInputLayout.attributes.push_back({ (u8)attributeLocation,(u8)attributeSize }); } } glUseProgram(0); // Textures app->diceTexIdx = LoadTexture2D(app, "dice.png"); app->whiteTexIdx = LoadTexture2D(app, "color_white.png"); app->blackTexIdx = LoadTexture2D(app, "color_black.png"); app->normalTexIdx = LoadTexture2D(app, "color_normal.png"); app->magentaTexIdx = LoadTexture2D(app, "color_magenta.png"); //--------------------- MODEL ---------------------- // // Camera ----------- app->camera = Camera(vec3(31, 17.0f, 45.0f), vec3(-129.0f, -27.f, 0.f)); app->camera.aspect_ratio = (float)app->displaySize.x / (float)app->displaySize.y; app->camera.projectionMatrix = glm::perspective(glm::radians(app->camera.vertical_fov), app->camera.aspect_ratio, app->camera.nearPlane, app->camera.farPlane); app->camera.viewMatrix = app->camera.CalculateCameraRotation(app); //app->camera.viewMatrix = glm::lookAt(app->camera.position, app->camera.target, glm::vec3(0, 1, 0)); // Program ---------- app->texturedMeshProgramIdx = LoadProgram(app, "shaders.glsl", "SHOW_TEXTURED_MESH"); Program& texturedMeshProgram = app->programs[app->texturedMeshProgramIdx]; // Attributes Program ---------- { int attributeCount; glGetProgramiv(texturedMeshProgram.handle, GL_ACTIVE_ATTRIBUTES, &attributeCount); GLchar attributeName[64]; GLsizei attributeNameLength; GLint attributeSize; GLenum attributeType; for (int i = 0; i < attributeCount; ++i) { glGetActiveAttrib(texturedMeshProgram.handle, i, 64, &attributeNameLength, &attributeSize, &attributeType, attributeName); GLint attributeLocation = glGetAttribLocation(texturedMeshProgram.handle, attributeName); texturedMeshProgram.vertexInputLayout.attributes.push_back({ (u8)attributeLocation,(u8)attributeSize }); } } // Uniform blocks --------- // Local Params glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &app->maxUniformBufferSize); glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &app->uniformBlockAlignment); app->ubuffer = CreateConstantBuffer(app->maxUniformBufferSize); // Global Params glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &app->maxGlobalParamsBufferSize); glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &app->globalParamsAlignment); app->gpBuffer = CreateConstantBuffer(app->maxGlobalParamsBufferSize); // Model ---------- app->model = LoadModel(app, "Patrick/Patrick.obj"); app->plane = app->geo.LoadPlane(app); app->sphere = app->geo.LoadSphere(app); app->mode = Mode_Model; // -------------------------------- ENTITIES -------------------------------- Entity e0 = Entity(glm::mat4(1.0), app->plane, 0, 0, EntityType::PLANE); e0.worldMatrix = TransformPositionScale(vec3(0.0, -1.0, 0.0), vec3(100.0, 1.0, 100.0)); e0.worldMatrix = TransformRotation(e0.worldMatrix, 90, { 1, 0, 0 }); app->entities.push_back(e0); const int COLUMNS = 6; const int ROWS = 6; const u32 distance = 6; for (int x = -ROWS; x < ROWS; ++x) { for (int y = -COLUMNS; y < COLUMNS; ++y) { Entity e1 = Entity(glm::mat4(1.0), app->model, 0, 0, EntityType::PATRICK); e1.worldMatrix = TransformPositionScale(vec3((float)x * (float)distance, 2.4f, (float)y * (float)distance), vec3(1.0f)); app->entities.push_back(e1); } } // -------------------------------- LIGHTS -------------------------------- // ----------- Point Lights ----------- const int LIGHTS = 6; const u32 offset = 2; std::srand(time(NULL)); for (int x = -LIGHTS; x < LIGHTS; ++x) { for (int y = -LIGHTS; y < LIGHTS; ++y) { vec3 color = GenerateRandomBrightColor(); app->lights.push_back(Light(glm::vec3((float)x * (float)distance, 1.0f, y * (float)distance + (float)offset), glm::vec3(color.x, color.y, color.z))); } } // ----------- Directional Lights ----------- app->lights.push_back(Light(glm::vec3(-20.0f, 45.0f, 3.f), glm::vec3(1.0f, 1.0f, 1.0f), LightType::LIGHT_TYPE_DIRECTIONAL, glm::vec3(-1.0, -1.0, -0.7), 32U)); app->lights.push_back(Light(glm::vec3(22.0f, 35.0f, -6.f), glm::vec3(0.3f, 0.0f, 0.0f), LightType::LIGHT_TYPE_DIRECTIONAL, glm::vec3(0.0, -1.0, 0.0), 10U)); // -------------------------------- RELIEF MAPPING -------------------------------- //Shader app->reliefMapShaderID = LoadProgram(app, "shaders.glsl", "RELIEF_MAPPING_SHADER"); Program& reliefMapShader = app->programs[app->reliefMapShaderID]; // Attributes Program ---------- { int attributeCount; glGetProgramiv(reliefMapShader.handle, GL_ACTIVE_ATTRIBUTES, &attributeCount); GLchar attributeName[64]; GLsizei attributeNameLength; GLint attributeSize; GLenum attributeType; for (int i = 0; i < attributeCount; ++i) { glGetActiveAttrib(reliefMapShader.handle, i, 64, &attributeNameLength, &attributeSize, &attributeType, attributeName); GLint attributeLocation = glGetAttribLocation(reliefMapShader.handle, attributeName); reliefMapShader.vertexInputLayout.attributes.push_back({ (u8)attributeLocation,(u8)attributeSize }); } } //Relief Textures app->reliefTextures.push_back(LoadTexture2D(app, "Relief/bricks2.jpg")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/bricks2_normal.jpg")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/bricks2_disp.jpg")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/LeatherPadded_03_BC.png")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/LeatherPadded_03_NOpenGL.png")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/LeatherPadded_03_H.png")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/BrokenTiles_01_BC.png")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/BrokenTiles_01_NOpenGL.png")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/BrokenTiles_01_H.png")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/Wood_Base.png")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/Wood_Normal.png")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/Wood_Height.png")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/CobbleStone_01_BC.png")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/CobbleStone_01_NOpenGL.png")); app->reliefTextures.push_back(LoadTexture2D(app, "Relief/CobbleStone_01_H.png")); glUseProgram(reliefMapShader.handle); glUniform1i(glGetUniformLocation(reliefMapShader.handle, "diffuseMap"), 0); glUniform1i(glGetUniformLocation(reliefMapShader.handle, "normalMap"), 1); glUniform1i(glGetUniformLocation(reliefMapShader.handle, "depthMap"), 2); //Shader app->reliefMapShaderForwardID = LoadProgram(app, "shaders.glsl", "RELIEF_MAPPING_SHADER_FORWARD"); Program& reliefMapShaderForward = app->programs[app->reliefMapShaderForwardID]; // Attributes Program ---------- { int attributeCount; glGetProgramiv(reliefMapShaderForward.handle, GL_ACTIVE_ATTRIBUTES, &attributeCount); GLchar attributeName[64]; GLsizei attributeNameLength; GLint attributeSize; GLenum attributeType; for (int i = 0; i < attributeCount; ++i) { glGetActiveAttrib(reliefMapShaderForward.handle, i, 64, &attributeNameLength, &attributeSize, &attributeType, attributeName); GLint attributeLocation = glGetAttribLocation(reliefMapShaderForward.handle, attributeName); reliefMapShaderForward.vertexInputLayout.attributes.push_back({ (u8)attributeLocation,(u8)attributeSize }); } } glUseProgram(reliefMapShaderForward.handle); glUniform1i(glGetUniformLocation(reliefMapShaderForward.handle, "diffuseMap"), 0); glUniform1i(glGetUniformLocation(reliefMapShaderForward.handle, "normalMap"), 1); glUniform1i(glGetUniformLocation(reliefMapShaderForward.handle, "depthMap"), 2); glUseProgram(0); srand(20); const int RELIEFS = 3; const u32 distance2 = 12; for (int i = 0; i < 36; i++) { app->ReliefRotationRate.push_back((float)std::rand() / (RAND_MAX) * 6.28 - 3.14); app->ReliefAngles.push_back(0.0f); } for (int x = -RELIEFS; x < RELIEFS; ++x) { for (int y = -RELIEFS; y < RELIEFS; ++y) { app->ReliefPositions.push_back(glm::vec3((float)x * (float)distance2, 15.0f, (float)y * (float)distance)); } } // FBO -------------- app->gFbo.Initialize(app->displaySize.x, app->displaySize.y); app->shadingFbo.Initialize(app->displaySize.x, app->displaySize.y); app->blurFbo.Initialize(app->displaySize.x, app->displaySize.y); } void Gui(App* app) { ImGui::BeginMainMenuBar(); if (ImGui::BeginMenu("App")) { if (ImGui::MenuItem("OpenGL info")) { app->show_opengl_info = true; } if (ImGui::MenuItem("Effects")) { app->show_effects = true; } ImGui::EndMenu(); } ImGui::EndMainMenuBar(); if (app->show_opengl_info) { ImGui::Begin("Info", &app->show_opengl_info); // FPS information ------------------ ImGui::Text("FPS: %f", 1.0f / app->deltaTime); // OpenGL information ------------------ ImGui::Text("OpenGL version: %s", app->info.version.c_str()); ImGui::Text("OpenGL renderer: %s", app->info.renderer.c_str()); ImGui::Text("GPU vendor: %s", app->info.vendor.c_str()); ImGui::Text("GLSL version: %s", app->info.shadingLanguageVersion.c_str()); //for (int i = 0; i < app->info.extensions.size(); ++i) //ImGui::Text("Extension %i: %s", i, app->info.extensions[i].c_str()); // Camera information ------------------- ImGui::Separator(); ImGui::Text("Camera"); ImGui::PushItemWidth(100); ImGui::DragFloat("X", &app->camera.position.x); ImGui::SameLine(); ImGui::DragFloat("Y", &app->camera.position.y); ImGui::SameLine(); ImGui::DragFloat("Z", &app->camera.position.z); ImGui::PopItemWidth(); ImGui::PushItemWidth(80); ImGui::DragFloat("Yaw", &app->camera.yaw); ImGui::SameLine(); ImGui::DragFloat("Pitch", &app->camera.pitch); ImGui::SameLine(); ImGui::DragFloat("Roll", &app->camera.roll); ImGui::PopItemWidth(); // Render Pipeline information ------------------- ImGui::Separator(); ImGui::Text("Render Pipeline"); const char* items_pipeline_list[] = { "Forward Shading", "Deferred Shading" }; static int item_pipeline = (int)app->render_pipeline; if (ImGui::Combo("Render Pipeline", &item_pipeline, items_pipeline_list, IM_ARRAYSIZE(items_pipeline_list))) { app->render_pipeline = (RenderPipeline)item_pipeline; } // Render target information ------------------- static int item_current = 0; if (app->render_pipeline == RenderPipeline::DEFERRED) { ImGui::Separator(); ImGui::Text("Render Targets"); const char* items[] = { "Default", "G_Position", "G_Normals", "G_Albedo", "Depth Texture", "Bright Color Texture", "Blurred Bloom Texture" }; if (ImGui::Combo("Render Target", &item_current, items, IM_ARRAYSIZE(items))) { app->displayedTexture = (RenderTargetType)item_current; } } else if (app->render_pipeline == RenderPipeline::FORWARD) { item_current = 0; app->displayedTexture = RenderTargetType::RENDER_TEXTURE; } // Light information ------------------- ImGui::Separator(); ImGui::Text("Lights"); ImGui::Spacing(); if (ImGui::TreeNode("Directional Lights")) { int j = 1; for (int i = 0; i < app->lights.size(); ++i) { if (app->lights[i].type == LightType::LIGHT_TYPE_DIRECTIONAL) { ImGui::PushID(i); ImGui::Text("Directional Light %d", j); ImGui::ColorEdit3("color", glm::value_ptr(app->lights[i].color), ImGuiColorEditFlags_::ImGuiColorEditFlags_Uint8); ImGui::DragFloat3("direction", glm::value_ptr(app->lights[i].direction), 0.01f); ImGui::DragInt("intensity", (int*)&app->lights[i].intensity, 0.5f, 0, 100); j++; ImGui::PopID(); } //ImGui::NewLine(); } ImGui::TreePop(); } if (ImGui::TreeNode("Point Lights")) { int j = 1; for (int i = 0; i < app->lights.size(); ++i) { if (app->lights[i].type == LightType::LIGHT_TYPE_POINT) { ImGui::PushID(i); ImGui::Text("Point Light %d", j); ImGui::ColorEdit3("color", glm::value_ptr(app->lights[i].color), ImGuiColorEditFlags_::ImGuiColorEditFlags_Uint8); ImGui::DragFloat3("position", glm::value_ptr(app->lights[i].position), 0.01f); ImGui::DragInt("intensity", (int*)&app->lights[i].intensity, 0.5f, 0, 100); j++; ImGui::PopID(); } //ImGui::NewLine(); } ImGui::TreePop(); } ImGui::End(); } if (app->show_effects) { ImGui::Begin("Effects", &app->show_effects); ImGui::Text("Relief Mapping"); ImGui::Spacing(); ImGui::Checkbox("Clip borders", &app->clip_borders); ImGui::Checkbox("Rotate", &app->rotate); ImGui::SliderFloat("Height Scale", &app->heigth_scale, 0.0f, 1.f); ImGui::SliderInt("Min layers", &app->min_layers, 0.0f, 100.f); ImGui::SliderInt("Max layers", &app->max_layers, 0.0f, 100.f); ImGui::SliderInt("Textures", &app->reliefIdx, 1.0f, 5.f); ImGui::Separator(); ImGui::Text("Bloom"); ImGui::Spacing(); ImGui::Checkbox("Bloom", &app->using_bloom); ImGui::DragInt("Blur Iterations", &app->blurIterations, 2.0f, 0, 50); ImGui::DragFloat("Threshold", &app->bright_threshold, 0.05f, 0.0f, 20.f); ImGui::End(); } } void Update(App* app) { // You can handle app->input keyboard/mouse here app->camera.Update(app); // Resize window if (app->lastFrameDisplaySize != app->displaySize) { app->gFbo.Resize(app->displaySize.x, app->displaySize.y); app->shadingFbo.Resize(app->displaySize.x, app->displaySize.y); app->blurFbo.Resize(app->displaySize.x, app->displaySize.y); } app->lastFrameDisplaySize = app->displaySize; // Global params MapBuffer(app->gpBuffer, GL_WRITE_ONLY); app->globalParamsOffset = app->gpBuffer.head; PushVec3(app->gpBuffer, app->camera.position); PushUInt(app->gpBuffer, app->lights.size()); for (u32 i = 0; i < app->lights.size(); ++i) { AlignHead(app->gpBuffer, sizeof(vec4)); const Light& light = app->lights[i]; PushUInt(app->gpBuffer, static_cast<u32>(light.type)); PushVec3(app->gpBuffer, light.position); PushVec3(app->gpBuffer, light.color); PushVec3(app->gpBuffer, light.direction); PushUInt(app->gpBuffer, light.intensity); } app->globalParamsSize = app->gpBuffer.head - app->globalParamsOffset; UnmapBuffer(app->gpBuffer); //Update uniform blocks ------ MapBuffer(app->ubuffer, GL_WRITE_ONLY); for (int i = 0; i < app->entities.size(); ++i) { app->ubuffer.head = Align(app->ubuffer.head, app->uniformBlockAlignment); app->entities[i].localParamsOffset = app->ubuffer.head; app->worldMatrix = app->entities[i].worldMatrix; app->worldViewProjectionMatrix = app->camera.projectionMatrix * app->camera.viewMatrix * app->entities[i].worldMatrix; PushMat4(app->ubuffer, app->worldMatrix); PushMat4(app->ubuffer, app->worldViewProjectionMatrix); app->entities[i].localParamsSize = app->ubuffer.head - app->entities[i].localParamsOffset; } UnmapBuffer(app->ubuffer); } void renderQuad(); void renderQuadTangentSpace(); void BindReliefTextures(int reliefIndex, App* app); u32 GetFinalTextureToRender(App* app); void Render(App* app) { switch (app->render_pipeline) { case RenderPipeline::DEFERRED: RenderUsingDeferredPipeline(app); break; case RenderPipeline::FORWARD: RenderUsingForwardPipeline(app); break; default: break; } } void RenderUsingDeferredPipeline(App* app) { // Clear the screen (also ImGui...) glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, app->displaySize.x, app->displaySize.y); glEnable(GL_DEPTH_TEST); app->gFbo.Bind(); // --------------------------------------- RELIEF MAPPING ------------------------------------- RenderReliefMapping(app, app->programs[app->reliefMapShaderID], true); // --------------------------------------- RENDERING ENTITIES ------------------------------------- RenderEntities(app, app->programs[app->geometryPassShaderID]); app->gFbo.Unbind(); // --------------------------------------- SHADING PASS ------------------------------------- glDisable(GL_DEPTH_TEST); app->shadingFbo.Bind(); Program& shaderPassProgram = app->programs[app->shadingPassShaderID]; glUseProgram(shaderPassProgram.handle); glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(0), app->gpBuffer.handle, app->globalParamsOffset, app->globalParamsSize); glUniform1i(app->programShadingPassUniformTexturePosition, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, app->gFbo.GetTexture(G_POSITION_TEXTURE)); glUniform1i(app->programShadingPassUniformTextureNormals, 1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, app->gFbo.GetTexture(G_NORMALS_TEXTURE)); glUniform1i(app->programShadingPassUniformTextureAlbedo, 2); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, app->gFbo.GetTexture(G_ALBEDO_TEXTURE)); glUniform1i(app->programShadingPassUniformTextureDepth, 3); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, app->gFbo.GetTexture(DEPTH_TEXTURE)); glUniform1f(glGetUniformLocation(shaderPassProgram.handle, "bright_color_threshold"), app->bright_threshold); renderQuad(); app->shadingFbo.Unbind(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); glEnable(GL_DEPTH_TEST); // --------------------------------------- LIGHTS RENDERING -------------------------------------- // ================ COPY DEPTH ATTACHMENT ================ glBindFramebuffer(GL_READ_FRAMEBUFFER, app->gFbo.GetTexture(FBO)); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, app->shadingFbo.GetTexture(FBO)); // write to default framebuffer glBlitFramebuffer(0, 0, app->displaySize.x, app->displaySize.y, 0, 0, app->displaySize.x, app->displaySize.y, GL_DEPTH_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_FRAMEBUFFER, 0); // ================ RENDER LIGHT MESHES ================ app->shadingFbo.Bind(false); RenderLights(app, app->programs[app->lightsShaderID]); app->shadingFbo.Unbind(); // --------------------------------------- BLOOM PASS ------------------------------------- Program& blurShader = app->programs[app->blurShaderID]; app->blurFbo.BlurImage(app->blurIterations, app->shadingFbo.GetTexture(BRIGHT_COLOR_TEXTURE), blurShader, renderQuad); // --------------------------------------- RENDER SCREEN QUAD ------------------------------------- FinalRenderPass(app); // ------------------------------------------------------------------------------------------------- } void RenderUsingForwardPipeline(App* app) { glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, app->displaySize.x, app->displaySize.y); glEnable(GL_DEPTH_TEST); // ------------------------ ENTITIES ------------------------------------- app->shadingFbo.Bind(); RenderReliefMapping(app, app->programs[app->reliefMapShaderForwardID], false); RenderEntities(app, app->programs[app->texturedMeshProgramIdx]); app->shadingFbo.Unbind(); // ------------------------ LIGHTS ------------------------------------- app->shadingFbo.Bind(false); RenderLights(app, app->programs[app->lightsShaderID]); app->shadingFbo.Unbind(); // ------------------------ BLOOM PASS ------------------------------------- Program& blurShader = app->programs[app->blurShaderID]; app->blurFbo.BlurImage(app->blurIterations, app->shadingFbo.GetTexture(BRIGHT_COLOR_TEXTURE), blurShader, renderQuad); // ------------------------ FINAL PASS ------------------------------------- FinalRenderPass(app); } void RenderReliefMapping(App* app, const Program& program, bool deferred_rendering) { Program reliefMapShading = program; glUseProgram(reliefMapShading.handle); glUniformMatrix4fv(glGetUniformLocation(reliefMapShading.handle, "projection"), 1, GL_FALSE, (GLfloat*)&app->camera.projectionMatrix); glUniformMatrix4fv(glGetUniformLocation(reliefMapShading.handle, "view"), 1, GL_FALSE, (GLfloat*)&app->camera.viewMatrix); if (deferred_rendering) { glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(0), app->gpBuffer.handle, app->globalParamsOffset, app->globalParamsSize); } glUniform3f(glGetUniformLocation(reliefMapShading.handle, "viewPos"), app->camera.position.x, app->camera.position.y, app->camera.position.z); glUniform3f(glGetUniformLocation(reliefMapShading.handle, "lightPos"), app->lights[0].position.x, app->lights[0].position.y, app->lights[0].position.z); glUniform1f(glGetUniformLocation(reliefMapShading.handle, "heightScale"), app->heigth_scale); glUniform1i(glGetUniformLocation(reliefMapShading.handle, "clipBorders"), app->clip_borders); glUniform1i(glGetUniformLocation(reliefMapShading.handle, "minLayers"), app->min_layers); glUniform1i(glGetUniformLocation(reliefMapShading.handle, "maxLayers"), app->max_layers); BindReliefTextures(app->reliefIdx, app); //for (int i = 0; i < 36; i++) //{ //modelMatrix = glm::rotate(modelMatrix, app->ReliefAngles[i] += app->ReliefRotationRate[i] * app->deltaTime, glm::vec3(1.0f, 0.50f, 0.70f)); //} glm::mat4 modelMatrix = glm::mat4(1.0f); modelMatrix = TransformPositionScale(vec3(0.f, 25.0f, 0.f), vec3(15.0f)); if (app->rotate) { modelMatrix = TransformRotation(modelMatrix, app->ReliefAngles[0] += app->ReliefRotationRate[0] * app->deltaTime * 5.0f, glm::vec3(1.0f, 0.50f, 0.70f)); } else { modelMatrix = glm::mat4(1.0f); modelMatrix = TransformPositionScale(vec3(0.f, 25.0f, 0.f), vec3(15.0f)); } glUniformMatrix4fv(glGetUniformLocation(reliefMapShading.handle, "model"), 1, GL_FALSE, (GLfloat*)&modelMatrix); renderQuadTangentSpace(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); } void RenderEntities(App* app, const Program& program) { Program renderMeshShader = program; glUseProgram(renderMeshShader.handle); glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(0), app->gpBuffer.handle, app->globalParamsOffset, app->globalParamsSize); for (int i = 0; i < app->entities.size(); ++i) { Model& model = app->models[app->entities[i].modelIndex]; Mesh& mesh = app->meshes[model.meshIdx]; glBindBufferRange(GL_UNIFORM_BUFFER, BINDING(1), app->ubuffer.handle, app->entities[i].localParamsOffset, app->entities[i].localParamsSize); for (u32 i = 0; i < mesh.submeshes.size(); ++i) { GLuint vao = FindVAO(mesh, i, renderMeshShader); glBindVertexArray(vao); u32 submeshMaterialIdx = model.materialIdx[i]; Material& submeshMaterial = app->materials[submeshMaterialIdx]; glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, app->textures[submeshMaterial.albedoTextureIdx].handle); glUniform1i(app->texturedMeshProgram_uTexture, 0); Submesh& submesh = mesh.submeshes[i]; glDrawElements(GL_TRIANGLES, submesh.indices.size(), GL_UNSIGNED_INT, (void*)(u64)submesh.indexOffset); } } glBindTexture(GL_TEXTURE_2D, 0); glBindVertexArray(0); glUseProgram(0); } void RenderLights(App* app, const Program& shader) { Program lightsShader = shader; glUseProgram(lightsShader.handle); for (u32 i = 0; i < app->lights.size(); ++i) { // ------------------ Model ------------------ u32 modelIndex = 0U; glm::mat4 worldMatrix; switch (app->lights[i].type) { case LightType::LIGHT_TYPE_DIRECTIONAL: modelIndex = app->plane; worldMatrix = TransformPositionScale(app->lights[i].position, vec3(3.0f, 3.0f, 3.0f)); worldMatrix = TransformRotation(worldMatrix, 90.0, vec3(1.f, 0.f, 0.f)); //worldMatrix += app->lights[i].CalculateLightRotation(); //worldMatrix += glm::lookAt(app->lights[i].position, app->lights[i].position + app->lights[i].direction, vec3(0, 1, 0)); // Translate it here break; case LightType::LIGHT_TYPE_POINT: modelIndex = app->sphere; worldMatrix = TransformPositionScale(app->lights[i].position, vec3(0.3f, 0.3f, 0.3f)); break; } // ------------------ Uniforms ------------------ glm::mat4 worldViewProjectionMatrix = app->camera.projectionMatrix * app->camera.viewMatrix * worldMatrix; glUniformMatrix4fv(app->programLightsUniformWorldMatrix, 1, GL_FALSE, (GLfloat*)&worldViewProjectionMatrix); glUniform3f(app->programLightsUniformColor, app->lights[i].color.x, app->lights[i].color.y, app->lights[i].color.z); // ---------------------------------------------- Mesh& mesh = app->meshes[app->models[modelIndex].meshIdx]; GLuint vao = FindVAO(mesh, 0, lightsShader); glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, mesh.submeshes[0].indices.size(), GL_UNSIGNED_INT, (void*)(u64)mesh.submeshes[0].indexOffset); } } void FinalRenderPass(App* app) { Program& finalPassShader = app->programs[app->finalPassShaderIdx]; glUseProgram(finalPassShader.handle); glUniform1i(glGetUniformLocation(finalPassShader.handle, "using_bloom"), app->using_bloom); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, GetFinalTextureToRender(app)); if (app->using_bloom && app->displayedTexture == RENDER_TEXTURE) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, app->blurFbo.GetBlurredTexture()); } renderQuad(); glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); } unsigned int quadVAO2 = 0; unsigned int quadVBO2; void renderQuadTangentSpace() { if (quadVAO2 == 0) { // positions glm::vec3 pos1(-1.0f, 1.0f, 0.0f); glm::vec3 pos2(-1.0f, -1.0f, 0.0f); glm::vec3 pos3(1.0f, -1.0f, 0.0f); glm::vec3 pos4(1.0f, 1.0f, 0.0f); // texture coordinates glm::vec2 uv1(0.0f, 1.0f); glm::vec2 uv2(0.0f, 0.0f); glm::vec2 uv3(1.0f, 0.0f); glm::vec2 uv4(1.0f, 1.0f); // normal vector glm::vec3 nm(0.0f, 0.0f, 1.0f); // calculate tangent/bitangent vectors of both triangles glm::vec3 tangent1, bitangent1; glm::vec3 tangent2, bitangent2; // triangle 1 // ---------- glm::vec3 edge1 = pos2 - pos1; glm::vec3 edge2 = pos3 - pos1; glm::vec2 deltaUV1 = uv2 - uv1; glm::vec2 deltaUV2 = uv3 - uv1; float f = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV2.x * deltaUV1.y); tangent1.x = f * (deltaUV2.y * edge1.x - deltaUV1.y * edge2.x); tangent1.y = f * (deltaUV2.y * edge1.y - deltaUV1.y * edge2.y); tangent1.z = f * (deltaUV2.y * edge1.z - deltaUV1.y * edge2.z); tangent1 = glm::normalize(tangent1); bitangent1.x = f * (-deltaUV2.x * edge1.x + deltaUV1.x * edge2.x); bitangent1.y = f * (-deltaUV2.x * edge1.y + deltaUV1.x * edge2.y); bitangent1.z = f * (-deltaUV2.x * edge1.z + deltaUV1.x * edge2.z); bitangent1 = glm::normalize(bitangent1); // triangle 2 // ---------- edge1 = pos3 - pos1; edge2 = pos4 - pos1; deltaUV1 = uv3 - uv1; deltaUV2 = uv4 - uv1; f = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV2.x * deltaUV1.y); tangent2.x = f * (deltaUV2.y * edge1.x - deltaUV1.y * edge2.x); tangent2.y = f * (deltaUV2.y * edge1.y - deltaUV1.y * edge2.y); tangent2.z = f * (deltaUV2.y * edge1.z - deltaUV1.y * edge2.z); tangent2 = glm::normalize(tangent2); bitangent2.x = f * (-deltaUV2.x * edge1.x + deltaUV1.x * edge2.x); bitangent2.y = f * (-deltaUV2.x * edge1.y + deltaUV1.x * edge2.y); bitangent2.z = f * (-deltaUV2.x * edge1.z + deltaUV1.x * edge2.z); bitangent2 = glm::normalize(bitangent2); float quadVertices[] = { // positions // normal // texcoords // tangent // bitangent pos1.x, pos1.y, pos1.z, nm.x, nm.y, nm.z, uv1.x, uv1.y, tangent1.x, tangent1.y, tangent1.z, bitangent1.x, bitangent1.y, bitangent1.z, pos2.x, pos2.y, pos2.z, nm.x, nm.y, nm.z, uv2.x, uv2.y, tangent1.x, tangent1.y, tangent1.z, bitangent1.x, bitangent1.y, bitangent1.z, pos3.x, pos3.y, pos3.z, nm.x, nm.y, nm.z, uv3.x, uv3.y, tangent1.x, tangent1.y, tangent1.z, bitangent1.x, bitangent1.y, bitangent1.z, pos1.x, pos1.y, pos1.z, nm.x, nm.y, nm.z, uv1.x, uv1.y, tangent2.x, tangent2.y, tangent2.z, bitangent2.x, bitangent2.y, bitangent2.z, pos3.x, pos3.y, pos3.z, nm.x, nm.y, nm.z, uv3.x, uv3.y, tangent2.x, tangent2.y, tangent2.z, bitangent2.x, bitangent2.y, bitangent2.z, pos4.x, pos4.y, pos4.z, nm.x, nm.y, nm.z, uv4.x, uv4.y, tangent2.x, tangent2.y, tangent2.z, bitangent2.x, bitangent2.y, bitangent2.z }; // configure plane VAO glGenVertexArrays(1, &quadVAO2); glGenBuffers(1, &quadVBO2); glBindVertexArray(quadVAO2); glBindBuffer(GL_ARRAY_BUFFER, quadVBO2); glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 14 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(float), (void*)(8 * sizeof(float))); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(float), (void*)(11 * sizeof(float))); } glBindVertexArray(quadVAO2); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); } void BindReliefTextures(int reliefIndex, App* app) { switch (reliefIndex) { case 1: glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[0]].handle); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[1]].handle); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[2]].handle); break; case 2: glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[3]].handle); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[4]].handle); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[5]].handle); break; case 3: glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[6]].handle); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[7]].handle); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[8]].handle); break; case 4: glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[9]].handle); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[10]].handle); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[11]].handle); break; case 5: glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[12]].handle); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[13]].handle); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, app->textures[app->reliefTextures[14]].handle); break; } } unsigned int quadVAO = 0; unsigned int quadVBO; void renderQuad() { if (quadVAO == 0) { float quadVertices[] = { // positions // texture Coords -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, }; // setup plane VAO glGenVertexArrays(1, &quadVAO); glGenBuffers(1, &quadVBO); glBindVertexArray(quadVAO); glBindBuffer(GL_ARRAY_BUFFER, quadVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); } glBindVertexArray(quadVAO); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); } GLuint FindVAO(Mesh& mesh, u32 submeshIndex, const Program& program) { Submesh& submesh = mesh.submeshes[submeshIndex]; // Try finding a vao for this submesh/program for (u32 i = 0; i < (u32)submesh.vaos.size(); ++i) { if (submesh.vaos[i].programHandle == program.handle) return submesh.vaos[i].handle; } GLuint vaoHandle = 0; // Create a new vao for this submesh/program glGenVertexArrays(1, &vaoHandle); glBindVertexArray(vaoHandle); glBindBuffer(GL_ARRAY_BUFFER, mesh.vertexBufferHandle); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.indexBufferHandle); // We have to link all vertex inputs attributes to attributes in the vertex buffer for (u32 i = 0; i < program.vertexInputLayout.attributes.size(); ++i) { bool attributeWasLinked = false; for (u32 j = 0; j < submesh.vertexBufferLayout.attributes.size(); ++j) { if (program.vertexInputLayout.attributes[i].location == submesh.vertexBufferLayout.attributes[j].location) { const u32 index = submesh.vertexBufferLayout.attributes[j].location; const u32 ncomp = submesh.vertexBufferLayout.attributes[j].componentCount; const u32 offset = submesh.vertexBufferLayout.attributes[j].offset + submesh.vertexOffset; // attribute offset + vertex offset const u32 stride = submesh.vertexBufferLayout.stride; glVertexAttribPointer(index, ncomp, GL_FLOAT, GL_FALSE, stride, (void*)(u64)offset); glEnableVertexAttribArray(index); attributeWasLinked = true; break; } } assert(attributeWasLinked); // The submesh should provide an attribute for each vertex inputs } glBindVertexArray(0); // Store it in the list of vaos for this submesh Vao vao = { vaoHandle, program.handle }; submesh.vaos.push_back(vao); return vaoHandle; } glm::mat4 TransformScale(const vec3& scaleFactors) { glm::mat4 transform = scale(scaleFactors); return scale(scaleFactors); } glm::mat4 TransformPositionScale(const vec3& pos, const vec3& scaleFactors) { glm::mat4 transform = translate(pos); transform = scale(transform, scaleFactors); return transform; } glm::mat4 TransformRotation(const glm::mat4& matrix, float angle, vec3 axis) { float radians = glm::radians(angle); glm::mat4 transform = glm::rotate(matrix, radians, axis); return transform; } vec3 GenerateRandomBrightColor() { int rgb[3]; rgb[0] = std::rand() % 256; // red rgb[1] = std::rand() % 256; // green rgb[2] = std::rand() % 256; // blue // find max and min indexes. int max, min; if (rgb[0] > rgb[1]) { max = (rgb[0] > rgb[2]) ? 0 : 2; min = (rgb[1] < rgb[2]) ? 1 : 2; } else { max = (rgb[1] > rgb[2]) ? 1 : 2; int notmax = 1 + max % 2; min = (rgb[0] < rgb[notmax]) ? 0 : notmax; } rgb[max] = 255; rgb[min] = 0; return vec3((float)rgb[0], (float)rgb[1], (float)rgb[2]) / 255.f; } u32 GetFinalTextureToRender(App* app) { u32 texture = 0U; if (app->displayedTexture == RENDER_TEXTURE || app->displayedTexture == BRIGHT_COLOR_TEXTURE) { texture = app->shadingFbo.GetTexture(app->displayedTexture); } else if (app->displayedTexture == BLURRED_TEXTURE) { texture = app->blurFbo.GetBlurredTexture(); } else { texture = app->gFbo.GetTexture(app->displayedTexture); } return texture; }
33.693687
160
0.696246
[ "mesh", "render", "vector", "model", "transform" ]
d807b597e075e77cad6c8ab00312474e7aec9995
3,656
cpp
C++
src/state.cpp
ebassi/node-clutter
760b8f5704a216dcd633658051c0778151b21391
[ "MIT" ]
1
2017-08-31T00:58:33.000Z
2017-08-31T00:58:33.000Z
src/state.cpp
ebassi/node-clutter
760b8f5704a216dcd633658051c0778151b21391
[ "MIT" ]
null
null
null
src/state.cpp
ebassi/node-clutter
760b8f5704a216dcd633658051c0778151b21391
[ "MIT" ]
null
null
null
#include <v8.h> #include <node.h> #include <clutter/clutter.h> #include "clutter.hpp" #include "actor.hpp" #include "state.hpp" namespace clutter { using namespace node; using namespace v8; State::State() : node::ObjectWrap() { _state = clutter_state_new(); } void State::Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->InstanceTemplate()->SetInternalFieldCount(1); Local<String> name = String::NewSymbol("State"); /* Methods */ State::PrototypeMethodsInit(tpl); target->Set(name, tpl->GetFunction()); } void State::PrototypeMethodsInit(Handle<FunctionTemplate> constructor_template) { HandleScope scope; /* Inherit methods from Actor */ Actor::PrototypeMethodsInit(constructor_template); NODE_SET_PROTOTYPE_METHOD(constructor_template, "set", State::Set); NODE_SET_PROTOTYPE_METHOD(constructor_template, "setState", State::SetState); } /* ECMAScript constructor */ Handle<Value> State::New(const Arguments& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use the new operator to create instances of this object.")) ); } // Creates a new instance object of this type and wraps it. State* obj = new State(); obj->Wrap(args.This()); /* Set duration */ ClutterState *instance = obj->_state; if (args[0]->IsNumber()) { clutter_state_set_duration(CLUTTER_STATE(instance), NULL, NULL, args[0]->ToInteger()->Value()); } return args.This(); } Handle<Value> State::Set(const Arguments &args) { HandleScope scope; Local<Value> SourceStateName; Local<Value> TargetStateName; Local<Value> Settings; ClutterAnimator *animator; GValue gvalue = {0}; ClutterState *instance = ObjectWrap::Unwrap<State>(args.This())->_state; if (args.Length() == 2) { TargetStateName = args[0]; Settings = args[1]; } else if (args.Length() == 3) { SourceStateName = args[0]; TargetStateName = args[1]; Settings = args[2]; } else { return args.This(); } if (TargetStateName->IsString() && Settings->IsObject()) { Local<Array> settings = Local<Array>::Cast(Settings->ToObject()); for (int i = 0; i < settings->Length(); ++i) { Local<Array> obj = Local<Array>::Cast(settings->Get(i)->ToObject()); /* [ actor, property, alpha, value ] ] */ ClutterActor *actor = ObjectWrap::Unwrap<Actor>(obj->Get(0)->ToObject())->_actor; Local<Value> PropertyName = obj->Get(1); Local<Value> Alpha = obj->Get(2); Local<Value> Value = obj->Get(3); if (!PropertyName->IsString() || !Value->IsNumber()) { continue; } /* Prepare Value */ ObjectWrap::Unwrap<Actor>(obj->Get(0)->ToObject())->PropertyValueInit(&gvalue, PropertyName, Value); if (args.Length() == 2) { clutter_state_set_key(instance, NULL, *String::AsciiValue(TargetStateName->ToString()), G_OBJECT(actor), *String::AsciiValue(PropertyName->ToString()), Alpha->ToInteger()->Value(), &gvalue, 0, 0); } else { clutter_state_set(instance, *String::AsciiValue(SourceStateName->ToString()), *String::AsciiValue(TargetStateName->ToString()), G_OBJECT(actor), *String::AsciiValue(PropertyName->ToString()), Alpha->ToInteger()->Value(), &gvalue, 0, 0); } g_value_unset(&gvalue); } } return args.This(); } Handle<Value> State::SetState(const Arguments &args) { HandleScope scope; if (args[0]->IsString()) { ClutterState *instance = ObjectWrap::Unwrap<State>(args.This())->_state; clutter_state_set_state(instance, *String::AsciiValue(args[0]->ToString())); } return args.This(); } }
24.211921
103
0.678337
[ "object" ]
d80d24e0de9136d61ca47f019f250d00cb16d671
773
hpp
C++
include/natalie_parser/node/fixnum_node.hpp
natalie-lang/natalie_parser
683bec34f8708f5b9160359ca0107edda242fdb9
[ "MIT" ]
10
2022-03-14T14:57:17.000Z
2022-03-31T06:51:28.000Z
include/natalie_parser/node/fixnum_node.hpp
natalie-lang/natalie_parser
683bec34f8708f5b9160359ca0107edda242fdb9
[ "MIT" ]
1
2022-03-15T21:40:34.000Z
2022-03-16T02:05:41.000Z
include/natalie_parser/node/fixnum_node.hpp
natalie-lang/natalie_parser
683bec34f8708f5b9160359ca0107edda242fdb9
[ "MIT" ]
1
2022-03-15T20:24:53.000Z
2022-03-15T20:24:53.000Z
#pragma once #include "natalie_parser/node/node.hpp" #include "natalie_parser/node/node_with_args.hpp" #include "tm/hashmap.hpp" #include "tm/string.hpp" namespace NatalieParser { using namespace TM; class FixnumNode : public Node { public: FixnumNode(const Token &token, long long number) : Node { token } , m_number { number } { } virtual Type type() const override { return Type::Fixnum; } virtual bool is_numeric() const override { return true; } long long number() const { return m_number; } virtual void transform(Creator *creator) const override { creator->set_type("lit"); creator->append_fixnum(m_number); } void negate() { m_number *= -1; } protected: long long m_number; }; }
20.891892
63
0.659767
[ "transform" ]
d8126a614fc8c41271d1332ae12d4d20d53877e6
2,492
cpp
C++
pytorch/aten/src/ATen/native/quantized/cpu/qconv_unpack.cpp
raghavnauhria/whatmt
c20483a437c82936cb0fb8080925e37b9c4bba87
[ "MIT" ]
null
null
null
pytorch/aten/src/ATen/native/quantized/cpu/qconv_unpack.cpp
raghavnauhria/whatmt
c20483a437c82936cb0fb8080925e37b9c4bba87
[ "MIT" ]
1
2019-07-22T09:48:46.000Z
2019-07-22T09:48:46.000Z
pytorch/aten/src/ATen/native/quantized/cpu/qconv_unpack.cpp
raghavnauhria/whatmt
c20483a437c82936cb0fb8080925e37b9c4bba87
[ "MIT" ]
null
null
null
#include <ATen/ATen.h> #include <ATen/core/op_registration/op_registration.h> #include <ATen/cpp_custom_type_hack.h> #include <ATen/native/quantized/cpu/fbgemm_utils.h> namespace at { namespace native { namespace { /* * QConvPackWeightInt8 expects its input tensor to be in shape * [output_channels, kernel_height, kernel_width, input_channels/Groups] * Therefore, the unpacking of packed weight tensor using QConvUnpackWeightsInt8 * results in a tensor of the same shape. */ class QConvUnpackWeightsInt8 final : public c10::OperatorKernel { public: #ifdef USE_FBGEMM Tensor operator()(Tensor packed_weights) { // Pull out the packed weight instance from the owning tensor. auto& pack_ptr = cpp_custom_type_hack::cast<PackedConvWeight>(packed_weights); auto packed_weights_p = pack_ptr.w.get(); // output channels int output_channels = packed_weights_p->numCols(); // R*S*C/G int KDim_pre_group = packed_weights_p->numRows() / packed_weights_p->numGroups(); // R (kernel height) int kernel_h = pack_ptr.kernel[0]; // S (kernel width) int kernel_w = pack_ptr.kernel[1]; int C_per_G = KDim_pre_group / kernel_h / kernel_w; // Tensor for unpacked weights // Unpacked format would be KRS auto unpacked_weights = _empty_affine_quantized( {output_channels, kernel_h, kernel_w, C_per_G}, device(kCPU).dtype(kQInt8), pack_ptr.w_scale, pack_ptr.w_zp); int8_t* unpacked_weights_p = reinterpret_cast<int8_t*>(unpacked_weights.data<c10::qint8>()); // packed_weights_p->printPackedMatrix("packed weights inside fbgemm_unpack // (QConvUnpackWeightInt8): "); packed_weights_p->unpack(unpacked_weights_p); return unpacked_weights; } #else // USE_FBGEMM Tensor operator()(Tensor /* weight */ ) { // We make a strong guarantee that models using these operators will have // the same numerics across different machines. Therefore, we do not provide // a fallback path and rather fail loudly if we cannot run FBGEMM. TORCH_CHECK( false, "This PyTorch installation was not built with FBGEMM operators"); } #endif // USE_FBGEMM }; static auto registry = c10::RegisterOperators().op( "quantized::fbgemm_conv_unpack(Tensor packed_weights)" " -> Tensor unpacked_weights", c10::RegisterOperators::options().kernel<QConvUnpackWeightsInt8>( CPUTensorId())); } // namespace } // namespace native } // namespace at
33.675676
80
0.715088
[ "shape" ]
d8197a6e7b331d831fbde7a84d3d6158b0c17684
640
cpp
C++
test/unit_tests/tests/05_sort_test.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
test/unit_tests/tests/05_sort_test.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
test/unit_tests/tests/05_sort_test.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
#include "setting.h" #include "math/sort.h" using namespace bacchus; TEST(SortAlgs, QuickSort) { std::vector<float> a = {3,8,5,7,1,6,2,9,4}; std::cout << "a: " << a << std::endl; quick_sort(a,0,9); std::cout << "b: " << a << std::endl; } TEST(SortAlgs, CombSort) { std::vector<float> a = {-45,86,-75,-20,44,-14,-12,0}; std::cout << "a: " << a << std::endl; combsort(a); std::cout << "b: " << a << std::endl; } TEST(SortAlgs, MergeSort) { } TEST(SortAlgs, Median) { int a[] = {3, 13, 7, 5, 21, 23, 39, 23, 40, 23, 14, 12, 56, 23, 29}; EXPECT_EQ(23, (int)find_median(a,sizeof(a)/sizeof(int))); }
22.857143
72
0.539063
[ "vector" ]
d82619a08273766724b24010ff29b45dfcad5798
4,188
cpp
C++
code/steps/source/model/pvu_models/pv_irradiance_model/fileirrd.cpp
cuihantao/steps
60327bf42299cb7117ed5907a931583d7cdf590d
[ "MIT" ]
1
2021-01-21T13:10:40.000Z
2021-01-21T13:10:40.000Z
code/steps/source/model/pvu_models/pv_irradiance_model/fileirrd.cpp
cuihantao/steps
60327bf42299cb7117ed5907a931583d7cdf590d
[ "MIT" ]
null
null
null
code/steps/source/model/pvu_models/pv_irradiance_model/fileirrd.cpp
cuihantao/steps
60327bf42299cb7117ed5907a931583d7cdf590d
[ "MIT" ]
1
2020-10-01T03:48:38.000Z
2020-10-01T03:48:38.000Z
#include "header/model/pvu_models/pv_irradiance_model/fileirrd.h" #include "header/basic/utility.h" #include "header/steps_namespace.h" #include <istream> #include <iostream> using namespace std; FILEIRRAD::FILEIRRAD(STEPS& toolkit) : PV_IRRADIANCE_MODEL(toolkit) { clear(); } FILEIRRAD::~FILEIRRAD() { } void FILEIRRAD::clear() { } void FILEIRRAD::copy_from_const_model(const FILEIRRAD& model) { set_toolkit(model.get_toolkit()); clear(); } FILEIRRAD::FILEIRRAD(const FILEIRRAD& model):PV_IRRADIANCE_MODEL(model.get_toolkit()) { copy_from_const_model(model); } FILEIRRAD& FILEIRRAD::operator=(const FILEIRRAD& model) { if(this==&model) return *this; copy_from_const_model(model); return (*this); } string FILEIRRAD::get_model_name() const { return "FILEIRRAD"; } void FILEIRRAD::set_solar_irradiance_serial_file(string file) { ; } string FILEIRRAD::get_solar_irradiance_serial_file() const { return ""; } bool FILEIRRAD::setup_model_with_steps_string_vector(vector<string>& data) { ostringstream osstream; osstream<<get_model_name()<<"::"<<__FUNCTION__<<"() is not fully supported to set up model with following data:"<<endl <<string_vector2csv(data); STEPS& toolkit = get_toolkit(); toolkit.show_information_with_leading_time_stamp(osstream); return false; } bool FILEIRRAD::setup_model_with_psse_string(string data) { vector<string> record = psse_dyr_string2steps_string_vector(data); return setup_model_with_steps_string_vector(record); } bool FILEIRRAD::setup_model_with_bpa_string(string data) { ostringstream osstream; osstream<<get_model_name()<<"::"<<__FUNCTION__<<"() is not fully supported to set up model with following data:"<<endl <<data; STEPS& toolkit = get_toolkit(); toolkit.show_information_with_leading_time_stamp(osstream); return false; } void FILEIRRAD::setup_block_toolkit_and_parameters() { ; } void FILEIRRAD::initialize() { setup_block_toolkit_and_parameters(); } void FILEIRRAD::run(DYNAMIC_MODE mode) { ostringstream osstream; osstream<<get_model_name()<<"::"<<__FUNCTION__<<"() is not necessary to call. Input mode is provided: "<<mode; STEPS& toolkit = get_toolkit(); toolkit.show_information_with_leading_time_stamp(osstream); } double FILEIRRAD::get_solar_irradiance_in_pu() { return 0.0; } double FILEIRRAD::get_solar_irradiance_direction_in_deg() { return 0.0; } void FILEIRRAD::check() { ; } void FILEIRRAD::report() { STEPS& toolkit = get_toolkit(); toolkit.show_information_with_leading_time_stamp(get_standard_psse_string()); } void FILEIRRAD::save() { ; } string FILEIRRAD::get_standard_psse_string() const { return ""; } void FILEIRRAD::prepare_model_data_table() { clear_model_data_table(); unsigned int i=0; add_model_data_name_and_index_pair("A", i); i++; } double FILEIRRAD::get_model_data_with_name(string par_name) const { par_name = string2upper(par_name); if(par_name=="A") return 0.0; return 0.0; } void FILEIRRAD::set_model_data_with_name(string par_name, double value) { par_name = string2upper(par_name); if(par_name=="A") return; return; } double FILEIRRAD::get_minimum_nonzero_time_constant_in_s() { return INFINITE_THRESHOLD; } void FILEIRRAD::prepare_model_internal_variable_table() { clear_model_internal_variable_table(); unsigned int i=0; add_model_inernal_variable_name_and_index_pair("", i); i++; } double FILEIRRAD::get_model_internal_variable_with_name(string var_name) { ostringstream osstream; osstream<<get_model_name()<<"::"<<__FUNCTION__<<"() has not been implemented. Input var_name is provided: "<<var_name; STEPS& toolkit = get_toolkit(); toolkit.show_information_with_leading_time_stamp(osstream); return 0.0; } string FILEIRRAD::get_dynamic_data_in_psse_format() const { return get_standard_psse_string(); } string FILEIRRAD::get_dynamic_data_in_bpa_format() const { return get_standard_psse_string(); } string FILEIRRAD::get_dynamic_data_in_steps_format() const { return get_standard_psse_string(); }
21.151515
122
0.732569
[ "vector", "model" ]
d8296aed613bbacac2dcc7ad785df163022f0d51
15,766
hpp
C++
packages/utility/core/src/Utility_HDF5File.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/utility/core/src/Utility_HDF5File.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/utility/core/src/Utility_HDF5File.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file Utility_HDF5File.hpp //! \author Alex Robinson //! \brief The hdf5 file class declaration //! //---------------------------------------------------------------------------// #ifndef UTILITY_HDF5_FILE_HPP #define UTILITY_HDF5_FILE_HPP // Std Lib Includes #include <string> #include <memory> #include <stdexcept> #include <sstream> #include <initializer_list> // Boost Includes #include <boost/noncopyable.hpp> // FRENSIE Includes #include "Utility_ExceptionCatchMacros.hpp" namespace Utility{ /*! The HDF5 file class * * This class wraps the H5::File object and provides a simplified interface * for querying file properties and for reading from and writing to files. * Objects of this class cannot be copied - use smart pointers instead. * \ingroup hdf5 */ class HDF5File : private boost::noncopyable { public: //! File opening modes enum OpenMode{ READ_ONLY, READ_WRITE, OVERWRITE, }; //! The exception class class Exception; //! Constructor HDF5File( const std::string& filename, const HDF5File::OpenMode mode = HDF5File::OVERWRITE ); //! Destructor virtual ~HDF5File(); //! Get the file name const std::string& getFilename() const throw(); //! Check if the group exists bool doesGroupExist( const std::string& path_to_group ) const throw(); //! Check if the group attribute exists bool doesGroupAttributeExist( const std::string& path_to_group, const std::string& attribute_name ) const throw(); //! Check if the data set exists bool doesDataSetExist( const std::string& path_to_data_set ) const throw(); //! Check if the data set attribute exists bool doesDataSetAttributeExist( const std::string& path_to_data_set, const std::string& attribute_name ) const throw(); //! Get the size of a data set HDF5_ENABLED_DISABLED_SWITCH(hsize_t,size_t) getDataSetSize( const std::string& path_to_data_set ) const; //! Get the size of a data set attribute HDF5_ENABLED_DISABLED_SWITCH(hsize_t,size_t) getDataSetAttributeSize( const std::string& path_to_data_set, const std::string& attribute_name ) const; //! Get the size of a group attribute HDF5_ENABLED_DISABLED_SWITCH(hsize_t,size_t) getGroupAttributeSize( const std::string& path_to_group, const std::string& attribute_name ) const; //! Create a group void createGroup( const std::string& path_to_group ); //! Create a hard link void createHardLink( const std::string& existing_object_path, const std::string& path_to_link ); //! Create a soft link void createSoftLink( const std::string& existing_object_path, const std::string& path_to_link ); //! Write data to a data set template<typename T> void writeToDataSet( const std::string& path_to_data_set, const T* data, const size_t size ); //! Write data to a data set template<typename T> void writeToDataSet( const std::string& path_to_data_set, const T& data ); //! Read data from a data set template<typename T> void readFromDataSet( const std::string& path_to_data_set, T* data, const size_t size ) const; //! Write data to a data set attribute template<typename T> void writeToDataSetAttribute( const std::string& path_to_data_set, const std::string& attribute_name, const T* data, const size_t size ); //! Write data to a data set attribute template<typename T> void writeToDataSetAttribute( const std::string& path_to_data_set, const std::string& attribute_name, const T& data ); //! Read data from a data set attribute template<typename T> void readFromDataSetAttribute( const std::string& path_to_data_set, const std::string& attribute_name, T* data, const size_t size ) const; //! Write data to a group attribute template<typename T> void writeToGroupAttribute( const std::string& path_to_group, const std::string& attribute_name, const T* data, const size_t size ); //! Write data to a group attribute template<typename T> void writeToGroupAttribute( const std::string& path_to_group, const std::string& attribute_name, const T& data ); //! Read data from a group attribute template<typename T> void readFromGroupAttribute( const std::string& path_to_group, const std::string& attribute_name, T* data, const size_t size ) const; protected: //! Write opaque data to a data set void writeToDataSet( const std::string& path_to_data_set, const void* data, const size_t size ); //! Read data from a data set void readFromDataSet( const std::string& path_to_data_set, void* data, const size_t size ) const; //! Write data to a data set attribute void writeToDataSetAttribute( const std::string& path_to_data_set, const std::string& attribute_name, const void* data, const size_t size ); //! Read data from a data set attribute void readFromDataSetAttribute( const std::string& path_to_data_set, const std::string& attribute_name, void* data, const size_t size ) const; //! Write data to a group attribute void writeToGroupAttribute( const std::string& path_to_group, const std::string& attribute_name, const void* data, const size_t size ); //! Read data from a group attribute void readFromGroupAttribute( const std::string& path_to_group, const std::string& attribute_name, void* data, const size_t size ) const; private: // Extract the parent group path std::string extractParentGroupPath( const std::string& path ) const; // Check if the parent group exists bool doesParentGroupExist( const std::string& path ) const; // Create the parent group, if necessary, for the specified path void createParentGroup( const std::string& path ); #ifdef HAVE_FRENSIE_HDF5 // Create a group void createGroup( const std::string& path_to_group, std::unique_ptr<const H5::Group>& group ); // Open a group void openGroup( const std::string& path_to_group, std::unique_ptr<const H5::Group>& group ) const; // Create a data set template<typename T> void createDataSet( const std::string& path_to_data_set, const size_t data_set_size, std::unique_ptr<H5::DataSet>& data_set ); // Open a data set void openDataSet( const std::string& path_to_data_set, std::unique_ptr<const H5::DataSet>& data_set ) const; // Create a data set attribute template<typename T> void createDataSetAttribute( const H5::DataSet& data_set, const std::string& data_set_name, const std::string& attribute_name, const size_t attribute_size, std::unique_ptr<H5::Attribute>& attribute ); // Open a data set attribute void openDataSetAttribute( const H5::DataSet& data_set, const std::string& data_set_name, const std::string& attribute_name, std::unique_ptr<const H5::Attribute>& attribute ) const; // Create a group attribute template<typename T> void createGroupAttribute( const H5::Group& group, const std::string& group_name, const std::string& attribute_name, const size_t attribute_size, std::unique_ptr<H5::Attribute>& attribute ); // Open a group attribute void openGroupAttribute( const H5::Group& group, const std::string& group_name, const std::string& attribute_name, std::unique_ptr<const H5::Attribute>& attribute ) const; // Get the size of a data set HDF5_ENABLED_DISABLED_SWITCH(hsize_t,size_t) getDataSetSize( const H5::DataSet& data_set ) const; //! Get the size of an attribute HDF5_ENABLED_DISABLED_SWITCH(hsize_t,size_t) getAttributeSize( const H5::Attribute& attribute ) const; //! Get the size of a data space HDF5_ENABLED_DISABLED_SWITCH(hsize_t,size_t) getDataSpaceSize( const H5::DataSpace& data_space ) const; //! Check if the group attribute exists bool doesGroupAttributeExist( const H5::Group& group, const std::string& attribute_name ) const; //! Check if the data set attribute exists bool doesDataSetAttributeExist( const H5::DataSet& data_set, const std::string& attribute_name ) const; // Check that the type matches the data set type template<typename T> bool doesDataSetTypeMatch( const T& data_type, const H5::DataSet& data_set ) const; // Check that the type matches the attribute type template<typename T> bool doesAttributeTypeMatch( const T& data_type, const H5::Attribute& attribute ) const; // Check if an array can store the contents of a data set template<typename ExternalT, typename InternalT> bool canArrayStoreDataSetContents( const InternalT* data, const size_t size, const H5::DataSet& data_set ) const; // Check if an array can store the contents of a data set attribute template<typename ExternalT, typename InternalT> bool canArrayStoreAttributeContents( const InternalT* data, const size_t size, const H5::Attribute& attribute ) const; #endif // end HAVE_FRENSIE_HDF5 // The filename std::string d_filename; // The HDF5 file object std::unique_ptr<HDF5_ENABLED_DISABLED_SWITCH(H5::H5File,int)> d_hdf5_file; }; /*! The HDF5File::Exception class * \ingroup hdf5 */ class HDF5File::Exception : public std::runtime_error { public: //! Constructor Exception( const std::string& message ); //! Constructor (extra details) Exception( const std::string& file, const size_t line, const std::string& hdf5_function_name, const std::string& hdf5_error_message, const std::string& message ); //! Destructor ~Exception() throw() { /* ... */ } private: // Create an error message static std::string createErrorMessage( const std::string& file, const size_t line, const std::string& hdf5_function_name, const std::string& hdf5_error_message, const std::string& message ); }; //! Write a container to a data set template<typename Container> void writeToDataSet( HDF5File& hdf5_file, const std::string& path_to_data_set, const Container& container ); //! Write an initializer list to a data set template<typename T> void writeToDataSet( HDF5File& hdf5_file, const std::string& path_to_data_set, std::initializer_list<T> container ); //! Write a container to a data set attribute template<typename Container> void writeToDataSetAttribute( HDF5File& hdf5_file, const std::string& path_to_data_set, const std::string& attribute_name, const Container& container ); //! Write an initializer list to a data set attribute template<typename T> void writeToDataSetAttribute( HDF5File& hdf5_file, const std::string& path_to_data_set, const std::string& attribute_name, std::initializer_list<T> container ); //! Write a container to a group attribute template<typename Container> void writeToGroupAttribute( HDF5File& hdf5_file, const std::string& path_to_group, const std::string& attribute_name, const Container& container ); //! Write an initializer list to a group attribute template<typename T> void writeToGroupAttribute( HDF5File& hdf5_file, const std::string& path_to_group, const std::string& attribute_name, std::initializer_list<T> container ); //! Read a container from a data set template<typename Container> void readFromDataSet( const HDF5File& hdf5_file, const std::string& path_to_data_set, Container& container ); //! Read a container from a data set attribute template<typename Container> void readFromDataSetAttribute( const HDF5File& hdf5_file, const std::string& path_to_data_set, const std::string& attribute_name, Container& container ); //! Read a container from a group attribute template<typename Container> void readFromGroupAttribute( const HDF5File& hdf5_file, const std::string& path_to_group, const std::string& attribute_name, Container& container ); } // end Utility namespace /*! Catch statement macro for catching an H5::Exception * \ingroup hdf5 */ #ifdef HAVE_FRENSIE_HDF5 #define HDF5_EXCEPTION_CATCH( raw_msg ) \ catch( const H5::Exception& exception ) \ { \ std::ostringstream msg; \ msg << raw_msg; \ \ throw HDF5File::Exception( __FILE__, __LINE__, exception.getFuncName(), exception.getDetailMsg(), msg.str() ); \ } #else #define HDF5_EXCEPTION_CATCH( raw_msg ) \ EXCEPTION_CATCH_RETHROW( std::runtime_error, raw_msg ) #endif // end HAVE_FRENSIE_HDF5 //---------------------------------------------------------------------------// // Template includes. //---------------------------------------------------------------------------// #include "Utility_HDF5File_def.hpp" //---------------------------------------------------------------------------// #endif // end UTILITY_HDF5_FILE_HPP //---------------------------------------------------------------------------// // end Utility_HDF5File.hpp //---------------------------------------------------------------------------//
37.627685
114
0.569834
[ "object" ]
d82c82f7dad3e9e26c16320668f1d5bee8f1815c
7,034
cpp
C++
packages/geometry/dagmc/src/Geometry_DagMCProperties.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/geometry/dagmc/src/Geometry_DagMCProperties.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/geometry/dagmc/src/Geometry_DagMCProperties.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file Geometry_DagMCProperties.cpp //! \author Alex Robinson //! \brief DagMC property keywords class definition. //! //---------------------------------------------------------------------------// // Std Lib Includes #include <sstream> // FRENSIE Includes #include "Geometry_DagMCProperties.hpp" #include "Utility_ExceptionTestMacros.hpp" #include "Utility_ContractException.hpp" namespace Geometry{ // Initialize the static member data std::string DagMCProperties::termination_cell_property = "termination.cell"; std::string DagMCProperties::material_property = "material"; std::string DagMCProperties::density_property = "density"; std::string DagMCProperties::estimator_property = "estimator"; std::string DagMCProperties::surface_current_name = "surface.current"; std::string DagMCProperties::surface_flux_name = "surface.flux"; std::string DagMCProperties::cell_pulse_height_name = "cell.pulse.height"; std::string DagMCProperties::cell_track_length_flux_name = "cell.tl.flux"; std::string DagMCProperties::cell_collision_flux_name = "cell.c.flux"; // Set the termination cell property name void DagMCProperties::setTerminationCellPropertyName( const std::string& name ) { // Make sure the name is valid testPrecondition( name.find( "_" ) >= name.size() ); DagMCProperties::termination_cell_property = name; } // Get the termination cell property name const std::string& DagMCProperties::getTerminationCellPropertyName() { return DagMCProperties::termination_cell_property; } // Set the material property name void DagMCProperties::setMaterialPropertyName( const std::string& name ) { // Make sure the name is valid testPrecondition( name.find( "_" ) >= name.size() ); DagMCProperties::material_property = name; } // Get the material property name const std::string& DagMCProperties::getMaterialPropertyName() { return DagMCProperties::material_property; } // Set the density property name void DagMCProperties::setDensityPropertyName( const std::string& name ) { // Make sure the name is valid testPrecondition( name.find( "_" ) >= name.size() ); DagMCProperties::density_property = name; } // Get the density property name const std::string& DagMCProperties::getDensityPropertyName() { return DagMCProperties::density_property; } // Set the estimator property name void DagMCProperties::setEstimatorPropertyName( const std::string& name ) { // Make sure the name is valid testPrecondition( name.find( "_" ) >= name.size() ); DagMCProperties::estimator_property = name; } // Get the estimator property name const std::string& DagMCProperties::getEstimatorPropertyName() { return DagMCProperties::estimator_property; } // Set the surface current name void DagMCProperties::setSurfaceCurrentName( const std::string& name ) { // Make sure the name is valid testPrecondition( name.find( "_" ) >= name.size() ); DagMCProperties::surface_current_name = name; } // Get the surface current name const std::string& DagMCProperties::getSurfaceCurrentName() { return DagMCProperties::surface_current_name; } // Set the surface flux name void DagMCProperties::setSurfaceFluxName( const std::string& name ) { // Make sure the name is valid testPrecondition( name.find( "_" ) >= name.size() ); DagMCProperties::surface_flux_name = name; } // Get the surface flux name const std::string& DagMCProperties::getSurfaceFluxName() { return DagMCProperties::surface_flux_name; } // Set the cell pulse height name void DagMCProperties::setCellPulseHeightName( const std::string& name ) { // Make sure the name is valid testPrecondition( name.find( "_" ) >= name.size() ); DagMCProperties::cell_pulse_height_name = name; } // Get the cell pulse height name const std::string& DagMCProperties::getCellPulseHeightName() { return DagMCProperties::cell_pulse_height_name; } // Set the cell track-length flux name void DagMCProperties::setCellTrackLengthFluxName( const std::string& name ) { // Make sure the name is valid testPrecondition( name.find( "_" ) >= name.size() ); DagMCProperties::cell_track_length_flux_name = name; } // Get the cell pulse height name const std::string& DagMCProperties::getCellTrackLengthFluxName() { return DagMCProperties::cell_track_length_flux_name; } // Set the cell collision flux name void DagMCProperties::setCellCollisionFluxName( const std::string& name ) { // Make sure the name is valid testPrecondition( name.find( "_" ) >= name.size() ); DagMCProperties::cell_collision_flux_name = name; } // Get the cell collision flux name const std::string& DagMCProperties::getCellCollisionFluxName() { return DagMCProperties::cell_collision_flux_name; } // Extract estimator property values /*! \details An estimator property is assumed to have the form * id.type.ptype */ void DagMCProperties::extractEstimatorPropertyValues( const std::string& prop_value, unsigned& estimator_id, std::string& estimator_type, std::string& particle_type ) { unsigned first_pos = prop_value.find_first_of( "." ); unsigned last_pos = prop_value.find_last_of( "." ); std::string id_string = prop_value.substr( 0, first_pos ); std::istringstream iss( id_string ); iss >> estimator_id; estimator_type = prop_value.substr( first_pos+1, last_pos-first_pos-1 ); particle_type = prop_value.substr( last_pos+1, prop_value.size()-last_pos-1); } // Check if the cell estimator type is valid bool DagMCProperties::isCellEstimatorTypeValid( const std::string& estimator_type ) { return estimator_type.compare(DagMCProperties::cell_pulse_height_name)== 0 || estimator_type.compare(DagMCProperties::cell_track_length_flux_name)== 0 || estimator_type.compare( DagMCProperties::cell_collision_flux_name ) == 0; } // Check if the surface estimator type is valid bool DagMCProperties::isSurfaceEstimatorTypeValid( const std::string& estimator_type ) { return estimator_type.compare( DagMCProperties::surface_flux_name ) == 0 || estimator_type.compare( DagMCProperties::surface_current_name ) == 0; } // Check if the particle type is valid bool DagMCProperties::isParticleTypeValid( const std::string& particle_type ) { return particle_type.compare( "n" ) == 0 || particle_type.compare( "p" ) == 0 || particle_type.compare( "e" ) == 0; } // Get all of the properties void DagMCProperties::getProperties( std::vector<std::string>& properties ) { properties.clear(); properties.resize( 4 ); properties[0] = DagMCProperties::termination_cell_property; properties[1] = DagMCProperties::material_property; properties[2] = DagMCProperties::density_property; properties[3] = DagMCProperties::estimator_property; } } // end Geometry namespace //---------------------------------------------------------------------------// // end Geometry_DagMCProperties.cpp //---------------------------------------------------------------------------//
30.450216
79
0.716378
[ "geometry", "vector" ]
d82dd82eaace40bfa47020642dc5de5c9ae1a6cf
3,028
hpp
C++
packages/monte_carlo/collision/photon/src/MonteCarlo_LineEnergyAdjointPhotonScatteringDistributionNativeFactory.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/collision/photon/src/MonteCarlo_LineEnergyAdjointPhotonScatteringDistributionNativeFactory.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/collision/photon/src/MonteCarlo_LineEnergyAdjointPhotonScatteringDistributionNativeFactory.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_LineEnergyAdjointPhotonScatteringDistributionNativeFactory.hpp //! \author Alex Robinson //! \brief The line energy adjoint photon scattering distribution native //! factory class declaration //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_LINE_ENERGY_ADJOINT_PHOTON_SCATTERING_DISTRIBUTION_NATIVE_FACTORY_HPP #define MONTE_CARLO_LINE_ENERGY_ADJOINT_PHOTON_SCATTERING_DISTRIBUTION_NATIVE_FACTORY_HPP // Std Lib Includes #include <memory> // FRENSIE Includes #include "MonteCarlo_LineEnergyAdjointPhotonScatteringDistribution.hpp" #include "Data_AdjointElectronPhotonRelaxationDataContainer.hpp" namespace MonteCarlo{ /*! \brief The line energy adjoint photon scattering distribution factory * class that uses native data */ class LineEnergyAdjointPhotonScatteringDistributionNativeFactory { private: // This type typedef LineEnergyAdjointPhotonScatteringDistributionNativeFactory ThisType; public: //! Create the pair production distribution static void createPairProductionDistribution( const Data::AdjointElectronPhotonRelaxationDataContainer& raw_adjoint_photoatom_data, std::shared_ptr<LineEnergyAdjointPhotonScatteringDistribution>& pair_production_distribution, double& cross_section_value, const double max_energy ); //! Create the triplet production distribution static void createTripletProductionDistribution( const Data::AdjointElectronPhotonRelaxationDataContainer& raw_adjoint_photoatom_data, std::shared_ptr<LineEnergyAdjointPhotonScatteringDistribution>& triplet_production_distribution, double& cross_section_value, const double max_energy ); private: // Create an energy distribution from the raw distribution data static void createEnergyDistributionFromRawDistData( std::shared_ptr<const Utility::TabularUnivariateDistribution>& energy_distribution, const std::vector<double>& energy_grid, const std::vector<double>& energy_dist_values, const double max_energy ); // Calculate the cross section value static void calculateCrossSectionValue( const std::vector<double>& norm_constant_energy_grid, const std::vector<double>& norm_constant_values, const double max_energy, double& cross_section_value ); }; } // end MonteCarlo namespace #endif // end MONTE_CARLO_LINE_ENERGY_ADJOINT_PHOTON_SCATTERING_DISTRIBUTION_NATIVE_FACTORY_HPP //---------------------------------------------------------------------------// // end MonteCarlo_LineEnergyAdjointPhotonScatteringDistributionNativeFactory.hpp //---------------------------------------------------------------------------//
38.820513
95
0.665125
[ "vector" ]
d8328dbc0d49b3c6b642f152cc3e4d503224c9bc
1,728
cpp
C++
TP_EndlessRunner/Source/TP_EndlessRunner/TP_EndlessRunnerBlocker.cpp
lpinkhard/ue4-endless-runner
fbb625ba5f4a088766c81a24960844d41b363008
[ "MIT" ]
null
null
null
TP_EndlessRunner/Source/TP_EndlessRunner/TP_EndlessRunnerBlocker.cpp
lpinkhard/ue4-endless-runner
fbb625ba5f4a088766c81a24960844d41b363008
[ "MIT" ]
null
null
null
TP_EndlessRunner/Source/TP_EndlessRunner/TP_EndlessRunnerBlocker.cpp
lpinkhard/ue4-endless-runner
fbb625ba5f4a088766c81a24960844d41b363008
[ "MIT" ]
1
2021-02-20T12:22:32.000Z
2021-02-20T12:22:32.000Z
// Copyright Likotech Software. All Rights Reserved. #include "TP_EndlessRunnerBlocker.h" #include "TP_EndlessRunnerCharacter.h" #include "Components/StaticMeshComponent.h" // Sets default values ATP_EndlessRunnerBlocker::ATP_EndlessRunnerBlocker() { // Blockers don't need to call Tick() every frame. PrimaryActorTick.bCanEverTick = false; // Create static mesh and set as root StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMesh")); SetRootComponent(StaticMesh); // Set up collision on mesh StaticMesh->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); StaticMesh->SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Ignore); StaticMesh->SetCollisionResponseToChannel(ECollisionChannel::ECC_Pawn, ECollisionResponse::ECR_Block); // Do not allow objects to be rotated by default bRandomRotation = false; } // Called when the game starts or when spawned void ATP_EndlessRunnerBlocker::BeginPlay() { Super::BeginPlay(); // Bind hit event StaticMesh->OnComponentHit.AddDynamic(this, &ATP_EndlessRunnerBlocker::OnComponentHit); // Rotate object randomly, if applicable if (bRandomRotation) { SetActorRotation(FRotator(0.f, FMath::RandRange(0.f, 360.f), 0.f)); } } // Called when the object is hit void ATP_EndlessRunnerBlocker::OnComponentHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit) { // Check if other actor is player and cast as appropriate if (OtherActor) { ATP_EndlessRunnerCharacter* Player = Cast<ATP_EndlessRunnerCharacter>(OtherActor); if (Player) { // kill player Player->Death(); } } }
30.315789
179
0.755787
[ "mesh", "object" ]
d8424f04398ada5c1cb30d3ba67ff0855f97e377
973
cpp
C++
tests/RussianDollEnvelopesTest.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
tests/RussianDollEnvelopesTest.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
tests/RussianDollEnvelopesTest.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#include "catch.hpp" #include "RussianDollEnvelopes.hpp" TEST_CASE("Russian Doll Envelopes") { RussianDollEnvelopes s; SECTION("Sample tests") { vector<pair<int, int>> envelopes1{{5, 4}, {6, 4}, {6, 7}, {2, 3}}; REQUIRE(s.maxEnvelopes(envelopes1) == 3); vector<pair<int, int>> envelopes2{{30, 50}, {12, 2}, {3, 4}, {12, 15}}; REQUIRE(s.maxEnvelopes(envelopes2) == 3); vector<pair<int, int>> envelopes3{{4, 5}, {4, 6}, {6, 7}, {2, 3}, {1, 1}}; REQUIRE(s.maxEnvelopes(envelopes3) == 4); } }
36.037037
52
0.323741
[ "vector" ]
d843394a524605d644291424132edeeec7bad06c
633
cc
C++
cc/array/ShuffleTheArray.cc
zihengCat/leetcode-collections
e94d6ee7d17cc72c8f34162d60e8d869164cbd53
[ "MIT" ]
4
2021-12-08T15:36:36.000Z
2022-03-23T12:21:06.000Z
cc/array/ShuffleTheArray.cc
zihengCat/leetcode-collections
e94d6ee7d17cc72c8f34162d60e8d869164cbd53
[ "MIT" ]
null
null
null
cc/array/ShuffleTheArray.cc
zihengCat/leetcode-collections
e94d6ee7d17cc72c8f34162d60e8d869164cbd53
[ "MIT" ]
null
null
null
#include <vector> using namespace std; /** * LeetCode 1470. Shuffle the Array * https://leetcode.com/problems/shuffle-the-array/ */ class ShuffleTheArray { public: vector<int> shuffle(vector<int>& nums, int n) { int vLen = nums.size(); vector<int> v(vLen, 0); int idx = 0; for (int i = 0; i < n; i++) { v[idx] = nums[i]; idx += 2; } idx = 1; for (int i = n; i < vLen; i++) { v[idx] = nums[i]; idx += 2; } return v; } }; int main(int argc, char const *argv[]) { // ... return 0; } /* EOF */
18.617647
51
0.459716
[ "vector" ]
d85c2005ff95f875245bb8d4ccc99be2f372fdf8
953
cpp
C++
NOIP/oj.noi.cn/1041VolunteerSelection.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
14
2018-06-21T14:41:26.000Z
2021-12-19T14:43:51.000Z
NOIP/oj.noi.cn/1041VolunteerSelection.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
null
null
null
NOIP/oj.noi.cn/1041VolunteerSelection.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
2
2018-06-19T12:18:30.000Z
2019-03-18T03:23:45.000Z
#include <bits/stdc++.h> using namespace std; struct Volunteer { int number; int score; bool operator<(const Volunteer &other) const { if (this->score != other.score) return this->score > other.score; return this->number < other.number; } }; int main(int argc, char const *argv[]) { for (int n, m; cin >> n >> m;) { vector<Volunteer> volunteers(n); for (auto &v:volunteers)cin >> v.number >> v.score; sort(volunteers.begin(), volunteers.end()); int select = (int) (m * 1.5); int minScore = volunteers[select - 1].score; auto right = volunteers.begin(); while (right < volunteers.end() && right->score >= minScore) ++right; cout << minScore << " " << right - volunteers.begin() << endl; for (auto i = volunteers.begin(); i != right; i++) cout << i->number << " " << i->score << endl; } return 0; }
29.78125
70
0.543547
[ "vector" ]
d85d6ac108947ca7f9e1d91d0832293d32f5f19c
177,785
cpp
C++
src/sha1attackgenerator/collfind.cpp
killua4564/hashclash
f780f17ef579e4bb246f5c47f31765f665dab74f
[ "MIT" ]
398
2017-10-16T19:46:02.000Z
2022-03-30T23:45:05.000Z
src/sha1attackgenerator/collfind.cpp
killua4564/hashclash
f780f17ef579e4bb246f5c47f31765f665dab74f
[ "MIT" ]
10
2019-10-23T08:14:38.000Z
2021-07-10T09:33:44.000Z
src/sha1attackgenerator/collfind.cpp
killua4564/hashclash
f780f17ef579e4bb246f5c47f31765f665dab74f
[ "MIT" ]
72
2017-10-18T14:44:36.000Z
2022-03-27T18:07:19.000Z
/**************************************************************************\ | | Copyright (C) 2009 Marc Stevens | | This program is free software: you can redistribute it and/or modify | it under the terms of the GNU General Public License as published by | the Free Software Foundation, either version 3 of the License, or | (at your option) any later version. | | This program is distributed in the hope that it will be useful, | but WITHOUT ANY WARRANTY; without even the implied warranty of | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | GNU General Public License for more details. | | You should have received a copy of the GNU General Public License | along with this program. If not, see <http://www.gnu.org/licenses/>. | \**************************************************************************/ /* USE_SERIALIZATION * Necessary for extra verification of M-bitrelations * Warning: using an incompatible Boost version may cause exceptions during serialization * Build using boost version 1.43.0 */ //#define USE_SERIALIZATION /* CPUPERFORMANCE * Enable measuring of cpu time spent in each function for manual optimization purposes */ //#define CPUPERFORMANCE #include <iostream> #include <string> #include <cstring> #include <cmath> #include <algorithm> #include <stdexcept> #define SHA1DETAIL_INLINE_IMPL #include <hashclash/sha1detail.hpp> #ifdef USE_SERIALIZATION #include <map> #include <fstream> #include <hashclash/sha1differentialpath.hpp> #include <hashclash/booleanfunction.hpp> #include <hashclash/bestof.hpp> #include <hashclash/progress_display.hpp> #include <hashclash/sha1messagespace.hpp> #include <hashclash/saveload.hpp> #endif #include <hashclash/rng.hpp> #include <hashclash/timer.hpp> #include <boost/lexical_cast.hpp> #include <boost/program_options.hpp> using namespace std; using namespace hashclash; namespace po = boost::program_options; #ifdef CPUPERFORMANCE #include <hashclash/cpuperformance.hpp> uint64 cpu_step_t[80]; #define UPDATE(s) update_performance_counter __update(cpu_step_t[s]); #ifdef __GNUC__ #include <sched.h> #endif #else #define UPDATE(s) #endif const int offset = 4; uint32 firstmsg[16]; uint32 m[80]; uint32 m2[80]; uint32 Q[85]; uint32 Q2[85]; uint32 Qr30[85]; uint32 Q2r30[85]; uint32 metset1precomp[16][16]; #define MAX_LOOP_SIZE 22 uint64 tendcount = 0; uint32 m_diff[80] = { 201326594, 3221225488, 3019898908, 1006632964, 3154116634, 536870928, 603979804, 3959422996, 201326594, 3221225488, 3019898908, 738197508, 3154116632, 2952790032, 12, 3087007760, 134217752, 2013265936, 134217748, 1879048208, 3087007772, 3892314112, 2952790020, 1476395024, 2952790028, 1207959552, 2952790016, 3087007760, 2550136848, 2684354560, 0, 0, 536870912, 2147483648, 16, 0, 536870928, 536870912, 16, 1610612736, 24, 3758096384, 2415919104, 805306384, 2952790016, 536870912, 536870912, 2684354560, 16, 2147483648, 536870912, 536870912, 536870912, 2147483648, 16, 0, 536870928, 2684354560, 0, 536870912, 536870912, 0, 0, 0, 0, 0, 0, 1, 32, 1, 1073741826, 1073741889, 1073741858, 2147483653, 3221225602, 3221225542, 1073741899, 2147483911, 137, 20}; const uint32 dQ[85] = { 0, 0, 0, 0, 0, 201326594, 3221225522, 2952791598, 3221225410, 3221225554, 3489660914, 2147483648, 4026531840, 3758096384, 0, 3758096384, 3221225472, 2147483648, 3758096384, 2147483648, 1073741824, 2147483648, 2684354560, 2147483648, 536870912, 0, 536870912, 2147483648, 3758096384, 0, 0, 2147483648, 2147483648, 0, 0, 0, 0, 0, 2147483648, 0, 2147483648, 0, 2147483648, 0, 1073741824, 0, 0, 2147483648, 0, 0, 0, 0, 2147483648, 0, 0, 0, 0, 0, 2147483648, 0, 2147483648, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 4294967295, 0, 4, 2, 2, 8, 4, 0, 4294967282}; const uint32 Qvaluemask[85] = { 0, 0, 0, 268435976, 1409620809, 1610612683, 3355443195, 1442840575, 1174405099, 1140851679, 1342179318, 3288334836, 3019899004, 603980664, 2348810465, 671088945, 3355447418, 2550138130, 805306642, 2818572355, 3892314114, 2415919106, 2952790016, 2818572288, 2818572288, 2818572288, 671088640, 2818572289, 3892314112, 2013265920, 402653184, 2147483648, 2684354560, 2147483648, 536870912, 0, 0, 0, 2147483648, 2684354560, 2684354560, 2684354560, 2684354560, 2684354561, 1610612736, 1342177280, 268435458, 2147483648, 2684354560, 536870912, 0, 2, 2147483648, 2684354560, 536870912, 0, 0, 2, 2147483648, 2684354562, 2684354560, 2684354560, 536870912, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 1073741825, 1073741832, 6, 1, 1073741873, 1073741836, 7, 35, 24, 6, 0, 18}; const uint32 Qvaluemask_adj[85] = { 0, 0, 0, 268435976, 1409620809, 1610612683, 3355443195, 1442840575, 1174405099, 1140851679, 1342179318, 3288334836, 3019899004, 603980664, 2348810465, 671088945, 3355447418, 2550138130, 805306642, 2818572355, 3892314114, 2415919106, 2952790016, 2818572288, 2818572288, 2818572288, 671088640, 2818572289, 3892314112, 2013265920, 402653184, 2147483648, 2684354560, 2147483648, 536870912, 0, 0, 0, 2147483648, 2684354560, 2684354560, 2684354560, 2684354560, 2684354561, 1610612736, 1342177280, 268435458, 2147483648, 2684354560, 536870912, 0, 2, 2147483648, 2684354560, 536870912, 0, 0, 2, 2147483648, 2684354562, 2684354560, 2684354560, 536870912, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 1073741825, 1073741832, 6, 1, 1073741873, 1073741836, 7, 35, 24, 6, 0, 18}; const uint32 Qvalue[85] = { 0, 0, 0, 268435968, 67174985, 67377672, 3288334296, 1375727986, 1157625865, 1073742216, 1073742224, 3288334336, 3019898884, 536871032, 1, 671088640, 1207959666, 134217728, 805306386, 134217728, 1073741826, 268435458, 2147483648, 2147483648, 0, 0, 0, 2147483649, 3355443200, 939524096, 134217728, 2147483648, 2684354560, 2147483648, 0, 0, 0, 0, 0, 2684354560, 0, 536870912, 2684354560, 536870913, 536870912, 1342177280, 2, 0, 536870912, 536870912, 0, 2, 0, 2684354560, 0, 0, 0, 2, 0, 536870914, 2684354560, 2684354560, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1073741824, 4, 1, 49, 1073741828, 5, 1, 16, 0, 0, 16}; const uint32 Qprev[85] = { 0, 0, 0, 0, 1073741824, 200991744, 0, 0, 0, 0, 1024, 0, 0, 768, 2147483648, 256, 4098, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 8, 4, 0, 48, 0, 0, 32, 16, 0, 0, 0}; const uint32 Qprev2[85] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 134217728, 0, 134217728, 0, 134217728, 0, 402653184, 0, 0, 536870912, 0, 0, 0, 0, 0, 0, 536870912, 0, 536870912, 0, 536870912, 0, 268435456, 0, 0, 536870912, 0, 0, 0, 0, 536870912, 0, 0, 0, 0, 0, 536870912, 0, 536870912, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1073741824, 0, 0, 0, 1073741824, 0, 0, 0, 0, 0, 0, 0}; const uint32 dF[80] = { 0, 0, 67108866, 3288283664, 1946159120, 1828713930, 738197918, 2952789616, 1946157076, 3489660928, 3758096384, 4227858432, 0, 939524096, 2147483648, 0, 2550136832, 2013265920, 2415919104, 268435456, 2281701376, 671088640, 3892314112, 671088640, 2281701376, 939524096, 3892314112, 4160749568, 2147483648, 2684354560, 0, 536870912, 0, 0, 0, 2147483648, 3758096384, 1610612736, 3758096384, 1610612736, 3758096384, 536870912, 268435456, 268435456, 2147483648, 536870912, 536870912, 0, 0, 2147483648, 536870912, 536870912, 0, 0, 0, 2147483648, 536870912, 2684354560, 3758096384, 3758096384, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1073741824, 3221225472, 2, 2147483649, 1073741824, 3221225468, 1, 2147483647, 8, 2147483646}; #ifdef USE_SERIALIZATION // all M-bitrelations (including tunnel M-bitrelations) // saved in BOOST_1_43_0 serialization string, use compatible BOOST version to load // only used for verification purposes: verify_block() vector< vector< vector<uint32> > > pathbitrelationsmatrix; char pathbitrelationsmatrixstring[] = "22 serialization::archive 7 0 0 16 0 0 0 32 0 0 0 17 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 67108864 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 134217728 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 268435456 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 32 0 0 0 0 0 0 0 0 0 17 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 4096 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 134217728 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 1073741824 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 32 0 0 0 0 0 17 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 67108864 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 134217728 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 268435456 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 536870912 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 0 0 0 17 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 67108864 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 134217728 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 268435456 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 32 0 0 0 17 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 64 2048 64 2048 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 67108864 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 134217728 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 268435456 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 32 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 134217728 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 17 0 0 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 32 0 0 0 0 0 17 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 1024 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 67108864 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 134217728 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 268435456 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 32 0 0 0 0 0 17 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 17 0 0 8 0 8 0 0 0 8 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 1024 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 2048 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 4096 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 8192 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 67108864 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 134217728 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 268435456 0 268435456 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 1073741824 0 0 0 0 0 0 0 0 0 0 0 32 0 0 0 17 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 67108864 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 134217728 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 268435456 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 32 0 0 0 0 0 17 0 0 4 0 0 0 0 0 0 0 4 0 0 0 0 0 0 4294967295 17 0 0 8 0 8 0 0 0 0 0 8 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 4294967295 0 0 17 0 0 0 0 0 0 0 0 0 0 64 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 128 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 134217728 0 0 0 0 0 0 4294967295 17 0 0 268435456 0 0 0 0 0 0 0 268435456 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 536870912 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 1073741824 0 0 0 0 0 0 0 0 0 32 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 2048 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 4096 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 67108864 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 134217728 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 268435456 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 0 32 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 17 0 0 0 0 8 0 8 0 0 0 0 0 8 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 16 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 128 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 67108864 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 134217728 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 268435456 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 536870912 0 0 0 0 4294967295 0 0 0 0 32 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 1024 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 2048 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 67108864 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 134217728 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 268435456 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 536870912 0 0 0 0 0 0 17 0 1073741824 1 1 0 1073741829 1073741825 1 0 3221225476 1 1073741824 0 2147483650 0 0 0 0 32 0 0 0 17 0 8 0 2 8 0 268435468 0 0 8 0 0 0 0 2 0 0 4294967295 17 0 4 0 0 0 0 0 0 0 4 0 0 0 0 4 0 0 4294967295 17 0 8 0 0 0 0 0 0 0 8 0 0 0 0 8 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32768 0 0 4294967295 0 0 17 0 1080956941 888266766 3238303744 30003210 19038209 3238735880 3236978689 17072128 1654290440 2195628034 1128693760 2174808065 1120501764 202752 0 0 4294967295 17 0 2201829388 887160846 3246473216 33259530 3229351936 36864008 1110769664 2150367233 1130905612 2278490114 3273392130 2167439361 1075052549 344065 0 0 4294967295 17 0 2739996672 399777862 1133086721 58101826 33030144 2449055745 3259801600 2154463232 20776964 95903747 1106812928 40906753 1076887553 546817 0 0 4294967295 17 0 11091980 938541067 2178236417 1136885771 3283877889 3248128008 6619138 49020928 1621901324 2151612419 1121714177 2159575041 22282245 1130497 0 0 0 17 0 3254272004 346357770 2159296513 28672003 2156658689 1352171525 1109458947 2174484481 3224977408 2243100674 1114374147 2148696065 1128529921 2113537 0 0 4294967295 17 0 4194304 83886080 4194304 25165824 0 8388608 16777216 0 20971520 50331648 0 41943040 0 4194304 0 0 4294967295 17 0 8388608 33554432 8388608 50331648 0 16777216 33554432 0 41943040 100663296 0 16777216 0 8388608 0 0 4294967295 17 0 3780708353 393486405 100352 63344705 7864320 3236536321 3261898755 2213183488 3272935424 131555328 3229130752 35663872 1085276167 16799745 0 0 0 17 0 33554432 0 33554432 0 0 67108864 0 0 33554432 0 0 0 0 33554432 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 67108864 0 0 0 17 0 0 0 0 0 0 268435456 0 0 0 0 0 0 0 134217728 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 268435456 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 536870912 0 0 0 0 0 17 0 2147483648 2 2147483648 3 4 1 2 0 2147483648 2 0 1 4 2147483648 0 0 0 32 0 17 0 0 1 0 1 0 0 2 0 0 1 0 0 2 0 1 0 0 17 0 0 2 0 2 4 0 0 0 0 2 0 0 4 0 2 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64 0 0 0 0 0 0 0 0 0 0 17 0 1132073476 603775050 3253916160 1083368514 3284422656 2169132036 1115543553 30588929 2700409344 2153410562 58662915 2176734209 389126 513 2048 0 0 17 0 596957189 377544712 3284342787 62799874 51109893 1134931972 3228385280 2213068803 3809261572 2230710273 3265150979 1106800643 40968194 1073764353 4096 0 4294967295 17 0 1102725121 627122180 25477123 5480451 1096204292 2149220352 54870019 2183954434 3787276288 40345600 2199224320 3249569795 30228480 16385 8192 0 4294967295 17 0 3262988296 272187393 48513024 1089454088 2198437888 2252242957 65896449 2190278657 1622425612 5652481 1127153666 31227904 1095139334 81920 16384 0 0 17 0 2737913868 60915727 3230089216 37421067 3285647365 347242505 1135869954 2200829952 1651261448 2242740226 3225026560 2207285249 40960005 81921 32768 0 4294967295 17 0 3806140417 661446656 1131649026 1115869187 2175041536 1119694849 6184963 34635778 555055108 19898369 1113227265 3245273091 28540930 6145 65536 0 0 17 0 1652099080 926294087 1074366465 1134858314 1104412672 382312460 2150146049 14843905 2689927176 110977026 1138794498 33566721 2359301 22529 131072 0 0 17 0 2174238725 379650057 3229892608 61964288 2178154497 345538565 1109983232 2173435905 1654788 2259091457 3277586435 2165473280 1080819719 16385 262144 0 0 17 0 1082130433 17301507 1075838977 25690115 45088768 1082130432 17825795 2097152 3238002692 86507523 2187329536 8388609 38797318 0 524288 0 4294967295 17 0 2209955852 882966542 3229958144 28540938 3252420608 112885768 1107623936 2175533057 1090273292 2259615746 3239837698 2165866497 1089732613 81921 1048576 0 0 17 0 551569420 837099592 2168768513 21303368 3255042048 2538807305 2181668864 42369025 1089030152 2206752769 2149883906 2184753152 27525124 71680 2097152 0 4294967295 17 0 45694988 921763855 2177187841 1122205707 3241934853 3283779592 10813442 15466496 1660698636 2243887107 1121714177 2149089281 47448065 81921 4194304 0 4294967295 17 0 0 8388612 33554432 8388608 50331652 0 16777216 33554432 0 41943040 33554432 0 16777220 0 8388608 0 4294967295 17 0 0 16777216 0 16777216 33554432 0 33554432 0 0 83886080 0 0 33554432 0 16777216 0 0 17 0 0 33554432 0 33554432 0 0 0 0 0 33554432 0 0 0 0 33554432 0 0 17 0 0 67108864 0 0 0 0 0 0 0 67108864 0 0 0 0 67108864 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 134217728 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 268435456 0 4294967295 17 0 0 536870912 0 0 0 0 0 0 0 0 0 0 0 0 536870912 0 0 17 0 3221225473 3 1073741825 3 0 3221225472 2147483651 2147483648 1073741829 3 2147483649 1 1073741828 0 1073741824 0 0 17 0 0 536870914 1073741824 3 5 0 1073741827 1 536870917 2 3221225474 1073741825 1073741824 0 2147483648 0 0 32 0 17 0 0 0 3 0 1 2 0 2 4 0 1 0 0 0 0 1 0 17 0 0 0 2 0 0 0 0 0 0 0 2 0 0 0 0 2 4294967295 17 0 30949376 103088130 3264495617 1131773954 42729477 3570958336 1117847552 60555265 2694397952 2217934850 7077888 2169667584 1094975491 16384 0 4 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2048 4294967295 0 0 17 0 1092884488 857464835 15382528 1086672907 1139056645 1376120845 3273285635 58769409 575207437 100835331 2213683202 52260865 1082884098 22529 0 8192 4294967295 17 0 3820666884 650313739 2173075457 57901058 2193113092 1345847300 1127153665 2156691456 3780165636 2269446146 1081950209 2167439361 19398657 16385 0 16384 0 17 0 549781513 298582022 36012032 786443 1080590340 29425676 52166658 35717121 1670578188 116129795 2260995 12845057 1087897602 0 0 32768 4294967295 17 0 2204780556 106766408 3247425536 1132269640 3222601728 1188110344 3228672000 2185527297 1137657868 2196791296 31563779 2175840256 22282240 71680 0 65536 0 17 0 3272867848 657457157 9830400 1076887560 1101135876 2265186317 1081081857 2156134401 2722889740 61865985 9043970 51380224 1130364928 0 0 131072 0 17 0 2157002761 13697026 1105805313 1120108555 2214068224 3249700877 12910594 2162425857 2724478984 60751874 3234332674 37257217 1116995584 81920 0 262144 4294967295 17 0 1122582541 846266376 3265085440 1113817096 3258187777 2208989192 31784961 66846720 2748071944 2185166848 3287547905 2153283584 30670851 81921 0 524288 4294967295 17 0 2210463753 554958854 1122041857 1079377931 1126170628 3544317965 1090781186 2186280961 1610940424 88866818 2178940930 30015489 1108344838 65536 0 1048576 0 17 0 3238809601 589086790 1090670594 33603648 61243393 316411905 2159132673 60948482 2188980224 124698626 19013633 3255582722 34439174 0 0 2097152 0 17 0 1115684865 100663299 1119879169 33554435 4194304 1350565888 33554435 8388608 3246391300 100663299 2168455168 33554433 6 0 0 4194304 0 17 0 2209955852 850460686 3242541056 44269578 3225157632 381321224 1076166656 2162950145 1107050508 2164195330 3277586434 2149089281 1079246853 81921 0 8388608 4294967295 17 0 1625311245 633675851 3267676160 56954955 3250847744 3344113673 2185863171 425985 2196326412 2267570178 10788866 2151198721 14942210 71680 0 16777216 0 17 0 0 0 33554432 0 33554432 67108864 0 0 0 0 33554432 0 0 0 0 33554432 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 67108864 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 134217728 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 268435456 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 536870912 4294967295 17 0 1130430468 815005710 2186346498 1104543747 1110441984 1398931461 1115947009 40894464 40173568 13369347 1102053378 21626883 17825796 65537 0 1073741824 4294967295 17 0 1 0 2147483649 0 2147483648 1 0 1 1 0 2147483650 0 0 0 0 2147483648 0"; // base M-bitrelations (excluding tunnel M-bitrelations) // saved in BOOST_1_43_0 serialization string, use compatible BOOST version to load // only used for verification purposes: check40(); vector< vector< vector<uint32> > > pathbitrelationsmatrix_base; char pathbitrelationsmatrixstring_base[] = "22 serialization::archive 7 0 0 16 0 0 0 32 0 0 0 17 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 67108864 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 134217728 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 268435456 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 32 0 0 0 0 0 0 0 0 0 17 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 134217728 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 1073741824 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 32 0 0 0 0 0 17 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 67108864 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 134217728 0 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 268435456 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 536870912 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 0 0 0 0 0 17 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 67108864 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 134217728 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 268435456 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 32 0 0 0 17 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 67108864 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 134217728 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 268435456 0 0 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 32 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 134217728 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 17 0 0 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 32 0 0 0 0 0 17 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 67108864 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 134217728 0 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 268435456 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 4294967295 0 0 0 0 32 0 0 0 0 0 17 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 17 0 0 8 0 8 0 0 0 8 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 67108864 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 134217728 0 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 268435456 0 268435456 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 1073741824 0 0 0 0 0 0 0 0 0 0 0 32 0 0 0 17 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 67108864 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 134217728 0 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 268435456 0 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 32 0 0 0 0 0 17 0 0 4 0 0 0 0 0 0 0 4 0 0 0 0 0 0 4294967295 17 0 0 8 0 8 0 0 0 0 0 8 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 134217728 0 0 0 0 0 0 4294967295 17 0 0 268435456 0 0 0 0 0 0 0 268435456 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 536870912 0 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 1073741824 0 0 0 0 0 0 0 0 0 32 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 67108864 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 134217728 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 268435456 0 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 536870912 0 0 0 0 0 0 0 0 0 0 32 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 17 0 0 0 0 8 0 8 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 67108864 0 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 134217728 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 268435456 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 536870912 0 0 0 0 4294967295 0 0 0 0 32 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 67108864 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 134217728 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 268435456 0 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 536870912 0 0 0 0 0 0 17 0 1073741824 1 1 0 1073741829 1073741825 1 0 3221225476 1 1073741824 0 2147483650 0 0 0 0 32 0 0 0 17 0 8 0 2 8 0 268435468 0 0 8 0 0 0 0 2 0 0 4294967295 17 0 4 0 0 0 0 0 0 0 4 0 0 0 0 4 0 0 4294967295 17 0 8 0 0 0 0 0 0 0 8 0 0 0 0 8 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 0 0 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 1080956941 888266766 3238303744 30003210 19038209 3238735880 3236978689 17072128 1654290440 2195628034 1128693760 2174808065 1120501764 202752 0 0 4294967295 17 0 2201829388 887160846 3246473216 33259530 3229351936 36864008 1110769664 2150367233 1130905612 2278490114 3273392130 2167439361 1075052549 344065 0 0 4294967295 0 0 17 0 11091980 938541067 2178236417 1136885771 3283877889 3248128008 6619138 49020928 1621901324 2151612419 1121714177 2159575041 22282245 1130497 0 0 0 17 0 3254272004 346357770 2159296513 28672003 2156658689 1352171525 1109458947 2174484481 3224977408 2243100674 1114374147 2148696065 1128529921 2113537 0 0 4294967295 17 0 4194304 83886080 4194304 25165824 0 8388608 16777216 0 20971520 50331648 0 41943040 0 4194304 0 0 4294967295 17 0 8388608 33554432 8388608 50331648 0 16777216 33554432 0 41943040 100663296 0 16777216 0 8388608 0 0 4294967295 17 0 1107820545 10485763 1132986369 11534339 25165824 1360003072 2097155 58720256 3257401348 39845891 2172649472 5242881 8388614 17301504 0 0 4294967295 17 0 33554432 0 33554432 0 0 67108864 0 0 33554432 0 0 0 0 33554432 0 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 67108864 0 0 0 17 0 0 0 0 0 0 268435456 0 0 0 0 0 0 0 134217728 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 268435456 0 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 536870912 0 0 0 0 0 17 0 2147483648 2 2147483648 3 4 1 2 0 2147483648 2 0 1 4 2147483648 0 0 0 32 0 17 0 0 1 0 1 0 0 2 0 0 1 0 0 2 0 1 0 0 17 0 0 2 0 2 4 0 0 0 0 2 0 0 4 0 2 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 0 3760921092 875085836 2189122049 1139045376 3258732544 280228869 2150725633 2176335873 2714366468 2246905857 1116176387 2211341312 1077276679 547328 2048 0 4294967295 17 0 596957189 377548808 3284342787 62799874 51109893 1134931972 3228385280 2213068803 3809261572 2230710273 3265150979 1106800643 40968194 1073797121 4096 0 4294967295 17 0 1102725121 627122180 25477123 5480451 1096204292 2149220352 54870019 2183954434 3787276288 40345600 2199224320 3249569795 30228480 16385 8192 0 4294967295 17 0 3262988296 272187393 48513024 1089454088 2198437888 2252242957 65896449 2190278657 1622425612 5652481 1127153666 31227904 1095139334 81920 16384 0 0 17 0 2737913868 60915727 3230089216 37421067 3285647365 347242505 1135869954 2200829952 1651261448 2242740226 3225026560 2207285249 40960005 81921 32768 0 4294967295 17 0 3806140417 661446656 1131649026 1115869187 2175041536 1119694849 6184963 34635778 555055108 19898369 1113227265 3245273091 28540930 6145 65536 0 0 17 0 3240624136 551682049 58720256 1087504392 1076625408 2268069901 1113849857 2156396545 2707947532 53084161 35127298 7340032 1075052548 524288 131072 0 4294967295 17 0 2174238725 379650057 3229892608 61964288 2178154497 345538565 1109983232 2173435905 1654788 2259091457 3277586435 2165473280 1080819719 16385 262144 0 0 17 0 1082130433 17301507 1075838977 25690115 45088768 1082130432 17825795 2097152 3238002692 86507523 2187329536 8388609 38797318 0 524288 0 4294967295 17 0 2209955852 882966542 3229958144 28540938 3252420608 112885768 1107623936 2175533057 1090273292 2259615746 3239837698 2165866497 1089732613 81921 1048576 0 0 17 0 2209431564 640745486 3268231168 36929546 3288072192 111837192 1078263808 2196504577 1104429068 2252275714 3252420610 2152235009 1100218373 606209 2097152 0 0 17 0 45694988 921763855 2177187841 1122205707 3241934853 3283779592 10813442 15466496 1660698636 2243887107 1121714177 2149089281 47448065 81921 4194304 0 4294967295 17 0 0 8388612 33554432 8388608 50331652 0 16777216 33554432 0 41943040 33554432 0 16777220 0 8388608 0 4294967295 17 0 0 16777216 0 16777216 33554432 0 33554432 0 0 83886080 0 0 33554432 0 16777216 0 0 17 0 0 33554432 0 33554432 0 0 0 0 0 33554432 0 0 0 0 33554432 0 0 17 0 0 67108864 0 0 0 0 0 0 0 67108864 0 0 0 0 67108864 0 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 134217728 0 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 268435456 0 4294967295 17 0 0 536870912 0 0 0 0 0 0 0 0 0 0 0 0 536870912 0 0 17 0 3221225473 3 1073741825 3 0 3221225472 2147483651 2147483648 1073741829 3 2147483649 1 1073741828 0 1073741824 0 0 17 0 0 536870914 1073741824 3 5 0 1073741827 1 536870917 2 3221225474 1073741825 1073741824 0 2147483648 0 0 32 0 17 0 0 0 3 0 1 2 0 2 4 0 1 0 0 0 0 1 0 17 0 0 0 2 0 0 0 0 0 0 0 2 0 0 0 0 2 4294967295 17 0 30949376 103088130 3264495617 1131773954 42729477 3570958336 1117847552 60555265 2694397952 2217934850 7077888 2169667584 1094975491 16384 0 4 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 4294967295 0 0 0 0 0 0 0 0 0 0 0 0 17 0 2739996672 399777798 1133084673 58101762 33032192 2449055745 3259801600 2154467328 20776964 95903747 1106814976 40906753 1076887553 546817 0 2048 4294967295 0 0 17 0 1092884488 857464835 15382528 1086672907 1139056645 1376120845 3273285635 58769409 575207437 100835331 2213683202 52260865 1082884098 22529 0 8192 4294967295 17 0 3820666884 650313739 2173075457 57901058 2193113092 1345847300 1127153665 2156691456 3780165636 2269446146 1081950209 2167439361 19398657 16385 0 16384 0 17 0 549781513 298582022 36012032 786443 1080590340 29425676 52166658 35717121 1670578188 116129795 2260995 12845057 1087897602 0 0 32768 4294967295 17 0 540753932 294191118 2181447681 1074495498 3253534720 3609755657 37552128 36569089 1123172360 2269577219 1075380227 2210430977 1097072641 606209 0 65536 4294967295 17 0 3272867848 657457157 9830400 1076887560 1101135876 2265186317 1081081857 2156134401 2722889740 61865985 9043970 51380224 1130364928 0 0 131072 0 17 0 2157002761 13697026 1105805313 1120108555 2214068224 3249700877 12910594 2162425857 2724478984 60751874 3234332674 37257217 1116995584 81920 0 262144 4294967295 17 0 1122582541 846266376 3265085440 1113817096 3258187777 2208989192 31784961 66846720 2748071944 2185166848 3287547905 2153283584 30670851 81921 0 524288 4294967295 17 0 2210463753 554958854 1122041857 1079377931 1126170628 3544317965 1090781186 2186280961 1610940424 88866818 2178940930 30015489 1108344838 65536 0 1048576 0 17 0 1650284545 885579776 42719235 24530946 39747585 2200285184 1123901441 2210955266 2202286084 47816705 1088061441 3229380611 1111326727 546817 0 2097152 4294967295 17 0 1115684865 100663299 1119879169 33554435 4194304 1350565888 33554435 8388608 3246391300 100663299 2168455168 33554433 6 0 0 4194304 0 17 0 2209955852 850460686 3242541056 44269578 3225157632 381321224 1076166656 2162950145 1107050508 2164195330 3277586434 2149089281 1079246853 81921 0 8388608 4294967295 17 0 3283173389 839974925 2169323521 1277961 3225157632 1454014472 1074069507 2154561537 2211725320 2191458305 1096548354 2185789440 1087635459 606209 0 16777216 4294967295 17 0 0 0 33554432 0 33554432 67108864 0 0 0 0 33554432 0 0 0 0 33554432 0 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 67108864 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 134217728 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 268435456 4294967295 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 536870912 4294967295 17 0 1130430468 815005710 2186346498 1104543747 1110441984 1398931461 1115947009 40894464 40173568 13369347 1102053378 21626883 17825796 65537 0 1073741824 4294967295 17 0 1 0 2147483649 0 2147483648 1 0 1 1 0 2147483650 0 0 0 0 2147483648 0"; #endif uint32 Qtp1valsvec[30][1<<13]; uint32* Qtp1valsvecptr[30]; uint32 metpartialvec[30]; vector< vector<uint32> > target_dIHVs; /***** Differential path over steps t=0,...,32 (w/o tunnels) *****/ /* Qt | b31 Q-conditions b0 | Delta mt (BSDR) ---------------------------------------------------------------------- Q-4: |........ ........ ........ ........| Q-3: |........ ........ ........ ........| Q-2: |........ ........ ........ ........| Q-1: |...1.... ........ ........ ....0...| Q0: |.^.0.1.. .....0.1 ...00.10 .1..1..1|[!1,26,27!] Q1: |.0.+^-^^ ^^^^^1^0 ^^^11^10 .0..1.+0|[!-4,-30,+-31!] Q2: |1-...+-- -------- -------- --.-1.+0|[!-2,3,-4,-26,28,29,+-31!] Q3: |.-.-.0.1 11111111 11110++1 +-1-00-0|[!-2,26,27,28,-29!] Q4: |.-...1.0 11111111 1111-+++ ++0.1.+1|[!1,-3,4,26,-27,-28,-29,+-31!] Q5: |.-...0.. ........ ......0. .+.+10+0|[!-4,-29!] Q6: |.-.+.... ........ ......01 100-.0+.|[!2,3,4,26,-29!] Q7: |-1...1.. ........ ........ ...0.0..|[!2,4,-26,-27,29,30,+-31!] Q8: |1.1-.1.. ........ ........ .....1..|[!-1,26,-27!] Q9: |..-..0.. ........ ........ ........|[!-4,30,+-31!] Q10: |^...00.. ........ ........ .......1|[!-2,-3,4,-26,-28,29,+-31!] Q11: |..-.1... ........ ........ .......0|[!2,-26,27,-29!] Q12: |0-..1... ........ ........ ......!.|[!-3,4,-26,-27,-28,29,+-31!] Q13: |+..01... ........ ........ ........|[!-4,28,29,+-31!] Q14: |..-1.... ........ ........ ......!.|[!-2,3!] Q15: |+.0.1... ........ ........ ......!^|[!-4,-27,-28,-29,+-31!] Q16: |+-0.0... ........ ........ ......!.|[!3,-4,-27!] Q17: |+..1.... ........ ........ ......^.|[!-4,-27,-28,-29,30!] Q18: |-.+0.... ........ ........ ........|[!-2,4,-27!] Q19: |-...m... ........ ........ ........|[!4,28,29,-30!] Q20: |..+.r... ........ ........ ........|[!2,3,-4,-27,28,-29,+-31!] Q21: |^.r.m... ........ ........ ........|[!-27,29,30,+-31!] Q22: |..+.r... ........ ........ ........|[!-2,28,29,+-31!] Q23: |-...m... ........ ........ .......!|[!4,27,28,-30!] Q24: |.-+.R... ........ ........ ........|[!-2,3,28,-29,+-31!] Q25: |..r##... ........ ........ ........|[!27,-30!] Q26: |...rr... ........ ........ ........|[!-28,29,+-31!] Q27: |-....... ........ ........ ........|[!4,-27,28,29,+-31!] // alternative delta mt allowed Q28: |-.#..... ........ ........ ........|[!4,-27,28,+-31!] // alternative delta mt allowed Q29: |........ ........ ........ ........|[!-29,+-31!] // alternative delta mt allowed Q30: |..R..... ........ ........ ........|[!!] conditions: * 0, 1, +, -: self explanatory * ^: Qt[b] == Qt-1[b] * !: Qt[b] != Qt-1[b] * r: Qt[b] == RL(Qt-1,30)[b] * R: Qt[b] != RL(Qt-1,30)[b] * m: Qt[b] == RL(Qt-2,30)[b] * #: Qt[b] != RL(Qt-2,30)[b] */ bool dorapidsectionstatistics = false; /***** MAIN FUNCTION *****/ void findfirstblock(); void build_target_dIHVs(); void sha1perf(); int maxruntime, statsinterval; int main(int argc, char** argv) { std::string seedstr; bool dosha1bench = false; po::options_description desc("Allowed options"); desc.add_options() ("help,h" , "Show options.") ("sha1benchmark,b" , po::bool_switch(&dosha1bench) , "Benchmark SHA-1 compression function.") ("rapidsectionstats" , po::bool_switch(&dorapidsectionstatistics) , "More rapid statistics over 'indep.' sections") ("seed" , po::value<string>(&seedstr)->default_value("") , "Specify seed") ("maxruntime" , po::value<int>(&maxruntime)->default_value(-1) , "Maximum runtime in minutes") ("statsinterval" , po::value<int>(&statsinterval)->default_value(5) , "Statistics interval in minutes") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << endl; cout << endl << "=== Help on statistics ===" << endl; cout << "'timeavg 40': #/s that steps t=[0,33) are ok." << endl; cout << "'avg 53 stats': success probability of steps t=[33,53)." << endl; cout << "'avg 61 stats': success probability of steps t=[53,61)." << endl; cout << "'avg 80 stats': success probability of steps t=[61,80)." << endl; return 0; } if (!seedstr.empty()) { cout << "Using seed: " << seedstr << endl; seed(0); for (unsigned i = 0; i < seedstr.size(); ++i) { seed32_1 ^= seedstr[i]; xrng128(); } } if (maxruntime <= 0) maxruntime = -1; if (statsinterval <= 1) statsinterval = 1; if (dosha1bench) { sha1perf(); return 0; } #ifdef USE_SERIALIZATION { stringstream tmp; tmp.str(string(pathbitrelationsmatrixstring)); boost::archive::text_iarchive ia(tmp); ia >> boost::serialization::make_nvp("pathbitrelationsmatrix", pathbitrelationsmatrix); } { stringstream tmp; tmp.str(string(pathbitrelationsmatrixstring_base)); boost::archive::text_iarchive ia(tmp); ia >> boost::serialization::make_nvp("pathbitrelationsmatrix", pathbitrelationsmatrix_base); } #if 0 // show inside message relations that are not automatically taken into account by automatic program generation for (unsigned t = 0; t < 16; ++t) for (unsigned b = 0; b < 32; ++b) if (pathbitrelationsmatrix[t][b].size()!=0 && pathbitrelationsmatrix[t][b][t] != 1<<b) { cout << "Inside message relation @ t=" << t << " b=" << b << ": "; for (unsigned b2 = 0; b2 < 32; ++b2) if (pathbitrelationsmatrix[t][b][t]&(1<<b2)) cout << "(" << t << "," << b2 << ")"; cout << endl; } // show free bits in steps t=14,15 cout << "Free bits @ t=14: "; for (unsigned b = 0; b < 32; ++b) if (pathbitrelationsmatrix[14][b].size() == 0) cout << b << " "; cout << endl; cout << "Free bits @ t=15: "; for (unsigned b = 0; b < 32; ++b) if (pathbitrelationsmatrix[15][b].size() == 0) cout << b << " "; cout << endl; // show # base M-bitrelations (excluding tunnel M-bitrelations) unsigned basebitrels = 0; for (unsigned t = 0; t < 16; ++t) for (unsigned b = 0; b < 32; ++b) if (pathbitrelationsmatrix_base[t][b].size()) ++basebitrels; cout << "Base # of message bitrelations: " << basebitrels << endl; #endif #endif // USE_SERIALIZATION // build sorted vector of the target dIHVs build_target_dIHVs(); cout << "Starting collision search..." << endl; while (true) { try { findfirstblock(); } catch (std::exception&e) { cerr << e.what() << endl; } catch (...) {} } } bool test_first_block(const uint32 block[16]) { static uint32 ihv[5]; static uint32 me[80]; memcpy(ihv, sha1_iv, 5*4); // or pick another IHV instead of default SHA-1 IV memcpy(me, block, 4*16); for (unsigned i = 16; i < 80; ++i) me[i]=rotate_left(me[i-3] ^ me[i-8] ^ me[i-14] ^ me[i-16], 1); sha1compress_me(ihv, me); Q2[0] = Q[0] = rotate_right(ihv[4], 30); Q2[1] = Q[1] = rotate_right(ihv[3], 30); Q2[2] = Q[2] = rotate_right(ihv[2], 30); Q2[3] = Q[3] = ihv[1]; Q2[4] = Q[4] = ihv[0]; if ((Q[0]&Qvaluemask_adj[0])!=Qvalue[0]) return false; if ((Q[1]&Qvaluemask_adj[1])!=(Qvalue[1]^(Q[0]&Qprev[1]))) return false; if ((Q[2]&Qvaluemask_adj[2])!=(Qvalue[2]^(Q[1]&Qprev[2])^(Q[0]&Qprev2[2]))) return false; if ((Q[3]&Qvaluemask_adj[3])!=(Qvalue[3]^(Q[2]&Qprev[3])^(Q[1]&Qprev2[3]))) return false; if ((Q[4]&Qvaluemask_adj[4])!=(Qvalue[4]^(Q[3]&Qprev[4])^(Q[2]&Qprev2[4]))) return false; return true; } bool step_0(); // this is where the actual near-collision attacks starts (in the second block) uint64 fbcnt = 0; void findfirstblock() { {UPDATE(79); while (true) { for (unsigned i = 0; i < 16; ++i) firstmsg[i] = xrng128(); if (0==((++fbcnt)&0xFFFFF)) cout << "(fb:" << fbcnt << ")" << flush; if (test_first_block(firstmsg)) break; } for (unsigned i = 0; i < 5; ++i) { Qr30[i] = rotate_left(Q[i], 30); Q2r30[i] = rotate_left(Q2[i], 30); } }//UPDATE(79); metset1precomp[0][0]=268435456; metset1precomp[0][1]=1073745936; metset1precomp[0][2]=201326612; metset1precomp[0][3]=536870916; metset1precomp[0][4]=939526152; metset1precomp[0][5]=671088656; metset1precomp[0][6]=671088640; metset1precomp[0][7]=201341960; metset1precomp[0][8]=402653186; metset1precomp[0][9]=671088668; metset1precomp[0][10]=469768204; metset1precomp[0][11]=603980016; metset1precomp[0][12]=469762056; metset1precomp[0][13]=49184798; metset1precomp[0][14]=350793780; metset1precomp[0][15]=2089592850; step_0(); } void build_target_dIHVs() { target_dIHVs.clear(); // base vector of 6 optimal dIHVs vector< vector<uint32> > base(6, vector<uint32>(5) ); for (unsigned i = 0; i < 6; ++i) { base[i][0] = 1<<31; base[i][1] = 1<<1; base[i][2] = (i<2) ? (1<<31) : 0; base[i][3] = base[i][4] = 0; if (i==1 || i==4 || i==5) base[i][3] += 1<<4; if (i==0 || i==1) base[i][3] += 1<<6; else base[i][3] += 1<<7; if (i==0 || i==1) base[i][4] += (1<<11)+(1<<4)-(1<<2); else base[i][4] += (1<<12); if (i==1 || i==4 || i==5) base[i][4] += (1<<9); if (i==2 || i==4) base[i][4] += (1<<1)+(1<<3); if (i==3 || i==5) base[i][4] += (1<<4)-(1<<1); } // allow 6 extra messagebitfreedoms that each also give 6 optimal dIHVs // for second near-collision only specific single dIHV is targeted (the outcome of first near-collision) // => loss of the 6 extra messagebitfreedoms, loss of factor 6 to target single dIHV instead of 6 dIHVs for (unsigned t794 = 0; t794 < 2; ++t794) for (unsigned t792 = 0; t792 < 2; ++t792) for (unsigned t787 = 0; t787 < 2; ++t787) for (unsigned t783 = 0; t783 < 2; ++t783) for (unsigned t763778 = 0; t763778 < 2; ++t763778) for (unsigned t771772 = 0; t771772 < 2; ++t771772) { for (unsigned i = 0; i < base.size(); ++i) { vector<uint32> tmptmp = base[i]; if (t794) tmptmp[4] -= (1<<5); if (t792) tmptmp[4] += (1<<3); if (t787) { tmptmp[3] -= (1<<8); tmptmp[4] -= (1<<13); } if (t783) { tmptmp[3] -= (1<<4); tmptmp[4] -= (1<<9); } if (t763778) tmptmp[1] -= (1<<2); if (t771772 && tmptmp[2]) { tmptmp[3] += (1<<7); tmptmp[4] += (1<<12); } target_dIHVs.push_back(tmptmp); } } sort(target_dIHVs.begin(), target_dIHVs.end()); cout << "# target dIHVs: " << target_dIHVs.size() << endl; } void sha1perf() { uint32 ihv[5]; uint32 msg[80]; for (unsigned i = 0; i < 5; ++i) ihv[i] = xrng128(); for (unsigned i = 0; i < 80; ++i) msg[i] = xrng128(); uint64 totcnt = 0; cout << "Determining SHA1 performance (takes 10 minutes).\nDon't run any other processes." << endl; for (unsigned i = 0; i < (1<<23); ++i) sha1compress(ihv, msg); timer runtime(true); while (true) { for (unsigned i = 0; i < (1<<23); ++i) sha1compress(ihv, msg); totcnt += 1<<23; if (runtime.time() > 300) break; } cout << "SHA1 perf (w/ me)\t: 2^(" << log(double(totcnt)*3600.0/runtime.time())/log(2.0) << ") compressions per hour." << endl; for (unsigned i = 0; i < (1<<23); ++i) sha1compress_me(ihv, msg); totcnt = 0; runtime.start(); while (true) { for (unsigned i = 0; i < (1<<23); ++i) sha1compress_me(ihv, msg); totcnt += 1<<23; if (runtime.time() > 300) break; } cout << "SHA1 perf (w/o me)\t: 2^(" << log(double(totcnt)*3600.0/runtime.time())/log(2.0) << ") compressions per hour." << endl; } /***** STATISTICS SECTION *****/ /* basic average statistics */ struct avg_data { uint64 avgcnt, avgsum; avg_data(): avgcnt(0), avgsum(0) {} void add_ok() { ++avgcnt; ++avgsum; } void add_bad() { ++avgcnt; } void add_cnt(uint64 toadd = 1) { avgcnt += toadd; } void add_sum(uint64 toadd = 1) { avgsum += toadd; } void show(const std::string& name) { double avg = double(avgsum)/double(avgcnt); double logavg = log(avg)/log(2.0); if (logavg >= 20 || logavg < -2.0) cout << name << ": 2^(" << logavg << ")"; else cout << name << ": " << avg; cout << " (#=" << avgcnt << ", #ok=" << avgsum << ")" << endl; } }; vector<avg_data> avg_data_vec(4000); /* more extensive loop statistics: what is the probability for a certain succes percentage of a loop? */ struct loop_data { uint64 proc_cnt[101]; uint64 totcnt; bool fulldetail; loop_data() { fulldetail = false; for (unsigned i = 0; i < 101; ++i) proc_cnt[i] = 0; totcnt = 0; } void add(uint32 ok, uint32 cnt) { unsigned proc = floor(0.5 + (float(ok*100)/float(cnt))); if (proc > 100) throw; ++proc_cnt[proc]; ++totcnt; } void add(unsigned proc) { if (proc > 100) throw; ++proc_cnt[proc]; ++totcnt; } void show(const std::string& name) { cout << name << ": "; uint64 mincnt = totcnt >> 3; uint64 remcnt = totcnt; if (mincnt == 0) mincnt = 1; for (unsigned i = 0; i < 101; ++i) if (proc_cnt[i] >= mincnt || i == 0 || i == 100 || (proc_cnt[i]>0 && fulldetail)) { cout << "(" << i << "% occurs with p=" << double(proc_cnt[i])/double(totcnt) << ") "; remcnt -= proc_cnt[i]; } cout << "(other p=" << double(remcnt)/double(totcnt) << ")" << endl; } }; vector<loop_data> loop_data_vec(1024); /* bit statistics over an array of uint32, see which bits have non-uniform distribution */ struct checkmaskcnt_type { void process(uint32* Qtbegin, uint32* Qtend, uint32 mask = 0xFFFFFFFF) { if (Qtend-Qtbegin < 2) return; bits.resize(32); for (unsigned b = 0; b < 32; ++b) { if ((mask & (1<<b))==0) continue; uint32 cnt = 0; for (uint32* p = Qtbegin; p != Qtend; ++p) if (*p & (1<<b)) ++cnt; bits[b].add(cnt, Qtend-Qtbegin); } } void show(const std::string& name) { if (bits.empty()) return; cout << name << ":" << endl; for (unsigned b = 0; b < 32; ++b) { if (bits[b].totcnt == 0) continue; bits[b].show("checkmaskbit " + boost::lexical_cast<string>(b)); } } vector<loop_data> bits; }; checkmaskcnt_type checkmaskcnt; void process_checkmask(uint32* Qtbegin, uint32* Qtend, uint32 mask = 0xFFFFFFFF, uint32 add = 0) { if (add) { for (uint32* ptr = Qtbegin; ptr != Qtend; ++ptr) *ptr += add; } checkmaskcnt.process(Qtbegin, Qtend,mask); if (add) { for (uint32* ptr = Qtbegin; ptr != Qtend; ++ptr) *ptr -= add; } } /* analyze which bits are affected by tunnel */ /* copy Q to Q2, change tunnel, recompute Q, call this function */ void tunnel_bitanalysis(unsigned Qtbegin, unsigned Qtend) { for (unsigned t = Qtbegin; t < Qtend; ++t) for (unsigned b = 0; b < 32; ++b) if (b == 0 || b >= 27) { avg_data_vec[t*100+b].add_cnt(1); if ((Q2[offset+t]^Q[offset+t])&(1<<b)) avg_data_vec[t*100+b].add_sum(1); } } vector<uint64> time_avg(1024,0); vector<uint64> step_cnt(20,0); timer spd_sw(true), runtime_sw(true), restart_sw(true), runtime_t40_sw(false); #ifdef CPUPERFORMANCE uint64 cpu_timestamp_begin = cpu_timestamp(); #endif /* the main function that shows performance statistics every 15 secs */ /* also automatically restarts to step7 or step0 when step15 hasn't been reached yet */ void show_performance_data(const int correct_cpu_step_t = -1) { // restart every 15 secs until time_avg[15] != 0 if (time_avg[40]!=1 && restart_sw.time() < 15) return; restart_sw.start(); if (time_avg[15] == 0) throw std::runtime_error("restart"); // show statistics every minute if (time_avg[40]!=1 && spd_sw.time() < 60*statsinterval) return; spd_sw.start(); UPDATE(78); cout << endl; #ifdef CPUPERFORMANCE uint64 cputime = cpu_timestamp(); uint64 cpuspend = cputime-cpu_timestamp_begin; if (correct_cpu_step_t != -1) { for (int t = 0; t <= correct_cpu_step_t; ++t) cpu_step_t[t] += cputime; } for (unsigned i = 0; i < 30; ++i) if (cpu_step_t[i]-cpu_step_t[i+1]) cout << "t=" << i << " " << floor(0.5 + (double(cpu_step_t[i]-cpu_step_t[i+1])*1000.0/double(cpuspend))) << " " << cpu_step_t[i]-cpu_step_t[i+1] << endl; for (unsigned i = 30; i < 80; ++i) { if (cpu_step_t[i] > (cpuspend<<1)) cout << "i=" << i << " " << floor(0.5 + (double(cpu_step_t[i]+cputime)*1000.0/double(cpuspend))) << " " << (cpu_step_t[i]+cputime) << endl; else if (cpu_step_t[i]) cout << "i=" << i << " " << floor(0.5 + (double(cpu_step_t[i])*1000.0/double(cpuspend))) << " " << (cpu_step_t[i]) << endl; } if (correct_cpu_step_t != -1) { for (int t = 0; t <= correct_cpu_step_t; ++t) cpu_step_t[t] -= cputime; } #endif for (unsigned i = 0; i < loop_data_vec.size(); ++i) if (loop_data_vec[i].totcnt) loop_data_vec[i].show("loop " + boost::lexical_cast<string>(i) + " stats"); for (unsigned i = 0; i < avg_data_vec.size(); ++i) if (avg_data_vec[i].avgcnt) avg_data_vec[i].show("avg " + boost::lexical_cast<string>(i) + " stats"); for (unsigned i = 0; i < time_avg.size(); ++i) if (time_avg[i] && i != 40) cout << "timeavg " << i << ": 2^" << log(double(time_avg[i])/double(runtime_sw.time()))/log(2.0) << "#/s" << endl; else if (time_avg[i] && i == 40) cout << "timeavg " << i << ": 2^" << log(double(time_avg[i])/double(runtime_t40_sw.time()))/log(2.0) << "#/s" << endl; for (unsigned i = 0; i < 20; ++i) if (step_cnt[i]) cout << "(" << i << ":" << step_cnt[i] << ") "; cout << endl; checkmaskcnt.show("checkmask"); if (maxruntime > 0 && runtime_sw.time() >= maxruntime*60) { cout << "Maximum runtime reached: aborting!" << endl; exit(0); } } /***** END STATISTICS SECTION *****/ // verify all Q-conditions and M-bitrelations // !including! tunnel Q-conditions and M-bitrelations // don't use after changing any tunnel void verify_block(unsigned tend = 16, bool force = false) { static uint32 cnt = 0; UPDATE(77); for (unsigned t = 16; t < tend; ++t) m[t]=rotate_left(m[t-3] ^ m[t-8] ^ m[t-14] ^ m[t-16], 1); for (unsigned t = 0; t < tend && t < 20; ++t) if (rotate_left(Q[offset+t-2],30)!=Qr30[offset+t-2]) { cout << "Precomp Qr30 error @ t=" << t << endl; exit(0); } for (unsigned t = 0; t < tend && t < 20; ++t) { bool terror = false; uint32 Qtp1 = m[t] + sha1_f1(Q[offset+t-1], rotate_left(Q[offset+t-2],30), rotate_left(Q[offset+t-3],30)) + sha1_ac[0] + rotate_left(Q[offset+t],5) + rotate_left(Q[offset+t-4],30); if (Qtp1 != Q[offset+t+1]) { cout << "Hash error @ t=" << t << ": " << hex << (Qtp1^Q[offset+t+1]) << dec << endl; terror = true; } if ((Q[offset+t+1]^Qvalue[offset+t+1]^(Qprev[offset+t+1]&Q[offset+t])) & Qvaluemask[offset+t+1]) { cout << "Verify error @ t=" << t << ": "; cout << hex << ((Q[offset+t+1]^Qvalue[offset+t+1]^(Qprev[offset+t+1]&Q[offset+t])) & Qvaluemask[offset+t+1]) << dec << endl; terror = true; } #ifdef USE_SERIALIZATION if (t < 16) { for (unsigned b = 0; b < 32; ++b) if (pathbitrelationsmatrix[t][b].size()) { uint32 r = pathbitrelationsmatrix[t][b][16]&1; for (unsigned j = 0; j <= t; ++j) r ^= m[j]&pathbitrelationsmatrix[t][b][j]; if (hw(r)&1) { cout << "Message relation error @ t=" << t << " b=" << b << ": "; for (unsigned j = 0; j <= t; ++j) for (unsigned b2 = 0; b2 < 32; ++b2) if (pathbitrelationsmatrix[t][b][j]&(1<<b2)) cout << "(" << j << "," << b2 << ")"; cout << endl; terror = true; } } } #endif if (terror) exit(1); } } // verify computation t=0,...,32 and check if zero difference working state is actually achieved void check40() { UPDATE(40); for (int t = -4; t <= 0; ++t) Q2[offset+t] = Q[offset+t] + dQ[offset+t]; for (int t = 0; t < 16; ++t) { uint32 Qtp1 = m[t] + sha1_f1(Q[offset+t-1], rotate_left(Q[offset+t-2],30), rotate_left(Q[offset+t-3],30)) + sha1_ac[0] + rotate_left(Q[offset+t],5) + rotate_left(Q[offset+t-4],30); if (Qtp1 != Q[offset+t+1]) { cerr << "check40(): Q error @ t=" << t << endl; exit(0); } m2[t] = m[t] ^ m_diff[t]; Q2[offset+t+1] = m2[t] + sha1_f1(Q2[offset+t-1], rotate_left(Q2[offset+t-2],30), rotate_left(Q2[offset+t-3],30)) + sha1_ac[0] + rotate_left(Q2[offset+t],5) + rotate_left(Q2[offset+t-4],30); if (Q2[offset+t+1]-Q[offset+t+1] != dQ[offset+t+1]) { cerr << "check40(): dQ error @ t=" << t << endl; exit(0); } } #ifdef USE_SERIALIZATION for (unsigned t = 0; t < 16; ++t) { for (unsigned b = 0; b < 32; ++b) if (pathbitrelationsmatrix_base[t][b].size()) { uint32 r = pathbitrelationsmatrix_base[t][b][16]&1; for (unsigned j = 0; j <= t; ++j) r ^= m[j]&pathbitrelationsmatrix_base[t][b][j]; if (hw(r)&1) { cout << "Message relation error @ t=" << t << " b=" << b << ": "; for (unsigned j = 0; j <= t; ++j) for (unsigned b2 = 0; b2 < 32; ++b2) if (pathbitrelationsmatrix_base[t][b][j]&(1<<b2)) cout << "(" << j << "," << b2 << ")"; cout << endl; exit(0); } } } #endif for (int t = 16; t < 20; ++t) { m[t]=rotate_left(m[t-3] ^ m[t-8] ^ m[t-14] ^ m[t-16], 1); m2[t] = m[t] ^ m_diff[t]; Q[offset+t+1] = m[t] + sha1_f1(Q[offset+t-1], rotate_left(Q[offset+t-2],30), rotate_left(Q[offset+t-3],30)) + sha1_ac[0] + rotate_left(Q[offset+t],5) + rotate_left(Q[offset+t-4],30); Q2[offset+t+1] = m2[t] + sha1_f1(Q2[offset+t-1], rotate_left(Q2[offset+t-2],30), rotate_left(Q2[offset+t-3],30)) + sha1_ac[0] + rotate_left(Q2[offset+t],5) + rotate_left(Q2[offset+t-4],30); } for (int t = 20; t < 33; ++t) { m[t]=rotate_left(m[t-3] ^ m[t-8] ^ m[t-14] ^ m[t-16], 1); m2[t] = m[t] ^ m_diff[t]; Q[offset+t+1] = m[t] + sha1_f2(Q[offset+t-1], rotate_left(Q[offset+t-2],30), rotate_left(Q[offset+t-3],30)) + sha1_ac[1] + rotate_left(Q[offset+t],5) + rotate_left(Q[offset+t-4],30); Q2[offset+t+1] = m2[t] + sha1_f2(Q2[offset+t-1], rotate_left(Q2[offset+t-2],30), rotate_left(Q2[offset+t-3],30)) + sha1_ac[1] + rotate_left(Q2[offset+t],5) + rotate_left(Q2[offset+t-4],30); } if (Q2[offset+33]==Q[offset+33] && Q2[offset+32]==Q[offset+32] && Q2[offset+31]==Q[offset+31] && Q2[offset+30]==Q[offset+30] && Q2[offset+29]==Q[offset+29]) { #ifdef USE_SERIALIZATION #if 0 // this section saves all paths that get to this step // for probability and Q-conditions analysis sha1differentialpath path; for (int t = 16-4; t <= 33; ++t) { path[t] = sdr(Q[offset+t],Q2[offset+t]); if (t >= 16 && t < 33) { path.getme(t) = sdr(m[t],m2[t]); for (unsigned b = 0; b < 32; ++b) { bool bittm1active = path(t-1,b) == bc_minus || path(t-1,b) == bc_plus; bool bittm2active = path(t-2,(b+2)&31) == bc_minus || path(t-2,(b+2)&31) == bc_plus; bool bittm3active = path(t-3,(b+2)&31) == bc_minus || path(t-3,(b+2)&31) == bc_plus; unsigned acnt = 0; if (bittm1active) ++acnt; if (bittm2active) ++acnt; if (bittm3active) ++acnt; if ( (t < 20 && (bittm1active || bittm2active || bittm3active)) || (t >= 20 && (acnt&1) && b < 31) // if two bits are active they cancel ) { // there is a difference hence boolean function bitconditions are required if (path(t-1,b)==bc_constant) { if (Q[offset+t-1]&(1<<b)) path.setbitcondition(t-1,b,bc_one); else path.setbitcondition(t-1,b,bc_zero); } if (path(t-2,(b+2)&31)==bc_constant) { if (rotate_left(Q[offset+t-2],30)&(1<<b)) path.setbitcondition(t-2,(b+2)&31,bc_one); else path.setbitcondition(t-2,(b+2)&31,bc_zero); } if (path(t-3,(b+2)&31)==bc_constant) { if (rotate_left(Q[offset+t-3],30)&(1<<b)) path.setbitcondition(t-3,(b+2)&31,bc_one); else path.setbitcondition(t-3,(b+2)&31,bc_zero); } } } } } if (!test_path(path)) { show_path(path); exit(0); } static vector<sha1differentialpath> okpaths; okpaths.push_back(path); static timer save_sw(true); if (save_sw.time() > 600 || hw(uint32(okpaths.size()))==1) { static string okpathsfile; if (okpathsfile.size() == 0) { okpathsfile = "okpaths." + boost::lexical_cast<string>(getpid()) + "."; char hostname[256]; if (0 == gethostname(hostname, 256)) okpathsfile += string(hostname); else okpathsfile += string("hostname"); } try { sort(okpaths.begin(), okpaths.end()); save_bz2(okpaths, okpathsfile, text_archive); } catch (std::exception& e) { cout << "Failed to save OK paths in '" << okpathsfile << "':" << endl; cout << e.what() << endl; } save_sw.start(); } // save_sw #endif #endif return; } else { cerr << "check40(): not really 40!" << endl; exit(0); } } template<int tstart, int tend> inline void compute_mt() { for (int t = tstart; t < tend; ++t) m[t] = rotate_left(m[t-3] ^ m[t-8] ^ m[t-14] ^ m[t-16], 1); } template<int r> inline uint32 sha1_f(uint32 b, uint32 c, uint32 d); template<> inline uint32 sha1_f<0>(uint32 b, uint32 c, uint32 d) { return sha1_f1(b,c,d) + 0x5A827999; } template<> inline uint32 sha1_f<1>(uint32 b, uint32 c, uint32 d) { return sha1_f2(b,c,d) + 0x6ED9EBA1; } template<> inline uint32 sha1_f<2>(uint32 b, uint32 c, uint32 d) { return sha1_f3(b,c,d) + 0x8F1BBCDC; } template<> inline uint32 sha1_f<3>(uint32 b, uint32 c, uint32 d) { return sha1_f4(b,c,d) + 0xCA62C1D6; } template<> inline uint32 sha1_f<4>(uint32 b, uint32 c, uint32 d) { cerr << "no 5th round!" << endl; exit(1); } template<int tstart, int tend> inline void compute_qt() { if (tstart >= tend) return; Qr30[offset+tstart-2] = rotate_left(Q[offset+tstart-2],30); uint32 a = Q[offset+tstart], b = Q[offset+tstart-1], c = Qr30[offset+tstart-2], d = Qr30[offset+tstart-3], e = Qr30[offset+tstart-4]; e += rotate_left(a, 5) + sha1_f<(tstart+0)/20>(b,c,d) + m[tstart+0]; Q[offset+tstart+1] = e; if (tstart+1 == tend) return; Qr30[offset+tstart-1] = b = rotate_left(b, 30); d += rotate_left(e, 5) + sha1_f<(tstart+1)/20>(a,b,c) + m[tstart+1]; Q[offset+tstart+2] = d; if (tstart+2 == tend) return; Qr30[offset+tstart+0] = a = rotate_left(a, 30); c += rotate_left(d, 5) + sha1_f<(tstart+2)/20>(e,a,b) + m[tstart+2]; Q[offset+tstart+3] = c; if (tstart+3 == tend) return; Qr30[offset+tstart+1] = e = rotate_left(e, 30); b += rotate_left(c, 5) + sha1_f<(tstart+3)/20>(d,e,a) + m[tstart+3]; Q[offset+tstart+4] = b; if (tstart+4 == tend) return; Qr30[offset+tstart+2] = d = rotate_left(d, 30); a += rotate_left(b, 5) + sha1_f<(tstart+4)/20>(c,d,e) + m[tstart+4]; Q[offset+tstart+5] = a; if (tstart+5 == tend) return; Qr30[offset+tstart+3] = c = rotate_left(c, 30); e += rotate_left(a, 5) + sha1_f<(tstart+5)/20>(b,c,d) + m[tstart+5]; Q[offset+tstart+6] = e; if (tstart+6 == tend) return; Qr30[offset+tstart+4] = b = rotate_left(b, 30); d += rotate_left(e, 5) + sha1_f<(tstart+6)/20>(a,b,c) + m[tstart+6]; Q[offset+tstart+7] = d; if (tstart+7 == tend) return; Qr30[offset+tstart+5] = a = rotate_left(a, 30); c += rotate_left(d, 5) + sha1_f<(tstart+7)/20>(e,a,b) + m[tstart+7]; Q[offset+tstart+8] = c; if (tstart+8 == tend) return; Qr30[offset+tstart+6] = e = rotate_left(e, 30); b += rotate_left(c, 5) + sha1_f<(tstart+8)/20>(d,e,a) + m[tstart+8]; Q[offset+tstart+9] = b; if (tstart+9 == tend) return; Qr30[offset+tstart+7] = d = rotate_left(d, 30); a += rotate_left(b, 5) + sha1_f<(tstart+9)/20>(c,d,e) + m[tstart+9]; Q[offset+tstart+10] = a; if (tstart+10 == tend) return; Qr30[offset+tstart+8] = c = rotate_left(c, 30); e += rotate_left(a, 5) + sha1_f<(tstart+10)/20>(b,c,d) + m[tstart+10]; Q[offset+tstart+11] = e; if (tstart+11 == tend) return; Qr30[offset+tstart+9] = b = rotate_left(b, 30); d += rotate_left(e, 5) + sha1_f<(tstart+11)/20>(a,b,c) + m[tstart+11]; Q[offset+tstart+12] = d; if (tstart+12 == tend) return; Qr30[offset+tstart+10] = a = rotate_left(a, 30); c += rotate_left(d, 5) + sha1_f<(tstart+12)/20>(e,a,b) + m[tstart+12]; Q[offset+tstart+13] = c; if (tstart+13 == tend) return; Qr30[offset+tstart+11] = e = rotate_left(e, 30); b += rotate_left(c, 5) + sha1_f<(tstart+13)/20>(d,e,a) + m[tstart+13]; Q[offset+tstart+14] = b; if (tstart+14 == tend) return; Qr30[offset+tstart+12] = d = rotate_left(d, 30); a += rotate_left(b, 5) + sha1_f<(tstart+14)/20>(c,d,e) + m[tstart+14]; Q[offset+tstart+15] = a; if (tstart+15 == tend) return; Qr30[offset+tstart+13] = c = rotate_left(c, 30); e += rotate_left(a, 5) + sha1_f<(tstart+15)/20>(b,c,d) + m[tstart+15]; Q[offset+tstart+16] = e; if (tstart+16 == tend) return; Qr30[offset+tstart+14] = b = rotate_left(b, 30); d += rotate_left(e, 5) + sha1_f<(tstart+16)/20>(a,b,c) + m[tstart+16]; Q[offset+tstart+17] = d; if (tstart+17 == tend) return; cerr << "compute_qt<" << tstart << "," << tend << ">(): t out of range!" << endl; exit(0); // prevent stupid mistake } template<int tstart, int tend> inline void compute_qt2() { if (tstart >= tend) return; Q2r30[offset+tstart-2] = rotate_left(Q2[offset+tstart-2],30); uint32 a = Q2[offset+tstart], b = Q2[offset+tstart-1], c = Q2r30[offset+tstart-2], d = Q2r30[offset+tstart-3], e = Q2r30[offset+tstart-4]; e += rotate_left(a, 5) + sha1_f<(tstart+0)/20>(b,c,d) + m2[tstart+0]; Q2[offset+tstart+1] = e; if (tstart+1 == tend) return; Q2r30[offset+tstart-1] = b = rotate_left(b, 30); d += rotate_left(e, 5) + sha1_f<(tstart+1)/20>(a,b,c) + m2[tstart+1]; Q2[offset+tstart+2] = d; if (tstart+2 == tend) return; Q2r30[offset+tstart+0] = a = rotate_left(a, 30); c += rotate_left(d, 5) + sha1_f<(tstart+2)/20>(e,a,b) + m2[tstart+2]; Q2[offset+tstart+3] = c; if (tstart+3 == tend) return; Q2r30[offset+tstart+1] = e = rotate_left(e, 30); b += rotate_left(c, 5) + sha1_f<(tstart+3)/20>(d,e,a) + m2[tstart+3]; Q2[offset+tstart+4] = b; if (tstart+4 == tend) return; Q2r30[offset+tstart+2] = d = rotate_left(d, 30); a += rotate_left(b, 5) + sha1_f<(tstart+4)/20>(c,d,e) + m2[tstart+4]; Q2[offset+tstart+5] = a; if (tstart+5 == tend) return; Q2r30[offset+tstart+3] = c = rotate_left(c, 30); e += rotate_left(a, 5) + sha1_f<(tstart+5)/20>(b,c,d) + m2[tstart+5]; Q2[offset+tstart+6] = e; if (tstart+6 == tend) return; Q2r30[offset+tstart+4] = b = rotate_left(b, 30); d += rotate_left(e, 5) + sha1_f<(tstart+6)/20>(a,b,c) + m2[tstart+6]; Q2[offset+tstart+7] = d; if (tstart+7 == tend) return; Q2r30[offset+tstart+5] = a = rotate_left(a, 30); c += rotate_left(d, 5) + sha1_f<(tstart+7)/20>(e,a,b) + m2[tstart+7]; Q2[offset+tstart+8] = c; if (tstart+8 == tend) return; Q2r30[offset+tstart+6] = e = rotate_left(e, 30); b += rotate_left(c, 5) + sha1_f<(tstart+8)/20>(d,e,a) + m2[tstart+8]; Q2[offset+tstart+9] = b; if (tstart+9 == tend) return; Q2r30[offset+tstart+7] = d = rotate_left(d, 30); a += rotate_left(b, 5) + sha1_f<(tstart+9)/20>(c,d,e) + m2[tstart+9]; Q2[offset+tstart+10] = a; if (tstart+10 == tend) return; Q2r30[offset+tstart+8] = c = rotate_left(c, 30); e += rotate_left(a, 5) + sha1_f<(tstart+10)/20>(b,c,d) + m2[tstart+10]; Q2[offset+tstart+11] = e; if (tstart+11 == tend) return; Q2r30[offset+tstart+9] = b = rotate_left(b, 30); d += rotate_left(e, 5) + sha1_f<(tstart+11)/20>(a,b,c) + m2[tstart+11]; Q2[offset+tstart+12] = d; if (tstart+12 == tend) return; Q2r30[offset+tstart+10] = a = rotate_left(a, 30); c += rotate_left(d, 5) + sha1_f<(tstart+12)/20>(e,a,b) + m2[tstart+12]; Q2[offset+tstart+13] = c; if (tstart+13 == tend) return; Q2r30[offset+tstart+11] = e = rotate_left(e, 30); b += rotate_left(c, 5) + sha1_f<(tstart+13)/20>(d,e,a) + m2[tstart+13]; Q2[offset+tstart+14] = b; if (tstart+14 == tend) return; Q2r30[offset+tstart+12] = d = rotate_left(d, 30); a += rotate_left(b, 5) + sha1_f<(tstart+14)/20>(c,d,e) + m2[tstart+14]; Q2[offset+tstart+15] = a; if (tstart+15 == tend) return; Q2r30[offset+tstart+13] = c = rotate_left(c, 30); e += rotate_left(a, 5) + sha1_f<(tstart+15)/20>(b,c,d) + m2[tstart+15]; Q2[offset+tstart+16] = e; if (tstart+16 == tend) return; Q2r30[offset+tstart+14] = b = rotate_left(b, 30); d += rotate_left(e, 5) + sha1_f<(tstart+16)/20>(a,b,c) + m2[tstart+16]; Q2[offset+tstart+17] = d; if (tstart+17 == tend) return; cerr << "compute_qt2<" << tstart << "," << tend << ">(): t out of range!" << endl; exit(0); // prevent stupid mistake } template<int tstart, int tend> void check_comp() { for (unsigned i = tstart; i < tend; ++i) { Q2[offset+i+1] = Q[offset+i+1]; Q2r30[offset+i-2] = Qr30[offset+i-2]; Q2r30[offset+i-3] = Qr30[offset+i-3]; Q2r30[offset+i-4] = Qr30[offset+i-4]; m2[i] = m[i]; } compute_mt<tstart,tend>(); compute_qt<tstart,tend>(); for (unsigned i = tstart; i < tend; ++i) { bool bad = false; if (Q2[offset+i+1]!=Q[offset+i+1]) { cerr << "Q[" << (i+1) << "]bad "; bad = true; } if (Q2r30[offset+i-2]!=Qr30[offset+i-2]) { cerr << "Qr30[" << (i-2) << "]bad "; bad = true; } if (Q2r30[offset+i-3]!=Qr30[offset+i-3]) { cerr << "Qr30[" << (i-3) << "]bad "; bad = true; } if (Q2r30[offset+i-4]!=Qr30[offset+i-4]) { cerr << "Qr30[" << (i-4) << "]bad "; bad = true; } if (m2[i] != m[i]) { cerr << "m[" << i << "]bad "; bad = true; } if (bad) { cout << endl; exit(0); } } } uint32 gQ19val; /* check whether near-collision is achieved and maintain statistics about 'independent' sections */ void check_nc() { UPDATE(53); bool t33ok = true; #if 1 // to enable more rapid collecting of statistics if (!(Q2[offset+33]==Q[offset+33] && Q2[offset+32]==Q[offset+32] && Q2[offset+31]==Q[offset+31] && Q2[offset+30]==Q[offset+30] && Q2[offset+29]==Q[offset+29])) t33ok = false; // 'assume' zero difference is achieved for statistics of subsequent sections for (unsigned i = 33-4; i <= 33; ++i) { Q2[offset+i] = Q[offset+i]; Q2r30[offset+i] = Qr30[offset+i]; } #endif compute_mt<33,80>(); for (int t = 33; t < 80; ++t) m2[t] = m[t] ^ m_diff[t]; // second section: t = [33,53) compute_qt<33,43>(); compute_qt<43,53>(); compute_qt2<33,43>(); compute_qt2<43,53>(); avg_data_vec[53].add_cnt(1); bool t53ok = false; if (Q2[offset+53]==Q[offset+53] && Q2[offset+52]==Q[offset+52] && Q2[offset+51]==Q[offset+51] && Q2[offset+50]==Q[offset+50] && Q2[offset+49]==Q[offset+49]) { avg_data_vec[53].add_sum(1); ++time_avg[53]; t53ok = true; } else { // return; // 'assume' zero difference is achieved for statistics of subsequent sections for (unsigned i = 53-4; i <= 53; ++i) { Q2[offset+i] = Q[offset+i]; Q2r30[offset+i] = Qr30[offset+i]; } } // third section: t = [53,61) compute_qt<53,61>(); compute_qt2<53,61>(); bool t61ok = false; avg_data_vec[61].add_cnt(1); if (Q2[offset+61]==Q[offset+61] && Q2[offset+60]==Q[offset+60] && Q2[offset+59]==Q[offset+59] && Q2[offset+58]==Q[offset+58] && Q2[offset+57]==Q[offset+57]) { avg_data_vec[61].add_sum(1); if (t53ok) ++time_avg[61]; t61ok = true; } else { // return; // 'assume' zero difference is achieved for statistics of subsequent section for (unsigned i = 61-4; i <= 61; ++i) { Q2[offset+i] = Q[offset+i]; Q2r30[offset+i] = Qr30[offset+i]; } } // fourth and final section: t = [61,80) compute_qt<61,70>(); compute_qt<70,80>(); compute_qt2<61,70>(); compute_qt2<70,80>(); static vector<uint32> dihv(5); dihv[0] = rotate_left(Q2[offset+80-4],30)-rotate_left(Q[offset+80-4],30); dihv[1] = rotate_left(Q2[offset+80-3],30)-rotate_left(Q[offset+80-3],30); dihv[2] = rotate_left(Q2[offset+80-2],30)-rotate_left(Q[offset+80-2],30); dihv[3] = Q2[offset+80-1]-Q[offset+80-1]; dihv[4] = Q2[offset+80]-Q[offset+80]; avg_data_vec[80].add_cnt(1); bool t80ok = false; if (binary_search(target_dIHVs.begin(), target_dIHVs.end(), dihv)) { t80ok = true; avg_data_vec[80].add_sum(1); if (t33ok && t53ok && t61ok) { ++time_avg[80]; cout << "blocks: " << endl; for (unsigned i = 0; i < 16; ++i) cout << firstmsg[i] << " "; cout << endl; for (unsigned i = 0; i < 16; ++i) cout << m[i] << " "; cout << endl; exit(0); } } if (t53ok && t61ok) avg_data_vec[90].add_ok(); else avg_data_vec[90].add_bad(); if (t53ok && t80ok) avg_data_vec[91].add_ok(); else avg_data_vec[91].add_bad(); if (t61ok && t80ok) avg_data_vec[92].add_ok(); else avg_data_vec[92].add_bad(); if (t53ok && t61ok && t80ok) avg_data_vec[93].add_ok(); else avg_data_vec[93].add_bad(); } void step_16_33() { const unsigned updatet = 25; UPDATE(updatet); #if 0 // verify computation check_comp<16,25>() compute_mt<25,33>(); compute_qt<25,33>(); // determine probability of Q-conditions disturbed by (later) tunnels bool badcond = false; if ( (Q[offset+17]&((1<<31)|(1<<28)|(1<<1)))==((1<<28)^(1<<1)) ) avg_data_vec[17].add_bad(); else { badcond = true; avg_data_vec[17].add_ok(); } if ((Q[offset+18]&2952790016)==2147483648) avg_data_vec[18].add_bad(); else { badcond = true; avg_data_vec[18].add_ok(); } if ( (Q[offset+19]&((1<<31)|(1<<27))) == ((1<<31)^((Q[offset+17]>>2)&(1<<27))) ) avg_data_vec[19].add_bad(); else { badcond = true; avg_data_vec[19].add_ok(); } if ( (Q[offset+20]&((1<<29)|(1<<27))) == ((Q[offset+19]>>2)&(1<<27)) ) avg_data_vec[20].add_bad(); else { badcond = true; avg_data_vec[20].add_ok(); } if ( (Q[offset+21]&((1<<31)|(1<<29)|(1<<27))) == ((Q[offset+20]&((1<<31)|(1<<27)))^((Q[offset+20]>>2)&(1<<29))) ) avg_data_vec[21].add_bad(); else { badcond = true; avg_data_vec[21].add_ok(); } if (badcond) avg_data_vec[39].add_ok(); else avg_data_vec[39].add_bad(); #else compute_mt<25,33>(); compute_qt<25,33>(); #endif for (int t = 16-4; t <= 16; ++t) { Q2[offset+t] = Q[offset+t] + dQ[offset+t]; Q2r30[offset+t] = rotate_left(Q2[offset+t],30); } for (int t = 16; t < 33; ++t) m2[t] = m[t] ^ m_diff[t]; compute_qt2<16,33>(); avg_data_vec[40].add_cnt(1); if (Q2[offset+33]==Q[offset+33] && Q2[offset+32]==Q[offset+32] && Q2[offset+31]==Q[offset+31] && Q2[offset+30]==Q[offset+30] && Q2[offset+29]==Q[offset+29]) { if (time_avg[40] == 0) runtime_t40_sw.start(); avg_data_vec[40].add_sum(1); ++time_avg[40]; show_performance_data(updatet); #if 0 static set< vector<uint32> > okmsg; static vector<uint32> msg(16); for (unsigned i = 0; i < 16; ++i) msg[i] = m[i]; if (okmsg.find(msg) != okmsg.end()) { cout << "msg found twice ?!?!" << endl; exit(0); } okmsg.insert(msg); #endif // check40(); check_nc(); } else { // to enable more rapid collecting of statistics if (dorapidsectionstatistics) check_nc(); } } void step_24_case01() { UPDATE(24); compute_mt<24,25>(); compute_qt<24,25>(); if ( ((Q[offset+25]^(Q[offset+23]>>2))&(3<<27)) != (3<<27) ) return; step_16_33(); } void step_24_case4() { UPDATE(24); compute_mt<24,25>(); compute_qt<24,25>(); const uint32 Q25val = ((Q[offset+24]>>2)&(1<<29)) ^ ((Q[offset+23]>>2)&(1<<27)) ^ (1<<27); if ( (Q[offset+25]&((1<<29)|(1<<27))) != Q25val) return; step_16_33(); } void step_23_case01() { UPDATE(23); compute_mt<23,24>(); compute_qt<23,24>(); const uint32 Q24val = ((Q[offset+23]>>2)&(1<<27))^(1<<27); if ( (Q[offset+24]&((1<<27)|(1<<29))) == Q24val)// && (Q[offset+24]&(3<<30))!=0 ) step_24_case01(); Q[offset+7] += 1<<6; m[6] += 1<<6; m[7] -= 1<<11; m[11] -= 1<<4; compute_mt<19,24>(); compute_qt<19,24>(); if ( (Q[offset+24]&((1<<27)|(1<<29))) == Q24val)// && (Q[offset+24]&(3<<30))!=0 ) step_24_case01(); Q[offset+7] -= 1<<6; m[6] -= 1<<6; m[7] += 1<<11; m[11] += 1<<4; Q[offset+7] += 1<<8; m[6] += 1<<8; m[7] -= 1<<13; m[11] -= 1<<6; compute_mt<19,24>(); compute_qt<19,24>(); if ( (Q[offset+24]&((1<<27)|(1<<29))) == Q24val)// && (Q[offset+24]&(3<<30))!=0 ) step_24_case01(); Q[offset+7] -= 1<<8; m[6] -= 1<<8; m[7] += 1<<13; m[11] += 1<<6; Q[offset+7] += 5<<6; m[6] += 5<<6; m[7] -= 5<<11; m[11] -= 5<<4; compute_mt<19,24>(); compute_qt<19,24>(); if ( (Q[offset+24]&((1<<27)|(1<<29))) == Q24val)// && (Q[offset+24]&(3<<30))!=0 ) step_24_case01(); Q[offset+7] -= 5<<6; m[6] -= 5<<6; m[7] += 5<<11; m[11] += 5<<4; } void step_23_case4() { UPDATE(23); compute_mt<23,24>(); compute_qt<23,24>(); const uint32 Q24val = ((Q[offset+23]>>2)&(3<<27))^(3<<27); if ( (Q[offset+24]&(3<<27)) == Q24val)// && (Q[offset+24]&(3<<29))!=0 ) step_24_case4(); Q[offset+7] += 1<<6; m[6] += 1<<6; m[7] -= 1<<11; m[11] -= 1<<4; compute_mt<19,24>(); compute_qt<19,24>(); if ( (Q[offset+24]&(3<<27)) == Q24val)// && (Q[offset+24]&(3<<29))!=0 ) step_24_case4(); Q[offset+7] -= 1<<6; m[6] -= 1<<6; m[7] += 1<<11; m[11] += 1<<4; Q[offset+7] += 1<<8; m[6] += 1<<8; m[7] -= 1<<13; m[11] -= 1<<6; compute_mt<19,24>(); compute_qt<19,24>(); if ( (Q[offset+24]&(3<<27)) == Q24val)// && (Q[offset+24]&(3<<29))!=0 ) step_24_case4(); Q[offset+7] -= 1<<8; m[6] -= 1<<8; m[7] += 1<<13; m[11] += 1<<6; Q[offset+7] += 5<<6; m[6] += 5<<6; m[7] -= 5<<11; m[11] -= 5<<4; compute_mt<19,24>(); compute_qt<19,24>(); if ( (Q[offset+24]&(3<<27)) == Q24val)// && (Q[offset+24]&(3<<29))!=0 ) step_24_case4(); Q[offset+7] -= 5<<6; m[6] -= 5<<6; m[7] += 5<<11; m[11] += 5<<4; } void step_22_case01() { UPDATE(22); compute_mt<22,23>(); compute_qt<22,23>(); if ( (Q[offset+23]&((1<<31)|(1<<27)|(1<<0))) == ((1<<31)^(1<<0)^(Q[offset+22]&((1<<27)|(1<<0)))) ) step_23_case01(); Q[offset+7] += 1<<7; m[6] += 1<<7; m[7] -= 1<<12; m[11] -= 1<<5; if (m[14]&(1<<6)) { Q[offset+15] -= 1<<6; m[14] -= 1<<6; m[15] +=1<<11; compute_mt<16,23>(); compute_qt<16,23>(); if ( (Q[offset+23]&((1<<31)|(1<<27)|(1<<0))) == ((1<<31)^(1<<0)^(Q[offset+22]&((1<<27)|(1<<0)))) ) step_23_case01(); Q[offset+15] += 1<<6; m[14] += 1<<6; m[15] -=1<<11; } else { Q[offset+15] += 1<<6; m[14] += 1<<6; m[15] -=1<<11; compute_mt<16,23>(); compute_qt<16,23>(); if ( (Q[offset+23]&((1<<31)|(1<<27)|(1<<0))) == ((1<<31)^(1<<0)^(Q[offset+22]&((1<<27)|(1<<0)))) ) step_23_case01(); Q[offset+15] -= 1<<6; m[14] -= 1<<6; m[15] +=1<<11; } Q[offset+7] -= 1<<7; m[6] -= 1<<7; m[7] += 1<<12; m[11] += 1<<5; } void step_22_case4() { UPDATE(22); compute_mt<22,23>(); compute_qt<22,23>(); const uint32 Q23val = ((1<<31)^((Q[offset+21]>>2)&(7<<27))) ; step_23_case4(); Q[offset+7] += 1<<7; m[6] += 1<<7; m[7] -= 1<<12; m[11] -= 1<<5; if (m[14]&(1<<6)) { Q[offset+15] -= 1<<6; m[14] -= 1<<6; m[15] +=1<<11; compute_mt<16,23>(); compute_qt<16,23>(); step_23_case4(); Q[offset+15] += 1<<6; m[14] += 1<<6; m[15] -=1<<11; } else { Q[offset+15] += 1<<6; m[14] += 1<<6; m[15] -=1<<11; compute_mt<16,23>(); compute_qt<16,23>(); step_23_case4(); Q[offset+15] -= 1<<6; m[14] -= 1<<6; m[15] +=1<<11; } Q[offset+7] -= 1<<7; m[6] -= 1<<7; m[7] += 1<<12; m[11] += 1<<5; } void step_21b() { UPDATE(21); compute_mt<21,22>(); compute_qt<21,22>(); const uint32 Q22val = (Q[offset+21]>>2) & (1<<27); const uint32 Q22val2 = Q22val ^ (3<<29); const uint32 Q22mask = (1<<27)|(1<<29); const uint32 Q22mask2 = (1<<27)|(7<<29); const uint32 Q22bu = Q[offset+22]; if ( (Q[offset+22]&Q22mask)==Q22val) step_22_case01(); else if ( (Q[offset+22]&Q22mask2)==Q22val2) step_22_case4(); if ( ((Q22bu-(1<<29))&Q22mask)==Q22val || ((Q22bu-(1<<29))&Q22mask2)==Q22val2) { Q[offset+12] -= 1<<6; Qr30[offset+12] = rotate_left(Q[offset+12],30); m[11] -= 1<<6; m[12] += 1<<11; compute_mt<16,22>(); compute_qt<16,22>(); if ( (Q[offset+22]&Q22mask)==Q22val) step_22_case01(); else if ( (Q[offset+22]&Q22mask2)==Q22val2) step_22_case4(); Q[offset+12] += 1<<6; Qr30[offset+12] = rotate_left(Q[offset+12],30); m[11] += 1<<6; m[12] -= 1<<11; } if ((( (Q22bu + (1<<26) - ((m[17]&(1<<6))<<21)) & (1<<27)) ) != Q22val) return; Q[offset+10] += 1<<7; m[9] += 1<<7; m[10] -= 1<<12; m[14] -= 1<<5; compute_mt<16,22>(); compute_qt<16,22>(); const uint32 Q22bu2 = Q[offset+22]; if ( (Q[offset+22]&Q22mask)==Q22val) step_22_case01(); else if ( (Q[offset+22]&Q22mask2)==Q22val2) step_22_case4(); if ( ((Q22bu2-(1<<29))&Q22mask)==Q22val || ((Q22bu2-(1<<29))&Q22mask2)==Q22val2) { Q[offset+12] -= 1<<6; Qr30[offset+12] = rotate_left(Q[offset+12],30); m[11] -= 1<<6; m[12] += 1<<11; compute_mt<16,22>(); compute_qt<16,22>(); if ( (Q[offset+22]&Q22mask)==Q22val) step_22_case01(); else if ( (Q[offset+22]&Q22mask2)==Q22val2) step_22_case4(); Q[offset+12] += 1<<6; Qr30[offset+12] = rotate_left(Q[offset+12],30); m[11] += 1<<6; m[12] -= 1<<11; } Q[offset+10] -= 1<<7; m[9] -= 1<<7; m[10] += 1<<12; m[14] += 1<<5; } void step_21() { UPDATE(20); step_21b(); Q[offset+10] += 1<<6; Q[offset+15] += 1<<6; m[9] += 1<<6; m[10] -= 1<<11; m[14] += (1<<6) - (1<<4); m[15] -= 1<<11; compute_mt<16,21>(); compute_qt<16,21>(); step_21b(); Q[offset+10] -= 1<<6; Q[offset+15] -= 1<<6; m[9] -= 1<<6; m[10] += 1<<11; m[14] -= (1<<6) - (1<<4); m[15] += 1<<11; } void step_19() { UPDATE(19); compute_mt<19,21>(); compute_qt<19,21>(); if ((Q[offset+21]^(Q[offset+20]>>2))&(1<<29)) return; const uint32 Q20mask = (1<<29)|(1<<27)|(1<<31); const uint32 Q20val = ((Q[offset+19]>>2)&(1<<27))|(Q[offset+20]&(1<<31)); const uint32 Q20bu = Q[offset+20]; const uint32 Q21mask = (1<<31)|(1<<29);//|(1<<27); const uint32 Q21mask2 = (1<<31)|(1<<29)|(1<<27); const uint32 Q21val = ((0-(Q[offset+20]>>31))&((1<<31)|(1<<29))) | ((Q[offset+19]>>2)&(1<<27)); const uint32 Q21bu = Q[offset+21]; const uint32 m16bu = m[16], m17bu = m[17], Q17bu = Q[offset+17]; if ((Q20bu&Q20mask)==Q20val && ((Q21bu^Q21val)&Q21mask2)==0) { step_21(); } #define m15tunnel(m15add) \ if (((Q20bu+(m15add<<20))&Q20mask)==Q20val && (((Q21bu+(m15add<<25))^Q21val)&Q21mask)==0) {\ m[15] += m15add; Q[offset+16] += m15add; Q[offset+17] = Q17bu + (m15add<<5);\ Qr30[offset+14] = rotate_left(Q[offset+14],30);\ m[16] = m16bu; m[17] = m17bu;\ compute_mt<18,20>();\ compute_qt<17,20>();\ if ((Q[offset+20]&Q20mask)==Q20val && (Q[offset+19]&((1<<31)|(1<<27)))==gQ19val \ && ((Q[offset+18]&2952790016)==2147483648) && ( (Q[offset+17]&((1<<31)|(1<<28)|(1<<1)))==((1<<28)^(1<<1)) ) \ ) {\ compute_mt<20,21>();\ compute_qt<20,21>();\ if ((Q[offset+21]&Q21mask2)==Q21val)\ step_21();\ }\ m[15] -= m15add; Q[offset+16] -= m15add;\ } m15tunnel(1<<5); m15tunnel(2<<5); m15tunnel(3<<5); m15tunnel(4<<5); m15tunnel(5<<5); m15tunnel(6<<5); m15tunnel(7<<5); m15tunnel(8<<5); m15tunnel(9<<5); m15tunnel(10<<5); m15tunnel(11<<5); m15tunnel(12<<5); m15tunnel(13<<5); m15tunnel(14<<5); m15tunnel(15<<5); } void step_18b() { UPDATE(18); const uint32 Q19mask = (1<<31)|(1<<27); gQ19val = (1<<31)^(rotate_left(Q[offset+17],30)&(1<<27)); const uint32 Q19bu = Q[offset+19]; const uint32 m16 = m[16]; if ((Q19bu&(1<<31))==(1<<31)) { const uint32 m17 = m[17]; if (((Q19bu&Q19mask)==gQ19val) && ((Q[offset+18]&2952790016)==2147483648) && ( (Q[offset+17]&((1<<31)|(1<<28)|(1<<1)))==((1<<28)^(1<<1)) )) step_19(); #define M15tunnel(m15add,m14add) \ if (((Q19bu+(m15add<<15)+(m14add<<20))&Q19mask)==gQ19val) {\ m[15] += m15add; Q[offset+16] += m15add; Q[offset+17] = Q17pc + rotate_left(Q[offset+16],5);\ m[16] = m16; m[17] = m17; \ compute_mt<18,19>();\ Qr30[offset+14] = rotate_left(Q[offset+14],30);\ compute_qt<17,19>();\ if (((Q[offset+19]&Q19mask)==gQ19val) && ((Q[offset+18]&2952790016)==2147483648) && ( (Q[offset+17]&((1<<31)|(1<<28)|(1<<1)))==((1<<28)^(1<<1)) ))\ step_19();\ m[15] -= m15add; Q[offset+16] -= m15add;\ } Qr30[offset+14] = rotate_left(Q[offset+14],30); const uint32 Q17pc = sha1_ac[0] + sha1_f1(Q[offset+15],Qr30[offset+14],Qr30[offset+13]) + Qr30[offset+12] + m16; M15tunnel( (1<<9), 0 ); // 9 M15tunnel( (2<<9), 0 ); // 10 M15tunnel( (3<<9), 0 ); // 9,10 M15tunnel( (8<<9), 0 ); // 12 M15tunnel( (9<<9), 0 ); // 9,12 M15tunnel( (10<<9), 0 ); // 10,12 M15tunnel( (11<<9), 0 ); // 9,10,12 } #define M14tunnel(m14add) \ if (((Q19bu+(m14add<<20))&(1<<31))==(1<<31)) {\ m[14] += m14add; Q[offset+15] += m14add; Q[offset+16] += m14add<<5;\ compute_mt<17,18>();\ const uint32 m17 = m[17];\ Qr30[offset+14] = rotate_left(Q[offset+14],30);\ const uint32 Q17pc = sha1_ac[0] + sha1_f1(Q[offset+15],Qr30[offset+14],Qr30[offset+13]) + Qr30[offset+12] + m16;\ M15tunnel( (0<<9), m14add ); \ M15tunnel( (1<<9), m14add ); \ M15tunnel( (2<<9), m14add ); \ M15tunnel( (3<<9), m14add ); \ M15tunnel( (8<<9), m14add ); \ M15tunnel( (9<<9), m14add ); \ M15tunnel( (10<<9), m14add ); \ M15tunnel( (11<<9), m14add ); \ m[14] -= m14add; Q[offset+15] -= m14add; Q[offset+16] -= m14add<<5;\ } M14tunnel( (1<<7) ); M14tunnel( (2<<7) ); M14tunnel( (3<<7) ); M14tunnel( (4<<7) ); M14tunnel( (5<<7) ); M14tunnel( (6<<7) ); M14tunnel( (7<<7) ); } void step_18() { UPDATE(17); compute_mt<18,19>(); compute_qt<18,19>(); step_18b(); if (Q[offset+1]&(1<<7)) { Q[offset+1]-=1<<7; m[0] -= 1<<7; m[1] += 1<<12; m[5] += 1<<5; Q[offset+13]+=1<<10; Qr30[offset+13] = rotate_left(Q[offset+13],30); m[12]+=1<<10; m[13]-=1<<15; compute_mt<16,19>(); compute_qt<16,19>(); step_18b(); Q[offset+13]-=1<<10; Qr30[offset+13] = rotate_left(Q[offset+13],30); m[12]-=1<<10; m[13]+=1<<15; Q[offset+1]+=1<<7; m[0] += 1<<7; m[1] -= 1<<12; m[5] -= 1<<5; } else { Q[offset+1]+=1<<7; m[0] += 1<<7; m[1] -= 1<<12; m[5] -= 1<<5; Q[offset+13]+=1<<10; Qr30[offset+13] = rotate_left(Q[offset+13],30); m[12]+=1<<10; m[13]-=1<<15; compute_mt<16,19>(); compute_qt<16,19>(); step_18b(); Q[offset+13]-=1<<10; Qr30[offset+13] = rotate_left(Q[offset+13],30); m[12]-=1<<10; m[13]+=1<<15; Q[offset+1]-=1<<7; m[0] -= 1<<7; m[1] += 1<<12; m[5] += 1<<5; } } void step_17() { UPDATE(16); compute_mt<17,18>(); compute_qt<17,18>(); const uint32 Q18bu = Q[offset+18]; if ((Q18bu&2952790016)==2147483648) { step_18(); } if (((Q18bu+(1<<25))&2952790016)==2147483648) { m[14] += 1<<10; Q[offset+15] += 1<<10; Q[offset+16] += 1<<15; compute_mt<16,18>(); compute_qt<16,18>(); if ( ((Q[offset+18]&2952790016)==2147483648) & ( (Q[offset+17]&((1<<31)|(1<<28)|(1<<1)))==((1<<28)^(1<<1)) ) ) step_18(); m[14] -= 1<<10; Q[offset+15] -= 1<<10; Q[offset+16] -= 1<<15; } const uint32 Q18budiff = Q18bu + ((1<<27) - ((m[14]<<16)&(1<<28))); // m14[!12!] = 1 => Q18diff = -(1<<27) // m14[!12!] = 0 => Q18diff = +(1<<27) if (((Q18budiff)&2952790016)==2147483648) { Q[offset+1]+=1<<7; m[0] += 1<<7; m[1] -= 1<<12; m[5] -= 1<<5; if (m[14]&(1<<12)) { m[14] -= 1<<12; Q[offset+15] -= 1<<12; Q[offset+16] -= 1<<17; compute_mt<16,18>(); compute_qt<16,18>(); if ( ((Q[offset+18]&2952790016)==2147483648) & ( (Q[offset+17]&((1<<31)|(1<<28)|(1<<1)))==((1<<28)^(1<<1)) ) ) step_18(); m[14] += 1<<12; Q[offset+15] += 1<<12; Q[offset+16] += 1<<17; } else { m[14] += 1<<12; Q[offset+15] += 1<<12; Q[offset+16] += 1<<17; compute_mt<16,18>(); compute_qt<16,18>(); if ( ((Q[offset+18]&2952790016)==2147483648) & ( (Q[offset+17]&((1<<31)|(1<<28)|(1<<1)))==((1<<28)^(1<<1)) ) ) step_18(); m[14] -= 1<<12; Q[offset+15] -= 1<<12; Q[offset+16] -= 1<<17; } Q[offset+1]-=1<<7; m[0] -= 1<<7; m[1] += 1<<12; m[5] += 1<<5; } if (((Q18budiff+(1<<25))&2952790016)==2147483648) { Q[offset+1]+=1<<7; m[0] += 1<<7; m[1] -= 1<<12; m[5] -= 1<<5; if (m[14]&(1<<12)) { m[14] += 0 - (1<<12) + (1<<10); Q[offset+15] += 0 - (1<<12) + (1<<10); Q[offset+16] += 0 - (1<<17) + (1<<15); compute_mt<16,18>(); compute_qt<16,18>(); if ( ((Q[offset+18]&2952790016)==2147483648) & ( (Q[offset+17]&((1<<31)|(1<<28)|(1<<1)))==((1<<28)^(1<<1)) ) ) step_18(); m[14] -= 0 - (1<<12) + (1<<10); Q[offset+15] -= 0 - (1<<12) + (1<<10); Q[offset+16] -= 0 - (1<<17) + (1<<15); } else { m[14] += (1<<12) + (1<<10); Q[offset+15] += (1<<12) + (1<<10); Q[offset+16] += (1<<17) + (1<<15); compute_mt<16,18>(); compute_qt<16,18>(); if ( ((Q[offset+18]&2952790016)==2147483648) & ( (Q[offset+17]&((1<<31)|(1<<28)|(1<<1)))==((1<<28)^(1<<1)) ) ) step_18(); m[14] -= (1<<12) + (1<<10); Q[offset+15] -= (1<<12) + (1<<10); Q[offset+16] -= (1<<17) + (1<<15); } Q[offset+1]-=1<<7; m[0] -= 1<<7; m[1] += 1<<12; m[5] += 1<<5; } } void step_15() { const unsigned t = 15; UPDATE(t); Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); uint32 m13bu = m[13], Q14bu = Q[offset+14], m14bu = m[14], Q15bu = Q[offset+15], m13adj = 0; uint32 m13ok = 0, cnt = 0; const uint32 m13mask = 9952; do { ++cnt; m[13] = m13bu ^ m13adj; m13adj -= 1; m13adj &= m13mask; Q[offset+14] = Q14bu + (m[13]-m13bu); m[13] ^= ((Q[offset+14]^Q14bu) & 256); Q[offset+14] = Q14bu + (m[13]-m13bu); const uint32 m14xor = (rotate_left(m[13]^m13bu,2)&2048); //2048=[!11!], 512=[!9!]; const uint32 Q15adj = rotate_left(Q[offset+14],5) - rotate_left(Q14bu,5); const uint32 mpartial2 = 0 - (sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) + sha1_ac[0] + Qr30[offset+t-4]); m[14] = m14bu ^ m14xor; Q[offset+t] = Q15bu + Q15adj + (m[14]-m14bu); const uint32 metset1 = metset1precomp[14][15]; const uint32 Qtp1val = Qvalue[offset+t+1]; const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); Q[offset+t+1] = metset1-mpartial; if (0 != ((Q[offset+t+1]^Qtp1val)&3892314114)) { if (cnt >= 2 && m13ok == 0) break; continue; } if ((Q[offset+14]^Q14bu) & 805306386) continue; if ((Q[offset+t]^Q15bu) & 2818572355) continue; m[t] = metset1; time_avg[t] += 1;//required to disable auto restart to step7 ++m13ok; compute_mt<16,17>(); compute_qt<16,17>(); if ((Q[offset+17]&2415919104)!=268435456) continue; if ((Q[offset+17]&2)!=2) { Q[offset+7] ^= 1<<5; Q[offset+12] ^= 1<<3; Qr30[offset+12] = rotate_left(Q[offset+12],30); m[6] += 1<<5; m[7] -= 1<<10; m[12] -= 1<<8; Q[offset+17] += 1<<2; step_17(); Q[offset+7] ^= 1<<5; Q[offset+12] ^= 1<<3; Qr30[offset+12] = rotate_left(Q[offset+12],30); m[6] -= 1<<5; m[7] += 1<<10; m[12] += 1<<8; } else step_17(); } while (m13adj != 0); m[13] = m13bu; Q[offset+14] = Q14bu; } void step_14() { const unsigned t = 14; if (time_avg[40]) ++time_avg[t]; UPDATE(t); Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); m[t-1] = *Qtp1valsvec[t-1] + metpartialvec[t-1]; const uint32 metset13m13precomp = metset1precomp[13][14] ^ 0 ^((0-(m[13]&(1<<0)))&5748736) //5748736=[!11,12,13,15,16,17,18,20,22!] ^(rotate_left(m[13],2)&2048) //2048=[!11!], 512=[!9!] ^(rotate_left(m[13],14)&4096) //4096=[!12!], 1073741824=[!30!] ; const uint32 m12mask = 159744; uint32 m12bu = m[12], Q13bu = Q[offset+13], m12adj = 0; uint32 m12okcnt = 0; do { m[12] = m12bu ^ m12adj; m12adj -= 1; m12adj &= m12mask; Q[offset+13] = Q13bu + (m[12]-m12bu); if ((Q[offset+13]^Q13bu)&2550137872) continue; const uint32 Q14adj = rotate_left(Q[offset+13],5)-rotate_left(Q13bu,5); const uint32 m14precomp = metset13m13precomp ^(rotate_left(m[12]^m12bu,31)&31455235) //31455235=[!0,1,11,12,13,14,15,16,17,18,19,20,22,23,24!], 62910470=[!1,2,12,13,14,15,16,17,18,19,20,21,23,24,25!] ^(rotate_left(m[12]^m12bu,29)&8153088) //8153088=[!11,13,14,18,19,20,21,22!], 65224704=[!14,16,17,21,22,23,24,25!] ^(rotate_left(m[12]^m12bu,30)&2099200) //2099200=[!11,21!], 8396800=[!13,23!] ; const uint32 m15precomp = 0 ^(rotate_left(m[12]^m12bu,28)&1076600832) //1076600832=[!13,15,16,17,19,21,30!], 45744132=[!2,17,19,20,21,23,25!] ; const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; for (uint32* Qtvalsptr = Qtp1valsvec[t-1]; Qtvalsptr < Qtp1valsvecptr[t-1]; ++Qtvalsptr) { m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = m14precomp // metset13m13precomp // metset1precomp[13][14] ^ 0 // ^((0-(m[13]&(1<<0)))&5748736) //5748736=[!11,12,13,15,16,17,18,20,22!] ^((0-((m[13]>>14)&1))&5697536) //5697536=[!12,13,14,15,17,18,20,22!] ^((0-((m[13]>>16)&1))&7389184) //7389184=[!14,15,20,21,22!] ^((0-(m[13]&(1<<11)))&2297856) //2297856=[!12,16,17,21!] ^((0-(m[13]&(1<<12)))&2297856) //2297856=[!12,16,17,21!] // ^(rotate_left(m[13],2)&2048) //2048=[!11!], 512=[!9!] // ^(rotate_left(m[13],14)&4096) //4096=[!12!], 1073741824=[!30!] ; m[14] = metset1; Q[offset+t] = *Qtvalsptr + Q14adj; const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); Q[offset+t+1] = metset1 - mpartial; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]); if (Qtvalsptr == Qtp1valsvec[t-1] && 0 != ((Q[offset+t+1]^Qtp1val)&67)) { m[12] = m12bu; Q[offset+13] = Q13bu; return; } if (0 != ((Q[offset+t+1]^Qtp1val)&2818572355)) continue; if ((Q[offset+t]^*Qtvalsptr) & 805306386) continue; metset1precomp[14][15] = metset1precomp[13][15] ^ 0 ^((0-(m[13]&(1<<16)))&1100808192) //1100808192=[!16,18,19,20,23,24,30!] ^((0-((m[13]>>14)&1))&9199620) //9199620=[!2,13,14,18,19,23!] ^((0-(m[13]&(1<<0)))&1082679296) //1082679296=[!13,14,19,23,30!] ^((0-(m[13]&(1<<11)))&16850944) //16850944=[!13,16,24!] ^((0-(m[13]&(1<<12)))&16850944) //16850944=[!13,16,24!] ^m15precomp; ; step_15(); } } while (m12adj != 0); m[12] = m12bu; Q[offset+13] = Q13bu; } #define M13BIT11 ((1<<11)|(1<<17)|(1<<19)|(1<<24)) #define M13BIT12 ((1<<12)|(1<<17)|(1<<19)|(1<<24)) #define M13BIT14 ((1<<14)|(1<<18)|(1<<19)|(1<<20)|(1<<21)|(1<<24)) #define M13BIT16 ((1<<16)|(1<<17)|(1<<18)|(1<<20)) const uint32 metcur13vals[1<<4] = { 0, M13BIT11, M13BIT12, M13BIT11^M13BIT12, 0^M13BIT14, M13BIT11^M13BIT14, M13BIT12^M13BIT14, M13BIT11^M13BIT12^M13BIT14, 0^M13BIT16, M13BIT11^M13BIT16, M13BIT12^M13BIT16, M13BIT11^M13BIT12^M13BIT16, 0^M13BIT16^M13BIT14, M13BIT11^M13BIT16^M13BIT14, M13BIT12^M13BIT16^M13BIT14, M13BIT11^M13BIT12^M13BIT16^M13BIT14 }; bool step_13() { const unsigned t = 13; if (time_avg[40]) ++time_avg[t]; UPDATE(t); bool step13ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 3221127198; const uint32 m12bu = m[12] = *Qtp1valsvec[t-1] + metpartialvec[t-1]; const uint32 metset1precomp12 = metset1precomp[12][13] ^ 0 ^((0-(m[12]&(1<<0)))&20709376) //20709376=[!18,19,20,21,24!] ^((0-(m[12]&(1<<2)))&2165702656) //2165702656=[!17,18,20,24,31!] ^((0-((m[12]>>30)&1))&19791872) //19791872=[!17,18,19,21,24!] ^((0-(m[12]&(1<<18)))&3407872) //3407872=[!18,20,21!] ^((0-((m[12]>>20)&1))&18350080) //18350080=[!19,20,24!] ^((0-((m[12]>>22)&1))&2228224) //2228224=[!17,21!] ^(rotate_left(m[12],30)&1966080) //1966080=[!17,18,19,20!], 7864320=[!19,20,21,22!] ^(rotate_left(m[12],1)&16908288) //16908288=[!17,24!], 8454144=[!16,23!] ^(rotate_left(m[12],28)&3145728) //3145728=[!20,21!], 50331648=[!24,25!] ^(rotate_left(m[12],2)&131072) //131072=[!17!], 32768=[!15!] ^(rotate_left(m[12],3)&16777216) //16777216=[!24!], 2097152=[!21!] ^(rotate_left(m[12],23)&16777216) //16777216=[!24!], 2=[!1!] ^(rotate_left(m[12],24)&131072) //131072=[!17!], 33554432=[!25!] ^(rotate_left(m[12],26)&131072) //131072=[!17!], 8388608=[!23!] ^(rotate_left(m[12],29)&2097152) //2097152=[!21!], 16777216=[!24!] ; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; bool didmp = false; const uint32 metset1 = metset1precomp12 ^((0-((m[12]^m12bu)&(1<<18)))&3407872) //3407872=[!18,20,21!] ^(rotate_left(m[12]^m12bu,1)&16908288) //16908288=[!17,24!], 8454144=[!16,23!] ^(rotate_left(m[12]^m12bu,2)&131072) //131072=[!17!], 32768=[!15!] ; const uint32 Qtp1val = Qvalue[offset+t+1];// ^ (Qprev[offset+t+1]&Q[offset+t]); const uint32 metset1adj = metset1 ^ ((~Qtp1val) & 256);// ^ (xrng64()&1073839841); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 1|(1<<30); do { cur -= 1; cur &= curmask; const uint32 curadj = metset1adj ^ cur ^ ( (0-(cur&1))&( (1<<18)|(1<<19)|(1<<20)|(1<<21)|(1<<24) ) ) ; Qtp1valsptr = Qtp1valsvec[t]; for (unsigned jj = 0; jj < (1<<4); ++jj) { // m[t] = metcur13vals[jj] ^ curadj; Q[offset+t+1] = (metcur13vals[jj] ^ curadj) - mpartial; if (0 != ((Q[offset+t+1]^Qtp1val)&805306386)) break; //continue; uint32 Qtp1xorfix = (Q[offset+t+1]^Qtp1val) & 256; *(Qtp1valsptr++) = Q[offset+t+1]^Qtp1xorfix; } if (Qtp1valsptr == Qtp1valsvec[t]) continue; step13ok = true; if (!didmp) { UPDATE(73); metset1precomp[13][14] = metset1precomp[12][14] ^ 0 ^((0-(m[12]&(1<<2)))&1086244864) //1086244864=[!11,14,15,17,18,19,20,21,23,30!] ^((0-((m[12]>>18)&1))&7628800) //7628800=[!11,13,14,18,20,21,22!] ^((0-((m[12]>>22)&1))&5566464) //5566464=[!12,13,14,15,18,20,22!] ^((0-(m[12]&(1<<1)))&874496) //874496=[!11,12,14,16,18,19!] ^((0-((m[12]>>20)&1))&5345280) //5345280=[!12,15,16,20,22!] ^((0-((m[12]>>21)&1))&2330624) //2330624=[!12,15,16,17,21!] ^((0-(m[12]&(1<<0)))&1474560) //1474560=[!15,17,18,20!] ^((0-((m[12]>>30)&1))&3221504000) //3221504000=[!14,18,30,31!] ^((0-((m[12]>>16)&1))&71680) //71680=[!11,12,16!] ^((0-((m[12]>>15)&1))&67584) //67584=[!11,16!] ^((0-((m[12]>>24)&1))&73728) //73728=[!13,16!] ^(rotate_left(m[12],31)&31455235) //31455235=[!0,1,11,12,13,14,15,16,17,18,19,20,22,23,24!], 62910470=[!1,2,12,13,14,15,16,17,18,19,20,21,23,24,25!] ^(rotate_left(m[12],29)&8153088) //8153088=[!11,13,14,18,19,20,21,22!], 65224704=[!14,16,17,21,22,23,24,25!] ^(rotate_left(m[12],22)&5300224) //5300224=[!13,14,15,20,22!], 1132462081=[!0,23,24,25,30!] ^(rotate_left(m[12],26)&532480) //532480=[!13,19!], 34078720=[!19,25!] ^(rotate_left(m[12],30)&2099200) //2099200=[!11,21!], 8396800=[!13,23!] ^(rotate_left(m[12],19)&4096) //4096=[!12!], 33554432=[!25!] ^(rotate_left(m[12],25)&65536) //65536=[!16!], 8388608=[!23!] ; metset1precomp[13][15] = metset1precomp[12][15] ^ 0 ^((0-(m[12]&(1<<1)))&24682500) //24682500=[!2,13,15,19,20,21,22,24!] ^((0-((m[12]>>18)&1))&28114948) //28114948=[!2,16,18,19,21,23,24!] ^((0-((m[12]>>22)&1))&25919492) //25919492=[!2,15,16,17,19,23,24!] ^((0-((m[12]>>30)&1))&9871364) //9871364=[!2,13,15,17,18,20,23!] ^((0-((m[12]>>20)&1))&1083998208) //1083998208=[!15,18,19,20,23,30!] ^((0-((m[12]>>24)&1))&1074479108) //1074479108=[!2,14,16,17,19,30!] ^((0-(m[12]&(1<<0)))&8929284) //8929284=[!2,14,19,23!] ^((0-(m[12]&(1<<2)))&15728640) //15728640=[!20,21,22,23!] ^((0-((m[12]>>23)&1))&17080320) //17080320=[!13,15,18,24!] ^((0-((m[12]>>19)&1))&2121728) //2121728=[!13,14,21!] ^((0-((m[12]>>25)&1))&1441792) //1441792=[!17,18,20!] ^((0-((m[12]>>15)&1))&2105344) //2105344=[!13,21!] ^((0-((m[12]>>16)&1))&2105344) //2105344=[!13,21!] ^((0-((m[12]>>21)&1))&16793600) //16793600=[!14,24!] ^(rotate_left(m[12],28)&1076600832) //1076600832=[!13,15,16,17,19,21,30!], 45744132=[!2,17,19,20,21,23,25!] ; } didmp = true; Qtp1valsvecptr[t] = Qtp1valsptr; step_14(); } while (cur != 0); } return true; // step13ok; } bool step_12() { static bool firsttime = true; if (firsttime) { cout << "t12 " << endl; firsttime = false; } const unsigned t = 12; if (time_avg[40]) ++time_avg[t]; UPDATE(t); show_performance_data(t); bool step12ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 3154119704; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; bool didmp = false; bool s13ok = false; const uint32 metset1 = metset1precomp[11][12]; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]); const uint32 metset1adj = metset1 ^ ((~Qtp1val) & 258); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 1140327141;//1136657125; do { cur -= 1; cur &= curmask; uint32 metcur = 0; Qtp1valsptr = Qtp1valsvec[t]; do { m[t] = metcur ^ cur ^ metset1adj; metcur -= 1; metcur &= 1140847333^curmask^159744; // 21 bits of freedom Q[offset+t+1] = m[t] - mpartial; // don't check for Q13[31] if (0 != ((Q[offset+t+1]^Qtp1val) & (2550137872^(1<<31)) )) break; uint32 Qtp1xorfix = (Q[offset+t+1]^Qtp1val) & 258; // compute fixed m[t] m[t] = (Q[offset+t+1]^Qtp1xorfix) + mpartial; if ((m[t]&768)==0) continue; // tunnel Q7-5 Q12-3 me condition m[t] ^= (m[t]&(1<<1))<<30; // intrel bit 31: (12,1)(12,31) Q[offset+t+1] = m[t] - mpartial; // check for Q13[31] (and the rest) if (0 != ((Q[offset+t+1]^Qtp1val) & (2550137872) )) continue; *(Qtp1valsptr++) = Q[offset+t+1]; } while (metcur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step12ok = true; if (!didmp) { metset1precomp[12][13] = metset1precomp[11][13] ^ 0 ^((0-(m[11]&(1<<0)))&4063232) //4063232=[!17,18,19,20,21!] ^((0-(m[11]&(1<<15)))&3538944) //3538944=[!17,18,20,21!] ^((0-((m[11]>>31)&1))&3538944) //3538944=[!17,18,20,21!] ^((0-(m[11]&(1<<12)))&17432576) //17432576=[!17,19,24!] ^((0-(m[11]&(1<<13)))&17432576) //17432576=[!17,19,24!] ^((0-((m[11]>>20)&1))&3407872) //3407872=[!18,20,21!] ^((0-((m[11]>>21)&1))&17432576) //17432576=[!17,19,24!] ^(rotate_left(m[11],31)&2178416640) //2178416640=[!19,20,22,23,24,31!], 61865985=[!0,20,21,23,24,25!] ^(rotate_left(m[11],29)&6029312) //6029312=[!18,19,20,22!], 48234496=[!21,22,23,25!] ^(rotate_left(m[11],26)&917504) //917504=[!17,18,19!], 58720256=[!23,24,25!] ^(rotate_left(m[11],1)&1048576) //1048576=[!20!], 524288=[!19!] ^(rotate_left(m[11],3)&131072) //131072=[!17!], 16384=[!14!] ^(rotate_left(m[11],4)&2097152) //2097152=[!21!], 131072=[!17!] ^(rotate_left(m[11],25)&131072) //131072=[!17!], 16777216=[!24!] ; metset1precomp[12][14] = metset1precomp[11][14] ^ 0 ^((0-(m[11]&(1<<0)))&3227236352) //3227236352=[!11,12,13,15,16,17,19,20,22,30,31!] ^((0-((m[11]>>20)&1))&7665664) //7665664=[!11,12,13,14,15,18,20,21,22!] ^((0-((m[11]>>15)&1))&7725056) //7725056=[!13,14,15,16,18,20,21,22!] ^((0-((m[11]>>24)&1))&1439744) //1439744=[!11,12,13,14,15,16,18,20!] ^((0-((m[11]>>31)&1))&7710720) //7710720=[!11,13,15,16,18,20,21,22!] ^((0-((m[11]>>19)&1))&7428096) //7428096=[!11,12,14,16,20,21,22!] ^((0-((m[11]>>23)&1))&587776) //587776=[!11,12,13,14,15,19!] ^((0-((m[11]>>12)&1))&2299904) //2299904=[!11,12,16,17,21!] ^((0-((m[11]>>21)&1))&2177024) //2177024=[!11,12,13,16,21!] ^((0-((m[11]>>13)&1))&2297856) //2297856=[!12,16,17,21!] ^((0-((m[11]>>30)&1))&2147561472) //2147561472=[!12,13,16,31!] ^((0-(m[11]&(1<<1)))&77824) //77824=[!12,13,16!] ^((0-((m[11]>>14)&1))&71680) //71680=[!11,12,16!] ^((0-((m[11]>>17)&1))&329728) //329728=[!11,16,18!] ^((0-((m[11]>>18)&1))&83968) //83968=[!11,14,16!] ^((0-((m[11]>>22)&1))&86016) //86016=[!12,14,16!] ^((0-((m[11]>>25)&1))&2260992) //2260992=[!15,17,21!] ^(rotate_left(m[11],1)&2048) //2048=[!11!], 1024=[!10!] ; metset1precomp[12][15] = metset1precomp[11][15] ^ 0 ^((0-(m[11]&(1<<0)))&1104470016) //1104470016=[!13,14,15,18,20,22,23,24,30!] ^((0-((m[11]>>20)&1))&26173444) //26173444=[!2,13,14,16,17,18,19,23,24!] ^((0-((m[11]>>19)&1))&1102848000) //1102848000=[!13,18,19,20,21,23,24,30!] ^((0-((m[11]>>15)&1))&26034180) //26034180=[!2,14,16,18,19,23,24!] ^((0-((m[11]>>24)&1))&1075011588) //1075011588=[!2,13,14,16,17,20,30!] ^((0-((m[11]>>31)&1))&27869188) //27869188=[!2,14,16,19,21,23,24!] ^((0-(m[11]&(1<<12)))&16850944) //16850944=[!13,16,24!] ^((0-((m[11]>>22)&1))&1074790404) //1074790404=[!2,20,30!] ^((0-((m[11]>>25)&1))&2236416) //2236416=[!13,17,21!] ^((0-(m[11]&(1<<13)))&16785408) //16785408=[!13,24!] ^((0-((m[11]>>14)&1))&2105344) //2105344=[!13,21!] ^((0-((m[11]>>17)&1))&1073741828) //1073741828=[!2,30!] ^(rotate_left(m[11],29)&1079812096) //1079812096=[!13,15,18,19,20,22,30!], 48562178=[!1,16,18,21,22,23,25!] ^(rotate_left(m[11],3)&19988480) //19988480=[!16,20,21,24!], 2498560=[!13,17,18,21!] ^(rotate_left(m[11],25)&376832) //376832=[!14,15,16,18!], 48234496=[!21,22,23,25!] ^(rotate_left(m[11],27)&73728) //73728=[!13,16!], 2359296=[!18,21!] ^(rotate_left(m[11],20)&2097152) //2097152=[!21!], 2=[!1!] ^(rotate_left(m[11],23)&2097152) //2097152=[!21!], 1073741824=[!30!] ^(rotate_left(m[11],24)&32768) //32768=[!15!], 8388608=[!23!] ; } didmp = true; Qtp1valsvecptr[t] = Qtp1valsptr; if (step_13()) s13ok = true; } while (cur != 0); if (!s13ok) return step12ok; } return step12ok; } bool step_11() { static bool firsttime = true; if (firsttime) { cout << "t11 " << flush; firsttime = false; } const unsigned t = 11; if (time_avg[40]) ++time_avg[t]; UPDATE(t); show_performance_data(t); bool step11ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 1006633212; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = metset1precomp[10][11] ^ 0 ; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]); const uint32 metset1adj = metset1 ^ ((~Qtp1val) & 3221229570) ^ (xrng64()&67104513); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; bool didmp = false; bool step12ok = false; //uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 62914561; // 5 bits do { cur -= 1; cur &= curmask; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 metcur = 0; do { m[t] = metcur ^ cur ^ metset1adj; metcur -= 1; metcur &= 67104513^curmask; // 18 bits of freedom Q[offset+t+1] = m[t] - mpartial; if (0 != ((Q[offset+t+1]^Qtp1val)&134217848)) break; uint32 Qtp1xorfix = (Q[offset+t+1]^Qtp1val) & 3221229570; *(Qtp1valsptr++) = Q[offset+t+1]^Qtp1xorfix; } while (metcur != 0); //} while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step11ok = true; if (!didmp) { didmp = true; metset1precomp[11][12] = metset1precomp[10][12] ^ 0 ^(rotate_left(m[10],1)&2147483648) //2147483648=[!31!], 1073741824=[!30!] ; metset1precomp[11][13] = metset1precomp[10][13] ^ 0 ^((0-((m[10]>>30)&1))&20840448) //20840448=[!17,18,19,20,21,24!] ^((0-((m[10]>>22)&1))&20578304) //20578304=[!17,19,20,21,24!] ^((0-((m[10]>>19)&1))&20185088) //20185088=[!18,20,21,24!] ^((0-((m[10]>>25)&1))&3538944) //3538944=[!17,18,20,21!] ^((0-(m[10]&(1<<15)))&17432576) //17432576=[!17,19,24!] ^((0-((m[10]>>18)&1))&3276800) //3276800=[!17,20,21!] ^((0-((m[10]>>20)&1))&17563648) //17563648=[!18,19,24!] ^((0-((m[10]>>24)&1))&917504) //917504=[!17,18,19!] ^((0-(m[10]&(1<<13)))&17301504) //17301504=[!19,24!] ^((0-((m[10]>>21)&1))&17301504) //17301504=[!19,24!] ^((0-((m[10]>>23)&1))&1572864) //1572864=[!19,20!] ^((0-((m[10]>>31)&1))&17039360) //17039360=[!18,24!] ^(rotate_left(m[10],0)&4063232) //4063232=[!17,18,19,20,21!], 4063232=[!17,18,19,20,21!] ^(rotate_left(m[10],20)&3145728) //3145728=[!20,21!], 3=[!0,1!] ^(rotate_left(m[10],17)&262144) //262144=[!18!], 2=[!1!] ^(rotate_left(m[10],21)&2097152) //2097152=[!21!], 1=[!0!] ; metset1precomp[11][14] = metset1precomp[10][14] ^ 0 ^((0-((m[10]>>25)&1))&5208064) //5208064=[!11,12,13,14,16,17,18,19,22!] ^((0-((m[10]>>30)&1))&2153238528) //2153238528=[!12,14,15,16,17,18,20,22,31!] ^((0-((m[10]>>31)&1))&3225202688) //3225202688=[!12,13,15,18,19,20,21,30,31!] ^((0-((m[10]>>18)&1))&7632896) //7632896=[!11,12,13,14,18,20,21,22!] ^((0-((m[10]>>19)&1))&5625856) //5625856=[!11,12,14,15,16,18,20,22!] ^((0-(m[10]&(1<<1)))&3561472) //3561472=[!11,12,14,17,18,20,21!] ^((0-((m[10]>>20)&1))&5355520) //5355520=[!11,12,13,15,16,20,22!] ^((0-((m[10]>>22)&1))&5179392) //5179392=[!11,16,17,18,19,22!] ^((0-((m[10]>>24)&1))&1468416) //1468416=[!11,13,14,17,18,20!] ^((0-(m[10]&(1<<0)))&4528128) //4528128=[!11,12,16,18,22!] ^((0-((m[10]>>21)&1))&2279424) //2279424=[!11,14,15,17,21!] ^((0-((m[10]>>17)&1))&88064) //88064=[!11,12,14,16!] ^((0-(m[10]&(1<<15)))&2293760) //2293760=[!16,17,21!] ^((0-((m[10]>>23)&1))&4329472) //4329472=[!12,17,22!] ^((0-(m[10]&(1<<13)))&2228224) //2228224=[!17,21!] ^((0-((m[10]>>16)&1))&10240) //10240=[!11,13!] ^(rotate_left(m[10],30)&3230464000) //3230464000=[!11,12,13,14,15,18,19,23,30,31!], 36954115=[!0,1,13,14,15,16,17,20,21,25!] ; metset1precomp[11][15] = metset1precomp[10][15] ^ 0 ^((0-(m[10]&(1<<1)))&3247939584) //3247939584=[!13,15,16,17,18,20,23,24,30,31!] ^((0-((m[10]>>21)&1))&1092214788) //1092214788=[!2,13,14,15,16,19,20,24,30!] ^((0-((m[10]>>22)&1))&10313732) //10313732=[!2,13,14,16,18,19,20,23!] ^((0-((m[10]>>23)&1))&1092558848) //1092558848=[!13,16,17,18,19,20,24,30!] ^((0-((m[10]>>24)&1))&1090068480) //1090068480=[!13,16,19,20,21,22,23,30!] ^((0-((m[10]>>31)&1))&14426112) //14426112=[!13,18,19,20,22,23!] ^((0-(m[10]&(1<<0)))&2736128) //2736128=[!14,15,16,19,21!] ^((0-((m[10]>>18)&1))&25706500) //25706500=[!2,14,19,23,24!] ^((0-((m[10]>>19)&1))&8798212) //8798212=[!2,14,17,18,23!] ^((0-((m[10]>>20)&1))&1082679296) //1082679296=[!13,14,19,23,30!] ^((0-((m[10]>>30)&1))&9191424) //9191424=[!14,18,19,23!] ^((0-(m[10]&(1<<13)))&18939904) //18939904=[!16,21,24!] ^((0-(m[10]&(1<<15)))&16842752) //16842752=[!16,24!] ^((0-((m[10]>>17)&1))&2105344) //2105344=[!13,21!] ^((0-((m[10]>>25)&1))&532480) //532480=[!13,19!] ^(rotate_left(m[10],0)&3261325315) //3261325315=[!0,1,13,14,15,16,17,21,22,25,30,31!], 3261325315=[!0,1,13,14,15,16,17,21,22,25,30,31!] ^(rotate_left(m[10],30)&8437760) //8437760=[!14,15,23!], 33751040=[!16,17,25!] ; } Qtp1valsvecptr[t] = Qtp1valsptr; if (step_12()) step12ok = true; } while (cur != 0); if (!step12ok) return step11ok; } return step11ok; } bool step_10() { static bool firsttime = true; if (firsttime) { cout << "t10 " << flush; firsttime = false; } const unsigned t = 10; UPDATE(t); show_performance_data(t); bool step10ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 1006639132; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = metset1precomp[9][10] ^ 0 ; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]); const uint32 metset1adj = metset1 ^ ((~Qtp1val) & 289) ^ (xrng64()&3288327874); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; bool didmp = false; bool step11ok = false; //uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 66060290;// 62914562; // 5 bits do { cur -= 1; cur &= curmask; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 metcur = 0; do { m[t] = metcur ^ cur ^ metset1adj; metcur -= 1; metcur &= 3288327874^curmask; // 20 bits of freedom Q[offset+t+1] = m[t] - mpartial; if (0 != ((Q[offset+t+1]^Qtp1val)&671088656)) break; uint32 Qtp1xorfix = (Q[offset+t+1]^Qtp1val) & 289; *(Qtp1valsptr++) = Q[offset+t+1]^Qtp1xorfix; } while (metcur != 0); //} while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step10ok = true; if (!didmp) { didmp = true; metset1precomp[10][11] = metset1precomp[9][11] ^ 0 ; metset1precomp[10][12] = metset1precomp[9][12] ^ 0 ^(rotate_left(m[9],31)&2147483648) //2147483648=[!31!], 1=[!0!] ; metset1precomp[10][13] = metset1precomp[9][13] ^ 0 ^((0-(m[9]&(1<<17)))&20840448) //20840448=[!17,18,19,20,21,24!] ^((0-(m[9]&(1<<1)))&4063232) //4063232=[!17,18,19,20,21!] ^((0-(m[9]&(1<<16)))&20709376) //20709376=[!18,19,20,21,24!] ^((0-((m[9]>>31)&1))&3538944) //3538944=[!17,18,20,21!] ^((0-(m[9]&(1<<13)))&17432576) //17432576=[!17,19,24!] ^((0-(m[9]&(1<<0)))&1572864) //1572864=[!19,20!] ^((0-(m[9]&(1<<14)))&17301504) //17301504=[!19,24!] ^(rotate_left(m[9],30)&2179596288) //2179596288=[!17,19,21,22,23,24,31!], 128450562=[!1,19,21,23,24,25,26!] ^(rotate_left(m[9],31)&18743296) //18743296=[!17,18,19,20,24!], 37486592=[!18,19,20,21,25!] ^(rotate_left(m[9],0)&20185088) //20185088=[!18,20,21,24!], 20185088=[!18,20,21,24!] ^(rotate_left(m[9],1)&20447232) //20447232=[!19,20,21,24!], 10223616=[!18,19,20,23!] ^(rotate_left(m[9],27)&3014656) //3014656=[!17,18,19,21!], 96468992=[!22,23,24,26!] ^(rotate_left(m[9],29)&14811136) //14811136=[!17,21,22,23!], 118489088=[!20,24,25,26!] ^(rotate_left(m[9],2)&17956864) //17956864=[!17,20,24!], 4489216=[!15,18,22!] ^(rotate_left(m[9],24)&393216) //393216=[!17,18!], 100663296=[!25,26!] ^(rotate_left(m[9],25)&786432) //786432=[!18,19!], 100663296=[!25,26!] ^(rotate_left(m[9],26)&393216) //393216=[!17,18!], 25165824=[!23,24!] ^(rotate_left(m[9],28)&786432) //786432=[!18,19!], 12582912=[!22,23!] ^(rotate_left(m[9],4)&16777216) //16777216=[!24!], 1048576=[!20!] ^(rotate_left(m[9],6)&16777216) //16777216=[!24!], 262144=[!18!] ; metset1precomp[10][14] = metset1precomp[9][14] ^ 0 ^((0-(m[9]&(1<<0)))&7163904) //7163904=[!12,14,16,18,19,21,22!] ^((0-((m[9]>>31)&1))&7641088) //7641088=[!11,12,15,18,20,21,22!] ^((0-(m[9]&(1<<1)))&5933056) //5933056=[!11,15,17,19,20,22!] ^(rotate_left(m[9],0)&126742531) //126742531=[!0,1,12,13,14,15,16,18,19,23,24,25,26!], 126742531=[!0,1,12,13,14,15,16,18,19,23,24,25,26!] ^(rotate_left(m[9],30)&3253417984) //3253417984=[!11,12,13,16,17,19,21,22,23,24,30,31!], 128770051=[!0,1,13,14,15,18,19,21,23,24,25,26!] ^(rotate_left(m[9],29)&1077409792) //1077409792=[!11,12,13,14,15,16,17,18,20,21,30!], 29343746=[!1,14,15,16,17,18,19,20,21,23,24!] ^(rotate_left(m[9],24)&522240) //522240=[!11,12,13,14,15,16,17,18!], 133693440=[!19,20,21,22,23,24,25,26!] ^(rotate_left(m[9],31)&5478400) //5478400=[!11,12,15,16,17,20,22!], 10956800=[!12,13,16,17,18,21,23!] ^(rotate_left(m[9],26)&1234944) //1234944=[!11,12,14,15,17,20!], 79036416=[!17,18,20,21,23,26!] ^(rotate_left(m[9],28)&6352896) //6352896=[!12,13,14,15,21,22!], 101646336=[!16,17,18,19,25,26!] ^(rotate_left(m[9],1)&5701632) //5701632=[!16,17,18,20,22!], 2850816=[!15,16,17,19,21!] ^(rotate_left(m[9],23)&178176) //178176=[!11,12,13,15,17!], 91226112=[!20,21,22,24,26!] ^(rotate_left(m[9],27)&1908736) //1908736=[!13,16,18,19,20!], 61079552=[!18,21,23,24,25!] ^(rotate_left(m[9],2)&7602176) //7602176=[!18,20,21,22!], 1900544=[!16,18,19,20!] ^(rotate_left(m[9],3)&5439488) //5439488=[!16,17,20,22!], 679936=[!13,14,17,19!] ^(rotate_left(m[9],4)&5373952) //5373952=[!17,20,22!], 335872=[!13,16,18!] ^(rotate_left(m[9],21)&38912) //38912=[!11,12,15!], 79691776=[!22,23,26!] ^(rotate_left(m[9],25)&786432) //786432=[!18,19!], 100663296=[!25,26!] ^(rotate_left(m[9],5)&4194304) //4194304=[!22!], 131072=[!17!] ^(rotate_left(m[9],6)&4194304) //4194304=[!22!], 65536=[!16!] ^(rotate_left(m[9],7)&2097152) //2097152=[!21!], 16384=[!14!] ^(rotate_left(m[9],8)&2097152) //2097152=[!21!], 8192=[!13!] ^(rotate_left(m[9],18)&4096) //4096=[!12!], 67108864=[!26!] ^(rotate_left(m[9],20)&8192) //8192=[!13!], 33554432=[!25!] ^(rotate_left(m[9],22)&4096) //4096=[!12!], 4194304=[!22!] ; metset1precomp[10][15] = metset1precomp[9][15] ^ 0 ^((0-(m[9]&(1<<1)))&1106567172) //1106567172=[!2,13,14,15,18,20,21,22,23,24,30!] ^((0-((m[9]>>25)&1))&24109056) //24109056=[!13,14,15,16,17,18,19,21,22,24!] ^((0-((m[9]>>18)&1))&1086111744) //1086111744=[!14,15,18,19,20,21,23,30!] ^((0-((m[9]>>19)&1))&1102872576) //1102872576=[!15,18,19,20,21,23,24,30!] ^((0-((m[9]>>21)&1))&28016644) //28016644=[!2,15,16,17,19,21,23,24!] ^((0-((m[9]>>26)&1))&24174596) //24174596=[!2,13,14,15,20,21,22,24!] ^((0-((m[9]>>22)&1))&1085390848) //1085390848=[!14,15,16,20,21,23,30!] ^((0-((m[9]>>17)&1))&11280388) //11280388=[!2,13,18,19,21,23!] ^((0-((m[9]>>20)&1))&9371652) //9371652=[!2,16,17,18,19,23!] ^((0-((m[9]>>23)&1))&1082621952) //1082621952=[!15,16,17,18,23,30!] ^((0-((m[9]>>24)&1))&20332544) //20332544=[!14,17,18,20,21,24!] ^((0-((m[9]>>31)&1))&25772036) //25772036=[!2,14,16,19,23,24!] ^((0-(m[9]&(1<<0)))&1078108160) //1078108160=[!13,15,17,22,30!] ^((0-((m[9]>>16)&1))&9191428) //9191428=[!2,14,18,19,23!] ^((0-(m[9]&(1<<13)))&16850944) //16850944=[!13,16,24!] ^((0-(m[9]&(1<<14)))&18939904) //18939904=[!16,21,24!] ^((0-((m[9]>>15)&1))&2105344) //2105344=[!13,21!] ; } Qtp1valsvecptr[t] = Qtp1valsptr; if (step_11()) step11ok = true; } while (cur != 0); if (!step11ok) return step10ok; } return step10ok; } bool step_9() { static bool firsttime = true; if (firsttime) { cout << "t9 " << flush; firsttime = false; } const unsigned t = 9; UPDATE(t); show_performance_data(t); bool step9ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 2013266140; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = metset1precomp[8][9] ^ 0 ; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]); const uint32 metset1adj = metset1 ^ ((~Qtp1val) & 2214592545) ^ (xrng64()&67108610); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; bool didmp = false; bool step10ok = false; //uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 65011714;// 62914562; // 5 bits do { cur -= 1; cur &= curmask; uint32 metcur = 0; uint32* Qtp1valsptr = Qtp1valsvec[t]; do { m[t] = metcur ^ cur ^ metset1adj; metcur -= 1; metcur &= 67108610^curmask; // 19 bits of freedom Q[offset+t+1] = m[t] - mpartial; if (0 != ((Q[offset+t+1]^Qtp1val)&134217920)) break; uint32 Qtp1xorfix = (Q[offset+t+1]^Qtp1val) & 2214592545; *(Qtp1valsptr++) = Q[offset+t+1]^Qtp1xorfix; } while (metcur != 0); //} while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step9ok = true; if (!didmp) { didmp = true; metset1precomp[9][10] = metset1precomp[8][10] ^ 0 ; metset1precomp[9][11] = metset1precomp[8][11] ^ 0 ; metset1precomp[9][12] = metset1precomp[8][12] ^ 0 ^(rotate_left(m[8],0)&2147483648) //2147483648=[!31!], 2147483648=[!31!] ^(rotate_left(m[8],1)&2147483648) //2147483648=[!31!], 1073741824=[!30!] ^(rotate_left(m[8],29)&2147483648) //2147483648=[!31!], 4=[!2!] ; metset1precomp[9][13] = metset1precomp[8][13] ^ 0 ^((0-((m[8]>>30)&1))&20316160) //20316160=[!17,18,20,21,24!] ^((0-(m[8]&(1<<14)))&3538944) //3538944=[!17,18,20,21!] ^((0-(m[8]&(1<<2)))&1835008) //1835008=[!18,19,20!] ^((0-(m[8]&(1<<3)))&1441792) //1441792=[!17,18,20!] ^((0-(m[8]&(1<<11)))&17432576) //17432576=[!17,19,24!] ^((0-(m[8]&(1<<16)))&19398656) //19398656=[!19,21,24!] ^((0-((m[8]>>29)&1))&1179648) //1179648=[!17,20!] ^(rotate_left(m[8],0)&2213150732) //2213150732=[!2,3,17,19,21,22,23,24,25,31!], 2213150732=[!2,3,17,19,21,22,23,24,25,31!] ^(rotate_left(m[8],30)&13238274) //13238274=[!1,17,19,22,23!], 52953096=[!3,19,21,24,25!] ^(rotate_left(m[8],31)&18612224) //18612224=[!18,19,20,24!], 37224448=[!19,20,21,25!] ^(rotate_left(m[8],1)&3670016) //3670016=[!19,20,21!], 1835008=[!18,19,20!] ^(rotate_left(m[8],29)&1441792) //1441792=[!17,18,20!], 11534336=[!20,21,23!] ^(rotate_left(m[8],2)&3145728) //3145728=[!20,21!], 786432=[!18,19!] ^(rotate_left(m[8],4)&16908288) //16908288=[!17,24!], 1056768=[!13,20!] ^(rotate_left(m[8],25)&17039360) //17039360=[!18,24!], 2181038080=[!25,31!] ^(rotate_left(m[8],26)&393216) //393216=[!17,18!], 25165824=[!23,24!] ^(rotate_left(m[8],5)&131072) //131072=[!17!], 4096=[!12!] ^(rotate_left(m[8],6)&16777216) //16777216=[!24!], 262144=[!18!] ^(rotate_left(m[8],22)&2097152) //2097152=[!21!], 2147483648=[!31!] ^(rotate_left(m[8],24)&131072) //131072=[!17!], 33554432=[!25!] ^(rotate_left(m[8],27)&524288) //524288=[!19!], 16777216=[!24!] ^(rotate_left(m[8],28)&262144) //262144=[!18!], 4194304=[!22!] ; metset1precomp[9][14] = metset1precomp[8][14] ^ 0 ^((0-(m[8]&(1<<2)))&3227340800) //3227340800=[!12,14,16,18,19,20,22,30,31!] ^((0-((m[8]>>29)&1))&2151938048) //2151938048=[!11,12,13,14,15,16,17,22,31!] ^((0-((m[8]>>30)&1))&1081667584) //1081667584=[!12,13,14,15,19,20,21,22,30!] ^((0-((m[8]>>14)&1))&7718912) //7718912=[!11,14,15,16,18,20,21,22!] ^((0-((m[8]>>18)&1))&5371904) //5371904=[!11,12,13,14,15,16,20,22!] ^((0-((m[8]>>20)&1))&5728256) //5728256=[!11,13,14,16,17,18,20,22!] ^((0-(m[8]&(1<<3)))&7520256) //7520256=[!14,15,17,20,21,22!] ^((0-((m[8]>>19)&1))&7385088) //7385088=[!12,13,15,20,21,22!] ^((0-((m[8]>>21)&1))&6350848) //6350848=[!11,13,14,15,21,22!] ^((0-(m[8]&(1<<11)))&2299904) //2299904=[!11,12,16,17,21!] ^((0-((m[8]>>16)&1))&2564096) //2564096=[!13,16,17,18,21!] ^((0-((m[8]>>22)&1))&5408768) //5408768=[!11,15,17,20,22!] ^((0-((m[8]>>23)&1))&3172352) //3172352=[!11,13,14,20,21!] ^((0-((m[8]>>31)&1))&669696) //669696=[!11,12,13,17,19!] ^((0-((m[8]>>24)&1))&602112) //602112=[!12,13,16,19!] ^((0-((m[8]>>25)&1))&4231168) //4231168=[!12,15,22!] ^((0-(m[8]&(1<<12)))&69632) //69632=[!12,16!] ^((0-((m[8]>>15)&1))&6144) //6144=[!11,12!] ^(rotate_left(m[8],31)&2155231232) //2155231232=[!11,12,13,17,18,20,21,22,31!], 15495169=[!0,12,13,14,18,19,21,22,23!] ^(rotate_left(m[8],30)&1073743872) //1073743872=[!11,30!], 8193=[!0,13!] ^(rotate_left(m[8],2)&2048) //2048=[!11!], 512=[!9!] ^(rotate_left(m[8],3)&65536) //65536=[!16!], 8192=[!13!] ; metset1precomp[9][15] = metset1precomp[8][15] ^ 0 ^((0-(m[8]&(1<<3)))&27238400) //27238400=[!13,15,16,17,18,19,20,23,24!] ^((0-((m[8]>>2)&1))&29614081) //29614081=[!0,13,14,15,16,17,22,23,24!] ^((0-((m[8]>>22)&1))&1099915264) //1099915264=[!13,14,16,17,18,19,23,24,30!] ^((0-((m[8]>>19)&1))&27992068) //27992068=[!2,13,16,17,19,21,23,24!] ^((0-((m[8]>>25)&1))&1076862976) //1076862976=[!13,15,16,17,18,19,21,30!] ^((0-((m[8]>>29)&1))&2023428) //2023428=[!2,13,14,15,17,18,19,20!] ^((0-((m[8]>>31)&1))&24002564) //24002564=[!2,14,17,18,19,21,22,24!] ^((0-((m[8]>>14)&1))&26034180) //26034180=[!2,14,16,18,19,23,24!] ^((0-((m[8]>>16)&1))&1093730308) //1093730308=[!2,16,20,21,24,30!] ^((0-((m[8]>>18)&1))&1084030976) //1084030976=[!16,18,19,20,23,30!] ^((0-((m[8]>>23)&1))&25788420) //25788420=[!2,15,16,19,23,24!] ^((0-((m[8]>>30)&1))&13746176) //13746176=[!14,15,16,20,22,23!] ^((0-((m[8]>>20)&1))&10534916) //10534916=[!2,14,15,21,23!] ^((0-((m[8]>>21)&1))&1101266944) //1101266944=[!18,21,23,24,30!] ^((0-((m[8]>>24)&1))&4833280) //4833280=[!14,15,16,19,22!] ^((0-(m[8]&(1<<11)))&16850944) //16850944=[!13,16,24!] ^((0-(m[8]&(1<<12)))&2105344) //2105344=[!13,21!] ^((0-(m[8]&(1<<13)))&2105344) //2105344=[!13,21!] ^(rotate_left(m[8],31)&2179194880) //2179194880=[!13,14,15,16,17,21,22,23,24,31!], 63422465=[!0,14,15,16,17,18,22,23,24,25!] ^(rotate_left(m[8],30)&40960) //40960=[!13,15!], 163840=[!15,17!] ^(rotate_left(m[8],13)&8192) //8192=[!13!], 1=[!0!] ; } Qtp1valsvecptr[t] = Qtp1valsptr; if (step_10()) step10ok = true; } while (cur != 0); if (!step10ok) return step9ok; } return step9ok; } bool step_8() { static bool firsttime = true; if (firsttime) { cout << "t8 " << flush; firsttime = false; } const unsigned t = 8; UPDATE(t); show_performance_data(t); bool step8ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 469762050; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = metset1precomp[7][8] ^ 0 ; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]) ^ ((~metset1) & 402653186) ^ (xrng64()&3288333445); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; bool didmp = false; //uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 66846720;//65011712; // 5 bits do { cur -= 1; cur &= curmask; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 Qtp1cur = 0; do { Q[offset+t+1] = Qtp1cur ^ cur ^ Qtp1val; Qtp1cur -= 1; Qtp1cur &= 3288333445^curmask; // 21 bits of freedom m[t] = Q[offset+t+1] + mpartial; if (0 != ((m[t]^metset1)&67108864)) break; uint32 metxorfix = (m[t]^metset1) & 402653186; *(Qtp1valsptr++) = Q[offset+t+1]^metxorfix; } while (Qtp1cur != 0); //} while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step8ok = true; if (!didmp) { didmp = true; metset1precomp[8][9] = metset1precomp[7][9] ^ 0 ; metset1precomp[8][10] = metset1precomp[7][10] ^ 0 ; metset1precomp[8][11] = metset1precomp[7][11] ^ 0 ; metset1precomp[8][12] = metset1precomp[7][12] ^ 0 ; metset1precomp[8][13] = metset1precomp[7][13] ^ 0 ^((0-((m[7]>>31)&1))&19660800) //19660800=[!18,19,21,24!] ^((0-(m[7]&(1<<0)))&2359296) //2359296=[!18,21!] ^((0-(m[7]&(1<<15)))&17301504) //17301504=[!19,24!] ^(rotate_left(m[7],2)&20578304) //20578304=[!17,19,20,21,24!], 5144576=[!15,17,18,19,22!] ^(rotate_left(m[7],29)&3932160) //3932160=[!18,19,20,21!], 31457280=[!21,22,23,24!] ^(rotate_left(m[7],31)&18219008) //18219008=[!17,18,20,24!], 36438016=[!18,19,21,25!] ^(rotate_left(m[7],0)&17563648) //17563648=[!18,19,24!], 17563648=[!18,19,24!] ^(rotate_left(m[7],1)&19922944) //19922944=[!20,21,24!], 9961472=[!19,20,23!] ^(rotate_left(m[7],30)&3670016) //3670016=[!19,20,21!], 14680064=[!21,22,23!] ^(rotate_left(m[7],3)&18874368) //18874368=[!21,24!], 2359296=[!18,21!] ^(rotate_left(m[7],5)&16777216) //16777216=[!24!], 524288=[!19!] ^(rotate_left(m[7],7)&16777216) //16777216=[!24!], 131072=[!17!] ^(rotate_left(m[7],25)&131072) //131072=[!17!], 16777216=[!24!] ^(rotate_left(m[7],27)&1048576) //1048576=[!20!], 33554432=[!25!] ; metset1precomp[8][14] = metset1precomp[7][14] ^ 0 ^((0-(m[7]&(1<<0)))&2151045120) //2151045120=[!11,12,14,17,18,20,21,31!] ^((0-((m[7]>>23)&1))&7755776) //7755776=[!11,12,14,17,18,20,21,22!] ^((0-((m[7]>>31)&1))&1075113984) //1075113984=[!12,13,14,15,18,20,30!] ^((0-((m[7]>>18)&1))&7643136) //7643136=[!13,15,18,20,21,22!] ^((0-((m[7]>>19)&1))&5533696) //5533696=[!12,13,14,18,20,22!] ^((0-((m[7]>>21)&1))&5287936) //5287936=[!12,13,15,20,22!] ^((0-((m[7]>>25)&1))&126976) //126976=[!12,13,14,15,16!] ^((0-((m[7]>>15)&1))&2297856) //2297856=[!12,16,17,21!] ^((0-((m[7]>>22)&1))&4331520) //4331520=[!11,12,17,22!] ^((0-((m[7]>>24)&1))&301056) //301056=[!11,12,15,18!] ^((0-(m[7]&(1<<1)))&77824) //77824=[!12,13,16!] ^((0-((m[7]>>17)&1))&2230272) //2230272=[!11,17,21!] ^(rotate_left(m[7],28)&3393536) //3393536=[!11,14,15,16,17,20,21!], 54296576=[!15,18,19,20,21,24,25!] ^(rotate_left(m[7],30)&8974336) //8974336=[!12,13,14,15,19,23!], 35897344=[!14,15,16,17,21,25!] ^(rotate_left(m[7],23)&2048) //2048=[!11!], 1048576=[!20!] ^(rotate_left(m[7],29)&2048) //2048=[!11!], 16384=[!14!] ; metset1precomp[8][15] = metset1precomp[7][15] ^ 0 ^((0-(m[7]&(1<<0)))&2174197764) //2174197764=[!2,13,15,16,17,18,20,23,24,31!] ^((0-((m[7]>>23)&1))&15622148) //15622148=[!2,13,14,17,18,19,21,22,23!] ^((0-((m[7]>>18)&1))&26165252) //26165252=[!2,14,16,17,18,19,23,24!] ^((0-((m[7]>>25)&1))&1077518340) //1077518340=[!2,13,15,16,19,20,21,30!] ^((0-((m[7]>>21)&1))&1085046784) //1085046784=[!15,18,19,21,23,30!] ^((0-((m[7]>>22)&1))&1084030976) //1084030976=[!16,18,19,20,23,30!] ^((0-((m[7]>>31)&1))&9912320) //9912320=[!14,16,17,18,20,23!] ^((0-((m[7]>>19)&1))&8929284) //8929284=[!2,14,19,23!] ^((0-((m[7]>>24)&1))&2629636) //2629636=[!2,13,19,21!] ^((0-((m[7]>>15)&1))&16850944) //16850944=[!13,16,24!] ^((0-((m[7]>>20)&1))&1074790404) //1074790404=[!2,20,30!] ^((0-(m[7]&(1<<17)))&18874368) //18874368=[!21,24!] ^(rotate_left(m[7],31)&581633) //581633=[!0,13,14,15,19!], 1163266=[!1,14,15,16,20!] ^(rotate_left(m[7],20)&2097152) //2097152=[!21!], 2=[!1!] ; } Qtp1valsvecptr[t] = Qtp1valsptr; step_9(); } while (cur != 0); } return step8ok; } bool step_7() { static bool firsttime = true; if (firsttime) { cout << "t7 " << endl; firsttime = false; } const unsigned t = 7; UPDATE(t); show_performance_data(t); bool step7ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 2080390172; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = metset1precomp[6][7] ^ 0 ; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]); const uint32 metset1adj = metset1 ^ ((~Qtp1val) & 2147483744) ^ (xrng64()&67093379); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; bool didmp = false; //uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 65011715; // 7 bits do { cur -= 1; cur &= curmask; uint32 metcur = 0; uint32* Qtp1valsptr = Qtp1valsvec[t]; do { m[t] = metcur ^ cur ^ metset1adj; metcur -= 1; metcur &= 67093379^curmask; // 17 bits of freedom Q[offset+t+1] = m[t] - mpartial; if (0 != ((Q[offset+t+1]^Qtp1val)&872415260)) break; uint32 Qtp1xorfix = (Q[offset+t+1]^Qtp1val) & 2147483744; *(Qtp1valsptr++) = Q[offset+t+1]^Qtp1xorfix; } while (metcur != 0); //} while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step7ok = true; if (!didmp) { didmp = true; metset1precomp[7][8] = metset1precomp[6][8] ^ 0 ; metset1precomp[7][9] = metset1precomp[6][9] ^ 0 ; metset1precomp[7][10] = metset1precomp[6][10] ^ 0 ; metset1precomp[7][11] = metset1precomp[6][11] ^ 0 ; metset1precomp[7][12] = metset1precomp[6][12] ^ 0 ^(rotate_left(m[6],31)&2147483648) //2147483648=[!31!], 1=[!0!] ; metset1precomp[7][13] = metset1precomp[6][13] ^ 0 ^((0-((m[6]>>21)&1))&20316160) //20316160=[!17,18,20,21,24!] ^((0-((m[6]>>30)&1))&19791872) //19791872=[!17,18,19,21,24!] ^((0-(m[6]&(1<<18)))&18612224) //18612224=[!18,19,20,24!] ^((0-((m[6]>>25)&1))&19660800) //19660800=[!18,19,21,24!] ^((0-(m[6]&(1<<0)))&19005440) //19005440=[!17,21,24!] ^((0-(m[6]&(1<<1)))&19922944) //19922944=[!20,21,24!] ^((0-((m[6]>>22)&1))&17432576) //17432576=[!17,19,24!] ^((0-((m[6]>>31)&1))&17432576) //17432576=[!17,19,24!] ^((0-(m[6]&(1<<13)))&17301504) //17301504=[!19,24!] ^(rotate_left(m[6],30)&2161377280) //2161377280=[!18,20,22,23,31!], 55574530=[!1,20,22,24,25!] ^(rotate_left(m[6],4)&1703936) //1703936=[!17,19,20!], 106496=[!13,15,16!] ^(rotate_left(m[6],5)&18874368) //18874368=[!21,24!], 589824=[!16,19!] ^(rotate_left(m[6],0)&524288) //524288=[!19!], 524288=[!19!] ^(rotate_left(m[6],2)&262144) //262144=[!18!], 65536=[!16!] ^(rotate_left(m[6],3)&131072) //131072=[!17!], 16384=[!14!] ^(rotate_left(m[6],9)&16777216) //16777216=[!24!], 32768=[!15!] ^(rotate_left(m[6],26)&131072) //131072=[!17!], 8388608=[!23!] ^(rotate_left(m[6],29)&131072) //131072=[!17!], 1048576=[!20!] ; metset1precomp[7][14] = metset1precomp[6][14] ^ 0 ^((0-((m[6]>>16)&1))&7632896) //7632896=[!11,12,13,14,18,20,21,22!] ^((0-((m[6]>>18)&1))&5371904) //5371904=[!11,12,13,14,15,16,20,22!] ^((0-(m[6]&(1<<0)))&1074489344) //1074489344=[!11,13,14,16,17,19,30!] ^((0-(m[6]&(1<<1)))&3226050560) //3226050560=[!13,15,16,19,22,30,31!] ^((0-((m[6]>>21)&1))&4642816) //4642816=[!11,12,14,15,17,18,22!] ^((0-((m[6]>>25)&1))&3467264) //3467264=[!11,13,14,15,18,20,21!] ^((0-((m[6]>>19)&1))&2316288) //2316288=[!11,12,14,16,17,21!] ^((0-((m[6]>>30)&1))&2148833280) //2148833280=[!11,12,15,18,20,31!] ^((0-((m[6]>>22)&1))&96256) //96256=[!11,12,13,14,16!] ^((0-((m[6]>>24)&1))&581632) //581632=[!13,14,15,19!] ^((0-(m[6]&(1<<13)))&2293760) //2293760=[!16,17,21!] ^((0-((m[6]>>14)&1))&71680) //71680=[!11,12,16!] ^((0-((m[6]>>15)&1))&2230272) //2230272=[!11,17,21!] ^((0-((m[6]>>20)&1))&100352) //100352=[!11,15,16!] ^((0-((m[6]>>31)&1))&2232320) //2232320=[!12,17,21!] ^((0-((m[6]>>23)&1))&49152) //49152=[!14,15!] ^(rotate_left(m[6],31)&3251464193) //3251464193=[!0,11,13,14,16,18,19,22,23,24,30,31!], 2207961091=[!0,1,12,14,15,17,19,20,23,24,25,31!] ^(rotate_left(m[6],0)&2048) //2048=[!11!], 2048=[!11!] ; metset1precomp[7][15] = metset1precomp[6][15] ^ 0 ^((0-(m[6]&(1<<0)))&1097490432) //1097490432=[!13,14,17,19,21,22,24,30!] ^((0-((m[6]>>16)&1))&28131332) //28131332=[!2,14,16,18,19,21,23,24!] ^((0-((m[6]>>30)&1))&1083400196) //1083400196=[!2,13,14,16,17,20,23,30!] ^((0-((m[6]>>25)&1))&1094770692) //1094770692=[!2,13,14,15,22,24,30!] ^((0-(m[6]&(1<<1)))&22323200) //22323200=[!13,15,18,20,22,24!] ^((0-((m[6]>>18)&1))&1083998208) //1083998208=[!15,18,19,20,23,30!] ^((0-((m[6]>>21)&1))&11026436) //11026436=[!2,14,19,21,23!] ^((0-((m[6]>>31)&1))&18948096) //18948096=[!13,16,21,24!] ^((0-(m[6]&(1<<13)))&16850944) //16850944=[!13,16,24!] ^((0-(m[6]&(1<<15)))&18939904) //18939904=[!16,21,24!] ^((0-((m[6]>>23)&1))&1075838980) //1075838980=[!2,21,30!] ^((0-((m[6]>>24)&1))&57344) //57344=[!13,14,15!] ^((0-((m[6]>>14)&1))&2105344) //2105344=[!13,21!] ^((0-((m[6]>>20)&1))&2105344) //2105344=[!13,21!] ^(rotate_left(m[6],28)&2088960) //2088960=[!13,14,15,16,17,18,19,20!], 33423360=[!17,18,19,20,21,22,23,24!] ^(rotate_left(m[6],27)&1032192) //1032192=[!14,15,16,17,18,19!], 33030144=[!19,20,21,22,23,24!] ^(rotate_left(m[6],29)&671744) //671744=[!14,17,19!], 5373952=[!17,20,22!] ^(rotate_left(m[6],26)&73728) //73728=[!13,16!], 4718592=[!19,22!] ^(rotate_left(m[6],2)&16777216) //16777216=[!24!], 4194304=[!22!] ^(rotate_left(m[6],5)&16777216) //16777216=[!24!], 524288=[!19!] ; } Qtp1valsvecptr[t] = Qtp1valsptr; try { // restart from step 7, after 4 tries restart from step 0 step_8(); } catch (std::exception& e) { cout << "step7: " << e.what() << endl; if (time_avg[15] || time_avg[40]) { cout << "Restart after step 15: tunnel changes might corrupt current workingstate!" << endl; exit(0); } static unsigned throwcnt = 0; if (((++throwcnt)&3)==0) throw; } } while (cur != 0); } return step7ok; } bool step_6() { static bool firsttime = true; if (firsttime) { cout << "t6 " << flush; firsttime = false; } const unsigned t = 6; UPDATE(t); show_performance_data(t); bool step6ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 1006634012; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = metset1precomp[5][6] ^ 0 ; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]) ^ ((~metset1) & 939525128) ^ (xrng64()&67107331); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; bool didmp = false; bool step7ok = false; //uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 65011715; // 7 bits do { cur -= 1; cur &= curmask; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 Qtp1cur = 0; do { Q[offset+t+1] = Qtp1cur ^ cur ^ Qtp1val; Qtp1cur -= 1; Qtp1cur &= 67107331^curmask; // 18 bits of freedom m[t] = Q[offset+t+1] + mpartial; if (0 != ((m[t]^metset1)&67108884)) break; uint32 metxorfix = (m[t]^metset1) & 939525128; *(Qtp1valsptr++) = Q[offset+t+1]^metxorfix; } while (Qtp1cur != 0); //} while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step6ok = true; if (!didmp) { didmp = true; metset1precomp[6][7] = metset1precomp[5][7] ^ 0 ^(rotate_left(m[5],0)&268435456) //268435456=[!28!], 268435456=[!28!] ; metset1precomp[6][8] = metset1precomp[5][8] ^ 0 ; metset1precomp[6][9] = metset1precomp[5][9] ^ 0 ; metset1precomp[6][10] = metset1precomp[5][10] ^ 0 ; metset1precomp[6][11] = metset1precomp[5][11] ^ 0 ^(rotate_left(m[5],0)&8) //8=[!3!], 8=[!3!] ; metset1precomp[6][12] = metset1precomp[5][12] ^ 0 ^(rotate_left(m[5],1)&2147483648) //2147483648=[!31!], 1073741824=[!30!] ^(rotate_left(m[5],31)&2147483648) //2147483648=[!31!], 1=[!0!] ; metset1precomp[6][13] = metset1precomp[5][13] ^ 0 ^((0-(m[5]&(1<<15)))&20709376) //20709376=[!18,19,20,21,24!] ^((0-((m[5]>>30)&1))&20054016) //20054016=[!17,20,21,24!] ^((0-(m[5]&(1<<0)))&19398656) //19398656=[!19,21,24!] ^((0-(m[5]&(1<<3)))&1441792) //1441792=[!17,18,20!] ^((0-(m[5]&(1<<13)))&17432576) //17432576=[!17,19,24!] ^((0-((m[5]>>31)&1))&1703936) //1703936=[!17,19,20!] ^(rotate_left(m[5],31)&2328363010) //2328363010=[!1,19,22,23,25,27,31!], 361758725=[!0,2,20,23,24,26,28!] ^(rotate_left(m[5],1)&20316160) //20316160=[!17,18,20,21,24!], 10158080=[!16,17,19,20,23!] ^(rotate_left(m[5],30)&3014658) //3014658=[!1,17,18,19,21!], 12058632=[!3,19,20,21,23!] ^(rotate_left(m[5],25)&19267584) //19267584=[!17,18,21,24!], 2466250752=[!24,25,28,31!] ^(rotate_left(m[5],0)&1703936) //1703936=[!17,19,20!], 1703936=[!17,19,20!] ^(rotate_left(m[5],3)&18350080) //18350080=[!19,20,24!], 2293760=[!16,17,21!] ^(rotate_left(m[5],5)&16908290) //16908290=[!1,17,24!], 268963840=[!12,19,28!] ^(rotate_left(m[5],29)&1835008) //1835008=[!18,19,20!], 14680064=[!21,22,23!] ^(rotate_left(m[5],2)&18874368) //18874368=[!21,24!], 4718592=[!19,22!] ^(rotate_left(m[5],28)&1572864) //1572864=[!19,20!], 25165824=[!23,24!] ^(rotate_left(m[5],8)&16777216) //16777216=[!24!], 65536=[!16!] ^(rotate_left(m[5],19)&2097152) //2097152=[!21!], 4=[!2!] ^(rotate_left(m[5],23)&524288) //524288=[!19!], 268435456=[!28!] ^(rotate_left(m[5],27)&524288) //524288=[!19!], 16777216=[!24!] ; metset1precomp[6][14] = metset1precomp[5][14] ^ 0 ^((0-((m[5]>>20)&1))&7725056) //7725056=[!13,14,15,16,18,20,21,22!] ^((0-(m[5]&(1<<3)))&7520256) //7520256=[!14,15,17,20,21,22!] ^((0-((m[5]>>15)&1))&5677056) //5677056=[!13,15,17,18,20,22!] ^((0-(m[5]&(1<<2)))&415744) //415744=[!11,12,14,17,18!] ^((0-((m[5]>>31)&1))&6318080) //6318080=[!11,13,14,21,22!] ^((0-(m[5]&(1<<0)))&376832) //376832=[!14,15,16,18!] ^((0-((m[5]>>30)&1))&69632) //69632=[!12,16!] ^(rotate_left(m[5],31)&1081366528) //1081366528=[!11,12,14,18,20,21,22,30!], 2162733056=[!12,13,15,19,21,22,23,31!] ^(rotate_left(m[5],21)&2807808) //2807808=[!11,12,14,15,17,19,21!], 1455423489=[!0,22,23,25,26,28,30!] ^(rotate_left(m[5],29)&7428096) //7428096=[!11,12,14,16,20,21,22!], 59424768=[!14,15,17,19,23,24,25!] ^(rotate_left(m[5],26)&1226752) //1226752=[!11,12,13,15,17,20!], 78512128=[!17,18,19,21,23,26!] ^(rotate_left(m[5],27)&3620864) //3620864=[!14,16,17,18,20,21!], 115867648=[!19,21,22,23,25,26!] ^(rotate_left(m[5],24)&4622336) //4622336=[!11,15,17,18,22!], 1183318016=[!19,23,25,26,30!] ^(rotate_left(m[5],28)&2650112) //2650112=[!12,13,14,19,21!], 42401792=[!16,17,18,23,25!] ^(rotate_left(m[5],1)&5376000) //5376000=[!11,17,20,22!], 2688000=[!10,16,19,21!] ^(rotate_left(m[5],30)&4423680) //4423680=[!15,16,17,22!], 17694720=[!17,18,19,24!] ^(rotate_left(m[5],0)&1073811456) //1073811456=[!12,16,30!], 1073811456=[!12,16,30!] ^(rotate_left(m[5],3)&5308416) //5308416=[!16,20,22!], 663552=[!13,17,19!] ^(rotate_left(m[5],4)&2293760) //2293760=[!16,17,21!], 143360=[!12,13,17!] ^(rotate_left(m[5],19)&38912) //38912=[!11,12,15!], 318767104=[!24,25,28!] ^(rotate_left(m[5],23)&200704) //200704=[!12,16,17!], 102760448=[!21,25,26!] ^(rotate_left(m[5],25)&2179072) //2179072=[!14,16,21!], 278921216=[!21,23,28!] ^(rotate_left(m[5],5)&6291456) //6291456=[!21,22!], 196608=[!16,17!] ^(rotate_left(m[5],20)&20480) //20480=[!12,14!], 83886080=[!24,26!] ^(rotate_left(m[5],8)&2097152) //2097152=[!21!], 8192=[!13!] ^(rotate_left(m[5],22)&262144) //262144=[!18!], 268435456=[!28!] ; metset1precomp[6][15] = metset1precomp[5][15] ^ 0 ^((0-(m[5]&(1<<3)))&27238400) //27238400=[!13,15,16,17,18,19,20,23,24!] ^((0-((m[5]>>30)&1))&1096114180) //1096114180=[!2,13,14,16,18,20,22,24,30!] ^((0-((m[5]>>28)&1))&1089495044) //1089495044=[!2,13,14,20,21,22,23,30!] ^((0-(m[5]&(1<<2)))&1075240960) //1075240960=[!13,14,15,17,18,20,30!] ^((0-((m[5]>>24)&1))&1092517888) //1092517888=[!15,17,18,19,20,24,30!] ^((0-((m[5]>>25)&1))&1077616640) //1077616640=[!13,16,17,19,20,21,30!] ^((0-(m[5]&(1<<0)))&20324352) //20324352=[!13,17,18,20,21,24!] ^((0-((m[5]>>23)&1))&9273348) //9273348=[!2,15,16,18,19,23!] ^((0-(m[5]&(1<<17)))&1099694080) //1099694080=[!18,19,23,24,30!] ^((0-((m[5]>>19)&1))&11026436) //11026436=[!2,14,19,21,23!] ^((0-((m[5]>>20)&1))&18956292) //18956292=[!2,14,16,21,24!] ^((0-((m[5]>>22)&1))&1090617348) //1090617348=[!2,15,16,24,30!] ^((0-((m[5]>>31)&1))&18743296) //18743296=[!17,18,19,20,24!] ^((0-((m[5]>>21)&1))&1082408960) //1082408960=[!14,18,23,30!] ^((0-((m[5]>>26)&1))&8585220) //8585220=[!2,16,17,23!] ^((0-((m[5]>>15)&1))&8912900) //8912900=[!2,19,23!] ^((0-((m[5]>>16)&1))&16850944) //16850944=[!13,16,24!] ^((0-(m[5]&(1<<12)))&2105344) //2105344=[!13,21!] ^((0-(m[5]&(1<<13)))&16785408) //16785408=[!13,24!] ^(rotate_left(m[5],31)&2204278785) //2204278785=[!0,13,15,17,21,22,24,25,31!], 113590275=[!0,1,14,16,18,22,23,25,26!] ^(rotate_left(m[5],30)&1102848000) //1102848000=[!13,18,19,20,21,23,24,30!], 116424705=[!0,15,20,21,22,23,25,26!] ^(rotate_left(m[5],3)&11862020) //11862020=[!2,16,18,20,21,23!], 2148966400=[!13,15,17,18,20,31!] ^(rotate_left(m[5],27)&8192) //8192=[!13!], 262144=[!18!] ; } Qtp1valsvecptr[t] = Qtp1valsptr; if (step_7()) step7ok = true; } while (cur != 0); if (!step7ok) return false; } return step6ok; } bool step_5() { static bool firsttime = true; if (firsttime) { cout << "t5 " << flush; firsttime = false; } const unsigned t = 5; UPDATE(t); show_performance_data(t); bool step5ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 671088656; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = metset1precomp[4][5] ^ 0 ; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]) ^ ((~metset1) & 671088640) ^ (xrng64()&2281699337); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; bool didmp = false; bool step6ok = false; //uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 125829129;// 9; // 2 bits do { cur -= 1; cur &= curmask; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 Qtp1cur = 0; do { Q[offset+t+1] = Qtp1cur ^ cur ^ Qtp1val; Qtp1cur -= 1; Qtp1cur &= 2281699337^curmask; // 19 bits of freedom m[t] = Q[offset+t+1] + mpartial; if (0 != ((m[t]^metset1)&16)) break; if ((m[t]&992)==0) continue; uint32 metxorfix = (m[t]^metset1) & 671088640; *(Qtp1valsptr++) = Q[offset+t+1]^metxorfix; } while (Qtp1cur != 0); //} while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step5ok = true; if (!didmp) { didmp = true; metset1precomp[5][6] = metset1precomp[4][6] ^ 0; metset1precomp[5][7] = metset1precomp[4][7] ^ 0; metset1precomp[5][8] = metset1precomp[4][8] ^ 0; metset1precomp[5][9] = metset1precomp[4][9] ^ 0; metset1precomp[5][10] = metset1precomp[4][10] ^ 0; metset1precomp[5][11] = metset1precomp[4][11] ^ 0; metset1precomp[5][12] = metset1precomp[4][12] ^ 0 ^(rotate_left(m[4],1)&2147483648) //2147483648=[!31!], 1073741824=[!30!] ^(rotate_left(m[4],29)&2147483648) //2147483648=[!31!], 4=[!2!] ^(rotate_left(m[4],31)&2147483648) //2147483648=[!31!], 1=[!0!] ; metset1precomp[5][13] = metset1precomp[4][13] ^ 0 ^((0-((m[4]>>19)&1))&20709376) //20709376=[!18,19,20,21,24!] ^((0-((m[4]>>21)&1))&18743296) //18743296=[!17,18,19,20,24!] ^((0-((m[4]>>20)&1))&18612224) //18612224=[!18,19,20,24!] ^((0-(m[4]&(1<<0)))&3276800) //3276800=[!17,20,21!] ^((0-((m[4]>>31)&1))&3407872) //3407872=[!18,20,21!] ^((0-((m[4]>>30)&1))&1310720) //1310720=[!18,20!] ^(rotate_left(m[4],2)&17956864) //17956864=[!17,20,24!], 4489216=[!15,18,22!] ^(rotate_left(m[4],28)&1835008) //1835008=[!18,19,20!], 29360128=[!22,23,24!] ^(rotate_left(m[4],29)&2149056512) //2149056512=[!19,20,31!], 12582916=[!2,22,23!] ^(rotate_left(m[4],0)&393216) //393216=[!17,18!], 393216=[!17,18!] ^(rotate_left(m[4],27)&1572864) //1572864=[!19,20!], 50331648=[!24,25!] ^(rotate_left(m[4],3)&2097152) //2097152=[!21!], 262144=[!18!] ^(rotate_left(m[4],25)&131072) //131072=[!17!], 16777216=[!24!] ^(rotate_left(m[4],30)&2097152) //2097152=[!21!], 8388608=[!23!] ; metset1precomp[5][14] = metset1precomp[4][14] ^ 0 ^((0-((m[4]>>24)&1))&1570816) //1570816=[!11,12,13,14,15,16,17,18,20!] ^((0-((m[4]>>31)&1))&7718912) //7718912=[!11,14,15,16,18,20,21,22!] ^((0-((m[4]>>30)&1))&7514112) //7514112=[!11,13,15,17,20,21,22!] ^((0-((m[4]>>25)&1))&2676736) //2676736=[!11,12,14,15,19,21!] ^((0-(m[4]&(1<<2)))&12627968) //12627968=[!12,13,15,22,23!] ^((0-(m[4]&(1<<0)))&4493312) //4493312=[!12,15,18,22!] ^((0-(m[4]&(1<<18)))&7602176) //7602176=[!18,20,21,22!] ^((0-((m[4]>>23)&1))&165888) //165888=[!11,15,17!] ^((0-(m[4]&(1<<20)))&5242880) //5242880=[!20,22!] ^((0-((m[4]>>22)&1))&10240) //10240=[!11,13!] ^(rotate_left(m[4],31)&2173368322) //2173368322=[!1,11,12,13,14,15,17,19,23,24,31!], 51769349=[!0,2,12,13,14,15,16,18,20,24,25!] ^(rotate_left(m[4],30)&14544896) //14544896=[!12,13,14,15,16,18,19,20,22,23!], 58179584=[!14,15,16,17,18,20,21,22,24,25!] ^(rotate_left(m[4],27)&520192) //520192=[!12,13,14,15,16,17,18!], 16646144=[!17,18,19,20,21,22,23!] ^(rotate_left(m[4],29)&2148702208) //2148702208=[!11,12,15,17,20,31!], 9748484=[!2,14,15,18,20,23!] ^(rotate_left(m[4],25)&112640) //112640=[!11,12,13,15,16!], 14417920=[!18,19,20,22,23!] ^(rotate_left(m[4],28)&798720) //798720=[!12,13,18,19!], 12779520=[!16,17,22,23!] ^(rotate_left(m[4],1)&5308416) //5308416=[!16,20,22!], 2654208=[!15,19,21!] ^(rotate_left(m[4],3)&4194304) //4194304=[!22!], 524288=[!19!] ; metset1precomp[5][15] = metset1precomp[4][15] ^ 0 ^((0-((m[4]>>21)&1))&1084153856) //1084153856=[!13,14,15,17,18,19,20,23,30!] ^((0-((m[4]>>25)&1))&1077698564) //1077698564=[!2,13,14,18,19,20,21,30!] ^((0-((m[4]>>30)&1))&26976256) //26976256=[!13,15,16,17,19,20,23,24!] ^((0-((m[4]>>18)&1))&27860996) //27860996=[!2,13,16,19,21,23,24!] ^((0-((m[4]>>23)&1))&19292164) //19292164=[!2,13,14,17,18,21,24!] ^((0-((m[4]>>20)&1))&1082998784) //1082998784=[!14,16,18,19,23,30!] ^((0-((m[4]>>31)&1))&26034176) //26034176=[!14,16,18,19,23,24!] ^((0-(m[4]&(1<<2)))&1236992) //1236992=[!13,14,15,17,20!] ^((0-((m[4]>>19)&1))&8699908) //8699908=[!2,14,15,18,23!] ^((0-((m[4]>>24)&1))&3547136) //3547136=[!13,17,18,20,21!] ^((0-(m[4]&(1<<0)))&2629636) //2629636=[!2,13,19,21!] ^((0-((m[4]>>22)&1))&17080320) //17080320=[!13,15,18,24!] ^((0-((m[4]>>15)&1))&2105344) //2105344=[!13,21!] ^(rotate_left(m[4],0)&3278102533) //3278102533=[!0,2,13,14,15,16,17,21,22,24,25,30,31!], 3278102533=[!0,2,13,14,15,16,17,21,22,24,25,30,31!] ^(rotate_left(m[4],4)&2097152) //2097152=[!21!], 131072=[!17!] ; } Qtp1valsvecptr[t] = Qtp1valsptr; if (step_6()) step6ok = true; } while (cur != 0); if (!step6ok) return step5ok; } return step5ok; } bool step_4() { static bool firsttime = true; if (firsttime) { cout << "t4 " << flush; firsttime = false; } const unsigned t = 4; UPDATE(t); bool step4ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 1006635034; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = metset1precomp[3][4] ^ 0 ^(rotate_left(m[3],5)&2048) //2048=[!11!], 64=[!6!] ; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]) ^ ((~metset1) & 939526144) ^ (xrng64()&2214589472); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; //uint32* Qtp1valsptr = Qtp1valsvec[t]; bool didmp = false; uint32 cur = 0; const uint32 curmask = 65011712; // 5 bits do { cur -= 1; cur &= curmask; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 Qtp1cur = 0; do { Q[offset+t+1] = Qtp1cur ^ cur ^ Qtp1val; Qtp1cur -= 1; Qtp1cur &= 2214589472^curmask; // 17 bits of freedom m[t] = Q[offset+t+1] + mpartial; if (0 != ((m[t]^metset1)&67108890)) break; uint32 metxorfix = (m[t]^metset1) & 939526144; *(Qtp1valsptr++) = Q[offset+t+1]^metxorfix; } while (Qtp1cur != 0); //} while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step4ok = true; if (!didmp) { metset1precomp[4][5] = metset1precomp[3][5] ^ 0; metset1precomp[4][6] = metset1precomp[3][6] ^ 0; metset1precomp[4][7] = metset1precomp[3][7] ^ 0 ^(rotate_left(m[3],0)&8) //8=[!3!], 8=[!3!] ; metset1precomp[4][8] = metset1precomp[3][8] ^ 0; metset1precomp[4][9] = metset1precomp[3][9] ^ 0 ^(rotate_left(m[3],0)&8) //8=[!3!], 8=[!3!] ; metset1precomp[4][10] = metset1precomp[3][10] ^ 0; metset1precomp[4][11] = metset1precomp[3][11] ^ 0 ^(rotate_left(m[3],0)&8) //8=[!3!], 8=[!3!] ; metset1precomp[4][12] = metset1precomp[3][12] ^ 0; metset1precomp[4][13] = metset1precomp[3][13] ^ 0 ^((0-((m[3]>>24)&1))&29229056) //29229056=[!17,18,19,20,21,23,24!] ^((0-(m[3]&(1<<15)))&20840448) //20840448=[!17,18,19,20,21,24!] ^((0-(m[3]&(1<<1)))&4063232) //4063232=[!17,18,19,20,21!] ^((0-((m[3]>>22)&1))&17694720) //17694720=[!17,18,19,24!] ^((0-(m[3]&(1<<0)))&19922944) //19922944=[!20,21,24!] ^((0-(m[3]&(1<<3)))&1441792) //1441792=[!17,18,20!] ^((0-(m[3]&(1<<12)))&17432576) //17432576=[!17,19,24!] ^((0-(m[3]&(1<<16)))&3407872) //3407872=[!18,20,21!] ^((0-((m[3]>>23)&1))&1441792) //1441792=[!17,18,20!] ^((0-(m[3]&(1<<6)))&17301504) //17301504=[!19,24!] ^((0-(m[3]&(1<<17)))&17301504) //17301504=[!19,24!] ^((0-((m[3]>>21)&1))&2359296) //2359296=[!18,21!] ^((0-((m[3]>>25)&1))&1572864) //1572864=[!19,20!] ^(rotate_left(m[3],30)&2164129794) //2164129794=[!1,17,18,19,20,21,22,23,31!], 66584586=[!1,3,19,20,21,22,23,24,25!] ^(rotate_left(m[3],1)&19791872) //19791872=[!17,18,19,21,24!], 9895936=[!16,17,18,20,23!] ^(rotate_left(m[3],31)&2169241600) //2169241600=[!18,19,22,24,31!], 43515905=[!0,19,20,23,25!] ^(rotate_left(m[3],3)&3276800) //3276800=[!17,20,21!], 409600=[!14,17,18!] ^(rotate_left(m[3],6)&16777216) //16777216=[!24!], 262144=[!18!] ^(rotate_left(m[3],22)&1048576) //1048576=[!20!], 1073741824=[!30!] ; metset1precomp[4][14] = metset1precomp[3][14] ^ 0 ^((0-(m[3]&(1<<1)))&3227236354) //3227236354=[!1,11,12,13,15,16,17,19,20,22,30,31!] ^((0-((m[3]>>23)&1))&14637056) //14637056=[!11,12,14,16,17,18,19,20,22,23!] ^((0-((m[3]>>15)&1))&5728256) //5728256=[!11,13,14,16,17,18,20,22!] ^((0-((m[3]>>17)&1))&5371904) //5371904=[!11,12,13,14,15,16,20,22!] ^((0-(m[3]&(1<<0)))&3226050560) //3226050560=[!13,15,16,19,22,30,31!] ^((0-((m[3]>>16)&1))&7659520) //7659520=[!13,14,15,18,20,21,22!] ^((0-((m[3]>>21)&1))&5689344) //5689344=[!12,14,15,17,18,20,22!] ^((0-(m[3]&(1<<3)))&7520256) //7520256=[!14,15,17,20,21,22!] ^((0-((m[3]>>24)&1))&4067328) //4067328=[!12,17,18,19,20,21!] ^((0-((m[3]>>25)&1))&4689920) //4689920=[!12,15,16,17,18,22!] ^((0-((m[3]>>20)&1))&309248) //309248=[!11,12,13,15,18!] ^((0-((m[3]>>30)&1))&4409344) //4409344=[!11,14,16,17,22!] ^((0-((m[3]>>18)&1))&2248704) //2248704=[!12,14,17,21!] ^((0-(m[3]&(1<<6)))&2230272) //2230272=[!11,17,21!] ^((0-(m[3]&(1<<12)))&2293760) //2293760=[!16,17,21!] ^((0-((m[3]>>14)&1))&71680) //71680=[!11,12,16!] ^((0-((m[3]>>19)&1))&53248) //53248=[!12,14,15!] ^((0-((m[3]>>22)&1))&2121728) //2121728=[!13,14,21!] ^(rotate_left(m[3],0)&56123393) //56123393=[!0,13,14,19,20,22,24,25!], 56123393=[!0,13,14,19,20,22,24,25!] ^(rotate_left(m[3],1)&2048) //2048=[!11!], 1024=[!10!] ^(rotate_left(m[3],30)&2048) //2048=[!11!], 8192=[!13!] ; metset1precomp[4][15] = metset1precomp[3][15] ^ 0 ^((0-(m[3]&(1<<1)))&1104470020) //1104470020=[!2,13,14,15,18,20,22,23,24,30!] ^((0-(m[3]&(1<<3)))&27238400) //27238400=[!13,15,16,17,18,19,20,23,24!] ^((0-((m[3]>>22)&1))&1092444164) //1092444164=[!2,13,14,16,18,19,20,24,30!] ^((0-((m[3]>>25)&1))&32325636) //32325636=[!2,14,16,18,19,21,22,23,24!] ^((0-((m[3]>>16)&1))&26042372) //26042372=[!2,13,14,16,18,19,23,24!] ^((0-((m[3]>>30)&1))&1075781636) //1075781636=[!2,13,16,17,18,19,20,30!] ^((0-(m[3]&(1<<0)))&1096065024) //1096065024=[!13,15,18,20,22,24,30!] ^((0-((m[3]>>18)&1))&1091674116) //1091674116=[!2,13,15,16,20,24,30!] ^((0-((m[3]>>21)&1))&25903108) //25903108=[!2,14,16,17,19,23,24!] ^((0-((m[3]>>15)&1))&11288580) //11288580=[!2,14,18,19,21,23!] ^((0-((m[3]>>17)&1))&1083981824) //1083981824=[!14,18,19,20,23,30!] ^((0-((m[3]>>20)&1))&1075003396) //1075003396=[!2,14,16,17,20,30!] ^((0-((m[3]>>24)&1))&1090600964) //1090600964=[!2,14,16,24,30!] ^((0-((m[3]>>23)&1))&1082400768) //1082400768=[!13,18,23,30!] ^((0-(m[3]&(1<<6)))&18939904) //18939904=[!16,21,24!] ^((0-(m[3]&(1<<12)))&16850944) //16850944=[!13,16,24!] ^((0-((m[3]>>14)&1))&2105344) //2105344=[!13,21!] ^((0-((m[3]>>19)&1))&98304) //98304=[!15,16!] ; didmp = true; } Qtp1valsvecptr[t] = Qtp1valsptr; step_5(); } while (cur != 0); } return step4ok; } bool step_3() { static bool firsttime = true; if (firsttime) { cout << "t3 " << flush; firsttime = false; } const unsigned t = 3; UPDATE(t); bool step3ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 1006632964; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = metset1precomp[2][3] ^ 0 ; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]) ^ ((~metset1) & 939524100) ^ (xrng64()&2181038096); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 33554432; do { cur -= 1; cur &= curmask; uint32 Qtp1cur = 0; do { Q[offset+t+1] = Qtp1cur ^ cur ^ Qtp1val; Qtp1cur -= 1; Qtp1cur &= 2181038096^curmask; // 3 bits of freedom m[t] = Q[offset+t+1] + mpartial; if (0 != ((m[t]^metset1)&67108864)) break; uint32 metxorfix = (m[t]^metset1) & 939524100; *(Qtp1valsptr++) = Q[offset+t+1]^metxorfix; } while (Qtp1cur != 0); } while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step3ok = true; metset1precomp[3][4] = metset1precomp[2][4] ^ 0 ^(rotate_left(m[2],0)&2048) //2048=[!11!], 2048=[!11!] ; metset1precomp[3][5] = metset1precomp[2][5] ^ 0 ; metset1precomp[3][6] = metset1precomp[2][6] ^ 0 ; metset1precomp[3][7] = metset1precomp[2][7] ^ 0 ; metset1precomp[3][8] = metset1precomp[2][8] ^ 0 ; metset1precomp[3][9] = metset1precomp[2][9] ^ 0 ; metset1precomp[3][10] = metset1precomp[2][10] ^ 0 ; metset1precomp[3][11] = metset1precomp[2][11] ^ 0 ; metset1precomp[3][12] = metset1precomp[2][12] ^ 0 ^(rotate_left(m[2],31)&2147483648) //2147483648=[!31!], 1=[!0!] ; metset1precomp[3][13] = metset1precomp[2][13] ^ 0 ^((0-(m[2]&(1<<16)))&18612224) //18612224=[!18,19,20,24!] ^((0-((m[2]>>23)&1))&3932160) //3932160=[!18,19,20,21!] ^((0-((m[2]>>24)&1))&1966080) //1966080=[!17,18,19,20!] ^((0-((m[2]>>31)&1))&3538944) //3538944=[!17,18,20,21!] ^((0-(m[2]&(1<<0)))&3670016) //3670016=[!19,20,21!] ^((0-(m[2]&(1<<11)))&17432576) //17432576=[!17,19,24!] ^((0-(m[2]&(1<<14)))&3407872) //3407872=[!18,20,21!] ^((0-(m[2]&(1<<15)))&17432576) //17432576=[!17,19,24!] ^((0-((m[2]>>18)&1))&3276800) //3276800=[!17,20,21!] ^((0-((m[2]>>30)&1))&917504) //917504=[!17,18,19!] ^(rotate_left(m[2],0)&2197291010) //2197291010=[!1,19,20,21,22,23,25,31!], 2197291010=[!1,19,20,21,22,23,25,31!] ^(rotate_left(m[2],1)&2097152) //2097152=[!21!], 1048576=[!20!] ^(rotate_left(m[2],5)&131072) //131072=[!17!], 4096=[!12!] ^(rotate_left(m[2],26)&524288) //524288=[!19!], 33554432=[!25!] ^(rotate_left(m[2],30)&1048576) //1048576=[!20!], 4194304=[!22!] ; metset1precomp[3][14] = metset1precomp[2][14] ^ 0 ^((0-((m[2]>>30)&1))&3223296000) //3223296000=[!11,12,15,16,17,18,19,20,30,31!] ^((0-((m[2]>>14)&1))&7661568) //7661568=[!11,13,14,15,18,20,21,22!] ^((0-((m[2]>>23)&1))&5568512) //5568512=[!11,12,13,14,15,18,20,22!] ^((0-((m[2]>>18)&1))&7659520) //7659520=[!13,14,15,18,20,21,22!] ^((0-((m[2]>>31)&1))&7641088) //7641088=[!11,12,15,18,20,21,22!] ^((0-(m[2]&(1<<0)))&6959104) //6959104=[!12,13,17,19,21,22!] ^((0-((m[2]>>16)&1))&5476352) //5476352=[!12,15,16,17,20,22!] ^((0-((m[2]>>22)&1))&6379520) //6379520=[!11,12,14,16,21,22!] ^((0-((m[2]>>24)&1))&2177024) //2177024=[!11,12,13,16,21!] ^((0-(m[2]&(1<<11)))&2297856) //2297856=[!12,16,17,21!] ^((0-((m[2]>>15)&1))&2295808) //2295808=[!11,16,17,21!] ^((0-(m[2]&(1<<1)))&77824) //77824=[!12,13,16!] ^((0-((m[2]>>12)&1))&71680) //71680=[!11,12,16!] ^((0-((m[2]>>17)&1))&71680) //71680=[!11,12,16!] ^((0-((m[2]>>21)&1))&83968) //83968=[!11,14,16!] ^((0-((m[2]>>25)&1))&86016) //86016=[!12,14,16!] ^((0-((m[2]>>20)&1))&67584) //67584=[!11,16!] ^(rotate_left(m[2],30)&1087021056) //1087021056=[!13,15,17,19,22,23,30!], 53116929=[!0,15,17,19,21,24,25!] ^(rotate_left(m[2],2)&2048) //2048=[!11!], 512=[!9!] ; metset1precomp[3][15] = metset1precomp[2][15] ^ 0 ^((0-((m[2]>>30)&1))&33357828) //33357828=[!2,16,18,19,20,21,22,23,24!] ^((0-((m[2]>>23)&1))&17784836) //17784836=[!2,13,14,16,17,18,19,24!] ^((0-((m[2]>>14)&1))&28114948) //28114948=[!2,16,18,19,21,23,24!] ^((0-((m[2]>>18)&1))&25772036) //25772036=[!2,14,16,19,23,24!] ^((0-((m[2]>>22)&1))&1100226560) //1100226560=[!13,18,20,23,24,30!] ^((0-((m[2]>>31)&1))&25772036) //25772036=[!2,14,16,19,23,24!] ^((0-(m[2]&(1<<0)))&5521412) //5521412=[!2,14,18,20,22!] ^((0-(m[2]&(1<<16)))&1083965440) //1083965440=[!18,19,20,23,30!] ^((0-((m[2]>>25)&1))&1075347460) //1075347460=[!2,15,19,20,30!] ^((0-(m[2]&(1<<11)))&16850944) //16850944=[!13,16,24!] ^((0-((m[2]>>15)&1))&16850944) //16850944=[!13,16,24!] ^((0-(m[2]&(1<<12)))&2105344) //2105344=[!13,21!] ^((0-((m[2]>>17)&1))&2105344) //2105344=[!13,21!] ^((0-((m[2]>>20)&1))&1073741828) //1073741828=[!2,30!] ^(rotate_left(m[2],31)&3252666369) //3252666369=[!0,14,15,16,17,18,19,20,22,23,24,30,31!], 2210365443=[!0,1,15,16,17,18,19,20,21,23,24,25,31!] ^(rotate_left(m[2],0)&2185994243) //2185994243=[!0,1,13,15,16,17,19,22,25,31!], 2185994243=[!0,1,13,15,16,17,19,22,25,31!] ^(rotate_left(m[2],29)&1081589760) //1081589760=[!14,15,16,17,18,20,21,22,30!], 62783490=[!1,17,18,19,20,21,23,24,25!] ^(rotate_left(m[2],26)&303104) //303104=[!13,15,18!], 19398656=[!19,21,24!] ^(rotate_left(m[2],24)&73728) //73728=[!13,16!], 18874368=[!21,24!] ^(rotate_left(m[2],20)&2097152) //2097152=[!21!], 2=[!1!] ^(rotate_left(m[2],22)&16384) //16384=[!14!], 16777216=[!24!] ; Qtp1valsvecptr[t] = Qtp1valsptr; step_4(); } return step3ok; } bool step_2() { static bool firsttime = true; if (firsttime) { cout << "t2 " << flush; firsttime = false; } const unsigned t = 2; UPDATE(t); bool step2ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 1006632988; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = metset1precomp[1][2] ^ 0 ; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]) ^ ((~metset1) & 671088640) ^ (xrng64()&2181038080); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 33554432; do { cur -= 1; cur &= curmask; uint32 Qtp1cur = 0; do { Q[offset+t+1] = Qtp1cur ^ cur ^ Qtp1val; Qtp1cur -= 1; Qtp1cur &= 2181038080^curmask; // 2 bits of freedom m[t] = Q[offset+t+1] + mpartial; if (0 != ((m[t]^metset1)&335544348)) break; uint32 metxorfix = (m[t]^metset1) & 671088640; *(Qtp1valsptr++) = Q[offset+t+1]^metxorfix; } while (Qtp1cur != 0); } while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step2ok = true; metset1precomp[2][3] = metset1precomp[1][3] ^ 0 ; metset1precomp[2][4] = metset1precomp[1][4] ^ 0 ^(rotate_left(m[1],5)&2048) //2048=[!11!], 64=[!6!] ; metset1precomp[2][5] = metset1precomp[1][5] ^ 0 ; metset1precomp[2][6] = metset1precomp[1][6] ^ 0 ; metset1precomp[2][7] = metset1precomp[1][7] ^ 0 ^(rotate_left(m[1],0)&8) //8=[!3!], 8=[!3!] ; metset1precomp[2][8] = metset1precomp[1][8] ^ 0 ; metset1precomp[2][9] = metset1precomp[1][9] ^ 0 ^(rotate_left(m[1],0)&268435468) //268435468=[!2,3,28!], 268435468=[!2,3,28!] ; metset1precomp[2][10] = metset1precomp[1][10] ^ 0 ; metset1precomp[2][11] = metset1precomp[1][11] ^ 0 ; metset1precomp[2][12] = metset1precomp[1][12] ^ 0 ^(rotate_left(m[1],31)&2147483648) //2147483648=[!31!], 1=[!0!] ; metset1precomp[2][13] = metset1precomp[1][13] ^ 0 ^((0-((m[1]>>26)&1))&25034752) //25034752=[!17,18,19,20,21,22,24!] ^((0-(m[1]&(1<<1)))&2151546880) //2151546880=[!17,18,19,20,21,31!] ^((0-((m[1]>>28)&1))&20840448) //20840448=[!17,18,19,20,21,24!] ^((0-((m[1]>>21)&1))&20316160) //20316160=[!17,18,20,21,24!] ^((0-((m[1]>>22)&1))&18743296) //18743296=[!17,18,19,20,24!] ^((0-((m[1]>>23)&1))&4063232) //4063232=[!17,18,19,20,21!] ^((0-(m[1]&(1<<2)))&17694720) //17694720=[!17,18,19,24!] ^((0-(m[1]&(1<<3)))&3538944) //3538944=[!17,18,20,21!] ^((0-(m[1]&(1<<16)))&3538944) //3538944=[!17,18,20,21!] ^((0-((m[1]>>20)&1))&18481152) //18481152=[!17,19,20,24!] ^((0-((m[1]>>24)&1))&22544384) //22544384=[!19,20,22,24!] ^((0-((m[1]>>25)&1))&26738688) //26738688=[!19,20,23,24!] ^((0-(m[1]&(1<<13)))&17432576) //17432576=[!17,19,24!] ^((0-(m[1]&(1<<18)))&19398656) //19398656=[!19,21,24!] ^((0-((m[1]>>29)&1))&1441792) //1441792=[!17,18,20!] ^((0-(m[1]&(1<<0)))&17825792) //17825792=[!20,24!] ^((0-(m[1]&(1<<6)))&17301504) //17301504=[!19,24!] ^(rotate_left(m[1],2)&131072) //131072=[!17!], 32768=[!15!] ^(rotate_left(m[1],3)&131072) //131072=[!17!], 16384=[!14!] ; metset1precomp[2][14] = metset1precomp[1][14] ^ 0 ^((0-((m[1]>>21)&1))&5490688) //5490688=[!11,14,15,16,17,20,22!] ^((0-(m[1]&(1<<3)))&1349632) //1349632=[!11,12,15,18,20!] ^((0-(m[1]&(1<<2)))&4366336) //4366336=[!13,15,17,22!] ^((0-(m[1]&(1<<6)))&2230272) //2230272=[!11,17,21!] ^((0-(m[1]&(1<<13)))&2293760) //2293760=[!16,17,21!] ^((0-(m[1]&(1<<16)))&7340032) //7340032=[!20,21,22!] ^((0-(m[1]&(1<<0)))&163840) //163840=[!15,17!] ^(rotate_left(m[1],0)&669704195) //669704195=[!0,1,13,14,15,17,19,21,22,23,24,25,26,29!], 669704195=[!0,1,13,14,15,17,19,21,22,23,24,25,26,29!] ^(rotate_left(m[1],29)&1081554944) //1081554944=[!11,12,13,16,17,18,20,21,22,30!], 62504962=[!1,14,15,16,19,20,21,23,24,25!] ^(rotate_left(m[1],24)&3647488) //3647488=[!11,13,15,16,17,18,20,21!], 933756928=[!19,21,23,24,25,26,28,29!] ^(rotate_left(m[1],18)&3954688) //3954688=[!11,12,14,18,19,20,21!], 369098767=[!0,1,2,3,25,26,28!] ^(rotate_left(m[1],19)&5847040) //5847040=[!11,12,13,16,19,20,22!], 654311435=[!0,1,3,24,25,26,29!] ^(rotate_left(m[1],30)&3223410688) //3223410688=[!11,12,14,16,21,30,31!], 8740867=[!0,1,13,14,16,18,23!] ^(rotate_left(m[1],21)&12728320) //12728320=[!11,12,13,17,22,23!], 297795590=[!1,2,22,23,24,28!] ^(rotate_left(m[1],23)&1288192) //1288192=[!11,13,15,16,17,20!], 659554304=[!20,22,24,25,26,29!] ^(rotate_left(m[1],25)&6686720) //6686720=[!11,17,18,21,22!], 855900160=[!18,24,25,28,29!] ^(rotate_left(m[1],31)&6459392) //6459392=[!12,15,17,21,22!], 12918784=[!13,16,18,22,23!] ^(rotate_left(m[1],2)&2152005632) //2152005632=[!16,18,22,31!], 538001408=[!14,16,20,29!] ^(rotate_left(m[1],22)&4554752) //4554752=[!15,16,18,22!], 369098753=[!0,25,26,28!] ^(rotate_left(m[1],26)&5324800) //5324800=[!14,16,20,22!], 340787200=[!20,22,26,28!] ^(rotate_left(m[1],14)&51200) //51200=[!11,14,15!], 536870915=[!0,1,29!] ^(rotate_left(m[1],16)&143360) //143360=[!12,13,17!], 805306370=[!1,28,29!] ^(rotate_left(m[1],27)&802816) //802816=[!14,18,19!], 25690112=[!19,23,24!] ^(rotate_left(m[1],20)&133120) //133120=[!11,17!], 545259520=[!23,29!] ^(rotate_left(m[1],28)&4196352) //4196352=[!11,22!], 67141632=[!15,26!] ^(rotate_left(m[1],1)&65536) //65536=[!16!], 32768=[!15!] ^(rotate_left(m[1],3)&2097152) //2097152=[!21!], 262144=[!18!] ^(rotate_left(m[1],10)&2048) //2048=[!11!], 2=[!1!] ; metset1precomp[2][15] = metset1precomp[1][15] ^ 0 ^((0-(m[1]&(1<<1)))&1106567172) //1106567172=[!2,13,14,15,18,20,21,22,23,24,30!] ^((0-((m[1]>>29)&1))&1102733312) //1102733312=[!13,14,17,19,20,21,23,24,30!] ^((0-(m[1]&(1<<3)))&1099513856) //1099513856=[!14,16,19,23,24,30!] ^((0-((m[1]>>20)&1))&1085808640) //1085808640=[!13,19,20,21,23,30!] ^((0-((m[1]>>23)&1))&1099218944) //1099218944=[!14,15,18,23,24,30!] ^((0-((m[1]>>25)&1))&745476) //745476=[!2,13,14,16,17,19!] ^((0-(m[1]&(1<<0)))&21127168) //21127168=[!13,14,17,22,24!] ^((0-(m[1]&(1<<2)))&11698176) //11698176=[!15,17,20,21,23!] ^((0-((m[1]>>16)&1))&25755652) //25755652=[!2,16,19,23,24!] ^((0-((m[1]>>18)&1))&1092616196) //1092616196=[!2,21,24,30!] ^((0-((m[1]>>24)&1))&16949248) //16949248=[!13,15,17,24!] ^((0-((m[1]>>26)&1))&212996) //212996=[!2,14,16,17!] ^((0-((m[1]>>28)&1))&8953856) //8953856=[!13,15,19,23!] ^((0-(m[1]&(1<<6)))&18939904) //18939904=[!16,21,24!] ^((0-(m[1]&(1<<13)))&16850944) //16850944=[!13,16,24!] ^((0-((m[1]>>22)&1))&114688) //114688=[!14,15,16!] ^((0-((m[1]>>14)&1))&2105344) //2105344=[!13,21!] ^(rotate_left(m[1],28)&1081581568) //1081581568=[!13,15,16,17,18,20,21,22,30!], 125435908=[!2,17,19,20,21,22,24,25,26!] ^(rotate_left(m[1],29)&7069696) //7069696=[!13,14,15,16,17,19,21,22!], 56557568=[!16,17,18,19,20,22,24,25!] ^(rotate_left(m[1],30)&26042368) //26042368=[!13,14,16,18,19,23,24!], 104169472=[!15,16,18,20,21,25,26!] ^(rotate_left(m[1],2)&1102315520) //1102315520=[!18,20,21,23,24,30!], 275578880=[!16,18,19,21,22,28!] ^(rotate_left(m[1],6)&2097152) //2097152=[!21!], 32768=[!15!] ^(rotate_left(m[1],13)&4) //4=[!2!], 2097152=[!21!] ^(rotate_left(m[1],26)&8192) //8192=[!13!], 524288=[!19!] ; Qtp1valsvecptr[t] = Qtp1valsptr; step_3(); } return step2ok; } bool step_1() { static bool firsttime = true; if (firsttime) { cout << "t1 " << flush; firsttime = false; } const unsigned t = 1; UPDATE(t); bool step1ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 1207963664; for (uint32* Qtvalsptr = Qtp1valsvecptr[t-1]-1; Qtvalsptr >= Qtp1valsvec[t-1]; --Qtvalsptr) { Q[offset+t] = *Qtvalsptr; m[t-1] = *Qtvalsptr + metpartialvec[t-1]; const uint32 metset1 = metset1precomp[0][1] ^ 0 ; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]) ^ ((~metset1) & 134217728) ^ (xrng64()&805306372); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 805306372; do { cur -= 1; cur &= curmask; uint32 Qtp1cur = 0; do { Q[offset+t+1] = Qtp1cur ^ cur ^ Qtp1val; Qtp1cur -= 1; Qtp1cur &= 805306372^curmask; // 3 bits of freedom m[t] = Q[offset+t+1] + mpartial; if (0 != ((m[t]^metset1)&1073745936)) break; uint32 metxorfix = (m[t]^metset1) & 134217728; *(Qtp1valsptr++) = Q[offset+t+1]^metxorfix; } while (Qtp1cur != 0); } while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) continue; step1ok = true; metset1precomp[1][2] = metset1precomp[0][2] ^ 0 ; metset1precomp[1][3] = metset1precomp[0][3] ^ 0 ; metset1precomp[1][4] = metset1precomp[0][4] ^ 0 ; metset1precomp[1][5] = metset1precomp[0][5] ^ 0 ; metset1precomp[1][6] = metset1precomp[0][6] ^ 0 ; metset1precomp[1][7] = metset1precomp[0][7] ^ 0 ; metset1precomp[1][8] = metset1precomp[0][8] ^ 0 ; metset1precomp[1][9] = metset1precomp[0][9] ^ 0 ; metset1precomp[1][10] = metset1precomp[0][10] ^ 0 ; metset1precomp[1][11] = metset1precomp[0][11] ^ 0 ; metset1precomp[1][12] = metset1precomp[0][12] ^ 0 ^(rotate_left(m[0],1)&2147483648) //2147483648=[!31!], 1073741824=[!30!] ; metset1precomp[1][13] = metset1precomp[0][13] ^ 0 ^((0-(m[0]&(1<<2)))&3538944) //3538944=[!17,18,20,21!] ^((0-(m[0]&(1<<16)))&18612224) //18612224=[!18,19,20,24!] ^((0-((m[0]>>31)&1))&19660800) //19660800=[!18,19,21,24!] ^((0-(m[0]&(1<<3)))&1441792) //1441792=[!17,18,20!] ^((0-(m[0]&(1<<11)))&17432576) //17432576=[!17,19,24!] ^((0-(m[0]&(1<<14)))&3407872) //3407872=[!18,20,21!] ^((0-(m[0]&(1<<19)))&19922944) //19922944=[!20,21,24!] ^((0-(m[0]&(1<<0)))&16908288) //16908288=[!17,24!] ^((0-(m[0]&(1<<20)))&18874368) //18874368=[!21,24!] ^((0-((m[0]>>30)&1))&2228224) //2228224=[!17,21!] ^(rotate_left(m[0],0)&2212888588) //2212888588=[!2,3,17,18,21,22,23,24,25,31!], 2212888588=[!2,3,17,18,21,22,23,24,25,31!] ^(rotate_left(m[0],31)&4063232) //4063232=[!17,18,19,20,21!], 8126464=[!18,19,20,21,22!] ^(rotate_left(m[0],29)&3932160) //3932160=[!18,19,20,21!], 31457280=[!21,22,23,24!] ^(rotate_left(m[0],30)&2490370) //2490370=[!1,17,18,21!], 9961480=[!3,19,20,23!] ^(rotate_left(m[0],26)&17563648) //17563648=[!18,19,24!], 1124073472=[!24,25,30!] ^(rotate_left(m[0],27)&17432576) //17432576=[!17,19,24!], 557842432=[!22,24,29!] ^(rotate_left(m[0],2)&16777216) //16777216=[!24!], 4194304=[!22!] ^(rotate_left(m[0],5)&131072) //131072=[!17!], 4096=[!12!] ^(rotate_left(m[0],22)&524288) //524288=[!19!], 536870912=[!29!] ^(rotate_left(m[0],25)&262144) //262144=[!18!], 33554432=[!25!] ^(rotate_left(m[0],28)&131072) //131072=[!17!], 2097152=[!21!] ; metset1precomp[1][14] = metset1precomp[0][14] ^ 0 ^((0-((m[0]>>20)&1))&5765120) //5765120=[!11,12,13,14,15,16,17,18,20,22!] ^((0-((m[0]>>14)&1))&7655424) //7655424=[!12,14,15,18,20,21,22!] ^((0-((m[0]>>19)&1))&5466112) //5466112=[!11,13,14,16,17,20,22!] ^((0-((m[0]>>21)&1))&6481920) //6481920=[!11,13,14,15,17,21,22!] ^((0-((m[0]>>23)&1))&4009984) //4009984=[!12,13,16,18,19,20,21!] ^((0-((m[0]>>25)&1))&5490688) //5490688=[!11,14,15,16,17,20,22!] ^((0-(m[0]&(1<<2)))&5543936) //5543936=[!11,12,15,18,20,22!] ^((0-((m[0]>>30)&1))&1074358272) //1074358272=[!11,13,14,16,19,30!] ^((0-(m[0]&(1<<0)))&1074081792) //1074081792=[!12,13,16,18,30!] ^((0-(m[0]&(1<<3)))&3325952) //3325952=[!14,15,17,20,21!] ^((0-((m[0]>>16)&1))&5455872) //5455872=[!14,16,17,20,22!] ^((0-((m[0]>>24)&1))&1355776) //1355776=[!12,13,15,18,20!] ^((0-(m[0]&(1<<11)))&2297856) //2297856=[!12,16,17,21!] ^((0-((m[0]>>22)&1))&215040) //215040=[!11,14,16,17!] ^((0-((m[0]>>29)&1))&2265088) //2265088=[!12,15,17,21!] ^((0-((m[0]>>31)&1))&1163264) //1163264=[!14,15,16,20!] ^((0-((m[0]>>18)&1))&86016) //86016=[!12,14,16!] ^((0-(m[0]&(1<<12)))&69632) //69632=[!12,16!] ^((0-((m[0]>>17)&1))&10240) //10240=[!11,13!] ^(rotate_left(m[0],19)&7280640) //7280640=[!11,12,16,17,18,19,21,22!], 3808428045=[!0,2,3,24,25,29,30,31!] ^(rotate_left(m[0],31)&1081387008) //1081387008=[!11,13,15,18,20,21,22,30!], 2162774016=[!12,14,16,19,21,22,23,31!] ^(rotate_left(m[0],2)&2048) //2048=[!11!], 512=[!9!] ^(rotate_left(m[0],29)&4096) //4096=[!12!], 32768=[!15!] ; metset1precomp[1][15] = metset1precomp[0][15] ^ 0 ^((0-(m[0]&(1<<3)))&27238400) //27238400=[!13,15,16,17,18,19,20,23,24!] ^((0-((m[0]>>23)&1))&31244292) //31244292=[!2,14,15,18,19,20,22,23,24!] ^((0-((m[0]>>24)&1))&1085497348) //1085497348=[!2,13,14,16,17,20,21,23,30!] ^((0-(m[0]&(1<<0)))&2172420096) //2172420096=[!15,18,19,20,21,22,24,31!] ^((0-((m[0]>>14)&1))&28131332) //28131332=[!2,14,16,18,19,21,23,24!] ^((0-((m[0]>>25)&1))&1088110592) //1088110592=[!14,16,17,19,20,22,23,30!] ^((0-((m[0]>>30)&1))&1097490432) //1097490432=[!13,14,17,19,21,22,24,30!] ^((0-((m[0]>>21)&1))&1099522048) //1099522048=[!13,14,16,19,23,24,30!] ^((0-((m[0]>>22)&1))&1092190212) //1092190212=[!2,15,16,19,20,24,30!] ^((0-((m[0]>>31)&1))&12009472) //12009472=[!14,16,17,18,20,21,23!] ^((0-(m[0]&(1<<2)))&1099513856) //1099513856=[!14,16,19,23,24,30!] ^((0-((m[0]>>16)&1))&1083998208) //1083998208=[!15,18,19,20,23,30!] ^((0-((m[0]>>19)&1))&11091972) //11091972=[!2,14,16,19,21,23!] ^((0-((m[0]>>20)&1))&8798212) //8798212=[!2,14,17,18,23!] ^((0-((m[0]>>18)&1))&2269184) //2269184=[!13,15,17,21!] ^((0-(m[0]&(1<<11)))&16850944) //16850944=[!13,16,24!] ^((0-((m[0]>>29)&1))&16826368) //16826368=[!14,15,24!] ^((0-(m[0]&(1<<12)))&2105344) //2105344=[!13,21!] ^(rotate_left(m[0],31)&81920) //81920=[!14,16!], 163840=[!15,17!] ^(rotate_left(m[0],29)&16384) //16384=[!14!], 131072=[!17!] ; Qtp1valsvecptr[t] = Qtp1valsptr; step_2(); } return step1ok; } bool step_0() { static bool firsttime = true; if (firsttime) { cout << "t0 " << flush; firsttime = false; } const unsigned t = 0; UPDATE(t); bool step0ok = false; Qr30[offset+t-2] = rotate_left(Q[offset+t-2],30); const uint32 mpartial2 = 0 - sha1_f1(Q[offset+t-1], Qr30[offset+t-2], Qr30[offset+t-3]) - sha1_ac[0] - Qr30[offset+t-4]; const uint32 metmask = 469762050; { const uint32 metset1 = 268435456; const uint32 Qtp1val = Qvalue[offset+t+1] ^ (Qprev[offset+t+1]&Q[offset+t]) ^ ((~metset1) & 0) ^ (xrng64()&2684354612); const uint32 mpartial = mpartial2 - rotate_left(Q[offset+t],5); metpartialvec[t] = mpartial; uint32* Qtp1valsptr = Qtp1valsvec[t]; uint32 cur = 0; const uint32 curmask = 0; do { cur -= 1; cur &= curmask; uint32 Qtp1cur = 0; do { Q[offset+t+1] = Qtp1cur ^ cur ^ Qtp1val; Qtp1cur -= 1; Qtp1cur &= 2684354612^curmask; // 5 bits of freedom m[t] = Q[offset+t+1] + mpartial; if (0 != ((m[t]^metset1)&469762050)) break; if ((m[t]&384)==384) continue; uint32 metxorfix = (m[t]^metset1) & 0; *(Qtp1valsptr++) = Q[offset+t+1]^metxorfix; } while (Qtp1cur != 0); } while (cur != 0); if (Qtp1valsptr == Qtp1valsvec[t]) return step0ok; step0ok = true; Qtp1valsvecptr[t] = Qtp1valsptr; step_1(); } return step0ok; }
55.995276
13,642
0.58753
[ "vector" ]
d8613f325c08427972829de0f7dcec6ebf842651
12,160
cpp
C++
project/XPPlayer.cpp
adamjoniec/theimp
96f60fd665099348959b1cfc0045cb62d3a2be70
[ "Apache-2.0" ]
null
null
null
project/XPPlayer.cpp
adamjoniec/theimp
96f60fd665099348959b1cfc0045cb62d3a2be70
[ "Apache-2.0" ]
null
null
null
project/XPPlayer.cpp
adamjoniec/theimp
96f60fd665099348959b1cfc0045cb62d3a2be70
[ "Apache-2.0" ]
null
null
null
// XPPlayer.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "XPPlayer.h" #include "MainWnd.h" #include "config.h" #include "language.h" #include "accelerators.h" #include "splashscreen.h" #include "timeout.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //void CheckExeSum(char *pszPath,char *pszName) #define CheckExeSum(pszPath,pszName)\ {\ char sz[_MAX_PATH+2]; _makepath(sz,"",pszPath,pszName,"exe");\ FILE *f = fopen( sz, "rb" );\ if ( f ) {\ fseek(f,0,SEEK_END); int s=ftell(f)-4; fseek(f,0,SEEK_SET);\ unsigned char *buff = new unsigned char [s]; \ fread( buff, s ,1, f); \ int filesum; fread( &filesum, 4, 1, f); fclose(f);\ unsigned char *b = buff; int sum=0;\ for (int i=0; i<s; i++,b++) sum += *b;\ delete buff; if (sum!=filesum) return FALSE;\ } else return FALSE;\ }\ /*#define CheckExeSum(pszPath,pszName)\ {\ char sz[_MAX_PATH]; _makepath(sz,"",pszPath,pszName,"exe");\ cFile *pFile = new cFile();\ if ( pFile->Open((char*)sz,"r") ) {\ int s = pFile->Size();\ unsigned char *buff = new unsigned char [s]; pFile->Read( buff, s-4 );\ int filesum; pFile->Read( &filesum, 4 );\ delete pFile;\ unsigned char *b = buff; int sum=0;\ for (int i=0; i<s; i++,b++) sum += *b;\ delete buff; if (sum!=filesum) return FALSE;\ } else return FALSE;\ }\*/ // Expire after 18.12.2002 . // Get current OS version. // If win9x get date from bios. //void CheckDateExpired(CWnd *pParentWnd) //{ #define ShowExpired {\ CSplashScreen *psplash = new CSplashScreen();\ psplash->Create(); Sleep( 6000 ); \ CTimeOut *pto = new CTimeOut();\ pto->DoModal(); delete pto; delete psplash;\ goto endCheckDateExpired; } #define LIMIT 24400 #define CheckDateExpired \ {\ \ int day, month, year;\ \ OSVERSIONINFO osvi;\ osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);\ GetVersionEx (&osvi);\ \ if ( osvi.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS )\ {\ int day, month, year;\ \ _outp(0x70,7); day = _inp(0x71);\ day = ((day&0x0F))+(((day&0xF0)>>4)*10);\ \ _outp(0x70,8); month = _inp(0x71);\ month = ((month&0x0F))+(((month&0xF0)>>4)*10);\ \ _outp(0x70,9); year = _inp(0x71);\ year = 2000+((year&0x0F))+(((year&0xF0)>>4)*10);\ \ _asm {\ push day\ push month\ push year\ push day\ push month\ push year\ }\ \ SYSTEMTIME st;\ GetSystemTime( &st );\ }\ else \ {\ \ int day, month, year;\ \ SYSTEMTIME st;\ GetLocalTime( &st );\ day = st.wDay;\ month = st.wMonth;\ year = st.wYear;\ \ _asm {\ push day\ push month\ push year\ push day\ push month\ push year\ }\ \ GetSystemTime( &st );\ \ }\ \ _asm { \ pop year\ pop month\ pop day\ }\ \ srand( GetTickCount() );\ int r1 = rand()%9,r2 = rand()%9,r3 = rand()%9,r4 = rand()%9,\ i1=0,i2=0,i3=0,i4=0;\ \ int days=(year<<4)-(year<<2)+(month<<5)-(month<<1)+day;\ \ int limit = LIMIT;\ int arrlimit[10], arrdays[10];\ \ int y,m,d;\ _asm { \ pop y\ pop m\ pop d\ }\ if ( days>LIMIT ) ShowExpired\ \ if ( days>limit ) goto showExpired1;\ \ for (i1=0; i1<r1; i1++) {\ \ if ( rand()%2 ) arrdays[i1] = days+i1;\ else arrdays[i1] = (y<<4)-(y<<2)+(m<<5)-(m<<1)+d+i1;\ \ }\ \ if ( (y<<4)-(y<<2)+(m<<5)-(m<<1)+d+i1>limit ) ShowExpired\ \ while (i2<r2) {\ \ if ( i2%3 ) arrlimit[i2] = limit+i2;\ else arrlimit[i2] = LIMIT+i2;\ \ i2++;\ }\ \ do {\ int d=arrdays[rand()%(5)+1], l=arrlimit[rand()%(5)+1];\ if (rand()%2) d=(y<<4)-(y<<2)+(m<<5)-(m<<1)+d+i1;\ if ( d>=l ) goto showExpired2;\ \ i3++;\ } while (i3<r3);\ \ goto endCheckDateExpired;\ \ int expired;\ showExpired1: expired = 1; ShowExpired\ showExpired2: expired = 2; ShowExpired\ \ endCheckDateExpired:\ }\ ///////////////////////////////////////////////////////////////////////////// // CXPPlayerApp BEGIN_MESSAGE_MAP(CXPPlayerApp, CWinApp) //{{AFX_MSG_MAP(CXPPlayerApp) //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CXPPlayerApp construction CXPPlayerApp::CXPPlayerApp() { } ///////////////////////////////////////////////////////////////////////////// // The one and only CXPPlayerApp object CXPPlayerApp theApp; ///////////////////////////////////////////////////////////////////////////// // CXPPlayerApp initialization HWND hwndCtrl, hwndFs, hwndPlaylist, hwndSubtitles, hwndSubtitlesFs; void CXPPlayerApp::ShowSplashScreen() { CSplashScreen *psplash = new CSplashScreen(); psplash->Create(); Sleep( 2000 ); delete psplash; } BOOL CXPPlayerApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif HANDLE hInstanceMutex = CreateMutex(NULL,TRUE, "The Imp Synchronization Mutex"); if( GetLastError() == ERROR_ALREADY_EXISTS) { if ( hInstanceMutex ) CloseHandle( hInstanceMutex ); HWND hPrevApp = FindWindow(NULL, "The Imp"); if ( hPrevApp ) { ShowWindow(hPrevApp, SW_RESTORE); SetForegroundWindow(hPrevApp); int len = strlen(m_lpCmdLine); if ( !len ) return 0; HANDLE handle = CreateFileMapping( (HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE, 0, len+1, "The Imp Shared File In Memory" ); if ( !handle || GetLastError()== ERROR_ALREADY_EXISTS ) { CloseHandle( handle ) ; return 0; } char *psz = (char*)MapViewOfFile( handle, FILE_MAP_WRITE, 0, 0, 0 ); if ( psz ) { strcpy( psz, m_lpCmdLine ); SendMessage( hPrevApp, WM_COMMAND, IDM_CALLBACK_OPENFROMMUTEX, NULL ); UnmapViewOfFile( psz ); } CloseHandle( handle ); } return 0; } stConfig Options; // Get The Imp.exe path. char path[_MAX_PATH], pathtemp[_MAX_PATH], drive[_MAX_DRIVE], dir[_MAX_DIR], *pszPath = path, *pszcl = GetCommandLine(); if (*pszcl=='"') pszcl++; while (*pszcl && *pszcl!='"' ) pszcl++; *pszcl=0; _splitpath( GetCommandLine(), drive, dir, NULL, NULL ); _makepath( path, drive, dir, NULL, NULL ); if ( *pszPath == '"' ) pszPath++; // Load config file. char szConfig[_MAX_PATH]; _makepath( szConfig, NULL, pszPath, "config", NULL ); if ( !ReadConfig( szConfig, &Options ) ) ShowSplashScreen(); // Set app path strcpy(Options.szAppPath, pszPath); // Set app name. strcpy( Options.szAppName, "The Imp" ); if ( Options.modeIdStartWhenNoMovie ) Options.modeId = Options.modeIdStartWhenNoMovie; InitLanguage(); _makepath( pathtemp, NULL, Options.szAppPath, Options.szLanguageDirectory, NULL ); _makepath( path, NULL, pathtemp, Options.szLanguageFileName, NULL ); ChangeLang( path ); // Check exe sum. Correct exe sum must be set after compiling app. CheckExeSum(Options.szAppPath, Options.szAppName); if ( Options.bRegisterOnStart ) RegisterFiletypes( &Options, Options.szRegisteredExts ); // Load accelerators. hAccel = CreateAcceleratorTable( accel, GetKeysCount() ); // Create playlist. CPlaylist *pPlaylist = new CPlaylist( ); pPlaylist->Create(Options.maxPlaylistFiles, TRUE, &Options); // Parse command line. BOOL bAddedFile = FALSE; char *psz = m_lpCmdLine, *pszbuff = new char[ strlen(psz)+1 ]; while ( *psz ) { while ( *psz && *psz==' ') psz++; //skip begining spaces if ( *psz=='"' ) { psz++; char *pszstart = psz; while ( *psz && *psz!='"' ) psz++; char c=*psz; *psz = 0; strcpy( pszbuff, pszstart ); *psz = c; if ( *pszstart ) psz++; } else if (*psz ) { char *pszstart = psz; while ( *psz && *psz!=' ' ) psz++; char c=*psz; *psz = 0; strcpy( pszbuff, pszstart ); *psz = c; } else *pszbuff = 0; if ( *pszbuff ) { if ( *pszbuff=='/' ) { if ( !_stricmp(pszbuff+1, "NoLoop") ) Options.bLoop = FALSE; } else { pPlaylist->Add(pszbuff, !bAddedFile); bAddedFile = TRUE; } } } delete[] pszbuff; if ( bAddedFile ) { if ( Options.modeIdStartWhenMovie ) Options.modeId = Options.modeIdStartWhenMovie; } //CheckDateExpired; { int day, month, year; OSVERSIONINFO osvi; osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO); GetVersionEx (&osvi); if ( osvi.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS ) { int day, month, year; _outp(0x70,7); day = _inp(0x71); day = ((day&0x0F))+(((day&0xF0)>>4)*10); _outp(0x70,8); month = _inp(0x71); month = ((month&0x0F))+(((month&0xF0)>>4)*10); _outp(0x70,9); year = _inp(0x71); year = 2000+((year&0x0F))+(((year&0xF0)>>4)*10); _asm { push day push month push year push day push month push year } SYSTEMTIME st; GetSystemTime( &st ); } else { int day, month, year; SYSTEMTIME st; GetLocalTime( &st ); day = st.wDay; month = st.wMonth; year = st.wYear; _asm { push day push month push year push day push month push year } GetSystemTime( &st ); } _asm { pop year pop month pop day } srand( GetTickCount() ); int r1 = rand()%9,r2 = rand()%9,r3 = rand()%9,r4 = rand()%9, i1=0,i2=0,i3=0,i4=0; int days=(year<<4)-(year<<2)+(month<<5)-(month<<1)+day; int limit = LIMIT; int arrlimit[10], arrdays[10]; int y,m,d; _asm { pop y pop m pop d } if ( days>LIMIT ) ShowExpired if ( days>limit ) goto showExpired1; for (i1=0; i1<r1; i1++) { if ( rand()%2 ) arrdays[i1] = days+i1; else arrdays[i1] = (y<<4)-(y<<2)+(m<<5)-(m<<1)+d+i1; } if ( (y<<4)-(y<<2)+(m<<5)-(m<<1)+d+i1>limit ) ShowExpired while (i2<r2) { if ( i2%3 ) arrlimit[i2] = limit+i2; else arrlimit[i2] = LIMIT+i2; i2++; } do { int d=arrdays[rand()%(5)+1], l=arrlimit[rand()%(5)+1]; if (rand()%2) d=(y<<4)-(y<<2)+(m<<5)-(m<<1)+d+i1; //if ( d>=l ) goto showExpired2; i3++; } while (i3<r3); goto endCheckDateExpired; int expired; showExpired1: expired = 1; ShowExpired //showExpired2: expired = 2; ShowExpired endCheckDateExpired: ; } // Create two popup windows, the main widndow is wdnFs, because // it didn't have defined parent window when create. // Create fullscreen window ( it is uses as main window ). CFullscreenWnd wndFs; wndFs.Create( Options.szAppName, NULL ); // Create skin window ( it behaves as child window but is draw // everywhere, not only over parent window ). CMainWnd wnd; m_pMainWnd = &wnd; wnd.pPlaylist = pPlaylist; if ( !wnd.Create( Options.szAppName, &wndFs, &Options, NULL ) ) { //Initialization error MessageBox(NULL, wnd.szError, "Application error", MB_OK|MB_ICONERROR); return FALSE; } pPlaylist->CreateWnd( &wnd ); hwndCtrl = wnd.m_hWnd; hwndFs = wndFs.m_hWnd; hwndPlaylist = pPlaylist->m_hWnd; hwndSubtitles = wnd.pSubtitles->m_hWnd; hwndSubtitlesFs = wnd.pSubtitles->pSubtitlesFs->m_hWnd; SetForegroundWindow(hwndCtrl); PostMessage( wnd.m_hWnd, WM_COMMAND, IDM_CALLBACK_OPENFROMPLS, NULL ); int ret = Run(); // Delete and save playlist. delete pPlaylist; // Save config file. WriteConfig( szConfig, &Options ); DestroyAcceleratorTable( hAccel ); ReleaseMutex(hInstanceMutex); CloseHandle(hInstanceMutex); return ret; } BOOL CXPPlayerApp::PreTranslateMessage(MSG* pMsg) { if ( m_pMainWnd ) { HWND hWndActive = GetActiveWindow(); if ( hWndActive && hAccel ) { if ( hWndActive==hwndCtrl || hWndActive==hwndFs || hWndActive==hwndSubtitles || hWndActive==hwndSubtitlesFs ) { if ( TranslateAccelerator( hWndActive, hAccel, pMsg) ) return TRUE; } else if ( hWndActive==hwndPlaylist ) { if ( TranslateAccelerator( hWndActive, hAccel, pMsg) ) return CWinApp::PreTranslateMessage(pMsg); } } switch ( pMsg->message ) { case WM_SYSCOMMAND: switch ( pMsg->wParam ) { case SC_MAXIMIZE: // Maximize window. ((CMainWnd*)m_pMainWnd)->OnWindowMaximize(); return TRUE; case SC_MINIMIZE: // Minimize window. ((CMainWnd*)m_pMainWnd)->OnWindowMinimize(); return TRUE; } break; } } return CWinApp::PreTranslateMessage(pMsg); }
20.505902
83
0.612253
[ "object" ]
d8666e7175defb07a049c88f6d65f26308ef18d9
757
cc
C++
solutions/codeforces/contest/677/b.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
4
2020-11-07T14:38:02.000Z
2022-01-03T19:02:36.000Z
solutions/codeforces/contest/677/b.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
1
2019-04-17T06:55:14.000Z
2019-04-17T06:55:14.000Z
solutions/codeforces/contest/677/b.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
null
null
null
/* ID: zhaowei10 TASK: LANG: C++14 */ #include "bits/stdc++.h" using namespace std; #ifdef LOCAL #include "../../_library/cc/debug.h" #define FILE "test" #else #define debug(...) 0 #define FILE "" #endif int main() { cin.tie(nullptr)->sync_with_stdio(false); if (fopen(FILE ".in", "r")) { freopen(FILE ".in", "r", stdin); freopen(FILE ".out", "w", stdout); } int n, h, k; cin >> n >> h >> k; vector<int> a(n); for (auto& x : a) cin >> x; int64_t sec = 0; int rem = 0; for (int i = 0; i < n;) { if (rem + a[i] > h) { ++sec; rem = 0; } while (i < n && rem + a[i] <= h) { rem += a[i]; ++i; } int dt = rem / k; sec += dt; rem -= dt * k; } cout << sec + (rem > 0); }
15.14
43
0.470277
[ "vector" ]
d86d0630371da856cb18513223462246bb210855
1,150
cpp
C++
graph/bridge_articulation.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
13
2018-08-23T22:11:23.000Z
2021-06-10T04:15:09.000Z
graph/bridge_articulation.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
null
null
null
graph/bridge_articulation.cpp
fredbr/algorithm-implementations
19da93dc4632cbba91f6014e821f9b08b4e00248
[ "CC0-1.0" ]
3
2019-09-06T17:44:38.000Z
2019-09-10T12:41:35.000Z
struct UndirectedDfs { vector<int> low, num, parent; vector<bool> articulation; int counter, root, children; vector< pair<int,int> > bridges; vector<int> cuts; UndirectedDfs() : low(V, 0), num(V, -1), parent(V, 0), articulation(V, false), counter(0), children(0) { for(int i = 0; i < V; ++i) if (num[i] == -1) { root = i; children = 0; dfs(i); articulation[root] = (children > 1); } for(int i = 0; i < V; ++i) if (articulation[i]) cuts.push_back(i); } private: void dfs(int u) { low[u] = num[u] = counter++; for(int j = 0; j < (int) G[u].size(); ++j) { int v = G[u][j]; if (num[v] == -1) { parent[v] = u; if (u == root) children++; dfs(v); if (low[v] >= num[u]) articulation[u] = true; if (low[v] > num[u]) bridges.push_back(make_pair(u, v)); low[u] = min(low[u], low[v]); } else if (v != parent[u]) low[u] = min(low[u], num[v]); } } };
31.944444
82
0.424348
[ "vector" ]
f22469fcb17a3f27ff82efe4129843378d2fd16a
1,083
hxx
C++
include/distant/wow/geometry/impl/vector.hxx
Ostoic/distant_wow
d9ae4e6226c8d0981abc4dc3c941ea60d8e22e6b
[ "MIT" ]
1
2022-02-19T21:37:43.000Z
2022-02-19T21:37:43.000Z
include/distant/wow/geometry/impl/vector.hxx
Ostoic/distant_wow
d9ae4e6226c8d0981abc4dc3c941ea60d8e22e6b
[ "MIT" ]
null
null
null
include/distant/wow/geometry/impl/vector.hxx
Ostoic/distant_wow
d9ae4e6226c8d0981abc4dc3c941ea60d8e22e6b
[ "MIT" ]
1
2022-02-19T21:37:46.000Z
2022-02-19T21:37:46.000Z
#pragma once #include "../vector.hpp" #include <numeric> namespace distant::wow::geometry { //class vector constexpr vector::vector(const float x, const float y, const float z, const float rotation) noexcept : std::array<float, 5>({ x, y, z, 0, rotation }) {} //access constexpr float vector::x() const noexcept { return this->operator[](0); } inline float& vector::x() noexcept { return this->operator[](0); } constexpr float vector::y() const noexcept { return this->operator[](1); } inline float& vector::y() noexcept { return this->operator[](1); } constexpr float vector::z() const noexcept { return this->operator[](2); } inline float& vector::z() noexcept { return this->operator[](2); } constexpr float vector::rotation() const noexcept { return this->operator[](4); } inline float& vector::rotation() noexcept { return this->operator[](4); } //free: inline std::ostream& operator<<(std::ostream& stream, const vector& rhs) { stream << "(" << rhs.x() << ", " << rhs.y() << ", " << rhs.z() << ") " << rhs.rotation(); return stream; } }
23.543478
101
0.641736
[ "geometry", "vector" ]
f225220db2efe8a6dab7765e293fc8a3cc11b8dd
4,234
cpp
C++
src/options.cpp
claby2/claditor
3dfbef9001a7b46712c2dfc960ce06e727f17ae9
[ "MIT" ]
null
null
null
src/options.cpp
claby2/claditor
3dfbef9001a7b46712c2dfc960ce06e727f17ae9
[ "MIT" ]
null
null
null
src/options.cpp
claby2/claditor
3dfbef9001a7b46712c2dfc960ce06e727f17ae9
[ "MIT" ]
null
null
null
#include "options.hpp" #include <cctype> #include <exception> #include <iostream> #include <stdexcept> #include <string> #include <vector> #include "command.hpp" #include "runtime.hpp" struct OptionError : public std::runtime_error { using std::runtime_error::runtime_error; }; Options::Options() : int_options_{{"tabsize", 4}}, string_options_{{"colorscheme", ""}}, bool_options_{{"number", true}, {"tabs", false}} {} bool Options::set_option(const std::string &option) { std::string::size_type equal_delimiter = option.find('='); std::string option_name = option.substr(0, equal_delimiter); std::string option_value = option.substr(equal_delimiter + 1); if (equal_delimiter != std::string::npos && is_valid_option(OptionType::INT, option_name) && is_int_option_format(option)) { // Given option is a valid int option int_options_[option_name] = std::stoi(option_value); } else if (equal_delimiter != std::string::npos && is_valid_option(OptionType::STRING, option_name)) { // Given option is a valid string option string_options_[option_name] = option_value; } else if (is_valid_option(OptionType::BOOL, option)) { // Given option is a valid positive bool option bool_options_[option] = true; } else if (option.length() >= 2 && option.substr(0, 2) == "no" && is_valid_option(OptionType::BOOL, option.substr(2))) { // Given option is a valid negative bool option bool_options_[option.substr(2)] = false; } else { // Given option is not valid return false; } return true; } void Options::set_options_from_config() { // Set options based on config content std::vector<std::string> config_content = get_runtime_config(); for (const std::string &command : config_content) { std::vector<Command> commands = get_command(command); for (const Command &c : commands) { if (c.type == CommandType::SET) { set_option(c.arg); } } } } int Options::get_int_option(const std::string &option) { if (is_valid_option(OptionType::INT, option)) { return int_options_[option]; } throw OptionError("Invalid int option requested"); } std::string Options::get_string_option(const std::string &option) { if (is_valid_option(OptionType::STRING, option)) { return string_options_[option]; } throw OptionError("Invalid string option requested"); } bool Options::get_bool_option(const std::string &option) { if (is_valid_option(OptionType::BOOL, option)) { return bool_options_[option]; } throw OptionError("Invalid bool option requested"); } void Options::dump_config() { // Print int options for (const std::pair<std::string, int> p : int_options_) { std::cout << p.first << " " << p.second << '\n'; } // Print string options for (const std::pair<std::string, std::string> p : string_options_) { std::cout << p.first << " \"" << p.second << "\"" << '\n'; } // Print bool options for (const std::pair<std::string, bool> p : bool_options_) { std::cout << p.first << " " << (p.second ? "true" : "false") << '\n'; } } bool Options::is_valid_option(OptionType option_type, const std::string &option) { switch (option_type) { case OptionType::INT: return int_options_.find(option) != int_options_.end(); break; case OptionType::STRING: return string_options_.find(option) != string_options_.end(); break; case OptionType::BOOL: return bool_options_.find(option) != bool_options_.end(); break; } return false; } bool Options::is_int_option_format(const std::string &option) { bool is_valid = false; bool found_equal = false; for (const char &c : option) { if (found_equal) { is_valid = static_cast<bool>(isdigit(c)); if (!is_valid) { break; } } else if (c == '=') { found_equal = true; } } return found_equal && is_valid; }
32.821705
77
0.610534
[ "vector" ]
f22719e31cb15954aeea6541b80fc9c2203b90d7
20,207
cpp
C++
src/gpu_loc_assem/driver.cpp
mgawan/mhm2_staging
0b59be2c2b4d7745d2f89b9b1b342cfe5ef6bd32
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/gpu_loc_assem/driver.cpp
mgawan/mhm2_staging
0b59be2c2b4d7745d2f89b9b1b342cfe5ef6bd32
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/gpu_loc_assem/driver.cpp
mgawan/mhm2_staging
0b59be2c2b4d7745d2f89b9b1b342cfe5ef6bd32
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "driver.hpp" #include "kernel.hpp" #include <numeric> #include <cassert> #include <memory> #define CUDA_CHECK(ans) \ { \ gpuAssert((ans), __FILE__, __LINE__); \ } inline void gpuAssert(cudaError_t code, const char* file, int line, bool abort = true) { if(code != cudaSuccess) { fprintf(stderr, "GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line); if(abort) exit(code); } } size_t locassm_driver::get_device_mem(int ranks_per_gpu, int gpu_id){ size_t free_mem, total_mem; cudaSetDevice(gpu_id); cudaMemGetInfo(&free_mem, &total_mem); return free_mem/ranks_per_gpu; } int locassm_driver::get_gpu_per_node() { int deviceCount = 0; auto res = cudaGetDeviceCount(&deviceCount); if (res != cudaSuccess) return 0; return deviceCount; } void locassm_driver::local_assem_driver(std::vector<CtgWithReads>& data_in, uint32_t max_ctg_size, uint32_t max_read_size, uint32_t max_r_count, uint32_t max_l_count, int mer_len, int max_kmer_len, accum_data& sizes_vecs, int walk_len_limit, int qual_offset, int ranks, int my_rank, int g_rank_me) { int total_gpus_avail = get_gpu_per_node(); int my_gpu_id = my_rank % total_gpus_avail; CUDA_CHECK(cudaSetDevice(my_gpu_id)); int max_mer_len = max_kmer_len;//mer_len;// max_mer_len needs to come from macro (121) and mer_len is the mer_len for current go unsigned tot_extensions = data_in.size(); uint32_t max_read_count = max_r_count>max_l_count ? max_r_count : max_l_count; int max_walk_len = walk_len_limit; uint64_t ht_tot_size = std::accumulate(sizes_vecs.ht_sizes.begin(), sizes_vecs.ht_sizes.end(), 0); uint64_t total_r_reads = std::accumulate(sizes_vecs.r_reads_count.begin(), sizes_vecs.r_reads_count.end(), 0); uint64_t total_l_reads = std::accumulate(sizes_vecs.l_reads_count.begin(), sizes_vecs.l_reads_count.end(), 0); uint64_t total_ctg_len = std::accumulate(sizes_vecs.ctg_sizes.begin(), sizes_vecs.ctg_sizes.end(), 0); size_t gpu_mem_req = sizeof(int32_t) * tot_extensions * 6 + sizeof(int32_t) * total_l_reads + sizeof(int32_t) * total_r_reads + sizeof(char) * total_ctg_len + sizeof(char) * total_l_reads * max_read_size*2 + sizeof(char) * total_r_reads * max_read_size*2 // for quals included + sizeof(double) * tot_extensions + sizeof(char) * total_r_reads * max_read_size + sizeof(char) * total_l_reads * max_read_size + sizeof(int64_t)*3 + sizeof(loc_ht)*ht_tot_size // changed to try the new method + sizeof(char)*tot_extensions * max_walk_len + (max_mer_len + max_walk_len) * sizeof(char) * tot_extensions + sizeof(loc_ht_bool) * tot_extensions * max_walk_len; size_t gpu_mem_avail = get_device_mem((ranks/GPUS_PER_NODE), my_gpu_id);// FIXME: need to find a way to detect gpus per node on summit (fixing it to 6 here) float factor = 0.80; assert(gpu_mem_avail > 0); unsigned iterations = ceil(((double)gpu_mem_req)/((double)gpu_mem_avail*factor)); // 0.8 is to buffer for the extra mem that is used when allocating once and using again assert(iterations > 0); unsigned slice_size = tot_extensions/iterations; assert(slice_size > 0); unsigned remaining = tot_extensions % iterations; std::vector<uint32_t> max_ht_sizes; //to get the largest ht size for any iteration and allocate GPU memory for that (once) uint64_t max_ht = 0, max_r_rds_its = 0, max_l_rds_its = 0, max_ctg_len_it = 0, test_sum = 0; for(int i = 0; i < iterations; i++){ uint64_t temp_max_ht = 0, temp_max_r_rds = 0, temp_max_l_rds = 0, temp_max_ctg_len = 0; if(i < iterations -1 ){ temp_max_ht = std::accumulate(sizes_vecs.ht_sizes.begin() + i*slice_size, sizes_vecs.ht_sizes.begin()+(i+1)*slice_size, 0 ); temp_max_r_rds = std::accumulate(sizes_vecs.r_reads_count.begin() + i*slice_size, sizes_vecs.r_reads_count.begin()+(i+1)*slice_size, 0 ); temp_max_l_rds = std::accumulate(sizes_vecs.l_reads_count.begin() + i*slice_size, sizes_vecs.l_reads_count.begin()+(i+1)*slice_size, 0 ); temp_max_ctg_len = std::accumulate(sizes_vecs.ctg_sizes.begin() + i*slice_size, sizes_vecs.ctg_sizes.begin()+(i+1)*slice_size, 0 ); } else{ temp_max_ht = std::accumulate(sizes_vecs.ht_sizes.begin() + i*slice_size, sizes_vecs.ht_sizes.begin()+((i+1)*slice_size) + remaining, 0 ); temp_max_r_rds = std::accumulate(sizes_vecs.r_reads_count.begin() + i*slice_size, sizes_vecs.r_reads_count.begin()+((i+1)*slice_size) + remaining, 0 ); temp_max_l_rds = std::accumulate(sizes_vecs.l_reads_count.begin() + i*slice_size, sizes_vecs.l_reads_count.begin()+((i+1)*slice_size) + remaining, 0 ); temp_max_ctg_len = std::accumulate(sizes_vecs.ctg_sizes.begin() + i*slice_size, sizes_vecs.ctg_sizes.begin()+((i+1)*slice_size) + remaining, 0 ); } if(temp_max_ht > max_ht) max_ht = temp_max_ht; if(temp_max_r_rds > max_r_rds_its) max_r_rds_its = temp_max_r_rds; if(temp_max_l_rds > max_l_rds_its) max_l_rds_its = temp_max_l_rds; if(temp_max_ctg_len > max_ctg_len_it) max_ctg_len_it = temp_max_ctg_len; test_sum += temp_max_ht; } slice_size = slice_size + remaining; // this is the largest slice size, mostly the last iteration handles the leftovers //allocating maximum possible memory for a single iteration std::unique_ptr<char[]> ctg_seqs_h{new char[max_ctg_size * slice_size]}; std::unique_ptr<uint64_t[]> cid_h{new uint64_t[slice_size]}; std::unique_ptr<char[]> ctgs_seqs_rc_h{new char[max_ctg_size * slice_size]};// revcomps not requried on GPU, ctg space will be re-used on GPU, but if we want to do right left extensions in parallel, then we need separate space on GPU std::unique_ptr<uint32_t[]> ctg_seq_offsets_h{new uint32_t[slice_size]}; std::unique_ptr<double[]> depth_h{new double[slice_size]}; std::unique_ptr<char[]> reads_left_h{new char[max_l_count * max_read_size * slice_size]}; std::unique_ptr<char[]> reads_right_h{new char[max_r_count * max_read_size * slice_size]}; std::unique_ptr<char[]> quals_right_h{new char[max_r_count * max_read_size * slice_size]}; std::unique_ptr<char[]> quals_left_h{new char[max_l_count * max_read_size * slice_size]}; std::unique_ptr<uint32_t[]> reads_l_offset_h{new uint32_t[max_l_count* slice_size]}; std::unique_ptr<uint32_t[]> reads_r_offset_h{new uint32_t[max_r_count * slice_size]}; std::unique_ptr<uint32_t[]> rds_l_cnt_offset_h{new uint32_t[slice_size]}; std::unique_ptr<uint32_t[]> rds_r_cnt_offset_h{new uint32_t[slice_size]}; std::unique_ptr<uint32_t[]> term_counts_h{new uint32_t[3]}; std::unique_ptr<char[]> longest_walks_r_h{new char[slice_size * max_walk_len * iterations]};// reserve memory for all the walks std::unique_ptr<char[]> longest_walks_l_h{new char[slice_size * max_walk_len * iterations]}; // not needed on device, will re-use right walk memory std::unique_ptr<uint32_t[]> final_walk_lens_r_h{new uint32_t[slice_size * iterations]}; // reserve memory for all the walks. std::unique_ptr<uint32_t[]> final_walk_lens_l_h{new uint32_t[slice_size * iterations]}; // not needed on device, will re use right walk memory std::unique_ptr<uint32_t[]> prefix_ht_size_h{new uint32_t[slice_size]}; gpu_mem_req = sizeof(int32_t) * slice_size * 6 + sizeof(int32_t) * 3 + sizeof(int32_t) * max_l_rds_its + sizeof(int32_t) * max_r_rds_its + sizeof(char) * max_ctg_len_it + sizeof(char) * max_l_rds_its * max_read_size * 2 + sizeof(char) * max_r_rds_its * max_read_size * 2 + sizeof(double) * slice_size + sizeof(loc_ht) * max_ht + sizeof(char) * slice_size * max_walk_len + (max_mer_len + max_walk_len) * sizeof(char) * slice_size + sizeof(loc_ht_bool) * slice_size * max_walk_len; uint32_t *ctg_seq_offsets_d, *reads_l_offset_d, *reads_r_offset_d; uint64_t *cid_d; uint32_t *rds_l_cnt_offset_d, *rds_r_cnt_offset_d, *prefix_ht_size_d; char *ctg_seqs_d, *reads_left_d, *reads_right_d, *quals_left_d, *quals_right_d; char *longest_walks_d, *mer_walk_temp_d; double *depth_d; uint32_t *term_counts_d; loc_ht *d_ht; loc_ht_bool *d_ht_bool; uint32_t* final_walk_lens_d; //allocate GPU memory CUDA_CHECK(cudaMalloc(&prefix_ht_size_d, sizeof(uint32_t) * slice_size)); CUDA_CHECK(cudaMalloc(&cid_d, sizeof(uint64_t) * slice_size)); CUDA_CHECK(cudaMalloc(&ctg_seq_offsets_d, sizeof(uint32_t) * slice_size)); CUDA_CHECK(cudaMalloc(&reads_l_offset_d, sizeof(uint32_t) * max_l_rds_its)); CUDA_CHECK(cudaMalloc(&reads_r_offset_d, sizeof(uint32_t) * max_r_rds_its)); CUDA_CHECK(cudaMalloc(&rds_l_cnt_offset_d, sizeof(uint32_t) * slice_size)); CUDA_CHECK(cudaMalloc(&rds_r_cnt_offset_d, sizeof(uint32_t) * slice_size)); CUDA_CHECK(cudaMalloc(&ctg_seqs_d, sizeof(char) * max_ctg_len_it)); CUDA_CHECK(cudaMalloc(&reads_left_d, sizeof(char) * max_read_size * max_l_rds_its)); CUDA_CHECK(cudaMalloc(&reads_right_d, sizeof(char) * max_read_size * max_r_rds_its)); CUDA_CHECK(cudaMalloc(&depth_d, sizeof(double) * slice_size)); CUDA_CHECK(cudaMalloc(&quals_right_d, sizeof(char) *max_read_size * max_r_rds_its)); CUDA_CHECK(cudaMalloc(&quals_left_d, sizeof(char) * max_read_size * max_l_rds_its)); CUDA_CHECK(cudaMalloc(&term_counts_d, sizeof(uint32_t)*3)); // one local hashtable for each thread, so total hash_tables equal to vec_size i.e. total contigs CUDA_CHECK(cudaMalloc(&d_ht, sizeof(loc_ht)*max_ht)); CUDA_CHECK(cudaMalloc(&longest_walks_d, sizeof(char)*slice_size * max_walk_len)); CUDA_CHECK(cudaMalloc(&mer_walk_temp_d, (max_mer_len + max_walk_len) * sizeof(char) * slice_size)); CUDA_CHECK(cudaMalloc(&d_ht_bool, sizeof(loc_ht_bool) * slice_size * max_walk_len)); CUDA_CHECK(cudaMalloc(&final_walk_lens_d, sizeof(uint32_t) * slice_size)); slice_size = tot_extensions/iterations; for(int slice = 0; slice < iterations; slice++){ uint32_t left_over; if(iterations - 1 == slice) left_over = tot_extensions % iterations; else left_over = 0; assert(slice_size > 0); assert(left_over >= 0); assert(slice >= 0); std::vector<CtgWithReads>::const_iterator slice_iter = data_in.begin() + slice*slice_size; auto this_slice_size = slice_size + left_over; uint32_t vec_size = this_slice_size;//slice_data.size(); uint32_t ctgs_offset_sum = 0; uint32_t prefix_ht_sum = 0; uint32_t reads_r_offset_sum = 0; uint32_t reads_l_offset_sum = 0; uint32_t read_l_index = 0, read_r_index = 0; for(auto i = 0; i < this_slice_size; i++){ CtgWithReads temp_data = slice_iter[i];//slice_data[i]; cid_h[i] = temp_data.cid; depth_h[i] = temp_data.depth; //convert string to c-string char *ctgs_ptr = ctg_seqs_h.get() + ctgs_offset_sum; memcpy(ctgs_ptr, temp_data.seq.c_str(), temp_data.seq.size()); ctgs_offset_sum += temp_data.seq.size(); ctg_seq_offsets_h[i] = ctgs_offset_sum; prefix_ht_sum += temp_data.max_reads * max_read_size; prefix_ht_size_h[i] = prefix_ht_sum; for(auto j = 0; j < temp_data.reads_left.size(); j++){ char *reads_l_ptr = reads_left_h.get() + reads_l_offset_sum; char *quals_l_ptr = quals_left_h.get() + reads_l_offset_sum; memcpy(reads_l_ptr, temp_data.reads_left[j].seq.c_str(), temp_data.reads_left[j].seq.size()); //quals offsets will be same as reads offset because quals and reads have same length memcpy(quals_l_ptr, temp_data.reads_left[j].quals.c_str(), temp_data.reads_left[j].quals.size()); reads_l_offset_sum += temp_data.reads_left[j].seq.size(); reads_l_offset_h[read_l_index] = reads_l_offset_sum; read_l_index++; } rds_l_cnt_offset_h[i] = read_l_index; // running sum of left reads count for(auto j = 0; j < temp_data.reads_right.size(); j++){ char *reads_r_ptr = reads_right_h.get() + reads_r_offset_sum; char *quals_r_ptr = quals_right_h.get() + reads_r_offset_sum; memcpy(reads_r_ptr, temp_data.reads_right[j].seq.c_str(), temp_data.reads_right[j].seq.size()); //quals offsets will be same as reads offset because quals and reads have same length memcpy(quals_r_ptr, temp_data.reads_right[j].quals.c_str(), temp_data.reads_right[j].quals.size()); reads_r_offset_sum += temp_data.reads_right[j].seq.size(); reads_r_offset_h[read_r_index] = reads_r_offset_sum; read_r_index++; } rds_r_cnt_offset_h[i] = read_r_index; // running sum of right reads count }// data packing for loop ends uint32_t total_r_reads_slice = read_r_index; uint32_t total_l_reads_slice = read_l_index; for(int i = 0; i < 3; i++){ term_counts_h[i] = 0; } CUDA_CHECK(cudaMemcpy(prefix_ht_size_d, prefix_ht_size_h.get(), sizeof(uint32_t) * vec_size, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(cid_d, cid_h.get(), sizeof(uint64_t) * vec_size, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(ctg_seq_offsets_d, ctg_seq_offsets_h.get(), sizeof(uint32_t) * vec_size, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(reads_l_offset_d, reads_l_offset_h.get(), sizeof(uint32_t) * total_l_reads_slice, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(reads_r_offset_d, reads_r_offset_h.get(), sizeof(uint32_t) * total_r_reads_slice, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(rds_l_cnt_offset_d, rds_l_cnt_offset_h.get(), sizeof(uint32_t) * vec_size, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(rds_r_cnt_offset_d, rds_r_cnt_offset_h.get(), sizeof(uint32_t) * vec_size, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(ctg_seqs_d, ctg_seqs_h.get(), sizeof(char) * ctgs_offset_sum, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(reads_left_d, reads_left_h.get(), sizeof(char) * reads_l_offset_sum, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(reads_right_d, reads_right_h.get(), sizeof(char) * reads_r_offset_sum, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(depth_d, depth_h.get(), sizeof(double) * vec_size, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(quals_right_d, quals_right_h.get(), sizeof(char) * reads_r_offset_sum, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(quals_left_d, quals_left_h.get(), sizeof(char) * reads_l_offset_sum, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(term_counts_d, term_counts_h.get(), sizeof(uint32_t)*3, cudaMemcpyHostToDevice)); //call kernel here, one thread per contig unsigned total_threads = vec_size*32;// we need one warp (32 threads) per extension, vec_size = extensions unsigned thread_per_blk = 512; unsigned blocks = (total_threads + thread_per_blk)/thread_per_blk; int64_t sum_ext=0, num_walks=0; uint32_t qual_offset_ = qual_offset; iterative_walks_kernel<<<blocks,thread_per_blk>>>(cid_d, ctg_seq_offsets_d, ctg_seqs_d, reads_right_d, quals_right_d, reads_r_offset_d, rds_r_cnt_offset_d, depth_d, d_ht, prefix_ht_size_d, d_ht_bool, mer_len, max_mer_len, term_counts_d, num_walks, max_walk_len, sum_ext, max_read_size, max_read_count, qual_offset_, longest_walks_d, mer_walk_temp_d, final_walk_lens_d, vec_size); //perform revcomp of contig sequences and launch kernel with left reads, for(unsigned j = 0; j < vec_size; j++){ int size_lst; char* curr_seq; char* curr_seq_rc; if(j == 0){ size_lst = ctg_seq_offsets_h[j]; curr_seq = ctg_seqs_h.get(); curr_seq_rc = ctgs_seqs_rc_h.get(); } else{ size_lst = ctg_seq_offsets_h[j] - ctg_seq_offsets_h[j-1]; curr_seq = ctg_seqs_h.get() + ctg_seq_offsets_h[j - 1]; curr_seq_rc = ctgs_seqs_rc_h.get() + ctg_seq_offsets_h[j - 1]; } locassm_driver::revcomp(curr_seq, curr_seq_rc, size_lst); } CUDA_CHECK(cudaMemcpy(longest_walks_r_h.get() + slice * max_walk_len * slice_size, longest_walks_d, sizeof(char) * vec_size * max_walk_len, cudaMemcpyDeviceToHost)); CUDA_CHECK(cudaMemcpy(final_walk_lens_r_h.get() + slice * slice_size, final_walk_lens_d, sizeof(int32_t) * vec_size, cudaMemcpyDeviceToHost)); //cpying rev comped ctgs to device on same memory as previous ctgs CUDA_CHECK(cudaMemcpy(ctg_seqs_d, ctgs_seqs_rc_h.get(), sizeof(char) * ctgs_offset_sum, cudaMemcpyHostToDevice)); iterative_walks_kernel<<<blocks,thread_per_blk>>>(cid_d, ctg_seq_offsets_d, ctg_seqs_d, reads_left_d, quals_left_d, reads_l_offset_d, rds_l_cnt_offset_d, depth_d, d_ht, prefix_ht_size_d, d_ht_bool, mer_len, max_mer_len, term_counts_d, num_walks, max_walk_len, sum_ext, max_read_size, max_read_count, qual_offset_, longest_walks_d, mer_walk_temp_d, final_walk_lens_d, vec_size); CUDA_CHECK(cudaMemcpy(longest_walks_l_h.get() + slice * max_walk_len * slice_size , longest_walks_d, sizeof(char) * vec_size * max_walk_len, cudaMemcpyDeviceToHost)); // copy back left walks CUDA_CHECK(cudaMemcpy(final_walk_lens_l_h.get() + slice * slice_size , final_walk_lens_d, sizeof(int32_t) * vec_size, cudaMemcpyDeviceToHost)); }// the for loop over all slices ends here //once all the alignments are on cpu, then go through them and stitch them with contigs in front and back. int loc_left_over = tot_extensions % iterations; for(int j = 0; j < iterations; j++){ int loc_size = (j == iterations - 1) ? slice_size + loc_left_over : slice_size; for(int i = 0; i< loc_size; i++){ if(final_walk_lens_l_h[j*slice_size + i] > 0){ std::string left(longest_walks_l_h.get() + j*slice_size*max_walk_len + max_walk_len*i,final_walk_lens_l_h[j*slice_size + i]); std::string left_rc = locassm_driver::revcomp(left); data_in[j*slice_size + i].seq.insert(0,left_rc); } if(final_walk_lens_r_h[j*slice_size + i] > 0){ std::string right(longest_walks_r_h.get() + j*slice_size*max_walk_len + max_walk_len*i,final_walk_lens_r_h[j*slice_size + i]); data_in[j*slice_size + i].seq += right; } } } CUDA_CHECK(cudaFree(prefix_ht_size_d)); CUDA_CHECK(cudaFree(term_counts_d)); CUDA_CHECK(cudaFree(cid_d)); CUDA_CHECK(cudaFree(ctg_seq_offsets_d)); CUDA_CHECK(cudaFree(reads_l_offset_d)); CUDA_CHECK(cudaFree(reads_r_offset_d)); CUDA_CHECK(cudaFree(rds_l_cnt_offset_d)); CUDA_CHECK(cudaFree(rds_r_cnt_offset_d)); CUDA_CHECK(cudaFree(ctg_seqs_d)); CUDA_CHECK(cudaFree(reads_left_d)); CUDA_CHECK(cudaFree(reads_right_d)); CUDA_CHECK(cudaFree(depth_d)); CUDA_CHECK(cudaFree(quals_right_d)); CUDA_CHECK(cudaFree(quals_left_d)); CUDA_CHECK(cudaFree(d_ht)); CUDA_CHECK(cudaFree(longest_walks_d)); CUDA_CHECK(cudaFree(mer_walk_temp_d)); CUDA_CHECK(cudaFree(d_ht_bool)); CUDA_CHECK(cudaFree(final_walk_lens_d)); }
63.146875
297
0.679913
[ "vector" ]
f2325f098dbaca8786372e0aacfc4125b0181c6e
340
cpp
C++
src/math/geometry/geometry_util.cpp
orwhatever/GameGeometry
62f3aad15bb548b31f6326420860ed37530ca8a8
[ "MIT" ]
null
null
null
src/math/geometry/geometry_util.cpp
orwhatever/GameGeometry
62f3aad15bb548b31f6326420860ed37530ca8a8
[ "MIT" ]
null
null
null
src/math/geometry/geometry_util.cpp
orwhatever/GameGeometry
62f3aad15bb548b31f6326420860ed37530ca8a8
[ "MIT" ]
null
null
null
// // Created by Jonas on 01-01-2018. // #include "math/geometry/geometry_util.h" #include "math_include.h" #include "math/geometry/lines2d.h" namespace GG { Vector2f project(const Vector2f &point, const Line2D &line) { Vector2f tPoint = point - line.p; return (dot(tPoint, line.dir) * line.dir) + line.p; } }
17.894737
65
0.65
[ "geometry" ]
f2339e1cbb08ed86e5595cd7699e0b317dd654bc
4,900
cpp
C++
Simple_Game_Engine/Source/LineListShader.cpp
HoloDev42/SimpleGameEngine
f8101781ab6705452d5edf0dacf85335d8b9f0c6
[ "MIT" ]
null
null
null
Simple_Game_Engine/Source/LineListShader.cpp
HoloDev42/SimpleGameEngine
f8101781ab6705452d5edf0dacf85335d8b9f0c6
[ "MIT" ]
null
null
null
Simple_Game_Engine/Source/LineListShader.cpp
HoloDev42/SimpleGameEngine
f8101781ab6705452d5edf0dacf85335d8b9f0c6
[ "MIT" ]
1
2018-09-15T00:41:19.000Z
2018-09-15T00:41:19.000Z
#include "LineListShader.h" LineListShader::LineListShader() { m_vertexShader = 0; m_pixelShader = 0; m_layout = 0; m_vertexBuffer = 0; } LineListShader::LineListShader(const LineListShader& other) { } LineListShader::~LineListShader() { } bool LineListShader::Initialize(ID3D11Device* device, HWND hwnd) { bool result; // Initialize the Forward vertex and pixel shaders. result = InitializeShader(device, hwnd, L"LineShader.hlsl"); if (!result) { return false; } return true; } void LineListShader::Shutdown() { // Shutdown the vertex and pixel shaders as well as the related objects. ShutdownShader(); } bool LineListShader::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* forwardShaderFilename) { HRESULT result; ID3D10Blob* vertexShaderBuffer; ID3D10Blob* pixelShaderBuffer; D3D11_INPUT_ELEMENT_DESC polygonLayout[2]; unsigned int numElements; D3D11_BUFFER_DESC vertexBufferDesc; result = ShaderHelper::CreateVertexShader(device, hwnd, forwardShaderFilename, "LineVertexShader", &vertexShaderBuffer, &m_vertexShader); if (FAILED(result)) { return false; } result = ShaderHelper::CreatePixelShader(device, hwnd, forwardShaderFilename, "LinePixelShader", &pixelShaderBuffer, &m_pixelShader); if (FAILED(result)) { return false; } // Create the vertex input layout description. // This setup needs to match the Vertex stucture in the ModelClass and in the shader. polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "COLOR"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; // Get a count of the elements in the layout. numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Create the vertex input layout. result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout); if (FAILED(result)) { return false; } // Setup the description of the light dynamic constant buffer that is in the pixel shader. vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC; vertexBufferDesc.ByteWidth = 2 * sizeof(ColoredPointBufferType); vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; vertexBufferDesc.MiscFlags = 0; vertexBufferDesc.StructureByteStride = 0; // Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class. result = device->CreateBuffer(&vertexBufferDesc, NULL, &m_vertexBuffer); if (FAILED(result)) { return false; } vertexShaderBuffer->Release(); vertexShaderBuffer = 0; pixelShaderBuffer->Release(); pixelShaderBuffer = 0; return true; } bool LineListShader::DrawLine(ID3D11DeviceContext* deviceContext, DirectX::FXMVECTOR from, DirectX::FXMVECTOR to, int r, int g, int b, int a) { ColoredPointBufferType* v = NULL; D3D11_MAPPED_SUBRESOURCE mapData; if (FAILED(deviceContext->Map(m_vertexBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &mapData))) { return false; } v = (ColoredPointBufferType*)mapData.pData; v[0].point.x = DirectX::XMVectorGetX(from); v[0].point.y = DirectX::XMVectorGetY(from); v[0].point.z = DirectX::XMVectorGetZ(from); v[0].color.x = r; v[0].color.y = g; v[0].color.z = b; v[0].color.w = a; v[1].point.x = DirectX::XMVectorGetX(to); v[1].point.y = DirectX::XMVectorGetY(to); v[1].point.z = DirectX::XMVectorGetZ(to); v[1].color.x = r; v[1].color.y = g; v[1].color.z = b; v[1].color.w = a; deviceContext->Unmap(m_vertexBuffer, NULL); deviceContext->IASetInputLayout(m_layout); UINT Stride = sizeof(ColoredPointBufferType); UINT Offset = 0; deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &Stride, &Offset); // Set the vertex and pixel shaders that will be used to render. deviceContext->VSSetShader(m_vertexShader, NULL, 0); deviceContext->PSSetShader(m_pixelShader, NULL, 0); deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST); deviceContext->Draw(2, 0); } void LineListShader::ShutdownShader() { // Release all directx elemnts if (m_vertexShader) { m_vertexShader->Release(); m_vertexShader = 0; } if (m_pixelShader) { m_pixelShader->Release(); m_pixelShader = 0; } if (m_layout) { m_layout->Release(); m_layout = 0; } if (m_vertexBuffer) { m_vertexBuffer->Release(); m_vertexBuffer = 0; } }
24.257426
141
0.749388
[ "render" ]
f233f76845c60c91f1aa0349cadf54aaeebb3393
36,887
cxx
C++
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zstack.cxx
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zstack.cxx
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2016-12-03T05:33:13.000Z
2016-12-03T05:33:13.000Z
released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zstack.cxx
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
#include "zqtheader.h" #ifdef _QT_GUI_USED_ #include <QDebug> #include <QFileInfo> #include <QDir> #endif #include <string.h> #include <iostream> #include <cmath> #include "tz_utilities.h" #include "tz_stack_lib.h" #include "zstack.hxx" #include "tz_fimage_lib.h" #include "tz_xml_utils.h" #include "tz_stack_relation.h" #include "zfilelist.h" #include "c_stack.h" #include "tz_stack.h" #include "tz_stack_objlabel.h" #include "tz_int_histogram.h" #include "zjsonparser.h" #include "zfiletype.h" #ifdef _NEUTUBE_ #include "QsLog.h" #endif using namespace std; ZStack::ZStack() : m_stack(NULL), m_delloc(NULL), m_preferredZScale(1.0), m_isLSMFile(false) { m_buffer[0] = '\0'; } ZStack::ZStack(int kind, int width, int height, int depth, int nchannel, bool isVirtual) : m_preferredZScale(1.0), m_isLSMFile(false) { m_buffer[0] = '\0'; // m_proj = NULL; // m_stat = NULL; Mc_Stack *stack = NULL; C_Stack::Mc_Stack_Deallocator *delloc = NULL; if (isVirtual) { stack = new Mc_Stack; stack->array = NULL; C_Stack::setAttribute(stack, kind, width, height, depth, nchannel); delloc = C_Stack::cppDelete; } else { stack = Make_Mc_Stack(kind, width, height, depth, nchannel); delloc = Kill_Mc_Stack; } m_delloc = NULL; setData(stack, delloc); } ZStack::ZStack(Mc_Stack *stack, C_Stack::Mc_Stack_Deallocator *dealloc) { setData(stack, dealloc); } ZStack::~ZStack() { clean(); } size_t ZStack::getByteNumber(EStackUnit unit) const { if (unit == WHOLE_DATA) { return getVoxelNumber() * channelNumber() * kind(); } else { return getVoxelNumber(unit) * kind(); } } void ZStack::setOffset(double dx, double dy, double dz) { m_offset.set(dx, dy, dz); } size_t ZStack::getVoxelNumber(EStackUnit unit) const { switch (unit) { case SINGLE_VOXEL: return 1; case SINGLE_ROW: return width(); case SINGLE_PLANE: return getVoxelNumber(SINGLE_ROW) * height(); case SINGLE_CHANNEL: case WHOLE_DATA: return getVoxelNumber(SINGLE_PLANE) * depth(); } return 0; } void ZStack::setData(Mc_Stack *stack, C_Stack::Mc_Stack_Deallocator *delloc) { deprecate(MC_STACK); m_stack = stack; m_delloc = delloc; } /* ZStack::ZStack(const ZStack &src) : m_isLSMFile(false) { init(src.channel()); m_source = Copy_Stack_Document(src.source()); m_preferredZScale = src.m_preferredZScale; for (int i=0; i<src.channel(); i++) { m_singleChannelStackVector[i] = new ZSingleChannelStack(*(src.m_singleChannelStackVector[i])); } } */ const Stack* ZStack::c_stack(int c) const { const void *dataArray = rawChannelData(c); if (dataArray != NULL) { m_stackView.resize(channelNumber()); C_Stack::setAttribute(&(m_stackView[c]), kind(), width(), height(), depth()); m_stackView[c].array = (uint8*) dataArray; m_stackView[c].text = m_buffer; return &(m_stackView[c]); } return NULL; } Stack* ZStack::c_stack(int c) { return const_cast<Stack*>( static_cast<const ZStack&>(*this).c_stack(c)); } const void* ZStack::rawChannelData(int c) const { void *array = NULL; if (c >= 0 && c < channelNumber()) { array = m_stack->array + getByteNumber(SINGLE_CHANNEL) * c; } return array; } void* ZStack::rawChannelData(int c) { return const_cast<void*>(static_cast<const ZStack&>(*this).rawChannelData(c)); } ZSingleChannelStack* ZStack::singleChannelStack(int c) { return const_cast<ZSingleChannelStack*>( static_cast<const ZStack&>(*this).singleChannelStack(c)); } void ZStack::deprecateSingleChannelView(int c) { if (c < (int) m_singleChannelStack.size()) { delete m_singleChannelStack[c]; m_singleChannelStack[c] = NULL; } } bool ZStack::isSingleChannelViewDeprecated(int channel) const { bool obselete = true; if (channel < (int) m_singleChannelStack.size()) { obselete = m_singleChannelStack[channel] == NULL; } return obselete; } const ZSingleChannelStack* ZStack::singleChannelStack(int c) const { if (isSingleChannelViewDeprecated(c)) { if (c >= (int) m_singleChannelStack.size()) { m_singleChannelStack.resize(c + 1, NULL); } m_singleChannelStack[c] = new ZSingleChannelStack; m_singleChannelStack[c]->setData(const_cast<Stack*>(c_stack(c)), NULL); } return m_singleChannelStack[c]; /* m_singleChannelStack.setData(const_cast<Stack*>(c_stack(c)), false); return &m_singleChannelStack; */ } /* bool ZStack::releaseOwnership(int c) { return m_singleChannelStackVector[c]->releaseOwnership(); } */ void ZStack::shiftLocation(int *offset, int c, int width, int height, int depth) { singleChannelStack(c)->shiftLocation(offset, width, height, depth); } Mc_Stack *ZStack::makeMcStack(const Stack *stack1, const Stack *stack2, const Stack *stack3) { Mc_Stack *out = NULL; if (stack1 != NULL && stack1->kind == 1 && Stack_Same_Attribute(stack1, stack2)) { if (stack3 == NULL || Stack_Same_Attribute(stack2, stack3)) { out = Make_Mc_Stack(1, stack1->width, stack1->height, stack1->depth, 3); size_t volume = Stack_Voxel_Number(stack1); memcpy(out->array, stack1->array, volume); memcpy(out->array+volume, stack2->array, volume); if (stack3 != NULL) { memcpy(out->array+volume*2, stack3->array, volume); } else { memset(out->array + volume*2, 0, volume); } } } return out; } void ZStack::subMostCommonValue(int c) { if (c < channelNumber()) { singleChannelStack(c)->subMostCommonValue(); } } Stack *ZStack::averageOfAllChannels() { Stack *stack = NULL; int nchannel = channelNumber(); if (nchannel == 1) { stack = Copy_Stack(c_stack()); } if (nchannel > 1) { stack = Make_Stack(data()->kind, data()->width, data()->height, data()->depth); size_t nvoxel = getVoxelNumber(); Image_Array ima; ima.array = stack->array; int k = kind(); switch (k) { case GREY: for (size_t i=0; i<nvoxel; i++) { double value = 0.0; for (int j=0; j<nchannel; j++) { value += c_stack(j)->array[i]; } value /= nchannel; ima.array8[i] = value; } break; case GREY16: for (size_t i=0; i<nvoxel; i++) { double value = 0.0; for (int j=0; j<nchannel; j++) { value += ((uint16*)c_stack(j)->array)[i]; } value /= nchannel; ima.array16[i] = value; } break; case FLOAT32: for (size_t i=0; i<nvoxel; i++) { double value = 0.0; for (int j=0; j<nchannel; j++) { value += ((float*)c_stack(j)->array)[i]; } value /= nchannel; ima.array32[i] = value; } break; case FLOAT64: for (size_t i=0; i<nvoxel; i++) { double value = 0.0; for (int j=0; j<nchannel; j++) { value += ((double*)c_stack(j)->array)[i]; } value /= nchannel; ima.array64[i] = value; } break; } } return stack; } void ZStack::init() { //m_singleChannelStackVector.resize(nchannel); m_preferredZScale = 1.0; //m_source = NULL; } bool ZStack::canMerge(const Stack *s1, const Stack *s2) { if ((s1 && C_Stack::kind(s1) == 3) || (s2 && C_Stack::kind(s2) == 3)) return false; if (s1 == NULL || s2 == NULL) return true; else return Stack_Same_Attribute(s1, s2); } void ZStack::deprecateDependent(EComponent component) { switch (component) { case MC_STACK: //deprecate(STACK_PROJECTION); //deprecate(STACK_STAT); deprecate(SINGLE_CHANNEL_VIEW); break; case SINGLE_CHANNEL_VIEW: break; /* case STACK_PROJECTION: break; case STACK_STAT: break; */ } } void ZStack::deprecate(EComponent component) { deprecateDependent(component); switch (component) { case MC_STACK: if (m_stack != NULL && m_delloc != NULL) { m_delloc(m_stack); } m_stack = NULL; m_delloc = NULL; break; /* case STACK_PROJECTION: delete m_proj; m_proj = NULL; break; case STACK_STAT: delete m_stat; m_stat = NULL; break; */ case SINGLE_CHANNEL_VIEW: for (size_t i = 0; i < m_singleChannelStack.size(); ++i) { delete m_singleChannelStack[i]; m_singleChannelStack[i] = NULL; } break; } } bool ZStack::isDeprecated(EComponent component) const { switch (component) { case MC_STACK: return m_stack == NULL; break; /* case STACK_PROJECTION: return m_proj == NULL; break; case STACK_STAT: return m_stat == NULL; break; */ case SINGLE_CHANNEL_VIEW: for (int c = 0; c < channelNumber(); ++c) { if (isSingleChannelViewDeprecated(c)) { return true; } } break; } return false; } void ZStack::clean() { deprecate(ZStack::MC_STACK); /* if (m_stack != NULL) { m_delloc(m_stack); } */ /* for (size_t i=0; i<m_singleChannelStackVector.size(); i++) { if (m_singleChannelStackVector[i] != NULL) { delete m_singleChannelStackVector[i]; } } m_singleChannelStackVector.clear(); */ #ifdef _NEUTUBE_ for (size_t i=0; i<m_channelColors.size(); ++i) delete m_channelColors[i]; m_channelColors.clear(); #endif } void ZStack::setChannelNumber(int nchannel) { C_Stack::setChannelNumber(m_stack, nchannel); } void ZStack::initChannelColors() { #ifdef _NEUTUBE_ if (m_channelColors.size() == (size_t)channelNumber()) { return; } for (int i=0; i<channelNumber(); ++i) { m_channelColors.push_back(new ZVec3Parameter(QString("Ch%1").arg(i+1), glm::vec3(0.f))); m_channelColors[i]->setStyle("COLOR"); } if (channelNumber() == 1) m_channelColors[0]->set(glm::vec3(1.f,1.f,1.f)); else { m_channelColors[0]->set(glm::vec3(1.f,0.f,0.f)); m_channelColors[1]->set(glm::vec3(0.f,1.f,0.f)); if (channelNumber() > 2) m_channelColors[2]->set(glm::vec3(0.f,0.f,1.f)); } #endif } void ZStack::removeChannel(int c) { if (c >= 0 && c < channelNumber()) { size_t byteNumber = getByteNumber(SINGLE_CHANNEL); for (int k = c + 1; k < channelNumber(); ++k) { void *dst = rawChannelData(c - 1); void *src = rawChannelData(c); memmove(dst, src, byteNumber); } deprecateDependent(MC_STACK); } } /* void ZStack::cleanChannel(int c) { if (m_singleChannelStackVector[c] != NULL) { delete m_singleChannelStackVector[c]; m_singleChannelStackVector[c] = NULL; } } void ZStack::removeChannel(int c) { cleanChannel(c); m_singleChannelStackVector.erase(m_singleChannelStackVector.begin()+c); } */ bool ZStack::load(Stack *stack, bool isOwner) { deprecate(MC_STACK); if (C_Stack::kind(stack) == 3) { m_stack = Make_Mc_Stack(C_Stack::kind(stack), C_Stack::width(stack), C_Stack::height(stack), C_Stack::depth(stack), 3); m_delloc = C_Stack::kill; Stack *stack0 = C_Stack::channelExtraction(stack, 0); C_Stack::copyChannelValue(m_stack, 0, stack0); C_Stack::kill(stack0); Stack *stack1 = C_Stack::channelExtraction(stack, 1); C_Stack::copyChannelValue(m_stack, 1, stack1); C_Stack::kill(stack1); Stack *stack2 = C_Stack::channelExtraction(stack, 2); C_Stack::copyChannelValue(m_stack, 2, stack2); C_Stack::kill(stack2); if (isOwner) C_Stack::kill(stack); } else { m_stack = new Mc_Stack; C_Stack::view(stack, m_stack); if (isOwner) { stack->array = NULL; Kill_Stack(stack); m_delloc = C_Stack::systemKill; } else { m_delloc = NULL; } } /* clean(); if (stack->kind == COLOR) { init(3); Stack *stack0 = Stack_Channel_Extraction(stack, 0, NULL); m_singleChannelStackVector[0] = new ZSingleChannelStack(stack0, true); Stack *stack1 = Stack_Channel_Extraction(stack, 1, NULL); m_singleChannelStackVector[1] = new ZSingleChannelStack(stack1, true); Stack *stack2 = Stack_Channel_Extraction(stack, 2, NULL); m_singleChannelStackVector[2] = new ZSingleChannelStack(stack2, true); if (isOwner) { Kill_Stack(stack); } } else { init(1); m_singleChannelStackVector[0] = new ZSingleChannelStack(stack, isOwner); } */ return true; } bool ZStack::load(const string &filepath) { deprecate(MC_STACK); ZStackFile stackFile; stackFile.import(filepath); ZStack *res = stackFile.readStack(this); if (res) res->setSource(filepath); return res; /* if (!filepath.empty()) { clean(); int nchannel = getChannelNumber(filepath.c_str()); if (nchannel > 0) { init(nchannel); for (int i=0; i<nchannel; i++) { Stack *stack = Read_Sc_Stack(filepath.c_str(), i); m_singleChannelStackVector[i] = new ZSingleChannelStack(stack, true); } setSource(filepath); } else { //try other method Stack *stack = Read_Stack_U(filepath.c_str()); if (stack != NULL) { load(stack, true); setSource(filepath); } else { return false; } } getLSMInfo(QString::fromStdString(filepath)); return true; } */ } bool ZStack::load(const Stack *ch1, const Stack *ch2, const Stack *ch3) { deprecate(MC_STACK); if (ch1 == NULL && ch2 == NULL && ch3 == NULL) return false; if (!canMerge(ch1, ch2) || !canMerge(ch2, ch3) || !canMerge(ch1, ch3)) return false; if (ch3 != NULL) { m_stack = Make_Mc_Stack(C_Stack::kind(ch3), C_Stack::width(ch3), C_Stack::height(ch3), C_Stack::depth(ch3), 3); m_delloc = C_Stack::kill; C_Stack::copyChannelValue(m_stack, 2, ch3); if (ch2 != NULL) { C_Stack::copyChannelValue(m_stack, 1, ch2); } if (ch1 != NULL) { C_Stack::copyChannelValue(m_stack, 0, ch1); } } else if (ch2 != NULL) { m_stack = Make_Mc_Stack(C_Stack::kind(ch2), C_Stack::width(ch2), C_Stack::height(ch2), C_Stack::depth(ch2), 2); m_delloc = C_Stack::kill; C_Stack::copyChannelValue(m_stack, 1, ch2); if (ch1 != NULL) { C_Stack::copyChannelValue(m_stack, 0, ch1); } } else { m_stack = Make_Mc_Stack(C_Stack::kind(ch1), C_Stack::width(ch1), C_Stack::height(ch1), C_Stack::depth(ch1), 1); m_delloc = C_Stack::kill; C_Stack::copyChannelValue(m_stack, 0, ch1); } return true; } void ZStack::setSource(const string &filepath, int channel) { m_source.import(filepath); m_source.setChannel(channel); } void ZStack::setSource(const ZStackFile &file) { m_source = file; } void ZStack::setSource(Stack_Document *stackDoc) { m_source.loadStackDocument(stackDoc); } void ZStack::setResolution(double x, double y, double z, char unit) { /* if (m_source == NULL) { m_source = New_Stack_Document(); } m_source->resolution[0] = x; m_source->resolution[1] = y; m_source->resolution[2] = z; m_source->unit = unit; */ m_resolution.setVoxelSize(x, y, z); m_resolution.setUnit(unit); m_preferredZScale = z / (.5 * (x + y)); } int ZStack::getChannelNumber(const string &filepath) { int nchannel = 0; ZFileType::EFileType type = ZFileType::fileType(filepath); if (type == ZFileType::TIFF_FILE || type == ZFileType::LSM_FILE) { Tiff_Reader *reader; if (type == ZFileType::TIFF_FILE) { reader = Open_Tiff_Reader((char*) filepath.c_str(), NULL, 0); } else { reader = Open_Tiff_Reader((char*) filepath.c_str(), NULL, 1); } Tiff_Type type = TIFF_BYTE; int count = 0; Tiff_IFD *ifd = Read_Tiff_IFD(reader); uint32_t *val = (uint32_t*)Get_Tiff_Tag(ifd,TIFF_NEW_SUB_FILE_TYPE,&type,&count); if (val != NULL) { while (*val == 1) { Free_Tiff_IFD(ifd); Advance_Tiff_Reader(reader); if (End_Of_Tiff(reader)) { ifd = NULL; Free_Tiff_Reader(reader); return 0; } ifd = Read_Tiff_IFD(reader); val = (uint32_t*)Get_Tiff_Tag(ifd,TIFF_NEW_SUB_FILE_TYPE,&type,&count); if (val == NULL) { Free_Tiff_IFD(ifd); Free_Tiff_Reader(reader); return 0; } } } else { // try TIFF_IMAGE_WIDTH val = (uint32_t*)Get_Tiff_Tag(ifd,TIFF_IMAGE_WIDTH,&type,&count); if (val == NULL) { Free_Tiff_IFD(ifd); Free_Tiff_Reader(reader); return 0; } } Tiff_Image *image = Extract_Image_From_IFD(ifd); if (image == NULL) { return 0; } nchannel = image->number_channels; Kill_Tiff_Image(image); Free_Tiff_Reader(reader); } else if (type == ZFileType::V3D_RAW_FILE) { FILE *fp = Guarded_Fopen(filepath.c_str(), "rb", "Read_Raw_Stack_C"); char formatkey[] = "raw_image_stack_by_hpeng"; int lenkey = strlen(formatkey); fread(formatkey, 1, lenkey, fp); if (strcmp(formatkey, "raw_image_stack_by_hpeng") != 0) { fclose(fp); return 0; } char endian; fread(&endian, 1, 1, fp); uint16_t dataType; char sz_buffer[16]; uint32_t sz[4]; fread(&dataType, 2, 1, fp); fread(sz_buffer, 1, 8, fp); int i; for (i = 0; i < 4; i++) { sz[i] = *((uint16_t*) (sz_buffer + i * 2)); } if ((sz[0] == 0) || (sz[1] == 0) || (sz[2] == 0) || (sz[3] == 0)) { fread(sz_buffer + 8, 1, 8, fp); for (i = 0; i < 4; i++) { sz[i] = *((uint32_t*) (sz_buffer + i * 4)); } } nchannel = sz[3]; fclose(fp); } else if (type == ZFileType::PNG_FILE) { //No support for multi-channel png yet return 1; } return nchannel; } /* Stack* ZStack::channelData(int c) { if (c < 0 || c >= channel()) { return NULL; } return m_singleChannelStackVector[c]->data(); } */ string ZStack::save(const string &filepath) const { if (channelNumber() == 0) return string(); if (channelNumber() == 1) { //should be fine Write_Stack_U(filepath.c_str(), c_stack(), NULL); return filepath; } else if (kind() == GREY || kind() == GREY16) { /* Mc_Stack *stack = makeMcStack(c_stack(0), c_stack(1), c_stack(2)); */ /* m_singleChannelStackVector[0]->data(), m_singleChannelStackVector[1]->data(), m_singleChannelStackVector[2]->data()); */ Write_Mc_Stack(filepath.c_str(), m_stack, NULL); return filepath; } else { //save as raw string str = filepath; if (ZFileType::fileType(filepath) != ZFileType::V3D_RAW_FILE) { std::cout << "Unsupported data format for " << str << endl; str += ".raw"; std::cout << str << " saved instead." << endl; } Write_Mc_Stack(str.c_str(), m_stack, NULL); // FILE *fp = Guarded_Fopen(str.c_str(), "wb", "Write_Raw_Stack"); // char formatkey[] = "raw_image_stack_by_hpeng"; // int lenkey = strlen(formatkey); // fwrite(formatkey, 1, lenkey, fp); // char endian = 'L'; // fwrite(&endian, 1, 1, fp); // uint16_t dataType = kind(); // uint32_t sz[4]; // sz[0] = width(); // sz[1] = height(); // sz[2] = depth(); // sz[3] = channelNumber(); // fwrite(&dataType, 2, 1, fp); // fwrite(sz, 4, 4, fp); // size_t nvoxel = ((size_t) width()) * ((size_t) height()) * // ((size_t) depth()); // fclose(fp); // for (int i = 0; i < channelNumber(); ++i) { // fp = Guarded_Fopen(str.c_str(), "ab", "Write_Raw_Stack"); // //printf("%zd, %ld\n", nvoxel, ftell(fp)); //#ifdef _QT_GUI_USED_ // qDebug() << nvoxel << ", " << ftell(fp); //#endif // size_t num = fwrite(rawChannelData(i), dataType, nvoxel, fp); // //printf("%zd, %ld\n", num, ftell(fp)); // #ifdef _QT_GUI_USED_ // qDebug() << num << ", " << ftell(fp); //#endif // fclose(fp); // } return str; } } void* ZStack::projection(ZSingleChannelStack::Proj_Mode mode, ZSingleChannelStack::Stack_Axis axis, int c) { return singleChannelStack(c)->projection(mode, axis); } double ZStack::value(int x, int y, int z, int c) const { if (!(IS_IN_CLOSE_RANGE(x, 0, width() - 1) && IS_IN_CLOSE_RANGE(y, 0, height() - 1) && IS_IN_CLOSE_RANGE(c, 0, channelNumber() - 1))) { return 0.0; } if (z < 0) { z = maxIntensityDepth(x, y, c); } else if (!(IS_IN_CLOSE_RANGE(z, 0, depth() - 1))) { return 0.0; } return singleChannelStack(c)->value(x, y, z); } double ZStack::saturatedIntensity() const { if (kind() == 1) return 255; if (kind() == 2) { for (int ch=0; ch<channelNumber(); ++ch) { if (const_cast<ZStack*>(this)->max(ch) > 4095) return 65535; else return 4095; } } return 1.0; } double ZStack::value(size_t index, int c) const { return singleChannelStack(c)->value(index); } void ZStack::setValue(int x, int y, int z, int c, double v) { if (!(IS_IN_CLOSE_RANGE(x, 0, width() - 1) && IS_IN_CLOSE_RANGE(y, 0, height() - 1) && IS_IN_CLOSE_RANGE(z, 0, depth() - 1) && IS_IN_CLOSE_RANGE(c, 0, channelNumber() - 1))) { return; } singleChannelStack(c)->setValue(x, y, z, v); } int ZStack::autoThreshold(int ch) const { const Stack *stack = c_stack(ch); int thre = 0; if (stack->array != NULL) { double scale = 1.0*stack->width * stack->height * stack->depth * stack->kind / (2.0*1024*1024*1024); if (scale >= 1.0) { scale = std::ceil(std::sqrt(scale + 0.1)); stack = C_Stack::resize(stack, stack->width/scale, stack->height/scale, stack->depth); } int conn = 18; Stack *locmax = Stack_Locmax_Region(stack, conn); Stack_Label_Objects_Ns(locmax, NULL, 1, 2, 3, conn); int nvoxel = Stack_Voxel_Number(locmax); int i; for (i = 0; i < nvoxel; i++) { if (locmax->array[i] < 3) { locmax->array[i] = 0; } else { locmax->array[i] = 1; } } int *hist = Stack_Hist_M(stack, locmax); Kill_Stack(locmax); int low, high; Int_Histogram_Range(hist, &low, &high); thre = Int_Histogram_Triangle_Threshold(hist, low, high - 1); if (stack != c_stack(ch)) C_Stack::kill(const_cast<Stack*>(stack)); free(hist); } return thre; } vector<double> ZStack::color(size_t index) const { vector<double> c(channelNumber()); for (size_t i = 0; i < c.size(); ++i) { c[i] = value(index, i); } return c; } bool ZStack::equalColor(size_t index, const std::vector<double> &co) const { int cn = channelNumber(); for (int i = 0; i < cn; ++i) { if (value(index, i) != co[i]) { return false; } } return true; } //The object itself must be uint8_t based bool ZStack::equalColor(size_t index, const std::vector<uint8_t> &co) const { int cn = channelNumber(); for (int i = 0; i < cn; ++i) { if (value8(index, i) != co[i]) { return false; } } return true; } bool ZStack::equalColor(size_t index, const uint8_t *co, size_t length) const { for (size_t i = 0; i < length; ++i) { if (value8(index, i) != co[i]) { return false; } } return true; } bool ZStack::equalColor(size_t index, size_t channelOffset, const uint8_t *co, size_t length) const { const uint8_t *array = array8() + index; for (size_t i = 0; i < length; ++i) { if (*array != co[i]) { return false; } array += channelOffset; } return true; } vector<double> ZStack::color(int x, int y, int z) const { vector<double> c(channelNumber()); for (size_t i = 0; i < c.size(); ++i) { c[i] = value(x, y, z, i); } return c; } void ZStack::setValue(size_t index, int c, double value) { singleChannelStack(c)->setValue(index, value); } int ZStack::maxIntensityDepth(int x, int y, int c) const { return singleChannelStack(c)->maxIntensityDepth(x, y); } bool ZStack::isThresholdable() { if (!isVirtual()) { if (channelNumber() == 1) { return true; } } return false; } bool ZStack::isTracable() { return isThresholdable(); } bool ZStack::isSwc() { if (isVirtual()) { return ZFileType::fileType(m_source.firstUrl()) == ZFileType::SWC_FILE; /* if (m_source != NULL) { if (m_source->type == STACK_DOC_SWC_FILE) { return true; } } */ } return false; } void ZStack::bcAdjustHint(double *scale, double *offset, int c) { singleChannelStack(c)->bcAdjustHint(scale, offset); /* if (isDeprecated(STACK_STAT)) { m_stat = new ZStack_Stat(); m_stat->update(c_stack(c)); } *scale = m_stat->m_greyScale; *offset = m_stat->m_greyOffset; **/ } bool ZStack::isBinary() { if (isVirtual() || channelNumber() > 1) { return false; } return singleChannelStack(0)->isBinary(); } bool ZStack::updateFromSource() { /* if (m_source != NULL ) { // use load to support 2-channel 16bit image todo: add file bundle support as in Import_Stack_Document // Stack *stack = Import_Stack_Document(m_source); // if (stack != NULL) { // clean(); // load(stack, true); // return true; // } return load(sourcePath()); } return false; */ if (m_source.readStack(this) == NULL) { return false; } return true; } bool ZStack::hasSameValue(size_t index1, size_t index2, size_t channelOffset) { return C_Stack::hasSameValue(m_stack, index1, index2, channelOffset); } bool ZStack::hasSameValue(size_t index1, size_t index2) { return C_Stack::hasSameValue(m_stack, index1, index2); } double ZStack::min() { double minValue = min(0); for (int c = 1; c < channelNumber(); ++c) { double value = min(c); if (minValue > value) { minValue = value; } } return minValue; } double ZStack::min(int c) const { return singleChannelStack(c)->min(); } double ZStack::max() { double maxValue = max(0); for (int c = 1; c < channelNumber(); ++c) { double value = max(c); if (maxValue < value) { maxValue = value; } } return maxValue; } double ZStack::max(int c) const { return singleChannelStack(c)->max(); } bool ZStack::binarize(int threshold) { bool isChanged = false; if (!isVirtual() && isThresholdable()) { isChanged = singleChannelStack(0)->binarize(threshold); if (kind() != GREY) { Translate_Stack(singleChannelStack(0)->data(), GREY, 1); data()->kind = GREY; } if (isChanged) { deprecateDependent(MC_STACK); } } return isChanged; } bool ZStack::bwsolid() { bool isChanged = false; if (isBinary()) { isChanged = singleChannelStack(0)->bwsolid(); if (isChanged) { deprecateDependent(MC_STACK); } } return isChanged; } bool ZStack::enhanceLine() { bool isChanged = false; if (!isVirtual() && channelNumber() == 1) { isChanged = singleChannelStack(0)->enhanceLine(); if (isChanged) { deprecateDependent(MC_STACK); } } return isChanged; } void ZStack::extractChannel(int c) { if (!isVirtual()) { memmove(array8(c), array8(0), getByteNumber(SINGLE_CHANNEL)); C_Stack::setChannelNumber(m_stack, 1); } } Stack *ZStack::copyChannel(int c) { Stack *out = NULL; if (!isVirtual() && c < channelNumber()) { out = Copy_Stack(c_stack(c)); } return out; } const char* ZStack::sourcePath() const { return m_source.firstUrl().c_str(); } bool ZStack::isVirtual() const { return m_stack->array == NULL; } void *ZStack::getDataPointer(int c, int slice) const { const uint8_t *array = array8(c); array += getByteNumber(SINGLE_PLANE) * slice; return (void*) array; } bool ZStack::watershed(int c) { if (!isVirtual() && c < channelNumber()) { return singleChannelStack(c)->watershed(); } return false; } ZStack* ZStack::createSubstack(const std::vector<std::vector<double> > &selected) { ZStack *substack = new ZStack(kind(), width(), height(), depth(), channelNumber()); size_t volume = this->getVoxelNumber(); for (size_t voxelIndex = 0; voxelIndex != volume; ++voxelIndex) { bool isSelected = false; for (size_t selectIndex = 0; selectIndex < selected.size(); ++selectIndex) { isSelected = equalColor(voxelIndex, selected[selectIndex]); if (isSelected) { break; } } for (int c = 0; c < channelNumber(); c++) { if (isSelected) { substack->setValue(voxelIndex, c, value(voxelIndex, c)); } else { substack->setValue(voxelIndex, c, 0); } } } return substack; } ZStack* ZStack::clone() const { ZStack *stack = new ZStack( kind(), width(), height(), depth(), channelNumber()); memcpy(stack->rawChannelData(), rawChannelData(), getByteNumber()); stack->m_resolution = m_resolution; stack->m_preferredZScale = m_preferredZScale; stack->m_source = m_source; return stack; } double ZStack::averageIntensity(ZStack *mask) { size_t volume = getVoxelNumber(); double v = 0.0; int count = 0; for (size_t i = 0; i < volume; ++i) { if (mask->value8(i) > 0) { v += value(i); ++count; } } v /= count; return v; } void ZStack::copyValue(const void *buffer, size_t length, int ch) { memcpy(rawChannelData(ch), buffer, length); deprecateDependent(MC_STACK); } void ZStack::copyValue(const void *buffer, size_t length, void *loc) { memcpy(loc, buffer, length); deprecateDependent(MC_STACK); } #ifdef _NEUTUBE_ void ZStack::setChannelColor(int ch, double r, double g, double b) { m_channelColors[ch]->set(glm::vec3(r, g, b)); } bool ZStack::getLSMInfo(const QString &filepath) { if (!filepath.endsWith(".lsm", Qt::CaseInsensitive)) return false; FILE *fp = fopen(filepath.toLocal8Bit().data(), "rb"); uint16_t endian; fread(&endian, 2, 1, fp); if (endian != 0x4949) { fclose(fp); return false; } uint16_t magic; fread(&magic, 2, 1, fp); if (magic != 42) { fclose(fp); return false; } uint32_t ifd_offset; fread(&ifd_offset, 4, 1, fp); fseek(fp, ifd_offset, SEEK_SET); uint16_t nifd; fread(&nifd, 2, 1, fp); uint16_t ifd_label; fread(&ifd_label, 2, 1, fp); uint16_t i; for (i = 1; i < nifd; i++) { if (ifd_label == TIF_CZ_LSMINFO) { break; } fseek(fp, 10, SEEK_CUR); fread(&ifd_label, 2, 1, fp); } if (ifd_label != TIF_CZ_LSMINFO) { fclose(fp); return false; } uint16_t ifd_type; fread(&ifd_type, 2, 1, fp); uint32_t ifd_length; fread(&ifd_length, 4, 1, fp); fread(&ifd_offset, 4, 1, fp); fseek(fp, ifd_offset, SEEK_SET); fread(&m_lsmInfo, sizeof(Cz_Lsminfo), 1, fp); //m_channelColors.clear(); initChannelColors(); m_lsmChannelNames.clear(); m_lsmTimeStamps.clear(); m_lsmChannelDataTypes.clear(); if (m_lsmInfo.u32OffsetChannelColors != 0) { fseek(fp, m_lsmInfo.u32OffsetChannelColors, SEEK_SET); fread(&m_lsmChannelInfo, sizeof(Lsm_Channel_Colors), 1, fp); char *chStruct = new char[m_lsmChannelInfo.s32BlockSize]; fseek(fp, m_lsmInfo.u32OffsetChannelColors, SEEK_SET); fread(chStruct, m_lsmChannelInfo.s32BlockSize, 1, fp); std::vector<glm::col4> cls(m_lsmChannelInfo.s32NumberColors); memcpy(&(cls[0]), chStruct+m_lsmChannelInfo.s32ColorsOffset, sizeof(uint32_t)*cls.size()); size_t offset = m_lsmChannelInfo.s32NamesOffset; int nameIdx = 0; while (nameIdx < m_lsmChannelInfo.s32NumberNames) { offset += 4; // skip uint32_t name length QString str(chStruct+offset); m_lsmChannelNames.push_back(str); ++nameIdx; offset += str.size() + 1; } for (int ch=0; ch<m_lsmChannelInfo.s32NumberColors; ++ch) { QString chName; if (m_lsmChannelNames.size() > (size_t)ch) chName = m_lsmChannelNames[ch]; if (!chName.isEmpty()) m_channelColors[ch]->setName(chName); m_channelColors[ch]->set(glm::vec3(cls[ch])/255.f); } delete[] chStruct; } if (m_lsmInfo.u32OffsetTimeStamps != 0) { fseek(fp, m_lsmInfo.u32OffsetTimeStamps, SEEK_SET); fread(&m_lsmTimeStampInfo, sizeof(Lsm_Time_Stamp_Info), 1, fp); double *stamps = new double[m_lsmTimeStampInfo.s32NumberTimeStamps]; fread(stamps, sizeof(double), m_lsmTimeStampInfo.s32NumberTimeStamps, fp); for (int i=0; i<m_lsmTimeStampInfo.s32NumberTimeStamps; ++i) m_lsmTimeStamps.push_back(stamps[i]); delete[] stamps; } if (m_lsmInfo.u32OffsetChannelDataTypes != 0) { fseek(fp, m_lsmInfo.u32OffsetChannelDataTypes, SEEK_SET); uint32_t *dataTypes = new uint32_t[m_lsmInfo.s32DimensionChannels]; fread(dataTypes, sizeof(uint32_t), m_lsmInfo.s32DimensionChannels, fp); for (int i=0; i<m_lsmInfo.s32DimensionChannels; ++i) m_lsmChannelDataTypes.push_back(dataTypes[i]); delete[] dataTypes; } fclose(fp); // fill zresolution setResolution(m_lsmInfo.f64VoxelSizeX * 1e6, m_lsmInfo.f64VoxelSizeY * 1e6, m_lsmInfo.f64VoxelSizeZ * 1e6, 'u'); m_isLSMFile = true; return true; } void ZStack::logLSMInfo() { if (!m_isLSMFile) { LINFO() << sourcePath() << "is not a valid LSM file."; return; } LINFO() << "Start LSM Info for" << sourcePath(); LINFO() << "MagicNumber:" << hex << m_lsmInfo.u32MagicNumber; LINFO() << "DimensionX:" << m_lsmInfo.s32DimensionX; LINFO() << "DimensionY:" << m_lsmInfo.s32DimensionY; LINFO() << "DimensionZ:" << m_lsmInfo.s32DimensionZ; LINFO() << "DimensionChannels:" << m_lsmInfo.s32DimensionChannels; LINFO() << "DimensionTime:" << m_lsmInfo.s32DimensionTime; switch (m_lsmInfo.s32DataType) { case 1: LINFO() << "DataType:" << "8-bit unsigned integer"; break; case 2: LINFO() << "DataType:" << "12-bit unsigned integer"; break; case 5: LINFO() << "DataType:" << "32-bit float(for \"Time Series Mean-of-ROIs\")"; break; //case 0: LINFO() << "DataType:" << "different data types for different channels, see 32OffsetChannelDataTypes"; break; } for (size_t i=0; i<m_lsmChannelDataTypes.size(); ++i) { switch (m_lsmChannelDataTypes[i]) { case 1: LINFO() << "Channel" << i+1 << "DataType:" << "8-bit unsigned integer"; break; case 2: LINFO() << "Channel" << i+1 << "DataType:" << "12-bit unsigned integer"; break; case 5: LINFO() << "Channel" << i+1 << "DataType:" << "32-bit float(for \"Time Series Mean-of-ROIs\")"; break; } } LINFO() << "ThumbnailX:" << m_lsmInfo.s32ThumbnailX; LINFO() << "ThumbnailY:" << m_lsmInfo.s32ThumbnailY; LINFO() << "VoxelSizeX in meter:" << m_lsmInfo.f64VoxelSizeX; LINFO() << "VoxelSizeY in meter:" << m_lsmInfo.f64VoxelSizeY; LINFO() << "VoxelSizeZ in meter:" << m_lsmInfo.f64VoxelSizeZ; switch (m_lsmInfo.u16ScanType) { case 0: LINFO() << "ScanType:" << "normal x-y-z-scan"; break; case 1: LINFO() << "ScanType:" << "z-Scan (x-z-plane)"; break; case 2: LINFO() << "ScanType:" << "line scan"; break; case 3: LINFO() << "ScanType:" << "time series x-y"; break; case 4: LINFO() << "ScanType:" << "time series x-z (release 2.0 or later)"; break; case 5: LINFO() << "ScanType:" << "time series \"Mean of ROIs\" (release 2.0 or later)"; break; case 6: LINFO() << "ScanType:" << "time series x-y-z (release 2.3 or later)"; break; case 7: LINFO() << "ScanType:" << "spline scan (release 2.5 or later)"; break; case 8: LINFO() << "ScanType:" << "spline plane x-z (release 2.5 or later)"; break; case 9: LINFO() << "ScanType:" << "time series spline plane x-z (release 2.5 or later)"; break; case 10: LINFO() << "ScanType:" << "point mode (release 3.0 or later)"; break; } switch (m_lsmInfo.u16SpectralScan) { case 0: LINFO() << "SpectralScan:" << "no spectral scan"; break; case 1: LINFO() << "SpectralScan:" << "image has been acquired in spectral scan mode with a META detector (release 3.0 or later)"; break; } switch (m_lsmInfo.u32DataType) { case 0: LINFO() << "DataType:" << "Original scan data"; break; case 1: LINFO() << "DataType:" << "Calculated data"; break; case 2: LINFO() << "DataType:" << "Animation"; break; } if (m_lsmInfo.f64TimeInterval != 0) { LINFO() << "TimeInterval in s:" << m_lsmInfo.f64TimeInterval; } for (size_t i=0; i<m_lsmTimeStamps.size(); ++i) { LINFO() << "TimeStamp" << i+1 << "in s:" << m_lsmTimeStamps[i]; } LINFO() << "DisplayAspectX:" << m_lsmInfo.f64DisplayAspectX; LINFO() << "DisplayAspectY:" << m_lsmInfo.f64DisplayAspectY; LINFO() << "DisplayAspectZ:" << m_lsmInfo.f64DisplayAspectZ; LINFO() << "DisplayAspectTime:" << m_lsmInfo.f64DisplayAspectTime; LINFO() << "ObjectiveSphereCorrection:" << m_lsmInfo.f64objectiveSphereCorrection; for (size_t i=0; i<m_channelColors.size(); ++i) { LINFO() << "Channel" << i+1 << "Name:" << m_lsmChannelNames[i] << "Color(RGB):" << m_channelColors[i]->get(); } LINFO() << "End LSM Info for" << sourcePath(); } #endif
24.856469
139
0.616911
[ "object", "vector" ]
f23404a25bbd2125d57f2c083fb9d01e51858939
1,769
hpp
C++
src/ecs/thinker.hpp
synaodev/apostellein
f664a88d13f533df54ad6fb58c2ad8134f8f942c
[ "BSD-3-Clause" ]
1
2022-01-16T07:06:13.000Z
2022-01-16T07:06:13.000Z
src/ecs/thinker.hpp
synaodev/apostellein
f664a88d13f533df54ad6fb58c2ad8134f8f942c
[ "BSD-3-Clause" ]
null
null
null
src/ecs/thinker.hpp
synaodev/apostellein
f664a88d13f533df54ad6fb58c2ad8134f8f942c
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <vector> #include <unordered_map> #include <entt/entity/fwd.hpp> #include <apostellein/struct.hpp> struct kernel; struct camera; struct player; struct environment; namespace ecs { struct thinker { using procedure = void(*)(entt::entity, kernel&, camera&, player&, environment&); thinker() noexcept = default; thinker(procedure _func) noexcept : func{ _func } {} u32 state {}; procedure func {}; public: static void handle(kernel& knl, camera& cam, player& plr, environment& env); }; using thinker_ctor = void(*)(entt::entity, environment&); using thinker_ctor_table = std::unordered_map<entt::id_type, thinker_ctor>; using thinker_ctor_table_callback = void(*)(thinker_ctor_table&); struct thinker_ctor_table_builder : public not_moveable { thinker_ctor_table_builder() = delete; thinker_ctor_table_builder(thinker_ctor_table_callback func) { auto& callbacks = thinker_ctor_table_builder::callbacks_(); callbacks.push_back(func); } public: static void build(thinker_ctor_table& table) { auto& callbacks = thinker_ctor_table_builder::callbacks_(); for (auto&& func : callbacks) { func(table); } callbacks.clear(); callbacks.shrink_to_fit(); } private: static std::vector<thinker_ctor_table_callback>& callbacks_() { static std::vector<thinker_ctor_table_callback> callbacks {}; return callbacks; } }; } #define APOSTELLEIN_THINKER_TABLE(SYMBOL) \ static void SYMBOL##_build_ctor_table(ecs::thinker_ctor_table& table); \ static const ecs::thinker_ctor_table_builder SYMBOL##_ctor_table_builder { SYMBOL##_build_ctor_table }; \ static void SYMBOL##_build_ctor_table(ecs::thinker_ctor_table& table) \ #define APOSTELLEIN_THINKER_ENTRY(AKTOR, ENTRY) table[AKTOR] = ENTRY
29.983051
106
0.747315
[ "vector" ]
f23da97a6b02dd6d1e1afbd2125b35710a9d44b4
4,240
cpp
C++
Engine/Source/Runtime/MoviePlayer/Private/MoviePlayerThreading.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/MoviePlayer/Private/MoviePlayerThreading.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/MoviePlayer/Private/MoviePlayerThreading.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "MoviePlayer.h" #include "Engine.h" #include "SlateBasics.h" #include "SpinLock.h" #include "MoviePlayerThreading.h" #include "DefaultGameMoviePlayer.h" /** * The Slate thread is simply run on a worker thread. * Slate is run on another thread because the game thread (where Slate is usually run) * is blocked loading things. Slate is very modular, which makes it very easy to run on another * thread with no adverse effects. * It does not enqueue render commands, because the RHI is not thread safe. Thus, it waits to * enqueue render commands until the render thread tickables ticks, and then it calls them there. */ class FSlateLoadingThreadTask : public FRunnable { public: FSlateLoadingThreadTask(class FSlateLoadingSynchronizationMechanism& InSyncMechanism) : SyncMechanism(&InSyncMechanism) { } /** FRunnable interface */ virtual bool Init() override; virtual uint32 Run() override; virtual void Stop() override; private: /** Hold a handle to our parent sync mechanism which handles all of our threading locks */ class FSlateLoadingSynchronizationMechanism* SyncMechanism; }; FSlateLoadingSynchronizationMechanism::FSlateLoadingSynchronizationMechanism() { } FSlateLoadingSynchronizationMechanism::~FSlateLoadingSynchronizationMechanism() { DestroySlateThread(); } void FSlateLoadingSynchronizationMechanism::Initialize() { ResetSlateDrawPassEnqueued(); SetSlateMainLoopRunning(); MainLoop.Lock(); SlateRunnableTask = new FSlateLoadingThreadTask( *this ); SlateLoadingThread = FRunnableThread::Create(SlateRunnableTask, TEXT("SlateLoadingThread")); } void FSlateLoadingSynchronizationMechanism::DestroySlateThread() { if (SlateLoadingThread) { IsRunningSlateMainLoop.Reset(); MainLoop.BlockUntilUnlocked(); delete SlateLoadingThread; delete SlateRunnableTask; SlateLoadingThread = NULL; SlateRunnableTask = NULL; } } bool FSlateLoadingSynchronizationMechanism::IsSlateDrawPassEnqueued() { return IsSlateDrawEnqueued.GetValue() != 0; } void FSlateLoadingSynchronizationMechanism::SetSlateDrawPassEnqueued() { IsSlateDrawEnqueued.Set(1); } void FSlateLoadingSynchronizationMechanism::ResetSlateDrawPassEnqueued() { IsSlateDrawEnqueued.Reset(); } bool FSlateLoadingSynchronizationMechanism::IsSlateMainLoopRunning() { return IsRunningSlateMainLoop.GetValue() != 0; } void FSlateLoadingSynchronizationMechanism::SetSlateMainLoopRunning() { IsRunningSlateMainLoop.Set(1); } void FSlateLoadingSynchronizationMechanism::ResetSlateMainLoopRunning() { IsRunningSlateMainLoop.Reset(); } void FSlateLoadingSynchronizationMechanism::SlateThreadRunMainLoop() { double LastTime = FPlatformTime::Seconds(); while (IsSlateMainLoopRunning()) { const double CurrentTime = FPlatformTime::Seconds(); const double DeltaTime = CurrentTime - LastTime; // 60 fps max const double MaxTickRate = 1.0/60.0f; const double TimeToWait = MaxTickRate - DeltaTime; if( TimeToWait > 0 ) { FPlatformProcess::Sleep(TimeToWait); } if (FSlateApplication::IsInitialized() && !IsSlateDrawPassEnqueued()) { // We can't pump messages because this is not the main thread // and that does not work at least in Windows // (HWNDs can only be pumped on the thread they're created on) // Thus, this function does nothing on the Slate thread //FSlateApplication::Get().PumpMessages(); FSlateApplication::Get().Tick(); SetSlateDrawPassEnqueued(); } LastTime = CurrentTime; } while (IsSlateDrawPassEnqueued()) { FPlatformProcess::Sleep(0.1f); } MainLoop.Unlock(); } bool FSlateLoadingThreadTask::Init() { // First thing to do is set the slate loading thread ID // This guarantees all systems know that a slate thread exists GSlateLoadingThreadId = FPlatformTLS::GetCurrentThreadId(); return true; } uint32 FSlateLoadingThreadTask::Run() { check( GSlateLoadingThreadId == FPlatformTLS::GetCurrentThreadId() ); SyncMechanism->SlateThreadRunMainLoop(); // Tear down the slate loading thread ID GSlateLoadingThreadId = 0; return 0; } void FSlateLoadingThreadTask::Stop() { SyncMechanism->ResetSlateDrawPassEnqueued(); SyncMechanism->ResetSlateMainLoopRunning(); }
24.508671
97
0.773585
[ "render" ]
f23fc1771a732eaaa8b963f947856c50dfe122b3
1,833
cpp
C++
C++/1088-Confusing-Number-II/soln.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/1088-Confusing-Number-II/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/1088-Confusing-Number-II/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
class Solution { public: int confusingNumberII(int N) { string bads = "23457"; int goods [] = {0, 1, 6, 8, 9}; ++N; string string_N = to_string(N); int n = string_N.length(); int ans = 0; for(int i = 1; i < n; ++i) ans += 4 * pow(5, i - 1); for(int i = 0; i < n; ++i) { char ch_d = string_N[i]; int start = (i == 0 ? 1 : 0); int d = ch_d - '0'; for(int j = start; j < 5; ++j) { if (goods[j] >= d) break; ans += pow(5, n - i - 1); } if (bads.find(ch_d) != string::npos) break; } return ans - count_sames(1, N - 1); } vector<string> generate_sames(int n) { vector<string> ans; if (n & 1 == 1) { ans.push_back("0"); ans.push_back("1"); ans.push_back("8"); } else { ans.push_back(""); } string pairs[5] = {"00", "11", "88", "96", "69"}; while (n > 1) { vector<string> temp; n -= 2; int start = (n >= 2) ? 0 : 1; for(int i = start; i < 5; ++i) { string first = pairs[i].substr(0, 1), last = pairs[i].substr(1); for(string item : ans) temp.push_back(first + item + last); } swap(temp, ans); } return ans; } int count_sames(int lo, int hi) { int L = to_string(lo).length(), H = to_string(hi).length(); int cnt = 0; for(int i = L; i <= H; ++i) { vector<string> lst = generate_sames(i); for(string s : lst) { long long num = stoll(s); if (lo <= num && num <= hi) ++cnt; } } return cnt; } };
30.04918
80
0.398254
[ "vector" ]
f24632201c60a5f3db3a2d0c72a2fcbbbd01c989
14,615
cc
C++
src/platform/modules/SerialComm.cc
openDSME/CometOS
1907325847f2efa746bd76854b65578201c383d8
[ "BSD-3-Clause" ]
3
2019-01-14T19:08:07.000Z
2021-01-19T11:57:16.000Z
src/platform/modules/SerialComm.cc
openDSME/CometOS
1907325847f2efa746bd76854b65578201c383d8
[ "BSD-3-Clause" ]
1
2016-11-11T14:35:03.000Z
2016-11-11T14:35:03.000Z
src/platform/modules/SerialComm.cc
openDSME/CometOS
1907325847f2efa746bd76854b65578201c383d8
[ "BSD-3-Clause" ]
2
2020-09-14T08:27:09.000Z
2020-10-19T14:41:48.000Z
/* * CometOS --- a component-based, extensible, tiny operating system * for wireless networks * * Copyright (c) 2015, Institute of Telematics, Hamburg University of Technology * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "SerialComm.h" #include "TaskScheduler.h" #include "Airframe.h" #include "DataRequest.h" #include "DataResponse.h" #include "crc16.h" #include "MacAbstractionBase.h" #include "palLed.h" #include "OverwriteAddrData.h" #include "palLocalTime.h" #include "MacControl.h" #include "ForwardMacMeta.h" #include <stdint.h> #include "palId.h" namespace cometos { #define MAX_LENGTH AIRFRAME_MAX_SIZE #define ACK_OFFSET 0x7E #if (ACK_OFFSET <= MAX_LENGTH) #error "ACK_OFFSET <= MAX_LENGTH" #endif #if (AIRFRAME_MAX_SIZE > MAX_LENGTH) #error "airframe size is insufficient" #endif //#define ACK_PENDING_BIT 1 #define ACK_SUCCESS_BIT 1 #define CRC_LEN 2 #define MAX_RETRIES 5 #define FLAG_MAC_CONTROL_MASK 0x01 #define FLAG_MAC_CONTROL_SHIFT 0 #define FLAG_MAC_RXINFO_MASK 0x02 #define FLAG_MAC_RXINFO_SHIFT 1 #define FLAG_REQ_SERIAL_RESPONSE_MASK 0x04 #define FLAG_REQ_SERIAL_RESPONSE_SHIFT 2 #define FLAG_SERIAL_RESPONSE_MASK 0x08 #define FLAG_SERIAL_RESPONSE_SHIFT 3 #define FLAG_MAC_TXINFO_MASK 0x10 #define FLAG_MAC_TXINFO_SHIFT 4 #define TASK_RESPONSE_TIMEOUT 250 uint8_t SerialComm::checkParity(uint8_t b) { uint8_t c = 0; while (b) { if (b & 1) { c++; } b >>= 1; } if (c % 2) { return 1; } else { return 0; } } void SerialComm::rxCallback() { getScheduler().replace(taskRx); } void SerialComm::initialize() { // initialize UART driver rxBuffer = make_checked<Airframe>(); serial->init(baudrate, &taskRxCallback, NULL, NULL); state = STATE_IDLE; retries = 0; waitingForACK = false; LOG_DEBUG("Init palSerial; baudrate=" << baudrate); #ifdef SERIAL_ENABLE_STATS remoteDeclare(&SerialComm::getStats, "gs"); #endif } #ifdef SERIAL_ENABLE_STATS SerialCommStats SerialComm::getStats() { return stats; } #endif void SerialComm::handleRequest(DataRequest* msg) { SC_STATS_INC(numReq); txHandle(msg); } node_t SerialComm::getAddr() { #ifdef PAL_ID return palId_id(); #else return MAC_BROADCAST; #endif } void SerialComm::serializeMeta(DataRequest* request) { uint8_t flagByte = 0; Airframe& frame = request->getAirframe(); serializeMetadataIfPresent<MacControl, FLAG_MAC_CONTROL_MASK>(request, frame, flagByte); serializeMetadataIfPresent<MacRxInfo, FLAG_MAC_RXINFO_MASK>(request, frame, flagByte); serializeMetadataIfPresent<MacTxInfo, FLAG_MAC_TXINFO_MASK>(request, frame, flagByte); serializeMetadataIfPresent<RequestResponseOverSerial, FLAG_REQ_SERIAL_RESPONSE_MASK>(request, frame, flagByte); serializeMetadataIfPresent<SerialResponse, FLAG_SERIAL_RESPONSE_MASK>(request, frame, flagByte); // mark which kind of metadata is attached frame << flagByte; LOG_DEBUG("Serializing metadata done, flag=" << cometos::hex << (int) flagByte << cometos::dec << " len=" << (int) frame.getLength()); } void SerialComm::deserializeMeta(DataIndication* ind) { Airframe& frame = ind->getAirframe(); // retrieve flag byte, which indicates meta information object's presence uint8_t flagByte; frame >> flagByte; LOG_DEBUG("Start deserializing; flag=" << (int) flagByte); // mind that order of deserialization matters here (confer serializeMeta)!!!!! deserializeMetadataIfPresent<SerialResponse, FLAG_SERIAL_RESPONSE_MASK>(ind, frame, flagByte); deserializeMetadataIfPresent<RequestResponseOverSerial, FLAG_REQ_SERIAL_RESPONSE_MASK>(ind, frame, flagByte); deserializeMetadataIfPresent<MacTxInfo, FLAG_MAC_TXINFO_MASK>(ind, frame, flagByte); if (ind->has<MacTxInfo>()) { ind->get<MacTxInfo>()->tsInfo.isValid = false; } if (!deserializeMetadataIfPresent<MacRxInfo, FLAG_MAC_RXINFO_MASK>(ind, frame, flagByte)) { ind->set(new MacRxInfo(LQI_MAX, true, MacRxInfo::RSSI_EMULATED, true, rxTs)); } deserializeMetadataIfPresent<MacControl, FLAG_MAC_CONTROL_MASK>(ind, frame, flagByte); } void SerialComm::txHandle(DataRequest* request) { if (queue.full()) { #ifdef SERIAL_ENABLE_STATS stats.numQueueFull++; #endif LOG_DEBUG(""); confirm(request, false, false, 0, false, 0); } else { LOG_DEBUG("Next msg: len=" << (int) request->getAirframe().getLength() << "|dst=" << request->dst); serializeMeta(request); // attach src and destination addr if (request->has<OverwriteAddrData>()) { OverwriteAddrData * meta = request->get<OverwriteAddrData>(); request->getAirframe() << meta->dst << meta->src; // getCout() << "S:d=" << meta->dst << "|s=" << meta->src << " -- "; } else { request->getAirframe() << request->dst << getAddr(); // getCout() << "S:d=" << request->dst << "|s=" << getAddr() << " -- "; } // attach sequence number request->getAirframe() << (txSeq++); // request->getAirframe().printFrame(&getCout()); queue.push(request); getScheduler().replace(taskTx); } } void SerialComm::rxHandle() { // remove CRC and ... ASSERT(rxBuffer); ASSERT(rxBuffer->getLength()>=0); // retrieve sequence number uint8_t seq; node_t src; node_t dst; (*rxBuffer) >> seq >> src >> dst; if (seq == rxSeq) { // filter duplicate return; } rxSeq = seq; DataIndication *ind = new DataIndication(rxBuffer, src, dst); deserializeMeta(ind); // getCout() << "R:s=" << src << "|d=" << dst << " -- "; // ind->getAirframe().printFrame(&getCout()); LowerEndpoint::sendIndication(ind); rxBuffer = make_checked<Airframe>(); } // MAIN TASKS------------------------------------------------------------------ void SerialComm::confirm( DataRequest * req, bool result, bool addTxInfo, uint8_t retries, bool isValidTxTs, time_ms_t txDuration) { DataResponse * resp = new DataResponse(result ? DataResponseStatus::SUCCESS : DataResponseStatus::FAIL_UNKNOWN); mac_dbm_t rssi; if (addTxInfo) { if (req->dst == MAC_BROADCAST || !result) { rssi = RSSI_INVALID; } else { rssi = MacRxInfo::RSSI_EMULATED; } // getCout() << "tsValid=" << isValidTxTs << "|reportedTs=" << txTs << endl; MacTxInfo * info = new MacTxInfo(req->dst, retries, 0, rssi, rssi, txDuration, isValidTxTs, txTs); resp->set(info); // getCout() << "tsData.tsValid=" << info->tsInfo.isValid << "|tsData.ts=" << info->tsInfo.ts << endl; } LOG_DEBUG("success=" << (int) result << "|retries=" << (int) retries << "|txDuration=" << txDuration); req->response(resp); delete(req); } void SerialComm::tx() { if (state != STATE_IDLE || waitingForACK) { return; } if (MAX_RETRIES < retries) { ASSERT(!queue.empty()); #ifdef SERIAL_ENABLE_STATS stats.numFail++; #endif LOG_DEBUG("no ack"); confirm(queue.front(), false, true, retries, false, palLocalTime_get() - txTs); retries = 0; queue.pop(); } if (!queue.empty()) { uint8_t len = queue.front()->getAirframe().getLength() + 2; uint8_t *data = queue.front()->getAirframe().getData(); uint16_t crc = 0xffff; uint8_t header = len; if (checkParity(header)) { header = header | 0x80; } // printf("%d %x\n",len,len); // Start sending of data, in parallel ... serial->write(&header, 1); // here we assume that the palSerial will send out that first // byte "immediately enough" to get a valid timestamp if (retries == 0) { txTs = palLocalTime_get(); } serial->write(data, len - 2); // we calculate CRC checksum and... for (uint8_t i = 0; i < len - 2; i++) { crc = crc16_update(crc, data[i]); } // transmit CRC uint8_t upper, lower; upper = 0xFF & (crc >> 8); lower = 0xFF & crc; serial->write(&lower, 1); serial->write(&upper, 1); retries++; // set frame timeout for the case that no ack is received //printf("Data Sent\n"); getScheduler().replace(taskResync, frameTimeout); // printf("SCHEDULE timeout %u\n", palLocalTime_get()); //state = STATE_WAIT_ACK; waitingForACK = true; getScheduler().replace(taskRx); } } void SerialComm::rx() { // printf("ENTER RX %u\n", palLocalTime_get()); if (state == STATE_FLUSH) { return; } if (0 == length) { uint8_t b; if (!serial->read(&b, 1)) { // printf("RETURN %u\n", palLocalTime_get()); return; } // timestamp reception of first byte // TODO could be moved to interrupt itself for more precision rxTs = palLocalTime_get(); if (checkParity(b)) { LOG_DEBUG("Parity check fail"); getScheduler().replace(taskResync, frameTimeout); state = STATE_FLUSH; return; } b = b & 0x7F; if (waitingForACK && b >= ACK_OFFSET) { LOG_DEBUG("rcvd ACK"); time_ms_t txDuration = palLocalTime_get() - txTs; state = STATE_IDLE; waitingForACK = false; getScheduler().remove(taskResync); // printf("remove\n"); if (b & ACK_SUCCESS_BIT) { LOG_DEBUG("ACK success"); // printf("got Ack %x %u\n",b, palLocalTime_get()); ASSERT(!queue.empty()); DataRequest* originalReq = queue.front(); // if (originalReq->has<RequestResponseOverSerial>()) { // awaitResponse = true; // LOG_DEBUG("wait for response until " << palLocalTime_get() + TASK_RESPONSE_TIMEOUT); // getScheduler().replace(taskResponseTimeout, TASK_RESPONSE_TIMEOUT); // //schedule // } else { getScheduler().replace(taskTx); LOG_DEBUG("tx success"); confirm(originalReq, true, true, retries, true, txDuration); retries = 0; queue.pop(); // } } else { LOG_DEBUG("ACK no success"); // reschedule to do next retry getScheduler().replace(taskTx); // printf("Ack invalid %u\n", palLocalTime_get()); } /* The ACK_PENDING_BIT is timing critical, but not necessary for the correct functionality, so remove it. * 1. A->B Message * 2. B->A Message * 3. B->A ACK for 1., containing PENDING_BIT, since 2. was not acked * 4. A->B ACK for 2. * 5. B receives 3. and falsely thinks there is a transmission pending. if (b & ACK_PENDING_BIT) { pushDebug('P'); state = STATE_RX; getScheduler().replace(taskResync, frameTimeout); } */ getScheduler().replace(taskRx); return; } else if (b <= (MAX_LENGTH + 2) && b > 2) { length = b; state = STATE_RX; getScheduler().replace(taskResync, frameTimeout); // printf("length %d %u\n",length, palLocalTime_get()); rxBuffer->setLength(length - 2); rxCrc = 0xffff; } else { getScheduler().replace(taskResync, frameTimeout); state = STATE_FLUSH; return; } } // try to receive packet if (length > 0) { uint8_t *data = NULL; uint8_t received = 0; if (length > 2) { data = rxBuffer->getData() + (rxBuffer->getLength() - (length - 2)); received = serial->read(data, length - 2); } else { data = &crcPkt[2 - length]; received = serial->read(data, length); } length -= received; for (uint8_t i = 0; i < received; i++) { rxCrc = crc16_update(rxCrc, data[i]); } // total frame is received, now --- if (0 == length) { getScheduler().remove(taskResync); // The frame reception resync can be canceled, // but add a new one if the ACK is still pending if(waitingForACK) { getScheduler().replace(taskResync, frameTimeout); } uint8_t ack = ACK_OFFSET; // check whether CRC is correct if (rxCrc == 0) { ack |= ACK_SUCCESS_BIT; } /* if (!queue.empty()) { ack |= ACK_PENDING_BIT; } */ if (checkParity(ack)) { ack |= 0x80; } LOG_DEBUG("Sending ACK: " << (int) ack); serial->write(&ack, 1); if (rxCrc == 0) { rxHandle(); } state = STATE_IDLE; tx(); // why not schedule this? } getScheduler().replace(taskRx); } } //void SerialComm::responseTimeout() { // ASSERT(awaitResponse); // DataRequest* origReq = queue.front(); // queue.pop(); // LOG_DEBUG(""); // confirm(origReq, false, false, 0, false, 0); //} void SerialComm::resync() { // palLed_toggle(1); #if defined(BOARD_local) || defined(BOARD_python) //printf("FLUSHING %u\n", palLocalTime_get()); #endif LOG_DEBUG("FLUSHING"); while (serial->read(rxBuffer->getData(), MAX_LENGTH) > 0) { } length = 0; state = STATE_IDLE; waitingForACK = false; if (!queue.empty()) { getScheduler().replace(taskTx, intrand(frameTimeout)+1); } } void serialize(ByteVector & buf, const SerialCommStats & val) { serialize(buf, val.numReq); serialize(buf, val.numFail); serialize(buf, val.numQueueFull); } void unserialize(ByteVector & buf, SerialCommStats & val) { unserialize(buf, val.numQueueFull); unserialize(buf, val.numFail); unserialize(buf, val.numReq); } }
28.214286
117
0.649812
[ "object" ]
f24a163d1171f66bd4433d21e9bf096552944863
21,782
hpp
C++
extern/magnetic-force/fmmtl_minimum/kernel/YukawaCartesian.hpp
hg2120223/SPlisHSPlasH
b1596c6dfde914533367f7d3124b46997a833af2
[ "MIT" ]
52
2019-10-06T17:25:39.000Z
2022-01-20T23:01:13.000Z
extern/magnetic-force/fmmtl_minimum/kernel/YukawaCartesian.hpp
hg2120223/SPlisHSPlasH
b1596c6dfde914533367f7d3124b46997a833af2
[ "MIT" ]
1
2019-10-08T18:44:41.000Z
2019-10-09T07:48:31.000Z
extern/magnetic-force/fmmtl_minimum/kernel/YukawaCartesian.hpp
hg2120223/SPlisHSPlasH
b1596c6dfde914533367f7d3124b46997a833af2
[ "MIT" ]
10
2019-10-07T16:33:24.000Z
2020-10-21T01:09:47.000Z
#pragma once /** @file YukawaCartesian.hpp * @brief Implements the Yukawa kernel with cartesian expansions * * K(t,s) = exp(-Kappa*|t-s|) / |t-s| // Potential * K(t,s) = -(Kappa*|t-s|+1) exp(-Kappa*|t-s|) (t-s) / |t-s|^3 // Force */ #include <complex> #include <vector> #include <cassert> #include "Yukawa.kern" #include "fmmtl/Expansion.hpp" #include "fmmtl/numeric/Vec.hpp" class YukawaCartesian : public fmmtl::Expansion<YukawaKernel, YukawaCartesian> { protected: typedef double real; typedef std::complex<real> complex; typedef std::vector<real> real_vec; struct IndexCache; //! Expansion order const int P; //! number of multipole terms unsigned MTERMS; //! I, J, K arrays std::vector<unsigned> I, J, K; //! indices of multipole terms std::vector<unsigned> index; //! factorial cache std::vector<double> fact; protected: //! Store all possible index combinations returned from setIndex // TODO: Static/Analytic computation struct IndexCache { private: unsigned setIndex(unsigned i, unsigned j, unsigned k) const { unsigned II = 0; for (unsigned ii = 0; ii < i; ++ii) for (unsigned jj = 1; jj < P_+2-ii; ++jj) II += jj; for (unsigned jj = P_+2-j; jj < P_+2; ++jj) II += jj-i; return II + k; } // use 1D vector & index into it std::vector<unsigned> indices; unsigned P_; public: IndexCache(unsigned P) : P_(P) { indices = std::vector<unsigned>((P_+1)*(P_+1)*(P_+1),0); for (unsigned i=0; i<P_+1; i++) { for (unsigned j=0; j<P_+1-i; j++) { for (unsigned k=0; k<P_+1-i-j; k++) { indices[i*(P_+1)*(P_+1)+j*(P_+1) + k] = setIndex(i,j,k); } } } } inline unsigned operator()(unsigned i, unsigned j, unsigned k) const { return indices[i*(P_+1)*(P_+1)+j*(P_+1)+k]; } }; IndexCache index_cache; public: //! Point type to use for the trees typedef Vec<3,real> point_type; //! Multipole expansion type typedef std::vector<real> multipole_type; //! Local expansion type typedef std::vector<real> local_type; //! Default constructor - use delegating constructor YukawaCartesian() : YukawaCartesian(4,0.125) { } //! Constructor YukawaCartesian(int p, double _kappa) : Expansion(YukawaKernel(_kappa)), P(p), MTERMS((P+1)*(P+2)*(P+3)/6), fact(2*P), index_cache(P) { //kappa = _kappa; // Sets the YukawaKernel kappa I = std::vector<unsigned>(MTERMS,0); J = std::vector<unsigned>(MTERMS,0); K = std::vector<unsigned>(MTERMS,0); index = std::vector<unsigned>(MTERMS,0); // generate n -> (i,j,k) arrays unsigned idx=0; for (int ii=0; ii<P+1; ii++) { for (int jj=0; jj<P+1-ii; jj++) { for (int kk=0; kk<P+1-ii-jj; kk++) { index[idx] = index_cache(ii,jj,kk); I[idx] = ii; J[idx] = jj; K[idx] = kk; idx++; } } } // generate factorials fact[0] = 1; for (int i=1; i<2*P; i++) fact[i] = i*fact[i-1]; } /** Initialize a multipole expansion with the size of a box at this level */ void init_multipole(multipole_type& M, const point_type&, unsigned) const { M = std::vector<real>((P+1)*(P+2)*(P+3)/6, 0); } /** Initialize a local expansion with the size of a box at this level */ void init_local(local_type& L, const point_type&, unsigned) const { L = std::vector<real>((P+1)*(P+2)*(P+3)/6, 0); } /** Kernel S2M operation * M += Op(s) * c where M is the multipole and s is the source * * @param[in] source The source to accumulate into the multipole * @param[in] charge The source's corresponding charge * @param[in] center The center of the box containing the multipole expansion * @param[in,out] M The multipole expansion to accumulate into */ void S2M(const source_type& source, const charge_type& charge, const point_type& center, multipole_type& M) const { point_type dX = center - source; for (unsigned i = 0; i < MTERMS; ++i) { double fact_term = fact[I[i]]*fact[J[i]]*fact[K[i]]; M[i] += charge * pow(dX[0],I[i]) * pow(dX[1],J[i]) * pow(dX[2],K[i]) / fact_term; } } /** Kernel M2M operator * M_t += Op(M_s) where M_t is the target and M_s is the source * * @param[in] source The multipole source at the child level * @param[in,out] target The multipole target to accumulate into * @param[in] translation The vector from source to target * @pre Msource includes the influence of all points within its box */ void M2M(const multipole_type& Msource, multipole_type& Mtarget, const point_type& translation) const { const unsigned MTERMS = (P+1)*(P+2)*(P+3)/6; const auto dX = translation; for (unsigned i=0; i<MTERMS; ++i) { unsigned n[3] = {I[i], J[i], K[i]}; for (unsigned ii=0; ii<n[0]+1; ii++) { for (unsigned jj=0; jj<n[1]+1; jj++) { for (unsigned kk=0; kk<n[2]+1; kk++) { unsigned Midx = index_cache(ii,jj,kk); double fact_term = fact[n[0]-ii]*fact[n[1]-jj]*fact[n[2]-kk]; Mtarget[i] += Msource[Midx]*pow(dX[0],n[0]- ii)*pow(dX[1],n[1]-jj)*pow(dX[2],n[2]-kk)/fact_term; } } } } } /** Kernel M2T operation * r += Op(M, t) where M is the multipole and r is the result * * @param[in] M The multpole expansion * @param[in] center The center of the box with the multipole expansion * @param[in] target The target to evaluate the multipole at * @param[in,out] result The target's corresponding result to accumulate into * @pre M includes the influence of all sources within its box */ void M2T(const multipole_type& M, const point_type& center, const target_type& target, result_type& result) const { std::vector<real> a_aux(MTERMS,0), ax_aux(MTERMS,0), ay_aux(MTERMS,0), az_aux(MTERMS,0); point_type dX = target - center; getCoeff(a_aux, ax_aux, ay_aux, az_aux, dX); // loop over tarSize for (unsigned j=0; j<MTERMS; j++) { double fact_term = fact[I[j]]*fact[J[j]]*fact[K[j]]; result[0] += a_aux[j]*M[j]*fact_term; result[1] += ax_aux[j]*M[j]*fact_term; result[2] += ay_aux[j]*M[j]*fact_term; result[3] += az_aux[j]*M[j]*fact_term; } } /** Kernel M2L operation * L += Op(M) * * @param[in] Msource The multpole expansion source * @param[in,out] Ltarget The local expansion target * @param[in] translation The vector from source to target * @pre translation obeys the multipole-acceptance criteria * @pre Msource includes the influence of all points within its box */ void M2L(const multipole_type& Msource, local_type& Ltarget, const point_type& translation) const { std::vector<real> a_aux(MTERMS,0), ax_aux(MTERMS,0), ay_aux(MTERMS,0), az_aux(MTERMS,0); getCoeff(a_aux, ax_aux, ay_aux, az_aux, translation); // get rid of factorial terms from getCoeff for (unsigned i=0; i<MTERMS; i++) { a_aux[i] *= fact[I[i]]*fact[J[i]]*fact[K[i]]; } for (int ik=0; ik<P+1; ik++) { for (int jk=0; jk<P+1-ik; jk++) { for (int kk=0; kk<P+1-ik-jk; kk++) { // k = (ik, jk, kk) int Lk = index_cache(ik,jk,kk); // for (int in=0; in<P+1-ik; in++) { // printf("in: %d\n",in); for (int jn=0; jn<P+1-jk; jn++) { for (int kn=0; kn<P+1-kk; kn++) { if (in+jn+kn > P) continue; if (in+ik+jn+jk+kn+kk > P) continue; // n = (in, jn, kn) // (n+k) = (ik+in, jk+jn, kk+kn) // L_k = \sum_{n=0}^{p-k} a_aux[getIndex(n+k)]*M[getIndex(n)] // int Mn = index_cache(in,jn,kn); int npk = index_cache(ik+in,jk+jn,kk+kn); Ltarget[Lk] += a_aux[npk] * Msource[Mn]; } } } // end inner loop } } } // end outer loop } /** Kernel L2L operation * L_t += Op(L_s) where L_t is the target and L_s is the source * * @param[in] source The local source at the parent level * @param[in,out] target The local target to accumulate into * @param[in] translation The vector from source to target * @pre Lsource includes the influence of all points outside its box */ void L2L(const local_type& Lsource, local_type& Ltarget, const point_type& translation) const { for (unsigned i=0; i<MTERMS; i++) { // n = (I[i], J[i], K[i]) unsigned n[3] = {I[i],J[i],K[i]}; for (int ii=I[i]; ii<P+1; ii++) { for (int jj=J[i]; jj<P+1-ii; jj++) { for (int kk=K[i]; kk<P+1-ii-jj; kk++) { // k = (ii, jj, kk) int Lk = index_cache(ii,jj,kk); double fact_term = fact[ii-n[0]]*fact[jj-n[1]]*fact[kk-n[2]]; Ltarget[i] += Lsource[Lk]*pow(translation[0],ii-n[0])*pow(translation[1],jj-n[1])*pow(translation[2],kk-n[2]) / fact_term; } } } } } /** Kernel L2T operation * r += Op(L, t) where L is the local expansion and r is the result * * @param[in] L The local expansion * @param[in] center The center of the box with the local expansion * @param[in] target The target of this L2T operation * @param[in] result The result to accumulate into * @pre L includes the influence of all sources outside its box */ void L2T(const local_type& L, const point_type& center, const target_type& target, result_type& result) const { auto dx = target-center; for (unsigned i=0; i<MTERMS; i++) { unsigned k[3] = {I[i], J[i], K[i]}; // calculate potential double phi = L[i]*pow(dx[0],k[0])*pow(dx[1],k[1])*pow(dx[2],k[2]) / (fact[k[0]]*fact[k[1]]*fact[k[2]]); result[0] += phi; double inv[3]; for (int i=0; i<3; i++) inv[i] = (fabs(dx[i]) < 1e-12) ? 0 : 1. / dx[i]; // using potential, calculate derivatives result[1] += phi * k[0] * inv[0]; result[2] += phi * k[1] * inv[1]; result[3] += phi * k[2] * inv[2]; } } protected: // get coefficients given by d^n / dx^n f(x) void getCoeff(real_vec& a, real_vec& ax, real_vec& ay, real_vec& az, const point_type& dX) const { real_vec b(a.size(),0); real dx = dX[0], dy = dX[1], dz = dX[2]; auto R2 = norm_2_sq(dX); auto R = sqrt(R2); int i,j,k,I,Im1x,Im2x,Im1y,Im2y,Im1z,Im2z; real C,C1,C2,Cb, R2_1; R2_1 = 1/R2; // First coefficient b[0] = exp(-kappa*R); a[0] = b[0]/R; // Two indices = 0 I = index_cache(1,0,0); // setIndex(P,1,0,0); b[I] = -kappa * (dx*a[0]); // 1,0,0 b[P+1] = -kappa * (dy*a[0]); // 0,1,0 b[1] = -kappa * (dz*a[0]); // 0,0,1 a[I] = -R2_1*dx*(kappa*b[0]+a[0]); a[P+1] = -R2_1*dy*(kappa*b[0]+a[0]); a[1] = -R2_1*dz*(kappa*b[0]+a[0]); ax[0] = a[I]; ay[0] = a[P+1]; az[0] = a[1]; for (i=2; i<P+1; i++) { Cb = -kappa/i; C = R2_1/i; I = index_cache(i,0,0); // setIndex(P,i,0,0); Im1x = index_cache(i-1,0,0); // setIndex(P,i-1,0,0); Im2x = index_cache(i-2,0,0); // setIndex(P,i-2,0,0); b[I] = Cb * (dx*a[Im1x] + a[Im2x]); a[I] = C * ( -kappa*(dx*b[Im1x] + b[Im2x]) -(2*i-1)*dx*a[Im1x] - (i-1)*a[Im2x] ); ax[Im1x] = a[I]*i; I = index_cache(0,i,0); // setIndex(P,0,i,0); Im1y = I-(P+2-i); Im2y = Im1y-(P+2-i+1); b[I] = Cb * (dy*a[Im1y] + a[Im2y]); a[I] = C * ( -kappa*(dy*b[Im1y] + b[Im2y]) -(2*i-1)*dy*a[Im1y] - (i-1)*a[Im2y] ); ay[Im1y] = a[I]*i; I = i; Im1z = I-1; Im2z = I-2; b[I] = Cb * (dz*a[Im1z] + a[Im2z]); a[I] = C * ( -kappa*(dz*b[Im1z] + b[Im2z]) -(2*i-1)*dz*a[Im1z] - (i-1)*a[Im2z] ); az[Im1z] = a[I]*i; } // One index = 0, one = 1 other >=1 Cb = -kappa/2; C = R2_1/2.; I = index_cache(1,1,0); //setIndex(P,1,1,0); Im1x = P+1; Im1y = I-P; b[I] = Cb * (dx*a[Im1x] + dy*a[Im1y]); a[I] = C * ( -kappa*(dx*b[Im1x]+dy*b[Im1y]) - 3*(dx*a[Im1x]+dy*a[Im1y]) ); ax[Im1x] = a[I]; ay[Im1y] = a[I]; I = index_cache(1,0,1); // setIndex(P,1,0,1); Im1x = 1; Im1z = I-1; b[I] = Cb * (dx*a[Im1x] + dz*a[Im1z]); a[I] = C * ( -kappa*(dx*b[Im1x]+dz*b[Im1z]) - 3*(dx*a[Im1x]+dz*a[Im1z]) ); ax[Im1x] = a[I]; az[Im1z] = a[I]; I = index_cache(0,1,1); // setIndex(P,0,1,1); Im1y = I-(P+1); Im1z = I-1; b[I] = Cb * (dy*a[Im1y] + dz*a[Im1z]); a[I] = C * ( -kappa*(dy*b[Im1y]+dz*b[Im1z]) - 3*(dy*a[Im1y]+dz*a[Im1z]) ); ay[Im1y] = a[I]; az[Im1z] = a[I]; for (i=2; i<P; i++) { Cb = -kappa/(i+1); C = R2_1/(1+i); C1 = 1+2*i; I = index_cache(1,i,0); // setIndex(P,1,i,0); Im1x = index_cache(0,i,0); // setIndex(P,0,i,0); Im1y = I-(P+1-i); Im2y = Im1y-(P+2-i); b[I] = Cb * (dx*a[Im1x] + dy*a[Im1y] + a[Im2y]); a[I] = C * ( -kappa*(dx*b[Im1x]+dy*b[Im1y]+b[Im2y]) - C1*(dx*a[Im1x]+dy*a[Im1y]) - (1+i-1)*(a[Im2y]) ); ax[Im1x] = a[I]; ay[Im1y] = a[I]*i; I = index_cache(1,0,i); // setIndex(P,1,0,i); Im1x = index_cache(0,0,i); // setIndex(P,0,0,i); Im1z = I-1; Im2z = I-2; b[I] = Cb * (dx*a[Im1x] + dz*a[Im1z] + a[Im2z]); a[I] = C * ( -kappa*(dx*b[Im1x]+dz*b[Im1z]+b[Im2z]) - C1*(dx*a[Im1x]+dz*a[Im1z]) - (1+i-1)*(a[Im2z]) ); ax[Im1x] = a[I]; az[Im1z] = a[I]*i; I = index_cache(0,1,i); // setIndex(P,0,1,i); Im1y = I-(P+1); Im1z = I-1; Im2z = I-2; b[I] = Cb * (dy*a[Im1y] + dz*a[Im1z] + a[Im2z]); a[I] = C * ( -kappa*(dy*b[Im1y]+dz*b[Im1z]+b[Im2z]) - C1*(dy*a[Im1y]+dz*a[Im1z]) - (1+i-1)*(a[Im2z]) ); ay[Im1y] = a[I]; az[Im1z] = a[I]*i; I = index_cache(i,1,0); // setIndex(P,i,1,0); Im1y = I-(P+1-i); Im1x = index_cache(i-1,1,0); // setIndex(P,i-1,1,0); Im2x = index_cache(i-2,1,0); // setIndex(P,i-2,1,0); b[I] = Cb * (dy*a[Im1y] + dx*a[Im1x] + a[Im2x]); a[I] = C * ( -kappa*(dy*b[Im1y]+dx*b[Im1x]+b[Im2x]) - C1*(dy*a[Im1y]+dx*a[Im1x]) - (1+i-1)*(a[Im2x]) ); ax[Im1x] = a[I]*i; ay[Im1y] = a[I]; I = index_cache(i,0,1); // setIndex(P,i,0,1); Im1z = I-1; Im1x = index_cache(i-1,0,1); // setIndex(P,i-1,0,1); Im2x = index_cache(i-2,0,1); // setIndex(P,i-2,0,1); b[I] = Cb * (dz*a[Im1z] + dx*a[Im1x] + a[Im2x]); a[I] = C * ( -kappa*(dz*b[Im1z]+dx*b[Im1x]+b[Im2x]) - C1*(dz*a[Im1z]+dx*a[Im1x]) - (1+i-1)*(a[Im2x]) ); ax[Im1x] = a[I]*i; az[Im1z] = a[I]; I = index_cache(0,i,1); // setIndex(P,0,i,1); Im1z = I-1; Im1y = I-(P+2-i); Im2y = Im1y-(P+3-i); b[I] = Cb * (dz*a[Im1z] + dy*a[Im1y] + a[Im2y]); a[I] = C * ( -kappa*(dz*b[Im1z]+dy*b[Im1y]+b[Im2y]) - C1*(dz*a[Im1z]+dy*a[Im1y]) - (1+i-1)*(a[Im2y]) ); ay[Im1y] = a[I]*i; az[Im1z] = a[I]; } // One index 0, others >=2 for (i=2; i<P+1; i++) { for (j=2; j<P+1-i; j++) { Cb = -kappa/(i+j); C = R2_1/(i+j); C1 = 2*(i+j)-1; I = index_cache(i,j,0); // setIndex(P,i,j,0); Im1x = index_cache(i-1,j,0); // setIndex(P,i-1,j,0); Im2x = index_cache(i-2,j,0); // setIndex(P,i-2,j,0); Im1y = I-(P+2-j-i); Im2y = Im1y-(P+3-j-i); b[I] = Cb * (dx*a[Im1x] + dy*a[Im1y] + a[Im2x] + a[Im2y]); a[I] = C * ( -kappa*(dx*b[Im1x]+dy*b[Im1y]+b[Im2x]+b[Im2y]) - C1*(dx*a[Im1x]+dy*a[Im1y]) -(i+j-1)*(a[Im2x]+a[Im2y]) ); ax[Im1x] = a[I]*i; ay[Im1y] = a[I]*j; I = index_cache(i,0,j); // setIndex(P,i,0,j); Im1x = index_cache(i-1,0,j); // setIndex(P,i-1,0,j); Im2x = index_cache(i-2,0,j); // setIndex(P,i-2,0,j); Im1z = I-1; Im2z = I-2; b[I] = Cb * (dx*a[Im1x] + dz*a[Im1z] + a[Im2x] + a[Im2z]); a[I] = C * ( -kappa*(dx*b[Im1x]+dz*b[Im1z]+b[Im2x]+b[Im2z]) - C1*(dx*a[Im1x]+dz*a[Im1z]) -(i+j-1)*(a[Im2x]+a[Im2z]) ); ax[Im1x] = a[I]*i; az[Im1z] = a[I]*j; I = index_cache(0,i,j); // setIndex(P,0,i,j); Im1y = I-(P+2-i); Im2y = Im1y-(P+3-i); Im1z = I-1; Im2z = I-2; b[I] = Cb * (dy*a[Im1y] + dz*a[Im1z] + a[Im2y] + a[Im2z]); a[I] = C * ( -kappa*(dy*b[Im1y]+dz*b[Im1z]+b[Im2y]+b[Im2z]) - C1*(dy*a[Im1y]+dz*a[Im1z]) -(i+j-1)*(a[Im2y]+a[Im2z]) ); ay[Im1y] = a[I]*i; az[Im1z] = a[I]*j; } } if (P>2) { // Two index = 1, other>=1 C = R2_1/3; Cb = -kappa/3; I = index_cache(1,1,1); // setIndex(P,1,1,1); Im1x = index_cache(0,1,1); // setIndex(P,0,1,1); Im1y = index_cache(1,0,1); // setIndex(P,1,0,1); Im1y = I-(P); Im1z = I-1; b[I] = Cb * (dx*a[Im1x] + dy*a[Im1y] + dz*a[Im1z]); a[I] = C * ( -kappa*(dx*b[Im1x]+dy*b[Im1y]+dz*b[Im1z]) - 5*(dx*a[Im1x]+dy*a[Im1y]+dz*a[Im1z]) ); ax[Im1x] = a[I]; ay[Im1y] = a[I]; az[Im1z] = a[I]; for (i=2; i<P-1; i++) { Cb = -kappa/(2+i); C = R2_1/(i+2); C1 = 2*i+3; I = index_cache(i,1,1); // setIndex(P,i,1,1); Im1x = index_cache(i-1,1,1); // setIndex(P,i-1,1,1); Im1y = I-(P+1-i); Im1z = I-1; Im2x = index_cache(i-2,1,1); // setIndex(P,i-2,1,1); b[I] = Cb * (dx*a[Im1x] + dy*a[Im1y] + dz*a[Im1z] + a[Im2x]); a[I] = C * ( -kappa*(dx*b[Im1x]+dy*b[Im1y]+dz*b[Im1z]+b[Im2x]) - C1*(dx*a[Im1x]+dy*a[Im1y]+dz*a[Im1z]) - (i+1)*(a[Im2x]) ); ax[Im1x] = a[I]*i; ay[Im1y] = a[I]; az[Im1z] = a[I]; I = index_cache(1,i,1); // setIndex(P,1,i,1); Im1x = index_cache(0,i,1); // setIndex(P,0,i,1); Im1y = I-(P+1-i); Im2y = Im1y-(P+2-i); Im1z = I-1 ; b[I] = Cb * (dx*a[Im1x] + dy*a[Im1y] + dz*a[Im1z] + a[Im2y]); a[I] = C * ( -kappa*(dx*b[Im1x]+dy*b[Im1y]+dz*b[Im1z]+b[Im2y]) - C1*(dx*a[Im1x]+dy*a[Im1y]+dz*a[Im1z]) - (i+1)*(a[Im2y]) ); ax[Im1x] = a[I]; ay[Im1y] = a[I]*i; az[Im1z] = a[I]; I = index_cache(1,1,i); // setIndex(P,1,1,i); Im1x = index_cache(0,1,i); // setIndex(P,0,1,i); Im1y = I-(P); Im1z = I-1; Im2z = I-2; b[I] = Cb * (dx*a[Im1x] + dy*a[Im1y] + dz*a[Im1z] + a[Im2z]); a[I] = C * ( -kappa*(dx*b[Im1x]+dy*b[Im1y]+dz*b[Im1z]+b[Im2z]) - C1*(dx*a[Im1x]+dy*a[Im1y]+dz*a[Im1z]) - (i+1)*(a[Im2z]) ); ax[Im1x] = a[I]; ay[Im1y] = a[I]; az[Im1z] = a[I]*i; } } // One index = 1, others >=2 if (P>4) { for (i=2; i<P-2; i++) { for (j=2; j<P-i; j++) { Cb = -kappa/(1+i+j); C = R2_1/(1+i+j); C1 = -(2.*(i+j)+1); C2 = (i+j); I = index_cache(1,i,j); // setIndex(P,1,i,j); Im1x = index_cache(0,i,j); // setIndex(P,0,i,j); Im1y = I-(P+1-i); Im2y = Im1y-(P+2-i); Im1z = I-1; Im2z = I-2; b[I] = Cb * (dx*a[Im1x] + dy*a[Im1y] + dz*a[Im1z] + a[Im2y] + a[Im2z]); a[I] = C * ( -kappa*(dx*b[Im1x]+dy*b[Im1y]+dz*b[Im1z]+b[Im2y]+b[Im2z]) + C1*(dx*a[Im1x]+dy*a[Im1y]+dz*a[Im1z]) - C2*(a[Im2y]+a[Im2z]) ); ax[Im1x] = a[I]; ay[Im1y] = a[I]*i; az[Im1z] = a[I]*j; I = index_cache(i,1,j); // setIndex(P,i,1,j); Im1x = index_cache(i-1,1,j); // setIndex(P,i-1,1,j); Im1y = I-(P+1-i); Im2x = index_cache(i-2,1,j); // setIndex(P,i-2,1,j); Im1z = I-1; Im2z = I-2; b[I] = Cb * (dx*a[Im1x] + dy*a[Im1y] + dz*a[Im1z] + a[Im2x] + a[Im2z]); a[I] = C * ( -kappa*(dx*b[Im1x]+dy*b[Im1y]+dz*b[Im1z]+b[Im2x]+b[Im2z]) + C1*(dx*a[Im1x]+dy*a[Im1y]+dz*a[Im1z]) - C2*(a[Im2x]+a[Im2z]) ); ax[Im1x] = a[I]*i; ay[Im1y] = a[I]; az[Im1z] = a[I]*j; I = index_cache(i,j,1); // setIndex(P,i,j,1); Im1x = index_cache(i-1,j,1); // setIndex(P,i-1,j,1); Im2x = index_cache(i-2,j,1); // setIndex(P,i-2,j,1); Im1y = I-(P+2-i-j); Im2y = Im1y-(P+3-i-j); Im1z = I-1; b[I] = Cb * (dx*a[Im1x] + dy*a[Im1y] + dz*a[Im1z] + a[Im2x] + a[Im2y]); a[I] = C * ( -kappa*(dx*b[Im1x]+dy*b[Im1y]+dz*b[Im1z]+b[Im2x]+b[Im2y]) + C1*(dx*a[Im1x]+dy*a[Im1y]+dz*a[Im1z]) - C2*(a[Im2x]+a[Im2y]) ); ax[Im1x] = a[I]*i; ay[Im1y] = a[I]*j; az[Im1z] = a[I]; } } } // All indices >= 2 if (P>5) { for (i=2;i<P-3;i++) { for (j=2;j<P-1-i;j++) { for (k=2;k<P+1-i-j;k++) { Cb = -kappa/(i+j+k); C = R2_1/(i+j+k); C1 = -(2.*(i+j+k)-1); C2 = i+j+k-1.; I = index_cache(i,j,k); // setIndex(P,i,j,k); Im1x = index_cache(i-1,j,k); // setIndex(P,i-1,j,k); Im2x = index_cache(i-2,j,k); // setIndex(P,i-2,j,k); Im1y = I-(P+2-i-j); Im2y = Im1y-(P+3-i-j); Im1z = I-1; Im2z = I-2; b[I] = Cb * (dx*a[Im1x] + dy*a[Im1y] + dz*a[Im1z] + a[Im2x] + a[Im2y] + a[Im2z]); a[I] = C * ( -kappa*(dx*b[Im1x]+dy*b[Im1y]+dz*b[Im1z]+b[Im2x]+b[Im2y]+b[Im2z]) + C1*(dx*a[Im1x]+dy*a[Im1y]+dz*a[Im1z]) - C2*(a[Im2x]+a[Im2y]+a[Im2z]) ); ax[Im1x] = a[I]*i; ay[Im1y] = a[I]*j; az[Im1z] = a[I]*k; } } } } } };
34.302362
164
0.490451
[ "vector" ]
f2509b2e84acaf33dfb0ea764621b6dc63cc6e79
5,105
cpp
C++
external/kspwlo_ref/algorithms/multipass.cpp
ashishkashinath/arlib
891aa8603a6e07a16aec5700e7129a0d14a40b84
[ "MIT" ]
12
2018-10-29T17:17:28.000Z
2021-11-01T02:09:37.000Z
external/kspwlo_ref/algorithms/multipass.cpp
ashishkashinath/arlib
891aa8603a6e07a16aec5700e7129a0d14a40b84
[ "MIT" ]
1
2019-04-05T07:27:35.000Z
2019-04-05T07:27:35.000Z
external/kspwlo_ref/algorithms/multipass.cpp
ashishkashinath/arlib
891aa8603a6e07a16aec5700e7129a0d14a40b84
[ "MIT" ]
4
2019-07-20T09:31:41.000Z
2022-03-11T12:06:49.000Z
/* Copyright (c) 2017 Theodoros Chondrogiannis */ #include "kspwlo.hpp" Path next_spwlo_bounds( RoadNetwork *rN, NodeID source, NodeID target, double theta, unordered_map<Edge, vector<int>, boost::hash<Edge>> &resEdges, vector<Path> &resPaths, vector<int> &bounds); /* * * multipass(RoadNetwork*, NodeID, NodeID, int, double) * ----- * Implementation of the MultiPass algorithm. * Calls function next_spwlo_bounds * */ vector<Path> multipass(RoadNetwork *rN, NodeID source, NodeID target, unsigned int k, double theta) { int count = 0; Edge edge; unordered_map<Edge, vector<int>, boost::hash<Edge>> resEdges; unordered_map<Edge, vector<int>, boost::hash<Edge>>::iterator iterE; vector<Path> resPaths; // Compute shortest path and add it to P_LO pair<Path, vector<int>> resDijkstra = dijkstra_path_and_bounds(rN, source, target); Path resNext = resDijkstra.first; resPaths.push_back(resNext); if (k == 1) return resPaths; // While |P_LO| < k for (unsigned int i = 1; i < k; i++) { // Keep a list of edges that are part of P_LO for (unsigned int j = 0; j < resNext.nodes.size() - 1; j++) { edge = make_pair(resNext.nodes[j], resNext.nodes[j + 1]); if ((iterE = resEdges.find(edge)) == resEdges.end()) resEdges.insert(make_pair(edge, vector<int>(1, count))); else iterE->second.push_back(count); } count++; resNext = next_spwlo_bounds(rN, source, target, theta, resEdges, resPaths, resDijkstra.second); if (resNext.length == -1) break; resPaths.push_back(resNext); } return resPaths; } /* next_spwlo_bounds(RoadNetwork, NodeID, NodeID, double, unordered_map<Edge, vector<int>,boost::hash<Edge>>, vector<Path>, vector<int>) ----- This is the internal function called by MultiPass to produce the shortest alternative to the provided set of paths. */ Path next_spwlo_bounds( RoadNetwork *rN, NodeID source, NodeID target, double theta, unordered_map<Edge, vector<int>, boost::hash<Edge>> &resEdges, vector<Path> &resPaths, vector<int> &bounds) { Path resPath; resPath.length = -1; PriorityQueueAS2 Q; SkylineContainer skyline; int newLength = 0; vector<double> newOverlap; EdgeList::iterator iterAdj; unordered_map<Edge, vector<int>, boost::hash<Edge>>::iterator iterE; Edge edge; bool check = true; vector<OlLabel *> allCreatedLabels; // Initialize V_sim vector newOverlap.resize(resPaths.size(), 0); int newLowerBound = bounds[source]; // Initialize Q with <source, empty_path> Q.push(new OlLabel(source, newLength, newLowerBound, newOverlap, -1)); while (!Q.empty()) { // Pop current path OlLabel *curLabel = static_cast<OlLabel *>(Q.top()); Q.pop(); // Found target. if (curLabel->node_id == target) { OlLabel *tempLabel = curLabel; // Compute the path back to the source while (tempLabel != NULL) { resPath.nodes.push_back(tempLabel->node_id); tempLabel = static_cast<OlLabel *>(tempLabel->previous); } reverse(resPath.nodes.begin(), resPath.nodes.end()); resPath.length = curLabel->length; break; } // Check Lemma 2 for current label. if (skyline.dominates(curLabel)) continue; skyline.insert(curLabel); // Expand search. For each outgoing edge. for (iterAdj = rN->adjListOut[curLabel->node_id].begin(); iterAdj != rN->adjListOut[curLabel->node_id].end(); iterAdj++) { // Avoid exploring self loops ? if (curLabel->previous != NULL && curLabel->previous->node_id == iterAdj->first) continue; // Expand path Pc (candidate path) newLength = curLabel->length + iterAdj->second; newOverlap = curLabel->overlapList; newLowerBound = newLength + bounds[iterAdj->first]; OlLabel *newPrevious = curLabel; edge = make_pair(curLabel->node_id, iterAdj->first); check = true; if ((iterE = resEdges.find(edge)) != resEdges.end()) { // If 'edge' is found in any subpath of P_LO // update V_sim for each node. If Lemma 1 is not satisfied, prune it. for (unsigned int j = 0; j < iterE->second.size(); j++) { // Sum weight of common 'edge' (to perform incremental computation // of Similarity) newOverlap[iterE->second[j]] += iterAdj->second; if (newOverlap[iterE->second[j]] / resPaths[iterE->second[j]].length > theta) { check = false; break; } } } // If Lemma 1 is satisfied, the two conditions hold, so Pc is a valid // candidate path. if (check) { OlLabel *label = new OlLabel(iterAdj->first, newLength, newLowerBound, newOverlap, -1, newPrevious); Q.push(label); allCreatedLabels.push_back(label); } } } for (unsigned int i = 0; i < allCreatedLabels.size(); i++) delete allCreatedLabels[i]; return resPath; }
30.386905
80
0.627816
[ "vector" ]
f253a9a815e876b006bc171ff3dc1f4f18d63042
2,771
cpp
C++
src/LpmEuclideanCoords.cpp
pbosler/lpmCxx
d8222d5a6a152f467b6a82751a404ea1e3716497
[ "MIT" ]
null
null
null
src/LpmEuclideanCoords.cpp
pbosler/lpmCxx
d8222d5a6a152f467b6a82751a404ea1e3716497
[ "MIT" ]
1
2018-11-27T21:02:33.000Z
2018-11-27T21:02:33.000Z
src/LpmEuclideanCoords.cpp
pbosler/lpmCxx
d8222d5a6a152f467b6a82751a404ea1e3716497
[ "MIT" ]
null
null
null
#include "LpmEuclideanCoords.h" #include "LpmXyzVector.h" #include <vector> #include <random> #include <chrono> namespace Lpm { scalar_type EuclideanCoords::distance(const index_type indA, const index_type indB) const { const XyzVector vecA(x[indA], y[indA], (_geometry != PLANAR_GEOMETRY ? z[indA] : 0.0)); const XyzVector vecB(x[indB], y[indB], (_geometry != PLANAR_GEOMETRY ? z[indB] : 0.0)); return Lpm::distance(vecA, vecB); } scalar_type EuclideanCoords::distance(const XyzVector& vec, const index_type ind) const { return Lpm::distance(vec, XyzVector(x[ind], y[ind], (_geometry != PLANAR_GEOMETRY ? z[ind] : 0.0))); } scalar_type EuclideanCoords::distance(const XyzVector& v0, const XyzVector& v1) const { return Lpm::distance(v0, v1); } XyzVector EuclideanCoords::midpoint(const index_type indA, const index_type indB) const { const XyzVector vecA(x[indA], y[indA], (_geometry != PLANAR_GEOMETRY ? z[indA] : 0.0)); const XyzVector vecB(x[indB], y[indB], (_geometry != PLANAR_GEOMETRY ? z[indB] : 0.0)); return Lpm::midpoint(vecA, vecB); } XyzVector EuclideanCoords::centroid(const std::vector<index_type>& inds) const { std::vector<XyzVector> vecs; for (index_type i = 0; i < inds.size(); ++i) vecs.push_back(XyzVector(x[inds[i]], y[inds[i]], (_geometry != PLANAR_GEOMETRY ? z[inds[i]] : 0.0))); return Lpm::centroid(vecs); } scalar_type EuclideanCoords::triArea(const index_type indA, const index_type indB, const index_type indC) const { const XyzVector vecA(x[indA], y[indA], (_geometry != PLANAR_GEOMETRY ? z[indA] : 0.0)); const XyzVector vecB(x[indB], y[indB], (_geometry != PLANAR_GEOMETRY ? z[indB] : 0.0)); const XyzVector vecC(x[indC], y[indC], (_geometry != PLANAR_GEOMETRY ? z[indC] : 0.0)); return Lpm::triArea(vecA, vecB, vecC); } scalar_type EuclideanCoords::triArea(const XyzVector& v0, const index_type indA, const index_type indB) const { const XyzVector v1(x[indA], y[indA], (_geometry != PLANAR_GEOMETRY ? z[indA] : 0.0)); const XyzVector v2(x[indB], y[indB], (_geometry != PLANAR_GEOMETRY ? z[indB] : 0.0)); return Lpm::triArea(v0, v1, v2); } void EuclideanCoords::initRandom(const bool useTimeSeed, const scalar_type domainRadius) { unsigned seed(1234); if (useTimeSeed) { seed = std::chrono::system_clock::now().time_since_epoch().count(); } std::default_random_engine generator(seed); std::uniform_real_distribution<scalar_type> randDist(-domainRadius, domainRadius); for (index_type i = 0; i < _nMax; ++i) { const scalar_type xx = randDist(generator); const scalar_type yy = randDist(generator); const scalar_type zz = randDist(generator); insert(xx, yy, zz); } } }
41.358209
113
0.68459
[ "vector" ]
f26062f89ce4a7a8b782342237afa24472960143
4,356
cc
C++
runtime/onert/core/src/backend/controlflow/kernel/IfLayer.cc
bogus-sudo/ONE-1
7052a817eff661ec2854ed2e7ee0de5e8ba82b55
[ "Apache-2.0" ]
null
null
null
runtime/onert/core/src/backend/controlflow/kernel/IfLayer.cc
bogus-sudo/ONE-1
7052a817eff661ec2854ed2e7ee0de5e8ba82b55
[ "Apache-2.0" ]
null
null
null
runtime/onert/core/src/backend/controlflow/kernel/IfLayer.cc
bogus-sudo/ONE-1
7052a817eff661ec2854ed2e7ee0de5e8ba82b55
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "IfLayer.h" #include <backend/ITensor.h> #include "exec/ExecutorBase.h" #include "PermuteLayer.h" namespace onert { namespace backend { namespace controlflow { namespace kernel { IfLayer::IfLayer(const std::shared_ptr<backend::ITensor> &cond_tensor, std::vector<std::shared_ptr<backend::ITensor>> input_tensors, std::vector<std::shared_ptr<backend::ITensor>> output_tensors, const ir::SubgraphIndex &then_subg_index, const ir::SubgraphIndex &else_subg_index, const std::shared_ptr<exec::ExecutorMap> &executor_map) : _cond_tensor{cond_tensor}, _input_tensors{input_tensors}, _output_tensors{output_tensors}, _then_subg_index{then_subg_index}, _else_subg_index{else_subg_index}, _executor_map{executor_map} { // At this point, executor_map may not have executors of then subg and else subg } void IfLayer::run() { // TODO Support dynamic tensor // Check condition // // If true // // // Copy _src_tensors -> then subg's inputs // // // Run then subg // // // Copy outputs of then subg -> _dst_tensors // // Else // // // Copy _src_tensors -> else subg's inputs if false // // // Run else subg // // // Copy outputs of else subg -> _dst_tensors auto getResultCond = [](backend::ITensor *tensor) -> bool { bool ret = false; tensor->access([&](ITensor &tensor) { ret = *reinterpret_cast<bool *>(tensor.buffer()); }); return ret; }; std::vector<size_t> input_ranks; for (size_t i = 0; i < _input_tensors.size(); ++i) { auto rank = _input_tensors.at(i)->num_dimensions(); input_ranks.emplace_back(rank); } std::vector<size_t> output_ranks; for (size_t i = 0; i < _output_tensors.size(); ++i) { auto rank = _output_tensors.at(i)->num_dimensions(); output_ranks.emplace_back(rank); } if (getResultCond(_cond_tensor.get())) { auto then_exec = dynamic_cast<exec::ExecutorBase *>(_executor_map->at(_then_subg_index).get()); if (then_exec == nullptr) { throw std::runtime_error{"If: Invalid then subgraph"}; } const auto &then_input_tensors = then_exec->getInputTensors(); const auto &then_output_tensors = then_exec->getOutputTensors(); PermuteLayer permute_op_input_to_then_input{_input_tensors, then_input_tensors, input_ranks}; PermuteLayer permute_then_output_to_op_output{then_output_tensors, _output_tensors, output_ranks}; // Remove copying of unused tensor permute_op_input_to_then_input.prepare(); permute_then_output_to_op_output.prepare(); // Copy & run permute_op_input_to_then_input.run(); then_exec->execute(); permute_then_output_to_op_output.run(); } else { auto else_exec = dynamic_cast<exec::ExecutorBase *>(_executor_map->at(_else_subg_index).get()); if (else_exec == nullptr) { throw std::runtime_error{"If: Invalid else subgraph"}; } const auto &else_input_tensors = else_exec->getInputTensors(); const auto &else_output_tensors = else_exec->getOutputTensors(); PermuteLayer permute_op_input_to_else_input{_input_tensors, else_input_tensors, input_ranks}; PermuteLayer permute_else_output_to_op_output{else_output_tensors, _output_tensors, output_ranks}; // Remove copying of unused tensor permute_op_input_to_else_input.prepare(); permute_else_output_to_op_output.prepare(); // Copy & run permute_op_input_to_else_input.run(); else_exec->execute(); permute_else_output_to_op_output.run(); } } } // namespace kernel } // namespace controlflow } // namespace backend } // namespace onert
34.299213
100
0.693756
[ "vector" ]
f267a300088baa36a8ab57622b3e7e5450526fc8
1,450
hpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F7508-DISCO/Demonstrations/TouchGFX/Gui/gui/include/gui/common/FrontendApplication.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F7508-DISCO/Demonstrations/TouchGFX/Gui/gui/include/gui/common/FrontendApplication.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F7508-DISCO/Demonstrations/TouchGFX/Gui/gui/include/gui/common/FrontendApplication.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
/** ****************************************************************************** * This file is part of the TouchGFX 4.10.0 distribution. * * @attention * * Copyright (c) 2018 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ #ifndef FRONTENDAPPLICATION_HPP #define FRONTENDAPPLICATION_HPP #include <gui_generated/common/FrontendApplicationBase.hpp> class FrontendHeap; using namespace touchgfx; class FrontendApplication : public FrontendApplicationBase { public: FrontendApplication(Model& m, FrontendHeap& heap); virtual ~FrontendApplication() { } virtual void handleTickEvent(); virtual void handleClickEvent(const ClickEvent& evt); virtual void handleDragEvent(const DragEvent& evt); void resetScreenSaver(); private: static const int SCREEN_SAVER_TIMEOUT = 180000; // Milliseconds static const int MINOR_TICK_FREQ = 3000 / 17; // Ticks - so Milliseconds / frequency (ms per frame) static const int MAJOR_TICK_FREQ = 10000 / 17; // Ticks - so Milliseconds / frequency (ms per frame) int tickCounter; int screenSaverTick; Time lastClickTime; }; #endif // FRONTENDAPPLICATION_HPP
30.208333
104
0.653793
[ "model" ]
f26801455801cc4e0f8534a6efd7510eaec89680
23,462
cpp
C++
parallel_io/bat_write.cpp
amelvill-umich/libbat
2a0594fa6b6e8d0f4fb776e95ba018396df11de4
[ "MIT" ]
5
2020-04-21T13:00:47.000Z
2022-03-10T06:07:04.000Z
parallel_io/bat_write.cpp
amelvill-umich/libbat
2a0594fa6b6e8d0f4fb776e95ba018396df11de4
[ "MIT" ]
null
null
null
parallel_io/bat_write.cpp
amelvill-umich/libbat
2a0594fa6b6e8d0f4fb776e95ba018396df11de4
[ "MIT" ]
null
null
null
#include "bat_write.h" #include <algorithm> #include <iostream> #include <memory> #include <numeric> #include <string> #include <thread> #include <vector> #include <glm/ext.hpp> #include <glm/glm.hpp> #include <json.hpp> #include <mpi.h> #include <sched.h> #include <stdlib.h> #include <sys/types.h> #include <tbb/global_control.h> #include <unistd.h> #include "aggregator_assignment.h" #include "bat_file.h" #include "binary_particle_file.h" #include "borrowed_array.h" #include "lba_tree_builder.h" #include "particle_data.h" #include "pbat_file.h" #include "profiling.h" #include "util.h" extern "C" BATParticleState bat_io_allocate(void) { auto *pd = new ParticleData; MPI_Comm_rank(MPI_COMM_WORLD, &pd->mpi_rank); MPI_Comm_size(MPI_COMM_WORLD, &pd->mpi_size); return reinterpret_cast<BATParticleState>(pd); } extern "C" void bat_io_free(BATParticleState state) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); delete pd; } extern "C" void bat_io_set_positions(BATParticleState state, void *positions, const uint64_t size, BATDataType btd_type) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); if (btd_type != BTD_VEC3_FLOAT) { std::cerr << "[ERROR] only vec3f positions are supported right now\n"; throw std::runtime_error("only vec3f positions are supported right now"); } const DTYPE type = static_cast<DTYPE>(btd_type); pd->positions = std::make_shared<BorrowedArray<glm::vec3>>( reinterpret_cast<glm::vec3 *>(positions), size * dtype_stride(type)); pd->num_particles = size; } extern "C" void bat_io_set_attribute(BATParticleState state, const char *name, void *data, const uint64_t size, BATDataType btd_type) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); const DTYPE type = static_cast<DTYPE>(btd_type); auto array = std::make_shared<BorrowedArray<uint8_t>>(reinterpret_cast<uint8_t *>(data), size * dtype_stride(type)); const std::string attrib_name = name; auto fnd = pd->attribute_indices.find(attrib_name); if (fnd != pd->attribute_indices.end()) { pd->attributes[fnd->second] = Attribute(AttributeDescription(attrib_name, type), array); } else { pd->attribute_indices[attrib_name] = pd->attributes.size(); pd->attributes.emplace_back(AttributeDescription(attrib_name, type), array); } } extern "C" void bat_io_set_local_bounds(BATParticleState state, const float *bounds) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); pd->local_bounds = Box(bounds); } extern "C" void bat_io_set_bytes_per_subfile(BATParticleState state, const uint64_t size) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); pd->max_bytes_per_subfile = size; } extern "C" void bat_io_set_find_best_axis(BATParticleState state, const uint32_t find_best) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); pd->options.find_best_axis = find_best != 0; } extern "C" void bat_io_set_max_split_imbalance_ratio(BATParticleState state, const float ratio) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); pd->options.max_split_imbalance_ratio = ratio; } extern "C" void bat_io_set_max_overfull_aggregator_factor(BATParticleState state, const float factor) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); pd->options.max_overfull_aggregator_factor = factor; } extern "C" void bat_io_set_build_local_trees(BATParticleState state, const uint32_t build_local) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); pd->options.build_local_trees = build_local != 0; } extern "C" void bat_io_set_fixed_aggregation(BATParticleState state, const uint32_t num_aggregators) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); pd->options.fixed_num_aggregators = num_aggregators; } extern "C" uint64_t bat_io_write(BATParticleState state, const char *cfname) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); pd->perf = WritePerformance(pd->mpi_rank, pd->mpi_size, pd->num_particles); const bool summit_cores = getenv("LIBBAT_SUMMIT_CORES") != nullptr; const int node_cores = summit_cores ? 168 : static_cast<int>(std::thread::hardware_concurrency()); pd->perf.node_core_count = node_cores; const uint64_t bytes_per_particle = std::accumulate( pd->attributes.begin(), pd->attributes.end(), sizeof(glm::vec3), [](const uint64_t sum, const Attribute &attr) { return sum + attr.desc.stride(); }); pd->max_particles_per_aggregator = std::ceil(static_cast<float>(pd->max_bytes_per_subfile) / bytes_per_particle); // Rank 0 needs to do some multi-threaded work here, so adjust our affinity // to get all cores std::unique_ptr<tbb::global_control> tbb_thread_control; cpu_set_t prev_affinity; { const int rc = sched_getaffinity(getpid(), sizeof(cpu_set_t), &prev_affinity); if (rc == -1) { perror("[ERROR] Failed to get schedular affinity for agg tree build"); } } if (pd->mpi_rank == 0) { cpu_set_t all_cores; CPU_ZERO(&all_cores); for (int i = 0; i < node_cores; ++i) { // Note: on Summit cores 84-87 don't exist or are reserved. Same with 172-176 if (summit_cores && i > 83 && i < 88) { continue; } CPU_SET(i, &all_cores); } const int rc = sched_setaffinity(getpid(), sizeof(cpu_set_t), &all_cores); if (rc == -1) { perror("[ERROR] Failed to set schedular affinity for agg tree build"); std::cout << "[ERROR] Failed to set schedular affinity for agg tree build" << "\n"; } tbb_thread_control = std::make_unique<tbb::global_control>( tbb::global_control::max_allowed_parallelism, node_cores); } const ProfilingPoint start_aggregator_assignment; // Compute our aggregator rank and the clients (if any) which will send // data to this rank. The client list is empty if this rank is not an aggregator auto aggregator_info = compute_aggregator_assignment(pd); const ProfilingPoint end_aggregator_assignment; if (pd->mpi_rank == 0) { pd->perf.total_agg_assign_time = elapsed_time_ms(start_aggregator_assignment, end_aggregator_assignment); } const ProfilingPoint start_agg_data; // TODO: Should we make subcomms for each group of aggregator and assigned ranks? // TODO: Need to handle chunking for Irecv/Isend if we want to send more than 2GB ParticleData aggregated_data; std::vector<Box> aggregated_bounds; MPI_Request req = MPI_REQUEST_NULL; std::vector<MPI_Request> requests; const bool is_aggregator = !aggregator_info.clients.empty(); if (is_aggregator) { aggregated_bounds.resize(aggregator_info.clients.size()); aggregated_data.mpi_rank = pd->mpi_rank; aggregated_data.mpi_size = pd->mpi_size; aggregated_data.num_particles = std::accumulate(aggregator_info.client_particle_counts.begin(), aggregator_info.client_particle_counts.end(), uint64_t(0), [](const uint64_t acc, const int n) { return acc + uint64_t(n); }); pd->perf.aggregator_num_clients = aggregator_info.clients.size(); pd->perf.aggregator_particle_count = aggregated_data.num_particles; aggregated_data.positions = std::make_shared<OwnedArray<glm::vec3>>(aggregated_data.num_particles); for (const auto &attr : pd->attributes) { auto array = std::make_shared<OwnedArray<uint8_t>>(aggregated_data.num_particles * attr.desc.stride()); aggregated_data.attributes.emplace_back(attr.desc, array); } // Post irecvs for all incoming client data, into a single set of buffers // Offset in # of particles size_t recv_offset = 0; for (size_t i = 0; i < aggregator_info.clients.size(); ++i) { const int client = aggregator_info.clients[i]; const int num_client_particles = aggregator_info.client_particle_counts[i]; MPI_Irecv( &aggregated_bounds[i], sizeof(Box), MPI_BYTE, client, 0, MPI_COMM_WORLD, &req); requests.push_back(req); if (num_client_particles > 0) { MPI_Irecv(aggregated_data.positions->data() + recv_offset, sizeof(glm::vec3) * num_client_particles, MPI_BYTE, client, 0, MPI_COMM_WORLD, &req); requests.push_back(req); for (auto &attr : aggregated_data.attributes) { MPI_Irecv(attr.at(recv_offset), attr.desc.stride() * num_client_particles, MPI_BYTE, client, 0, MPI_COMM_WORLD, &req); requests.push_back(req); } recv_offset += num_client_particles; } } } // Send our data to our assigned aggregator MPI_Isend(&pd->local_bounds, sizeof(Box), MPI_BYTE, aggregator_info.aggregator_rank, 0, MPI_COMM_WORLD, &req); requests.push_back(req); if (pd->num_particles > 0) { MPI_Isend(pd->positions->data(), sizeof(glm::vec3) * pd->num_particles, MPI_BYTE, aggregator_info.aggregator_rank, 0, MPI_COMM_WORLD, &req); requests.push_back(req); for (const auto &attr : pd->attributes) { MPI_Isend(attr.at(0), attr.desc.stride() * pd->num_particles, MPI_BYTE, aggregator_info.aggregator_rank, 0, MPI_COMM_WORLD, &req); requests.push_back(req); } } MPI_Waitall(requests.size(), requests.data(), MPI_STATUS_IGNORE); const ProfilingPoint end_agg_data; pd->perf.assigned_aggregator = aggregator_info.aggregator_rank; pd->perf.aggregator_send_time = elapsed_time_ms(start_agg_data, end_agg_data); if (is_aggregator) { pd->perf.aggregator_recv_time = elapsed_time_ms(start_agg_data, end_agg_data); } if (pd->mpi_rank == 0 && !is_aggregator) { throw std::runtime_error("Rank 0 is not an aggregator!?"); } // Split a comm for the aggregators to communicate with rank 0 MPI_Comm aggregator_comm = MPI_COMM_NULL; MPI_Comm_split(MPI_COMM_WORLD, is_aggregator ? 1 : 0, pd->mpi_rank, &aggregator_comm); int num_aggregators = 0; MPI_Comm_size(aggregator_comm, &num_aggregators); // For each aggregator, determine how many others are on its node so we // can adjust the thread affinity to share the cores effectively between // the local aggregators. MPI_Comm local_aggregator_comm = MPI_COMM_NULL; MPI_Comm_split_type(aggregator_comm, MPI_COMM_TYPE_SHARED, pd->mpi_rank, MPI_INFO_NULL, &local_aggregator_comm); int local_aggregator_rank = 0; int num_local_aggregators = 0; MPI_Comm_rank(local_aggregator_comm, &local_aggregator_rank); MPI_Comm_size(local_aggregator_comm, &num_local_aggregators); if (is_aggregator) { int extra_core_offset = 0; int threads_per_aggregator = node_cores / num_local_aggregators; const int remainder_threads = node_cores % num_local_aggregators; if (remainder_threads != 0) { extra_core_offset += std::min(local_aggregator_rank, remainder_threads); if (remainder_threads - local_aggregator_rank > 0) { threads_per_aggregator++; } } int start_core = local_aggregator_rank * threads_per_aggregator + extra_core_offset; int end_core = local_aggregator_rank * threads_per_aggregator + extra_core_offset + threads_per_aggregator; // Note: on Summit cores 84-87 don't exist or are reserved. Same with 172-176 if (summit_cores) { if (start_core > 83) { start_core += 4; } if (end_core > 83) { end_core += 4; } } cpu_set_t agg_cores; CPU_ZERO(&agg_cores); for (int i = start_core; i < end_core; ++i) { CPU_SET(i, &agg_cores); } const int rc = sched_setaffinity(getpid(), sizeof(cpu_set_t), &agg_cores); if (rc == -1) { perror("[ERROR] Failed to set schedular affinity for aggregator sharing"); } tbb_thread_control = std::make_unique<tbb::global_control>( tbb::global_control::max_allowed_parallelism, threads_per_aggregator); pd->perf.aggregator_num_cores = threads_per_aggregator; } MPI_Comm_free(&local_aggregator_comm); // Global bounds and attribute info for the top-level metadata Box global_bounds; std::vector<AttributeDescription> attribute_info; std::vector<uint32_t> aggregator_attribute_bitmaps; std::vector<glm::vec2> aggregator_attribute_ranges; size_t aggregator_tree_bytes = 0; const std::string file_name = std::string(cfname); if (is_aggregator) { std::shared_ptr<OwnedArray<glm::vec3>> positions = std::dynamic_pointer_cast<OwnedArray<glm::vec3>>(aggregated_data.positions); if (pd->options.build_local_trees) { BATree tree; if (aggregated_data.num_particles > 0) { const ProfilingPoint start_build_tree; auto builder = LBATreeBuilder(std::move(positions->array), aggregated_data.attributes); const ProfilingPoint end_build_tree; tree = builder.compact(); const ProfilingPoint end_compact_tree; pd->perf.bat_tree_time = elapsed_time_ms(start_build_tree, end_build_tree); pd->perf.bat_tree_compact_time = elapsed_time_ms(end_build_tree, end_compact_tree); pd->perf.bat_tree_cpu_use = cpu_utilization(start_build_tree, end_build_tree); const std::string fname = file_name + std::to_string(pd->mpi_rank) + ".bat"; const ProfilingPoint start_write_file; aggregator_tree_bytes = write_ba_tree(fname, tree); const ProfilingPoint end_write_file; pd->perf.data_write_time = elapsed_time_ms(start_write_file, end_write_file); pd->perf.aggregator_file_size = aggregator_tree_bytes; } // Send our bounding box to rank 0 and do a min/max across the ranks to compute // the global data bounds const Box aggregator_bounds = std::accumulate(aggregated_bounds.begin(), aggregated_bounds.end(), Box(), [](const Box &b, const Box &a) { return box_union(b, a); }); MPI_Barrier(aggregator_comm); const ProfilingPoint start_pbat_gather; MPI_Reduce(&aggregator_bounds.lower.x, &global_bounds.lower.x, 3, MPI_FLOAT, MPI_MIN, 0, aggregator_comm); MPI_Reduce(&aggregator_bounds.upper.x, &global_bounds.upper.x, 3, MPI_FLOAT, MPI_MAX, 0, aggregator_comm); if (pd->mpi_rank == 0) { std::transform(pd->attributes.begin(), pd->attributes.end(), std::back_inserter(attribute_info), [](const Attribute &a) { return a.desc; }); aggregator_attribute_ranges.resize(attribute_info.size() * num_aggregators); aggregator_attribute_bitmaps.resize(attribute_info.size() * num_aggregators); } const glm::vec2 empty_range(std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity()); for (size_t i = 0; i < pd->attributes.size(); ++i) { const glm::vec2 *r = aggregated_data.num_particles > 0 ? &tree.attributes[i].range : &empty_range; MPI_Gather(r, 2, MPI_FLOAT, &aggregator_attribute_ranges[i * num_aggregators], 2, MPI_FLOAT, 0, aggregator_comm); const uint32_t root_bitmap = aggregated_data.num_particles > 0 ? tree.bitmap_dictionary->at(tree.node_bitmap_ids->at(i)) : 0; MPI_Gather(&root_bitmap, 1, MPI_UNSIGNED, &aggregator_attribute_bitmaps[i * num_aggregators], 1, MPI_UNSIGNED, 0, aggregator_comm); } const ProfilingPoint end_pbat_gather; pd->perf.pbat_data_gather_time = elapsed_time_ms(start_pbat_gather, end_pbat_gather); } else if (aggregated_data.num_particles > 0) { BinaryParticleDump dump; dump.points = positions; dump.attribs = aggregated_data.attributes; const std::string fname = file_name + std::to_string(pd->mpi_rank) + ".bp"; const ProfilingPoint start_write_file; aggregator_tree_bytes = write_binary_particle_file(fname, dump); const ProfilingPoint end_write_file; pd->perf.data_write_time = elapsed_time_ms(start_write_file, end_write_file); pd->perf.aggregator_file_size = aggregator_tree_bytes; } } MPI_Barrier(MPI_COMM_WORLD); size_t pbat_bytes = 0; if (pd->mpi_rank == 0 && pd->options.build_local_trees) { const std::string pbat_name = file_name + ".pbat"; aggregator_info.tree.bat_prefix = get_file_basename(file_name); aggregator_info.tree.bounds = global_bounds; aggregator_info.tree.initialize_attributes( attribute_info, aggregator_attribute_bitmaps, aggregator_attribute_ranges); const ProfilingPoint pbat_write_start; pbat_bytes = write_pba_tree(pbat_name, aggregator_info.tree); const ProfilingPoint pbat_write_end; pd->perf.pbat_write_time = elapsed_time_ms(pbat_write_start, pbat_write_end); pd->perf.pbat_file_size = pbat_bytes; } // Compute the total number of bytes we wrote uint64_t local_bytes = pbat_bytes + aggregator_tree_bytes; uint64_t global_bytes = 0; if (is_aggregator) { MPI_Reduce(&local_bytes, &global_bytes, 1, MPI_UNSIGNED_LONG_LONG, MPI_SUM, 0, aggregator_comm); } MPI_Comm_free(&aggregator_comm); // Restore the original thread affinity being used by the simulation sched_setaffinity(getpid(), sizeof(cpu_set_t), &prev_affinity); tbb_thread_control = nullptr; MPI_Bcast(&global_bytes, 1, MPI_UNSIGNED_LONG_LONG, 0, MPI_COMM_WORLD); pd->perf.total_bytes_written = global_bytes; return global_bytes; } const char *bat_io_get_performance_statistics(BATParticleState state) { ParticleData *pd = reinterpret_cast<ParticleData *>(state); std::vector<WritePerformance> perf_stats; if (pd->mpi_rank == 0) { perf_stats.resize(pd->mpi_size, WritePerformance()); } MPI_Gather(&pd->perf, sizeof(WritePerformance), MPI_BYTE, perf_stats.data(), sizeof(WritePerformance), MPI_BYTE, 0, MPI_COMM_WORLD); if (pd->mpi_rank == 0) { using json = nlohmann::json; json info; info["mpi_size"] = pd->perf.mpi_size; info["node_core_count"] = pd->perf.node_core_count; info["total_bytes_written"] = pd->perf.total_bytes_written; json &rank_info = info["ranks"]; for (const auto &perf : perf_stats) { json &rank = rank_info[perf.mpi_rank]; rank["mpi_rank"] = perf.mpi_rank; rank["local_particle_count"] = perf.local_particle_count; rank["assigned_aggregator"] = perf.assigned_aggregator; rank["aggregator_send_time"] = perf.aggregator_send_time; if (perf.mpi_rank == 0) { rank["agg_tree_time"] = perf.agg_tree_time; rank["agg_tree_cpu_use"] = perf.agg_tree_cpu_use; rank["agg_assign_distrib_time"] = perf.agg_assign_distrib_time; rank["agg_info_distrib_time"] = perf.agg_info_distrib_time; rank["agg_list_distrib_time"] = perf.agg_list_distrib_time; rank["total_agg_assign_time"] = perf.total_agg_assign_time; rank["pbat_write_time"] = perf.pbat_write_time; rank["pbat_file_size"] = perf.pbat_file_size; } if (perf.aggregator_num_clients > 0) { rank["aggregator_num_clients"] = perf.aggregator_num_clients; rank["aggregator_particle_count"] = perf.aggregator_particle_count; rank["aggregator_recv_time"] = perf.aggregator_recv_time; rank["aggregator_num_cores"] = perf.aggregator_num_cores; rank["bat_tree_time"] = perf.bat_tree_time; rank["bat_tree_compact_time"] = perf.bat_tree_compact_time; rank["bat_tree_cpu_use"] = perf.bat_tree_cpu_use; rank["data_write_time"] = perf.data_write_time; rank["aggregator_file_size"] = perf.aggregator_file_size; rank["syncd_pbat_data_gather_time"] = perf.pbat_data_gather_time; } } pd->perf_json = info.dump(); return pd->perf_json.c_str(); } return NULL; }
40.945899
95
0.595303
[ "vector", "transform" ]
f26acd143be841558508c5f61a76e2d6bbf585c5
712
cpp
C++
60_getPermutation.cpp
imxiaobo/leetcode-solutions
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
[ "MIT" ]
null
null
null
60_getPermutation.cpp
imxiaobo/leetcode-solutions
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
[ "MIT" ]
null
null
null
60_getPermutation.cpp
imxiaobo/leetcode-solutions
a59c4c9fa424787771c8faca7ba444cae4ed6a4e
[ "MIT" ]
null
null
null
class Solution { public: // n = 3, k = 5 string getPermutation(int n, int k) { string result; vector<int> factorial; vector<int> digits; factorial.push_back(1); for (int x = 1; x <= n; ++x) { factorial.push_back(x * factorial.back()); digits.push_back(x); } // for (k; n > 0; --n) for (k--; n > 0; --n) { // int digit = digits[(k / factorial - 1 + n) % n]; int digit = digits[k / factorial[n - 1]]; // cout << (k / factorial[n - 1]) << " : " << digit << endl; result.push_back(digit + '0'); digits.erase(remove(digits.begin(), digits.end(), digit), digits.end()); k %= factorial[n - 1]; } return result; } };
20.941176
78
0.508427
[ "vector" ]
f283cab5a64454df28d28ff3ed0c40c319a9611a
66,690
cpp
C++
src/CQChartsViewSettings.cpp
Qt-Widgets/CQCharts
0ee923c5a2794b9e3845d0d88fa519fcdea7694a
[ "MIT" ]
null
null
null
src/CQChartsViewSettings.cpp
Qt-Widgets/CQCharts
0ee923c5a2794b9e3845d0d88fa519fcdea7694a
[ "MIT" ]
null
null
null
src/CQChartsViewSettings.cpp
Qt-Widgets/CQCharts
0ee923c5a2794b9e3845d0d88fa519fcdea7694a
[ "MIT" ]
null
null
null
#include <CQChartsViewSettings.h> #include <CQChartsModelDetailsWidget.h> #include <CQChartsWindow.h> #include <CQChartsView.h> #include <CQChartsPlot.h> #include <CQChartsFilterEdit.h> #include <CQChartsPropertyViewTree.h> #include <CQChartsLoadModelDlg.h> #include <CQChartsCreatePlotDlg.h> #include <CQChartsCreateAnnotationDlg.h> #include <CQChartsEditAnnotationDlg.h> #include <CQChartsModelData.h> #include <CQChartsModelDetails.h> #include <CQChartsAnnotation.h> #include <CQChartsTitleEdit.h> #include <CQChartsKeyEdit.h> #include <CQChartsAxisEdit.h> #include <CQChartsKey.h> #include <CQCharts.h> #include <CQChartsVariant.h> #include <CQChartsUtil.h> #include <CQColorsEditCanvas.h> #include <CQColorsEditControl.h> #include <CQColorsEditList.h> #include <CQColors.h> #include <CQColorsTheme.h> #include <CQPropertyViewItem.h> #include <CQTableWidget.h> #include <CQTabWidget.h> #include <CQTabSplit.h> #include <CQIconCombo.h> #include <CQIntegerSpin.h> #include <CQUtil.h> #include <CQGroupBox.h> #include <CQToolTip.h> #include <QTextBrowser> #include <QHeaderView> #include <QSpinBox> #include <QRadioButton> #include <QCheckBox> #include <QPushButton> #include <QToolButton> #include <QLabel> #include <QVBoxLayout> #include <QPainter> #include <QFileDialog> #include <QDir> #include <svg/info_svg.h> #include <fstream> #include <iostream> class CQChartsPlotTipLabel : public QLabel { public: CQChartsPlotTipLabel() { setWordWrap(true); } void setText(const QString &text) { QLabel::setText(text); updateSize(); } void updateSize() { setWordWrap(false); QFontMetrics fm(font()); QSize s = QLabel::sizeHint(); int w = std::min(s.width(), fm.width("X")*50); setMaximumWidth(w); setWordWrap(true); size_ = QLabel::sizeHint(); setMaximumWidth(QWIDGETSIZE_MAX); resize(size_); } QSize sizeHint() const { return size_; } public: QSize size_; }; class CQChartsPlotTip : public CQToolTipIFace { public: CQChartsPlotTip() : CQToolTipIFace() { } ~CQChartsPlotTip() { delete widget_; } void setPlot(CQChartsPlot *plot) { plot_ = plot; } QWidget *showWidget(const QPoint &p) override { if (! widget_) widget_ = new CQChartsPlotTipLabel; updateWidget(p); return widget_; } void hideWidget() override { delete widget_; widget_ = nullptr; } //bool trackMouse() const override { return true; } bool updateWidget(const QPoint &) override { if (! widget_) return false; if (plot_.isNull()) return false; QString text; QString desc = plot_->type()->description(); int pos = desc.indexOf("</h2>"); if (pos > 0) { QString lhs = desc.mid(0, pos); QString rhs = desc.mid(pos); if (! expanded_) text = lhs + " (" + plot_->id() + ")</h2>\n<p>(<b>PageDown</b> to expand)</p>"; else text = lhs + " (" + plot_->id() + ")" + rhs + "\n<p>(<b>PageUp</b> to collapse)</p>"; } else text = plot_->id(); widget_->setText(text); return true; } bool isHideKey(int key, Qt::KeyboardModifiers mod) const override { if (key == Qt::Key_PageUp || key == Qt::Key_PageDown) return false; return CQToolTipIFace::isHideKey(key, mod); } bool keyPress(int key, Qt::KeyboardModifiers mod) override { if (! expanded_) { if (key == Qt::Key_PageDown) { expanded_ = true; return true; } } else { if (key == Qt::Key_PageUp) { expanded_ = false; return true; } } return CQToolTipIFace::keyPress(key, mod); } private: using PlotP = QPointer<CQChartsPlot>; PlotP plot_; CQChartsPlotTipLabel* widget_ { nullptr }; bool expanded_ { false }; }; //------ class CQChartsViewSettingsModelTable : public CQTableWidget { public: CQChartsViewSettingsModelTable() { setObjectName("modelTable"); horizontalHeader()->setStretchLastSection(true); setSelectionBehavior(QAbstractItemView::SelectRows); } void updateModels(CQCharts *charts) { CQCharts::ModelDatas modelDatas; charts->getModelDatas(modelDatas); clear(); setColumnCount(2); setRowCount(modelDatas.size()); setHorizontalHeaderItem(0, new QTableWidgetItem("Name" )); setHorizontalHeaderItem(1, new QTableWidgetItem("Index")); int i = 0; for (const auto &modelData : modelDatas) { QTableWidgetItem *nameItem = new QTableWidgetItem(modelData->id()); QTableWidgetItem *indItem = new QTableWidgetItem(QString("%1").arg(modelData->ind())); nameItem->setFlags(nameItem->flags() & ~Qt::ItemIsEditable); indItem ->setFlags(indItem ->flags() & ~Qt::ItemIsEditable); setItem(i, 0, nameItem); setItem(i, 1, indItem ); nameItem->setData(Qt::UserRole, modelData->ind()); ++i; } } long selectedModel() const { QList<QTableWidgetItem *> items = selectedItems(); for (int i = 0; i < items.length(); ++i) { QTableWidgetItem *item = items[i]; if (item->column() != 0) continue; bool ok; long ind = CQChartsVariant::toInt(item->data(Qt::UserRole), ok); if (ok) return ind; } return -1; } }; //--- class CQChartsViewSettingsPlotTable : public CQTableWidget { public: CQChartsViewSettingsPlotTable() { setObjectName("plotTable"); horizontalHeader()->setStretchLastSection(true); setSelectionBehavior(QAbstractItemView::SelectRows); } void updatePlots(CQChartsView *view) { // add plots to plot table (id, type and state) clear(); int np = view->numPlots(); setColumnCount(3); setRowCount(np); setHorizontalHeaderItem(0, new QTableWidgetItem("Id" )); setHorizontalHeaderItem(1, new QTableWidgetItem("Type" )); setHorizontalHeaderItem(2, new QTableWidgetItem("State")); for (int i = 0; i < np; ++i) { CQChartsPlot *plot = view->plot(i); //-- // set id item store plot index in user data QTableWidgetItem *idItem = new QTableWidgetItem(plot->id()); idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable); setItem(i, 0, idItem); int ind = view->plotInd(plot); idItem->setData(Qt::UserRole, ind); //-- // set type item QTableWidgetItem *typeItem = new QTableWidgetItem(plot->type()->name()); typeItem->setFlags(typeItem->flags() & ~Qt::ItemIsEditable); setItem(i, 1, typeItem); //-- // set state item QStringList states; if (plot->isOverlay()) states += "overlay"; if (plot->isX1X2 ()) states += "x1x2"; if (plot->isY1Y2 ()) states += "y1y2"; QString stateStr = states.join("|"); if (stateStr == "") stateStr = "normal"; QTableWidgetItem *stateItem = new QTableWidgetItem(stateStr); stateItem->setFlags(stateItem->flags() & ~Qt::ItemIsEditable); setItem(i, 2, stateItem); } } void setCurrentInd(int ind) { int nr = rowCount(); for (int i = 0; i < nr; ++i) { QTableWidgetItem *item = this->item(i, 0); bool ok; long ind1 = CQChartsVariant::toInt(item->data(Qt::UserRole), ok); item->setSelected(ind1 == ind); } } void getSelectedPlots(CQChartsView *view, std::vector<CQChartsPlot *> &plots) { QList<QTableWidgetItem *> items = selectedItems(); for (int i = 0; i < items.length(); ++i) { QTableWidgetItem *item = items[i]; if (item->column() != 0) continue; QString id = item->text(); CQChartsPlot *plot = view->getPlot(id); plots.push_back(plot); } } }; //--- class CQChartsViewSettingsViewAnnotationsTable : public CQTableWidget { public: CQChartsViewSettingsViewAnnotationsTable() { setObjectName("viewTable"); horizontalHeader()->setStretchLastSection(true); verticalHeader()->setVisible(false); setSelectionBehavior(QAbstractItemView::SelectRows); } void updateAnnotations(CQChartsView *view) { clear(); const CQChartsView::Annotations &viewAnnotations = view->annotations(); int nv = viewAnnotations.size(); setColumnCount(2); setRowCount(nv); setHorizontalHeaderItem(0, new QTableWidgetItem("Id" )); setHorizontalHeaderItem(1, new QTableWidgetItem("Type")); for (int i = 0; i < nv; ++i) { CQChartsAnnotation *annotation = viewAnnotations[i]; QTableWidgetItem *idItem = new QTableWidgetItem(annotation->id()); idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable); setItem(i, 0, idItem); int ind = annotation->ind(); idItem->setData(Qt::UserRole, ind); QTableWidgetItem *typeItem = new QTableWidgetItem(annotation->typeName()); typeItem->setFlags(typeItem->flags() & ~Qt::ItemIsEditable); setItem(i, 1, typeItem); } } void getSelectedAnnotations(CQChartsView *view, std::vector<CQChartsAnnotation *> &annotations) { QList<QTableWidgetItem *> items = selectedItems(); for (int i = 0; i < items.length(); ++i) { QTableWidgetItem *item = items[i]; if (item->column() != 0) continue; QString id = item->text(); CQChartsAnnotation *annotation = view->getAnnotationByName(id); if (annotation) annotations.push_back(annotation); } } }; //--- class CQChartsViewSettingsPlotAnnotationsTable : public CQTableWidget { public: CQChartsViewSettingsPlotAnnotationsTable() { setObjectName("plotTable"); horizontalHeader()->setStretchLastSection(true); verticalHeader()->setVisible(false); setSelectionBehavior(QAbstractItemView::SelectRows); } void updateAnnotations(CQChartsPlot *plot) { clear(); if (! plot) return; const CQChartsPlot::Annotations &plotAnnotations = plot->annotations(); int np = plotAnnotations.size(); setColumnCount(2); setRowCount(np); setHorizontalHeaderItem(0, new QTableWidgetItem("Id" )); setHorizontalHeaderItem(1, new QTableWidgetItem("Type")); for (int i = 0; i < np; ++i) { CQChartsAnnotation *annotation = plotAnnotations[i]; QTableWidgetItem *idItem = new QTableWidgetItem(annotation->id()); idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable); setItem(i, 0, idItem); int ind = annotation->ind(); idItem->setData(Qt::UserRole, ind); QTableWidgetItem *typeItem = new QTableWidgetItem(annotation->typeName()); typeItem->setFlags(typeItem->flags() & ~Qt::ItemIsEditable); setItem(i, 1, typeItem); } } void getSelectedAnnotations(CQChartsPlot *plot, std::vector<CQChartsAnnotation *> &annotations) { QList<QTableWidgetItem *> items = selectedItems(); for (int i = 0; i < items.length(); ++i) { QTableWidgetItem *item = items[i]; if (item->column() != 0) continue; QString id = item->text(); CQChartsAnnotation *annotation = plot->getAnnotationByName(id); if (annotation) annotations.push_back(annotation); } } }; //--- class CQChartsViewSettingsViewLayerTable : public CQTableWidget { public: CQChartsViewSettingsViewLayerTable() { setObjectName("viewLayerTable"); horizontalHeader()->setStretchLastSection(true); setSelectionBehavior(QAbstractItemView::SelectRows); } QImage *selectedImage(CQChartsView *view) const { if (! view) return nullptr; QList<QTableWidgetItem *> items = selectedItems(); if (items.length() <= 0) return nullptr; QTableWidgetItem *item = items[0]; bool ok; long l = CQChartsVariant::toInt(item->data(Qt::UserRole), ok); if (! ok) return nullptr; CQChartsBuffer *buffer = nullptr; if (l == 0) buffer = view->objectsBuffer(); else if (l == 1) buffer = view->overlayBuffer(); if (! buffer) return nullptr; QImage *image = buffer->image(); return image; } void initLayers() { if (rowCount() != 0) return; clear(); setColumnCount(3); setRowCount(2); setHorizontalHeaderItem(0, new QTableWidgetItem("Buffer")); setHorizontalHeaderItem(1, new QTableWidgetItem("State" )); setHorizontalHeaderItem(2, new QTableWidgetItem("Rect" )); for (int l = 0; l < 2; ++l) { QTableWidgetItem *item = nullptr; if (l == 0) item = new QTableWidgetItem("Objects"); else item = new QTableWidgetItem("Overlay"); setItem(l, 0, item); item->setData(Qt::UserRole, l); QTableWidgetItem *stateItem = new QTableWidgetItem(""); stateItem->setFlags(stateItem->flags() & ~Qt::ItemIsEditable); setItem(l, 1, stateItem); QTableWidgetItem *rectItem = new QTableWidgetItem(""); rectItem->setFlags(rectItem->flags() & ~Qt::ItemIsEditable); setItem(l, 2, rectItem); } } void updateLayers(CQChartsView *view) { for (int l = 0; l < 2; ++l) { CQChartsBuffer *buffer = nullptr; if (l == 0) buffer = view->objectsBuffer(); else if (l == 1) buffer = view->overlayBuffer(); // QTableWidgetItem *idItem = item(l, 0); QTableWidgetItem *stateItem = item(l, 1); QTableWidgetItem *rectItem = item(l, 2); stateItem->setText(""); QRectF rect = (buffer ? buffer->rect() : QRectF()); QString rectStr = QString("X:%1, Y:%2, W:%3, H:%4"). arg(rect.x()).arg(rect.y()).arg(rect.width()).arg(rect.height()); rectItem->setText(rectStr); } } }; //--- class CQChartsViewSettingsPlotLayerTable : public CQTableWidget { public: CQChartsViewSettingsPlotLayerTable() { setObjectName("plotLayerTable"); horizontalHeader()->setStretchLastSection(true); setSelectionBehavior(QAbstractItemView::SelectRows); } QImage *selectedImage(CQChartsPlot *plot) const { if (! plot) return nullptr; QList<QTableWidgetItem *> items = selectedItems(); if (items.length() <= 0) return nullptr; QTableWidgetItem *item = items[0]; bool ok; long l = CQChartsVariant::toInt(item->data(Qt::UserRole), ok); if (! ok) return nullptr; CQChartsLayer *layer = plot->getLayer((CQChartsLayer::Type) l); if (! layer) return nullptr; CQChartsBuffer *buffer = plot->getBuffer(layer->buffer()); if (! buffer) return nullptr; QImage *image = buffer->image(); return image; } void initLayers() { if (rowCount() != 0) return; int l1 = (int) CQChartsLayer::firstLayer(); int l2 = (int) CQChartsLayer::lastLayer (); clear(); setColumnCount(3); setRowCount(l2 - l1 + 1); setHorizontalHeaderItem(0, new QTableWidgetItem("Layer")); setHorizontalHeaderItem(1, new QTableWidgetItem("State")); setHorizontalHeaderItem(2, new QTableWidgetItem("Rect" )); for (int l = l1; l <= l2; ++l) { int i = l - l1; CQChartsLayer::Type type = (CQChartsLayer::Type) l; QString name = CQChartsLayer::typeName(type); QTableWidgetItem *idItem = new QTableWidgetItem(name); idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable); setItem(i, 0, idItem); idItem->setData(Qt::UserRole, l); QTableWidgetItem *stateItem = new QTableWidgetItem(""); //stateItem->setFlags(stateItem->flags() | Qt::ItemIsEnabled); stateItem->setFlags(stateItem->flags() | Qt::ItemIsUserCheckable); //stateItem->setFlags(stateItem->flags() & ~Qt::ItemIsEditable); setItem(i, 1, stateItem); QTableWidgetItem *rectItem = new QTableWidgetItem(""); rectItem->setFlags(rectItem->flags() & ~Qt::ItemIsEditable); setItem(i, 2, rectItem); } } void updateLayers(CQChartsPlot *plot) { int l1 = (int) CQChartsLayer::firstLayer(); int l2 = (int) CQChartsLayer::lastLayer (); for (int l = l1; l <= l2; ++l) { int i = l - l1; CQChartsLayer::Type type = (CQChartsLayer::Type) l; CQChartsLayer *layer = plot->getLayer(type); const CQChartsBuffer *buffer = (layer ? plot->getBuffer(layer->buffer()) : nullptr); // QTableWidgetItem *idItem = item(i, 0); QTableWidgetItem *stateItem = item(i, 1); QTableWidgetItem *rectItem = item(i, 2); QStringList states; if (layer && layer ->isActive()) states += "active"; if (buffer && buffer->isValid ()) states += "valid"; stateItem->setText(states.join("|")); stateItem->setCheckState((layer && layer->isActive()) ? Qt::Checked : Qt::Unchecked); QRectF rect = (buffer ? buffer->rect() : QRectF()); QString rectStr = QString("X:%1, Y:%2, W:%3, H:%4"). arg(rect.x()).arg(rect.y()).arg(rect.width()).arg(rect.height()); rectItem->setText(rectStr); } } bool getLayerState(CQChartsPlot *plot, int row, CQChartsLayer::Type &type, bool &active) { QTableWidgetItem *nameItem = item(row, 0); QString name = nameItem->text(); type = CQChartsLayer::nameType(name); CQChartsLayer *layer = plot->getLayer(type); if (! layer) return false; QTableWidgetItem *stateItem = item(row, 1); active = (stateItem->checkState() == Qt::Checked); return true; } }; //------ CQChartsViewSettings:: CQChartsViewSettings(CQChartsWindow *window) : QFrame(window), window_(window) { CQChartsView *view = window_->view(); CQCharts *charts = view->charts(); connect(charts, SIGNAL(modelDataAdded(int)), this, SLOT(updateModels())); connect(charts, SIGNAL(modelDataRemoved(int)), this, SLOT(updateModels())); connect(charts, SIGNAL(currentModelChanged(int)), this, SLOT(invalidateModelDetails())); connect(charts, SIGNAL(modelNameChanged(const QString &)), this, SLOT(updateModels())); connect(view, SIGNAL(plotsChanged()), this, SLOT(updatePlots())); connect(view, SIGNAL(plotsReordered()), this, SLOT(updatePlots())); connect(view, SIGNAL(connectDataChanged()), this, SLOT(updatePlots())); connect(view, SIGNAL(currentPlotChanged()), this, SLOT(updateCurrentPlot())); connect(view, SIGNAL(annotationsChanged()), this, SLOT(updateAnnotations())); connect(view, SIGNAL(selectionChanged()), this, SLOT(updateSelection())); connect(window, SIGNAL(themePalettesChanged()), this, SLOT(updatePalettes())); connect(window, SIGNAL(interfacePaletteChanged()), this, SLOT(updateInterface())); //-- setObjectName("settings"); setAutoFillBackground(true); addWidgets(); } CQChartsViewSettings:: ~CQChartsViewSettings() { //delete propertiesWidgets_.plotTip; } void CQChartsViewSettings:: addWidgets() { QVBoxLayout *layout = CQUtil::makeLayout<QVBoxLayout>(this, 2, 2); tab_ = CQUtil::makeWidget<CQTabWidget>("tab"); layout->addWidget(tab_); tab_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); //---- // Properties Tab QFrame *propertiesFrame = CQUtil::makeWidget<QFrame>("propertiesFrame"); tab_->addTab(propertiesFrame, "Properties"); initPropertiesFrame(propertiesFrame); //-- // Models Tab QFrame *modelsFrame = CQUtil::makeWidget<QFrame>("modelsFrame"); tab_->addTab(modelsFrame, "Models"); initModelsFrame(modelsFrame); //-- // Plots Tab QFrame *plotsFrame = CQUtil::makeWidget<QFrame>("plotsFrame"); tab_->addTab(plotsFrame, "Plots"); initPlotsFrame(plotsFrame); //-- // Annotations Tab QFrame *annotationsFrame = CQUtil::makeWidget<QFrame>("annotationsFrame"); tab_->addTab(annotationsFrame, "Annotations"); initAnnotationsFrame(annotationsFrame); //-- // Theme Tab QFrame *themeFrame = CQUtil::makeWidget<QFrame>("themeFrame"); tab_->addTab(themeFrame, "Colors"); initThemeFrame(themeFrame); //-- // Layers Tab QFrame *layersFrame = CQUtil::makeWidget<QFrame>("layersFrame"); tab_->addTab(layersFrame, "Layers"); initLayersFrame(layersFrame); //---- updateModels(); updateAnnotations(); } //------ void CQChartsViewSettings:: initPropertiesFrame(QFrame *propertiesFrame) { auto createPushButton = [&](const QString &label, const QString &objName, const QString &tipStr, const char *slotName) { QPushButton *button = CQUtil::makeLabelWidget<QPushButton>(label, objName); button->setToolTip(tipStr); connect(button, SIGNAL(clicked()), this, slotName); return button; }; //--- CQChartsView *view = window_->view(); QVBoxLayout *propertiesLayout = CQUtil::makeLayout<QVBoxLayout>(propertiesFrame, 2, 2); //-- CQTabSplit *propertiesSplit = CQUtil::makeWidget<CQTabSplit>("propertiesSplit"); propertiesSplit->setOrientation(Qt::Vertical); propertiesSplit->setGrouped(true); propertiesLayout->addWidget(propertiesSplit); //---- // Create View Properties Frame QFrame *viewFrame = CQUtil::makeWidget<QFrame>("viewFrame"); QVBoxLayout *viewFrameLayout = CQUtil::makeLayout<QVBoxLayout>(viewFrame, 2, 2); propertiesSplit->addWidget(viewFrame, "View"); //-- propertiesWidgets_.viewPropertyTree = new CQChartsViewSettingsViewPropertiesWidget(this, view); viewFrameLayout->addWidget(propertiesWidgets_.viewPropertyTree); //-- QFrame *viewEditFrame = CQUtil::makeWidget<QFrame>("viewEditFrame"); QHBoxLayout *viewEditFrameLayout = CQUtil::makeLayout<QHBoxLayout>(viewEditFrame, 2, 2); QPushButton *viewKeyButton = createPushButton("Key" , "key" , "Edit View Key" , SLOT(editViewKeySlot())); QPushButton *viewWriteButton = createPushButton("Write", "write", "Write View Script", SLOT(writeViewSlot())); viewEditFrameLayout->addWidget(viewKeyButton); viewEditFrameLayout->addWidget(viewWriteButton); viewEditFrameLayout->addStretch(1); viewFrameLayout->addWidget(viewEditFrame); //---- // Create Plots Properties Frame QFrame *plotsFrame = CQUtil::makeWidget<QFrame>("plotsFrame"); QVBoxLayout *plotsFrameLayout = CQUtil::makeLayout<QVBoxLayout>(plotsFrame, 2, 2); propertiesSplit->addWidget(plotsFrame, "Plots"); //-- propertiesWidgets_.plotsTab = CQUtil::makeWidget<CQTabWidget>("tab"); plotsFrameLayout->addWidget(propertiesWidgets_.plotsTab); connect(propertiesWidgets_.plotsTab, SIGNAL(currentChanged(int)), this, SLOT(plotsTabChangedSlot())); //-- QFrame *plotEditFrame = CQUtil::makeWidget<QFrame>("plotEditFrame"); QHBoxLayout *plotEditFrameLayout = CQUtil::makeLayout<QHBoxLayout>(plotEditFrame, 2, 2); QPushButton *plotTitleButton = createPushButton("Title" , "title", "Edit Plot Title" , SLOT(editPlotTitleSlot())); QPushButton *plotKeyButton = createPushButton("Key" , "key" , "Edit Plot Key" , SLOT(editPlotKeySlot())); QPushButton *plotXAxisButton = createPushButton("X Axis", "xaxis", "Edit Plot X Axis" , SLOT(editPlotXAxisSlot())); QPushButton *plotYAxisButton = createPushButton("Y Axis", "yaxis", "Edit Plot Y Axis" , SLOT(editPlotYAxisSlot())); QPushButton *plotWriteButton = createPushButton("Write" , "write", "Write Plot Script", SLOT(writePlotSlot())); plotEditFrameLayout->addWidget(plotTitleButton); plotEditFrameLayout->addWidget(plotKeyButton); plotEditFrameLayout->addWidget(plotXAxisButton); plotEditFrameLayout->addWidget(plotYAxisButton); plotEditFrameLayout->addWidget(plotWriteButton); plotEditFrameLayout->addStretch(1); plotsFrameLayout->addWidget(plotEditFrame); //-- #if 0 propertiesWidgets_.plotTip = new CQChartsPlotTip; propertiesWidgets_.plotTipButton = new QToolButton; propertiesWidgets_.plotTipButton->setIcon(CQPixmapCacheInst->getIcon("INFO")); plotsFrame->setCornerWidget(propertiesWidgets_.plotTipButton); CQToolTip::setToolTip(propertiesWidgets_.plotTipButton, propertiesWidgets_.plotTip); #endif //--- int i1 = INT_MAX*0.4; int i2 = INT_MAX - i1; propertiesSplit->setSizes(QList<int>({i1, i2})); } void CQChartsViewSettings:: initModelsFrame(QFrame *modelsFrame) { QVBoxLayout *modelsFrameLayout = CQUtil::makeLayout<QVBoxLayout>(modelsFrame, 2, 2); //---- CQTabSplit *modelsSplit = CQUtil::makeWidget<CQTabSplit>("modelsSplit"); modelsSplit->setOrientation(Qt::Vertical); modelsFrameLayout->addWidget(modelsSplit); //---- // Models Frame QFrame *modelsModelsFrame = CQUtil::makeWidget<QFrame>("modelsModelsFrame"); QVBoxLayout *modelsModelsFrameLayout = CQUtil::makeLayout<QVBoxLayout>(modelsModelsFrame, 2, 2); modelsSplit->addWidget(modelsModelsFrame, "Models"); //-- modelsWidgets_.modelTable = new CQChartsViewSettingsModelTable; connect(modelsWidgets_.modelTable, SIGNAL(itemSelectionChanged()), this, SLOT(modelsSelectionChangeSlot())); modelsModelsFrameLayout->addWidget(modelsWidgets_.modelTable); //---- // Model Details modelsWidgets_.detailsFrame = CQUtil::makeWidget<QFrame>("detailsFrame"); QVBoxLayout *detailsFrameLayout = CQUtil::makeLayout<QVBoxLayout>(modelsWidgets_.detailsFrame, 2, 2); modelsSplit->addWidget(modelsWidgets_.detailsFrame, "Details"); //-- CQChartsView *view = window_->view(); CQCharts *charts = view->charts(); modelsWidgets_.detailsWidget = new CQChartsModelDetailsWidget(charts); detailsFrameLayout->addWidget(modelsWidgets_.detailsWidget); //---- // Model Buttons QHBoxLayout *modelControlLayout = CQUtil::makeLayout<QHBoxLayout>(nullptr, 2, 2); modelsModelsFrameLayout->addLayout(modelControlLayout); //-- auto createPushButton = [&](const QString &label, const QString &objName, const QString &tip, const char *slotName) { QPushButton *button = CQUtil::makeLabelWidget<QPushButton>(label, objName); button->setToolTip(tip); connect(button, SIGNAL(clicked()), this, slotName); return button; }; QPushButton *loadModelButton = createPushButton("Load", "load", "Load Model", SLOT(loadModelSlot())); modelsWidgets_.editButton = createPushButton("Edit", "edit", "Edit Model", SLOT(editModelSlot())); modelsWidgets_.plotButton = createPushButton("Plot", "plot", "Create Plot", SLOT(plotModelSlot())); modelControlLayout->addWidget(loadModelButton); modelControlLayout->addWidget(modelsWidgets_.editButton); modelControlLayout->addWidget(modelsWidgets_.plotButton); modelsWidgets_.editButton->setEnabled(false); modelsWidgets_.plotButton->setEnabled(false); //-- modelControlLayout->addStretch(1); //-- modelsSplit->setSizes(QList<int>({INT_MAX, INT_MAX})); } void CQChartsViewSettings:: initPlotsFrame(QFrame *plotsFrame) { QVBoxLayout *plotsFrameLayout = CQUtil::makeLayout<QVBoxLayout>(plotsFrame, 2, 2); //---- CQGroupBox *plotsGroup = CQUtil::makeLabelWidget<CQGroupBox>("Plots", "plotsGroup"); QVBoxLayout *plotsGroupLayout = CQUtil::makeLayout<QVBoxLayout>(plotsGroup, 2, 2); plotsFrameLayout->addWidget(plotsGroup); //-- plotsWidgets_.plotTable = new CQChartsViewSettingsPlotTable; connect(plotsWidgets_.plotTable, SIGNAL(itemSelectionChanged()), this, SLOT(plotsSelectionChangeSlot())); plotsGroupLayout->addWidget(plotsWidgets_.plotTable); //---- #if 0 QFrame *editFrame = CQUtil::makeWidget<QFrame>("editFrame"); QHBoxLayout *editLayout = CQUtil::makeLayout<QHBoxLayout>(editFrame, 2, 2); QPushButton *titleButton = CQUtil::makeLabelWidget<QPushButton>("Title" , "title"); QPushButton *keyButton = CQUtil::makeLabelWidget<QPushButton>("Key" , "key"); QPushButton *xAxisButton = CQUtil::makeLabelWidget<QPushButton>("X Axis", "xaxis"); QPushButton *yAxisButton = CQUtil::makeLabelWidget<QPushButton>("Y Axis", "yaxis"); connect(titleButton, SIGNAL(clicked()), this, SLOT(editPlotTitleSlot())); connect(keyButton, SIGNAL(clicked()), this, SLOT(editPlotKeySlot())); connect(xAxisButton, SIGNAL(clicked()), this, SLOT(editPlotXAxisSlot())); connect(yAxisButton, SIGNAL(clicked()), this, SLOT(editPlotYAxisSlot())); editLayout->addWidget(titleButton); editLayout->addWidget(keyButton); editLayout->addWidget(xAxisButton); editLayout->addWidget(yAxisButton); editLayout->addStretch(1); plotsFrameLayout->addWidget(editFrame); #endif //---- CQGroupBox *groupPlotsGroup = CQUtil::makeLabelWidget<CQGroupBox>("Group", "groupPlotsGroup"); QVBoxLayout *groupPlotsGroupLayout = CQUtil::makeLayout<QVBoxLayout>(groupPlotsGroup, 2, 2); plotsFrameLayout->addWidget(groupPlotsGroup); //---- QHBoxLayout *groupPlotsCheckLayout = CQUtil::makeLayout<QHBoxLayout>(nullptr, 2, 2); groupPlotsGroupLayout->addLayout(groupPlotsCheckLayout); //-- plotsWidgets_.overlayCheck = CQUtil::makeLabelWidget<QCheckBox>("Overlay", "overlay"); plotsWidgets_.x1x2Check = CQUtil::makeLabelWidget<QCheckBox>("X1/X2" , "x1x2"); plotsWidgets_.y1y2Check = CQUtil::makeLabelWidget<QCheckBox>("Y1/Y2" , "y1y2"); groupPlotsCheckLayout->addWidget(plotsWidgets_.overlayCheck); groupPlotsCheckLayout->addWidget(plotsWidgets_.x1x2Check); groupPlotsCheckLayout->addWidget(plotsWidgets_.y1y2Check); groupPlotsCheckLayout->addStretch(1); //---- QHBoxLayout *groupPlotsButtonsLayout = CQUtil::makeLayout<QHBoxLayout>(nullptr, 2, 2); groupPlotsGroupLayout->addLayout(groupPlotsButtonsLayout); //-- QPushButton *groupApplyButton = CQUtil::makeLabelWidget<QPushButton>("Apply", "apply"); connect(groupApplyButton, SIGNAL(clicked()), this, SLOT(groupPlotsSlot())); groupPlotsButtonsLayout->addWidget(groupApplyButton); //-- groupPlotsButtonsLayout->addStretch(1); //---- CQGroupBox *placePlotsGroup = CQUtil::makeLabelWidget<CQGroupBox>("Place", "placePlotsGroup"); QVBoxLayout *placePlotsGroupLayout = CQUtil::makeLayout<QVBoxLayout>(placePlotsGroup, 2, 2); plotsFrameLayout->addWidget(placePlotsGroup); //-- QHBoxLayout *placePlotsCheckLayout = CQUtil::makeLayout<QHBoxLayout>(nullptr, 2, 2); placePlotsGroupLayout->addLayout(placePlotsCheckLayout); plotsWidgets_.placeVerticalRadio = CQUtil::makeLabelWidget<QRadioButton>("Vertical", "vertical"); plotsWidgets_.placeHorizontalRadio = CQUtil::makeLabelWidget<QRadioButton>("Horizontal", "horizontal"); plotsWidgets_.placeGridRadio = CQUtil::makeLabelWidget<QRadioButton>("Grid", "grid"); plotsWidgets_.placeVerticalRadio->setChecked(true); placePlotsCheckLayout->addWidget(plotsWidgets_.placeVerticalRadio); placePlotsCheckLayout->addWidget(plotsWidgets_.placeHorizontalRadio); placePlotsCheckLayout->addWidget(plotsWidgets_.placeGridRadio); placePlotsCheckLayout->addStretch(1); //-- QHBoxLayout *placePlotsGridLayout = CQUtil::makeLayout<QHBoxLayout>(nullptr, 2, 2); placePlotsGroupLayout->addLayout(placePlotsGridLayout); plotsWidgets_.placeRowsEdit = CQUtil::makeWidget<CQIntegerSpin>("rowsEdit"); plotsWidgets_.placeColumnsEdit = CQUtil::makeWidget<CQIntegerSpin>("columnsEdit"); plotsWidgets_.placeRowsEdit ->setValue(1); plotsWidgets_.placeColumnsEdit->setValue(1); plotsWidgets_.placeRowsEdit ->setMinimum(1); plotsWidgets_.placeColumnsEdit->setMinimum(1); placePlotsGridLayout->addWidget(CQUtil::makeLabelWidget<QLabel>("Rows", "row")); placePlotsGridLayout->addWidget(plotsWidgets_.placeRowsEdit); placePlotsGridLayout->addWidget(CQUtil::makeLabelWidget<QLabel>("Columns", "columns")); placePlotsGridLayout->addWidget(plotsWidgets_.placeColumnsEdit); placePlotsGridLayout->addStretch(1); //-- QHBoxLayout *placePlotsButtonsLayout = CQUtil::makeLayout<QHBoxLayout>(nullptr, 2, 2); placePlotsGroupLayout->addLayout(placePlotsButtonsLayout); QPushButton *placeApplyButton = CQUtil::makeLabelWidget<QPushButton>("Apply", "apply"); placePlotsButtonsLayout->addWidget(placeApplyButton); placePlotsButtonsLayout->addStretch(1); connect(placeApplyButton, SIGNAL(clicked()), this, SLOT(placePlotsSlot())); //---- auto createPushButton = [&](const QString &label, const QString &objName, const char *slotName) { QPushButton *button = CQUtil::makeLabelWidget<QPushButton>(label, objName); connect(button, SIGNAL(clicked()), this, slotName); return button; }; CQGroupBox *controlPlotsGroup = CQUtil::makeLabelWidget<CQGroupBox>("Control", "controlPlotsGroup"); plotsFrameLayout->addWidget(controlPlotsGroup); QHBoxLayout *controlPlotsGroupLayout = CQUtil::makeLayout<QHBoxLayout>(controlPlotsGroup, 2, 2); plotsWidgets_.raiseButton = createPushButton("Raise" , "raise" , SLOT(raisePlotSlot())); plotsWidgets_.lowerButton = createPushButton("Lower" , "lower" , SLOT(lowerPlotSlot())); plotsWidgets_.removeButton = createPushButton("Remove", "remove", SLOT(removePlotsSlot())); //QPushButton* writePlotButton = createPushButton("Write" , "write" , SLOT(writePlotSlot())); plotsWidgets_.raiseButton ->setEnabled(false); plotsWidgets_.lowerButton ->setEnabled(false); plotsWidgets_.removeButton->setEnabled(false); controlPlotsGroupLayout->addWidget(plotsWidgets_.raiseButton); controlPlotsGroupLayout->addWidget(plotsWidgets_.lowerButton); controlPlotsGroupLayout->addWidget(plotsWidgets_.removeButton); //controlPlotsGroupLayout->addWidget(writePlotButton); //--- controlPlotsGroupLayout->addStretch(1); } void CQChartsViewSettings:: initAnnotationsFrame(QFrame *annotationsFrame) { QVBoxLayout *annotationsFrameLayout = CQUtil::makeLayout<QVBoxLayout>(annotationsFrame, 2, 2); //--- CQTabSplit *annotationsSplit = CQUtil::makeWidget<CQTabSplit>("annotationsSplit"); annotationsSplit->setOrientation(Qt::Vertical); annotationsFrameLayout->addWidget(annotationsSplit); //---- // view annotations QFrame *viewFrame = CQUtil::makeWidget<QFrame>("viewFrame"); QVBoxLayout *viewFrameLayout = CQUtil::makeLayout<QVBoxLayout>(viewFrame, 2, 2); //-- annotationsWidgets_.viewTable = new CQChartsViewSettingsViewAnnotationsTable; connect(annotationsWidgets_.viewTable, SIGNAL(itemSelectionChanged()), this, SLOT(viewAnnotationSelectionChangeSlot())); viewFrameLayout->addWidget(annotationsWidgets_.viewTable); //-- annotationsSplit->addWidget(viewFrame, "View"); //---- // plot annotations QFrame *plotFrame = CQUtil::makeWidget<QFrame>("plotFrame"); QVBoxLayout *plotFrameLayout = CQUtil::makeLayout<QVBoxLayout>(plotFrame, 2, 2); //-- annotationsWidgets_.plotTable = new CQChartsViewSettingsPlotAnnotationsTable; connect(annotationsWidgets_.plotTable, SIGNAL(itemSelectionChanged()), this, SLOT(plotAnnotationSelectionChangeSlot())); plotFrameLayout->addWidget(annotationsWidgets_.plotTable); //-- annotationsSplit->addWidget(plotFrame, "Plot"); //---- auto createPushButton = [&](const QString &label, const QString &objName, const char *slotName) { QPushButton *button = CQUtil::makeLabelWidget<QPushButton>(label, objName); connect(button, SIGNAL(clicked()), this, slotName); return button; }; // create annotation buttons CQGroupBox *controlGroup = CQUtil::makeLabelWidget<CQGroupBox>("Control", "controlGroup"); annotationsFrameLayout->addWidget(controlGroup); QHBoxLayout *controlGroupLayout = CQUtil::makeLayout<QHBoxLayout>(controlGroup, 2, 2); QPushButton *createButton = createPushButton("Create", "create", SLOT(createAnnotationSlot())); annotationsWidgets_.editButton = createPushButton("Edit" , "edit" , SLOT(editAnnotationSlot())); annotationsWidgets_.removeButton = createPushButton("Remove", "remove", SLOT(removeAnnotationsSlot())); QPushButton *writeButton = createPushButton("Write" , "write" , SLOT(writeAnnotationSlot())); annotationsWidgets_.editButton ->setEnabled(false); annotationsWidgets_.removeButton->setEnabled(false); controlGroupLayout->addWidget(createButton); controlGroupLayout->addWidget(annotationsWidgets_.editButton); controlGroupLayout->addWidget(annotationsWidgets_.removeButton); controlGroupLayout->addWidget(writeButton); controlGroupLayout->addStretch(1); //-- annotationsSplit->setSizes(QList<int>({INT_MAX, INT_MAX})); } void CQChartsViewSettings:: initThemeFrame(QFrame *themeFrame) { QVBoxLayout *themeFrameLayout = CQUtil::makeLayout<QVBoxLayout>(themeFrame, 2, 2); //-- CQTabWidget *themeSubTab = CQUtil::makeWidget<CQTabWidget>("themeSubTab"); themeFrameLayout->addWidget(themeSubTab); // tab for theme QFrame *themePalettesFrame = CQUtil::makeWidget<QFrame>("themePalettesFrame"); QVBoxLayout *themePalettesFrameLayout = CQUtil::makeLayout<QVBoxLayout>(themePalettesFrame, 2, 2); themeSubTab->addTab(themePalettesFrame, "Theme"); // tab for theme palettes QFrame *palettesFrame = CQUtil::makeWidget<QFrame>("palettesFrame"); QVBoxLayout *palettesFrameLayout = CQUtil::makeLayout<QVBoxLayout>(palettesFrame, 2, 2); themeSubTab->addTab(palettesFrame, "Palettes"); // tab for interface palette QFrame *interfaceFrame = CQUtil::makeWidget<QFrame>("interfaceFrame"); QHBoxLayout *interfaceFrameLayout = CQUtil::makeLayout<QHBoxLayout>(interfaceFrame, 2, 2); themeSubTab->addTab(interfaceFrame, "Interface"); //-- #if 0 QFrame *themeColorsFrame = CQUtil::makeWidget<QFrame>("themeColorsFrame"); QGridLayout *themeColorsLayout = CQUtil::makeLayout<QGridLayout>(themeColorsFrame, 2, 2); QLabel* selColorLabel = CQUtil::makeLabelWidget("Selection", "selColorLabel"); CQLineEdit* selColorEdit = CQUtil::makeWidget<CQLineEdit>("selColorEdit"); themeColorsLayout->addWidget(selColorLabel, 0, 0); themeColorsLayout->addWidget(selColorEdit , 0, 1); QLabel* insColorLabel = CQUtil::makeLabelWidget("Inside", "insColorLabel"); CQLineEdit* insColorEdit = CQUtil::makeWidget<CQLineEdit>("insColorEdit"); themeColorsLayout->addWidget(insColorLabel, 1, 0); themeColorsLayout->addWidget(insColorEdit , 1, 1); paletteLayout->addWidget(themeColorsFrame); #endif //-- CQChartsView *view = window_->view(); CQColorsTheme *theme = view->theme(); //-- // create palettes list themeWidgets_.palettesList = new CQColorsEditList(this); themePalettesFrameLayout->addWidget(themeWidgets_.palettesList); //connect(themeWidgets_.palettesList, SIGNAL(palettesChanged()), this, SLOT(updateView())); //-- // create palettes frame QFrame *palettesControlFrame = CQUtil::makeWidget<QFrame>("control"); QHBoxLayout *palettesControlFrameLayout = CQUtil::makeLayout<QHBoxLayout>(palettesControlFrame, 2, 2); //-- QLabel *paletteNameLabel = CQUtil::makeLabelWidget<QLabel>("Name", "paletteNameLabel"); themeWidgets_.palettesCombo = CQUtil::makeWidget<QComboBox>("palettesCombo"); QStringList paletteNames; CQColorsMgrInst->getPaletteNames(paletteNames); themeWidgets_.palettesCombo->addItems(paletteNames); palettesControlFrameLayout->addWidget(paletteNameLabel); palettesControlFrameLayout->addWidget(themeWidgets_.palettesCombo); connect(themeWidgets_.palettesCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(palettesComboSlot(int))); //-- QPushButton *resetButton = CQUtil::makeLabelWidget<QPushButton>("Reset", "resetButton"); palettesControlFrameLayout->addWidget(resetButton); connect(resetButton, SIGNAL(clicked()), this, SLOT(palettesResetSlot())); //-- palettesControlFrameLayout->addStretch(1); palettesFrameLayout->addWidget(palettesControlFrame); //---- // create palettes splitter and add canvas and control QSplitter *palettesSplitter = CQUtil::makeWidget<QSplitter>("splitter"); palettesSplitter->setOrientation(Qt::Vertical); palettesFrameLayout->addWidget(palettesSplitter); themeWidgets_.palettesPlot = new CQColorsEditCanvas(this, theme->palette()); themeWidgets_.palettesControl = new CQColorsEditControl(themeWidgets_.palettesPlot); palettesSplitter->addWidget(themeWidgets_.palettesPlot); palettesSplitter->addWidget(themeWidgets_.palettesControl); connect(themeWidgets_.palettesControl, SIGNAL(stateChanged()), view, SLOT(updatePlots())); connect(themeWidgets_.palettesPlot, SIGNAL(colorsChanged()), this, SLOT(paletteColorsChangedSlot())); //---- // create interface splitter and add canvas and control QSplitter *interfaceSplitter = CQUtil::makeWidget<QSplitter>("splitter"); interfaceSplitter->setOrientation(Qt::Vertical); interfaceFrameLayout->addWidget(interfaceSplitter); themeWidgets_.interfacePlot = new CQColorsEditCanvas(this, view->interfacePalette()); themeWidgets_.interfacePlot->setGray(true); themeWidgets_.interfaceControl = new CQColorsEditControl(themeWidgets_.interfacePlot); interfaceSplitter->addWidget(themeWidgets_.interfacePlot); interfaceSplitter->addWidget(themeWidgets_.interfaceControl); connect(themeWidgets_.interfaceControl, SIGNAL(stateChanged()), view, SLOT(updatePlots())); connect(themeWidgets_.interfacePlot, SIGNAL(colorsChanged()), this, SLOT(paletteColorsChangedSlot())); //--- updatePalettes(); //updatePaletteWidgets(); } void CQChartsViewSettings:: initLayersFrame(QFrame *layersFrame) { QVBoxLayout *layersFrameLayout = CQUtil::makeLayout<QVBoxLayout>(layersFrame, 2, 2); //--- layersWidgets_.viewLayerTable = new CQChartsViewSettingsViewLayerTable; layersWidgets_.viewLayerTable->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); layersFrameLayout->addWidget(layersWidgets_.viewLayerTable); connect(layersWidgets_.viewLayerTable, SIGNAL(itemSelectionChanged()), this, SLOT(viewLayersSelectionChangeSlot())); connect(layersWidgets_.viewLayerTable, SIGNAL(cellClicked(int, int)), this, SLOT(viewLayersClickedSlot(int, int))); //--- layersWidgets_.plotLayerTable = new CQChartsViewSettingsPlotLayerTable; layersWidgets_.plotLayerTable->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); layersFrameLayout->addWidget(layersWidgets_.plotLayerTable); connect(layersWidgets_.plotLayerTable, SIGNAL(itemSelectionChanged()), this, SLOT(plotLayersSelectionChangeSlot())); connect(layersWidgets_.plotLayerTable, SIGNAL(cellClicked(int, int)), this, SLOT(plotLayersClickedSlot(int, int))); //--- QFrame *controlFrame = CQUtil::makeWidget<QFrame>("control"); QHBoxLayout *controlLayout = CQUtil::makeLayout<QHBoxLayout>(controlFrame, 2, 2); layersFrameLayout->addWidget(controlFrame); //-- QPushButton *viewImageButton = CQUtil::makeLabelWidget<QPushButton>("View Image", "viewImage"); controlLayout->addWidget(viewImageButton); connect(viewImageButton, SIGNAL(clicked()), this, SLOT(viewLayerImageSlot())); QPushButton *plotImageButton = CQUtil::makeLabelWidget<QPushButton>("Plot Image", "plotImage"); controlLayout->addWidget(plotImageButton); connect(plotImageButton, SIGNAL(clicked()), this, SLOT(plotLayerImageSlot())); controlLayout->addStretch(1); } //------ class CQChartsViewSettingsLayerImage : public QDialog { public: CQChartsViewSettingsLayerImage() { setWindowTitle("Layer Image"); } void setImage(const QImage &image) { image_ = image; setFixedSize(image_.size()); } void paintEvent(QPaintEvent *) { QPainter p(this); p.drawImage(0, 0, image_); } private: QImage image_; }; //------ void CQChartsViewSettings:: viewLayerImageSlot() { static CQChartsViewSettingsLayerImage *layerImage; //--- CQChartsView *view = window_->view(); if (! view) return; QImage *image = layersWidgets_.viewLayerTable->selectedImage(view); if (! image) return; //--- if (! layerImage) layerImage = new CQChartsViewSettingsLayerImage; layerImage->setImage(*image); layerImage->show(); } void CQChartsViewSettings:: plotLayerImageSlot() { static CQChartsViewSettingsLayerImage *layerImage; //--- CQChartsPlot *plot = window_->view()->currentPlot(); if (! plot) return; QImage *image = layersWidgets_.plotLayerTable->selectedImage(plot); if (! image) return; //--- if (! layerImage) layerImage = new CQChartsViewSettingsLayerImage; layerImage->setImage(*image); layerImage->show(); } //------ CQChartsPropertyViewTree * CQChartsViewSettings:: viewPropertyTree() const { return propertiesWidgets_.viewPropertyTree->propertyTree(); } CQChartsPropertyViewTree * CQChartsViewSettings:: plotPropertyTree(CQChartsPlot *plot) const { for (int i = 0; i < propertiesWidgets_.plotsTab->count(); ++i) { CQChartsViewSettingsPlotPropertiesWidget *plotWidget = qobject_cast<CQChartsViewSettingsPlotPropertiesWidget *>( propertiesWidgets_.plotsTab->widget(i)); assert(plotWidget); if (plotWidget->plot() == plot) return plotWidget->propertyTree(); } return nullptr; } //------ void CQChartsViewSettings:: updateModels() { CQChartsView *view = window_->view(); CQCharts *charts = view->charts(); modelsWidgets_.modelTable->updateModels(charts); //--- invalidateModelDetails(); } void CQChartsViewSettings:: invalidateModelDetails() { CQCharts *charts = window_->view()->charts(); CQChartsModelData *modelData = charts->currentModelData(); CQChartsModelDetails *details = (modelData ? modelData->details() : nullptr); modelsWidgets_.detailsWidget->setDetails(details); } void CQChartsViewSettings:: modelsSelectionChangeSlot() { CQCharts *charts = window_->view()->charts(); long ind = modelsWidgets_.modelTable->selectedModel(); if (ind >= 0) charts->setCurrentModelInd(ind); modelsWidgets_.editButton->setEnabled(ind >= 0); modelsWidgets_.plotButton->setEnabled(ind >= 0); } void CQChartsViewSettings:: loadModelSlot() { CQCharts *charts = window_->view()->charts(); delete loadModelDlg_; loadModelDlg_ = new CQChartsLoadModelDlg(charts); loadModelDlg_->show(); } void CQChartsViewSettings:: editModelSlot() { long ind = modelsWidgets_.modelTable->selectedModel(); if (ind < 0) return; CQCharts *charts = window_->view()->charts(); CQChartsModelData *modelData = charts->getModelData(ind); if (! modelData) return; charts->editModelDlg(modelData); } void CQChartsViewSettings:: plotModelSlot() { long ind = modelsWidgets_.modelTable->selectedModel(); if (ind < 0) return; CQCharts *charts = window_->view()->charts(); CQChartsModelData *modelData = charts->getModelData(ind); if (! modelData) return; CQChartsCreatePlotDlg *createPlotDlg = charts->createPlotDlg(modelData); createPlotDlg->setViewName(window_->view()->id()); } //------ void CQChartsViewSettings:: writeViewSlot() { CQChartsView *view = window_->view(); if (! view) return; QString dir = QDir::current().dirName() + "/view.tcl"; QString fileName = QFileDialog::getSaveFileName(this, "Write View", dir, "Files (*.tcl)"); auto fs = std::ofstream(fileName.toStdString(), std::ofstream::out); //--- view->writeAll(fs); } //------ void CQChartsViewSettings:: plotsTabChangedSlot() { int ind = propertiesWidgets_.plotsTab->currentIndex(); CQChartsViewSettingsPlotPropertiesWidget *plotWidget = qobject_cast<CQChartsViewSettingsPlotPropertiesWidget *>( propertiesWidgets_.plotsTab->widget(ind)); assert(plotWidget); //propertiesWidgets_.plotTip->setPlot(plotWidget->plot()); } //------ void CQChartsViewSettings:: updatePlots() { CQChartsView *view = window_->view(); //--- using PlotSet = std::set<CQChartsPlot *>; int np = view->numPlots(); PlotSet plotSet; for (int i = 0; i < np; ++i) plotSet.insert(view->plot(i)); //--- // add plots to plot table (id, type and state) plotsWidgets_.plotTable->updatePlots(view); //--- auto findPlotTab = [&](CQChartsPlot *plot) { for (int i = 0; i < propertiesWidgets_.plotsTab->count(); ++i) { CQChartsViewSettingsPlotPropertiesWidget *plotWidget = qobject_cast<CQChartsViewSettingsPlotPropertiesWidget *>( propertiesWidgets_.plotsTab->widget(i)); assert(plotWidget); if (plotWidget->plot() == plot) return i; } return -1; }; // add new plots to tabbed property view for (int i = 0; i < np; ++i) { CQChartsPlot *plot = view->plot(i); int ind = findPlotTab(plot); if (ind < 0) { CQChartsViewSettingsPlotPropertiesWidget *plotWidget = new CQChartsViewSettingsPlotPropertiesWidget(this, plot); plotWidget->setObjectName(QString("plotTabWidget_%1"). arg(propertiesWidgets_.plotsTab->count() + 1)); connect(plotWidget, SIGNAL(propertyItemSelected(QObject *, const QString &)), this, SIGNAL(propertyItemSelected(QObject *, const QString &))); ind = propertiesWidgets_.plotsTab->addTab(plotWidget, plot->id()); //propertiesWidgets_.plotsTab->setTabToolTip(ind, plot->type()->description()); } } // remove deleted plots from tab using PlotWidgets = std::vector<CQChartsViewSettingsPlotPropertiesWidget *>; PlotWidgets plotWidgets; for (int i = 0; i < propertiesWidgets_.plotsTab->count(); ++i) { CQChartsViewSettingsPlotPropertiesWidget *plotWidget = qobject_cast<CQChartsViewSettingsPlotPropertiesWidget *>( propertiesWidgets_.plotsTab->widget(i)); assert(plotWidget); if (plotSet.find(plotWidget->plot()) == plotSet.end()) plotWidgets.push_back(plotWidget); } for (auto &plotWidget : plotWidgets) { int ind = propertiesWidgets_.plotsTab->indexOf(plotWidget); assert(ind >= 0); propertiesWidgets_.plotsTab->removeTab(ind); delete plotWidget; } //--- plotsSelectionChangeSlot(); } void CQChartsViewSettings:: updateCurrentPlot() { CQChartsView *view = window_->view(); assert(view); if (plotId_.length()) { CQChartsPlot *plot = view->getPlot(plotId_); if (plot) { disconnect(plot, SIGNAL(annotationsChanged()), this, SLOT(updateAnnotations())); disconnect(plot, SIGNAL(layersChanged()), this, SLOT(updateLayers())); } } //--- int ind = view->currentPlotInd(); plotsWidgets_.plotTable->setCurrentInd(ind); //--- CQChartsPlot *plot = view->currentPlot(); plotId_ = (plot ? plot->id() : ""); if (plot) { connect(plot, SIGNAL(annotationsChanged()), this, SLOT(updateAnnotations())); connect(plot, SIGNAL(layersChanged()), this, SLOT(updateLayers())); } //--- updateAnnotations(); updateLayers(); } CQChartsPlot * CQChartsViewSettings:: getPropertiesPlot() const { CQChartsViewSettingsPlotPropertiesWidget *plotWidget = qobject_cast<CQChartsViewSettingsPlotPropertiesWidget *>( propertiesWidgets_.plotsTab->currentWidget()); if (! plotWidget) return nullptr; return plotWidget->plot(); } CQChartsPlot * CQChartsViewSettings:: getSelectedPlot() const { Plots plots; getSelectedPlots(plots); if (plots.size() == 1) return plots[0]; return nullptr; } void CQChartsViewSettings:: getSelectedPlots(Plots &plots) const { CQChartsView *view = window_->view(); plotsWidgets_.plotTable->getSelectedPlots(view, plots); } void CQChartsViewSettings:: plotsSelectionChangeSlot() { Plots plots; getSelectedPlots(plots); plotsWidgets_.raiseButton->setEnabled(plots.size() == 1); plotsWidgets_.lowerButton->setEnabled(plots.size() == 1); plotsWidgets_.removeButton->setEnabled(plots.size() > 0); //--- CQChartsView *view = window_->view(); view->startSelection(); view->deselectAll(); for (auto &plot : plots) plot->setSelected(true); view->endSelection(); } void CQChartsViewSettings:: editViewKeySlot() { CQChartsView *view = window_->view(); if (! view->key()) return; if (editKeyDlg_) delete editKeyDlg_; editKeyDlg_ = new CQChartsEditKeyDlg(this, view->key()); editKeyDlg_->show(); } void CQChartsViewSettings:: editPlotTitleSlot() { //CQChartsPlot *plot = getSelectedPlot(); CQChartsPlot *plot = getPropertiesPlot(); if (! plot || ! plot->title()) return; if (editTitleDlg_) delete editTitleDlg_; editTitleDlg_ = new CQChartsEditTitleDlg(this, plot->title()); editTitleDlg_->show(); } void CQChartsViewSettings:: editPlotKeySlot() { //CQChartsPlot *plot = getSelectedPlot(); CQChartsPlot *plot = getPropertiesPlot(); if (! plot || ! plot->key()) return; if (editKeyDlg_) delete editKeyDlg_; editKeyDlg_ = new CQChartsEditKeyDlg(this, plot->key()); editKeyDlg_->show(); } void CQChartsViewSettings:: editPlotXAxisSlot() { //CQChartsPlot *plot = getSelectedPlot(); CQChartsPlot *plot = getPropertiesPlot(); if (! plot || ! plot->xAxis()) return; if (editXAxisDlg_) delete editXAxisDlg_; editXAxisDlg_ = new CQChartsEditAxisDlg(this, plot->xAxis()); editXAxisDlg_->show(); } void CQChartsViewSettings:: editPlotYAxisSlot() { //CQChartsPlot *plot = getSelectedPlot(); CQChartsPlot *plot = getPropertiesPlot(); if (! plot || ! plot->yAxis()) return; if (editYAxisDlg_) delete editYAxisDlg_; editYAxisDlg_ = new CQChartsEditAxisDlg(this, plot->yAxis()); editYAxisDlg_->show(); } void CQChartsViewSettings:: groupPlotsSlot() { CQChartsView *view = window_->view(); CQCharts *charts = view->charts(); // get selected plots ? Plots plots; view->getPlots(plots); bool overlay = plotsWidgets_.overlayCheck->isChecked(); bool x1x2 = plotsWidgets_.x1x2Check ->isChecked(); bool y1y2 = plotsWidgets_.y1y2Check ->isChecked(); if (x1x2) { if (plots.size() != 2) { charts->errorMsg("Need 2 plots for x1x2"); return; } view->initX1X2(plots[0], plots[1], overlay, /*reset*/true); } else if (y1y2) { if (plots.size() != 2) { charts->errorMsg("Need 2 plots for y1y2"); return; } view->initY1Y2(plots[0], plots[1], overlay, /*reset*/true); } else if (overlay) { if (plots.size() < 2) { charts->errorMsg("Need 2 or more plots for overlay"); return; } view->initOverlay(plots, /*reset*/true); } else { view->resetGrouping(); } } void CQChartsViewSettings:: placePlotsSlot() { CQChartsView *view = window_->view(); // get selected plots ? Plots plots; view->getPlots(plots); bool vertical = plotsWidgets_.placeVerticalRadio ->isChecked(); bool horizontal = plotsWidgets_.placeHorizontalRadio->isChecked(); int rows = plotsWidgets_.placeRowsEdit ->value(); int columns = plotsWidgets_.placeColumnsEdit ->value(); view->placePlots(plots, vertical, horizontal, rows, columns, /*reset*/true); } void CQChartsViewSettings:: raisePlotSlot() { CQChartsView *view = window_->view(); CQChartsPlot *plot = getSelectedPlot(); if (plot) view->raisePlot(plot); } void CQChartsViewSettings:: lowerPlotSlot() { CQChartsView *view = window_->view(); CQChartsPlot *plot = getSelectedPlot(); if (plot) view->lowerPlot(plot); } void CQChartsViewSettings:: removePlotsSlot() { Plots plots; getSelectedPlots(plots); CQChartsView *view = window_->view(); for (auto &plot : plots) view->removePlot(plot); updateView(); } void CQChartsViewSettings:: writePlotSlot() { CQChartsPlot *plot = getPropertiesPlot(); if (! plot) return; QString dir = QDir::current().dirName() + "/plot.tcl"; QString fileName = QFileDialog::getSaveFileName(this, "Write View", dir, "Files (*.tcl)"); auto fs = std::ofstream(fileName.toStdString(), std::ofstream::out); //--- CQChartsView *view = plot->view(); view->write(fs); CQChartsModelData *modelData = plot->getModelData(); if (modelData) modelData->write(fs); plot->write(fs); } //------ void CQChartsViewSettings:: updateAnnotations() { CQChartsView *view = window_->view(); annotationsWidgets_.viewTable->updateAnnotations(view); //--- CQChartsPlot *plot = view->currentPlot(); annotationsWidgets_.plotTable->updateAnnotations(plot); } void CQChartsViewSettings:: viewAnnotationSelectionChangeSlot() { Annotations viewAnnotations, plotAnnotations; getSelectedAnnotations(viewAnnotations, plotAnnotations); bool anyAnnotations = (viewAnnotations.size() > 0 || plotAnnotations.size() > 0); annotationsWidgets_.editButton ->setEnabled(anyAnnotations); annotationsWidgets_.removeButton->setEnabled(anyAnnotations); if (viewAnnotations.size()) { disconnect(annotationsWidgets_.plotTable, SIGNAL(itemSelectionChanged()), this, SLOT(plotAnnotationSelectionChangeSlot())); annotationsWidgets_.plotTable->selectionModel()->clear(); connect(annotationsWidgets_.plotTable, SIGNAL(itemSelectionChanged()), this, SLOT(plotAnnotationSelectionChangeSlot())); } //--- CQChartsView *view = window_->view(); view->startSelection(); view->deselectAll(); for (auto &annotation : viewAnnotations) annotation->setSelected(true); view->endSelection(); } void CQChartsViewSettings:: plotAnnotationSelectionChangeSlot() { Annotations viewAnnotations, plotAnnotations; getSelectedAnnotations(viewAnnotations, plotAnnotations); bool anyAnnotations = (viewAnnotations.size() > 0 || plotAnnotations.size() > 0); annotationsWidgets_.editButton ->setEnabled(anyAnnotations); annotationsWidgets_.removeButton->setEnabled(anyAnnotations); if (plotAnnotations.size()) { disconnect(annotationsWidgets_.viewTable, SIGNAL(itemSelectionChanged()), this, SLOT(viewAnnotationSelectionChangeSlot())); annotationsWidgets_.viewTable->selectionModel()->clear(); connect(annotationsWidgets_.viewTable, SIGNAL(itemSelectionChanged()), this, SLOT(viewAnnotationSelectionChangeSlot())); } //--- CQChartsView *view = window_->view(); view->startSelection(); view->deselectAll(); for (auto &annotation : plotAnnotations) annotation->setSelected(true); view->endSelection(); } void CQChartsViewSettings:: getSelectedAnnotations(Annotations &viewAnnotations, Annotations &plotAnnotations) const { CQChartsView *view = window_->view(); annotationsWidgets_.viewTable->getSelectedAnnotations(view, viewAnnotations); //--- CQChartsPlot *plot = view->currentPlot(); if (plot) annotationsWidgets_.plotTable->getSelectedAnnotations(plot, plotAnnotations); } void CQChartsViewSettings:: createAnnotationSlot() { CQChartsView *view = window_->view(); CQChartsPlot *plot = view->currentPlot(); if (! plot) return; if (createAnnotationDlg_) delete createAnnotationDlg_; createAnnotationDlg_ = new CQChartsCreateAnnotationDlg(this, plot); createAnnotationDlg_->show(); } void CQChartsViewSettings:: editAnnotationSlot() { Annotations viewAnnotations, plotAnnotations; getSelectedAnnotations(viewAnnotations, plotAnnotations); CQChartsAnnotation *annotation = nullptr; if (! viewAnnotations.empty()) annotation = viewAnnotations[0]; else if (! plotAnnotations.empty()) annotation = plotAnnotations[0]; if (! annotation) return; if (editAnnotationDlg_) delete editAnnotationDlg_; editAnnotationDlg_ = new CQChartsEditAnnotationDlg(this, annotation); editAnnotationDlg_->show(); } void CQChartsViewSettings:: removeAnnotationsSlot() { Annotations viewAnnotations, plotAnnotations; getSelectedAnnotations(viewAnnotations, plotAnnotations); CQChartsView *view = window_->view(); for (const auto &annotation : viewAnnotations) view->removeAnnotation(annotation); CQChartsPlot *plot = view->currentPlot(); if (plot) { for (const auto &annotation : plotAnnotations) plot->removeAnnotation(annotation); } updateView(); } void CQChartsViewSettings:: writeAnnotationSlot() { CQChartsView *view = window_->view(); if (! view) return; QString dir = QDir::current().dirName() + "/annotation.tcl"; QString fileName = QFileDialog::getSaveFileName(this, "Write View", dir, "Files (*.tcl)"); auto fs = std::ofstream(fileName.toStdString(), std::ofstream::out); //--- const CQChartsView::Annotations &viewAnnotations = view->annotations(); for (const auto &annotation : viewAnnotations) annotation->write(fs); //--- CQChartsView::Plots plots; view->getPlots(plots); for (const auto &plot : plots) { const CQChartsPlot::Annotations &plotAnnotations = plot->annotations(); for (const auto &annotation : plotAnnotations) annotation->write(fs); } } //------ void CQChartsViewSettings:: updateSelection() { window_->selectPropertyObjects(); } //------ void CQChartsViewSettings:: palettesComboSlot(int) { QString name = themeWidgets_.palettesCombo->currentText(); CQColorsPalette *palette = CQColorsMgrInst->getNamedPalette(name); themeWidgets_.palettesPlot->setPalette(palette); themeWidgets_.palettesControl->updateState(); } void CQChartsViewSettings:: palettesResetSlot() { QString name = themeWidgets_.palettesCombo->currentText(); CQColorsPalette *palette = CQColorsMgrInst->getNamedPalette(name); if (! palette) return; CQColorsMgrInst->resetPalette(name); updatePalettes(); } void CQChartsViewSettings:: paletteColorsChangedSlot() { updateView(); } void CQChartsViewSettings:: updatePalettes() { updatePaletteWidgets(); QString name = themeWidgets_.palettesCombo->currentText(); CQColorsPalette *palette = CQColorsMgrInst->getNamedPalette(name); themeWidgets_.palettesPlot->setPalette(palette); themeWidgets_.palettesControl->updateState(); updateView(); } void CQChartsViewSettings:: updatePaletteWidgets() { themeWidgets_.palettesCombo->setEnabled(true); } void CQChartsViewSettings:: updateView() { CQChartsView *view = window_->view(); view->updatePlots(); } void CQChartsViewSettings:: updateInterface() { CQChartsView *view = window_->view(); CQColorsPalette *palette = view->interfacePalette(); themeWidgets_.interfacePlot->setPalette(palette); themeWidgets_.interfaceControl->updateState(); } //------ void CQChartsViewSettings:: updateLayers() { layersWidgets_.viewLayerTable->initLayers(); layersWidgets_.plotLayerTable->initLayers(); //--- CQChartsView *view = window_->view(); if (view) layersWidgets_.viewLayerTable->updateLayers(view); CQChartsPlot *plot = (view ? view->currentPlot() : nullptr); if (plot) layersWidgets_.plotLayerTable->updateLayers(plot); } void CQChartsViewSettings:: viewLayersSelectionChangeSlot() { } void CQChartsViewSettings:: viewLayersClickedSlot(int row, int column) { if (column != 1) return; CQChartsView *view = window_->view(); if (row == 0) view->invalidateObjects(); else view->invalidateOverlay(); } void CQChartsViewSettings:: plotLayersSelectionChangeSlot() { } void CQChartsViewSettings:: plotLayersClickedSlot(int row, int column) { if (column != 1) return; CQChartsView *view = window_->view(); CQChartsPlot *plot = (view ? view->currentPlot() : nullptr); if (! plot) return; CQChartsLayer::Type type; bool active; if (! layersWidgets_.plotLayerTable->getLayerState(plot, row, type, active)) return; CQChartsLayer *layer = plot->getLayer(type); if (! layer) return; plot->setLayerActive(type, active); const CQChartsBuffer *buffer = plot->getBuffer(layer->buffer()); if (buffer->type() != CQChartsBuffer::Type::MIDDLE) plot->invalidateLayer(buffer->type()); else plot->drawObjs(); } //------ CQChartsViewSettingsViewPropertiesWidget:: CQChartsViewSettingsViewPropertiesWidget(CQChartsViewSettings *settings, CQChartsView *view) : view_(view) { setObjectName("viewWidget"); QVBoxLayout *layout = CQUtil::makeLayout<QVBoxLayout>(this, 2, 2); //-- propertyTree_ = new CQChartsPropertyViewTree(settings, view->propertyModel()); propertyTree_->setObjectName("propertyTree"); connect(propertyTree_, SIGNAL(itemSelected(QObject *, const QString &)), this, SIGNAL(propertyItemSelected(QObject *, const QString &))); connect(propertyTree_, SIGNAL(filterStateChanged(bool, bool)), this, SLOT(filterStateSlot(bool, bool))); //-- filterEdit_ = new CQChartsViewSettingsFilterEdit(propertyTree_); filterEdit_->setVisible(propertyTree_->isFilterDisplayed()); //-- layout->addWidget(filterEdit_); layout->addWidget(propertyTree_); } void CQChartsViewSettingsViewPropertiesWidget:: filterStateSlot(bool visible, bool focus) { filterEdit_->setVisible(visible); if (focus) filterEdit_->setFocus(); } //------ CQChartsViewSettingsPlotPropertiesWidget:: CQChartsViewSettingsPlotPropertiesWidget(CQChartsViewSettings *settings, CQChartsPlot *plot) : plot_(plot) { setObjectName("plotTabWidget"); QVBoxLayout *layout = CQUtil::makeLayout<QVBoxLayout>(this, 2, 2); //-- propertyTree_ = new CQChartsPropertyViewTree(settings, plot_->propertyModel()); propertyTree_->setObjectName("propertyTree"); connect(propertyTree_, SIGNAL(itemSelected(QObject *, const QString &)), this, SIGNAL(propertyItemSelected(QObject *, const QString &))); connect(propertyTree_, SIGNAL(filterStateChanged(bool, bool)), this, SLOT(filterStateSlot(bool, bool))); //-- filterEdit_ = new CQChartsViewSettingsFilterEdit(propertyTree_); filterEdit_->setVisible(propertyTree_->isFilterDisplayed()); //-- layout->addWidget(filterEdit_); layout->addWidget(propertyTree_); } void CQChartsViewSettingsPlotPropertiesWidget:: filterStateSlot(bool visible, bool focus) { filterEdit_->setVisible(visible); if (focus) filterEdit_->setFocus(); } //------ CQChartsViewSettingsFilterEdit:: CQChartsViewSettingsFilterEdit(CQChartsPropertyViewTree *tree) : tree_(tree) { setObjectName("filterEdit"); QVBoxLayout *layout = CQUtil::makeLayout<QVBoxLayout>(this, 2, 2); filterEdit_ = new CQChartsFilterEdit; connect(filterEdit_, SIGNAL(replaceFilter(const QString &)), this, SLOT(replaceFilterSlot(const QString &))); connect(filterEdit_, SIGNAL(addFilter(const QString &)), this, SLOT(addFilterSlot(const QString &))); connect(filterEdit_, SIGNAL(escapePressed()), this, SLOT(hideFilterSlot())); connect(filterEdit_, SIGNAL(replaceSearch(const QString &)), this, SLOT(replaceSearchSlot(const QString &))); connect(filterEdit_, SIGNAL(addSearch(const QString &)), this, SLOT(addSearchSlot(const QString &))); layout->addWidget(filterEdit_); setFocusProxy(filterEdit_); } void CQChartsViewSettingsFilterEdit:: replaceFilterSlot(const QString &text) { tree_->setFilter(text); } void CQChartsViewSettingsFilterEdit:: addFilterSlot(const QString &text) { //tree_->addFilter(text); tree_->setFilter(text); } void CQChartsViewSettingsFilterEdit:: replaceSearchSlot(const QString &text) { tree_->search(text); } void CQChartsViewSettingsFilterEdit:: addSearchSlot(const QString &text) { //tree_->addSearch(text); tree_->search(text); } void CQChartsViewSettingsFilterEdit:: hideFilterSlot() { tree_->setFilterDisplayed(false); }
24.366094
100
0.703539
[ "vector", "model" ]
f297c6789f23db5fbf1c742891f5e42559ba8b24
7,015
cpp
C++
source/core/Native.cpp
JohnnyCrazy/scripthookvdotnet
ff56a2ffbde0cc6e72ddd718fee615e74f6d1c4a
[ "Zlib" ]
null
null
null
source/core/Native.cpp
JohnnyCrazy/scripthookvdotnet
ff56a2ffbde0cc6e72ddd718fee615e74f6d1c4a
[ "Zlib" ]
1
2015-06-18T18:46:33.000Z
2015-06-18T18:47:06.000Z
source/core/Native.cpp
JohnnyCrazy/scripthookvdotnet
ff56a2ffbde0cc6e72ddd718fee615e74f6d1c4a
[ "Zlib" ]
2
2015-05-06T18:19:04.000Z
2019-08-11T22:03:23.000Z
/** * Copyright (C) 2015 crosire * * 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. */ #include "Native.hpp" #include "ScriptDomain.hpp" #include "Blip.hpp" #include "Camera.hpp" #include "Entity.hpp" #include "Ped.hpp" #include "Player.hpp" #include "Prop.hpp" #include "Rope.hpp" #include "Vector2.hpp" #include "Vector3.hpp" #include "Vehicle.hpp" #include <NativeCaller.h> namespace GTA { namespace Native { using namespace System; using namespace System::Collections::Generic; namespace { private ref struct NativeTask : IScriptTask { virtual void Run() { nativeInit(_hash); for each (auto argument in _arguments) { nativePush64(argument->_data); } _result = nativeCall(); } UINT64 _hash, *_result; array<InputArgument ^> ^_arguments; }; UINT64 ObjectToNative(Object ^value) { if (Object::ReferenceEquals(value, nullptr)) { return 0; } Type ^type = value->GetType(); // Fundamental types if (type == Boolean::typeid) { return static_cast<bool>(value) ? 1 : 0; } if (type == Int32::typeid) { return static_cast<int>(value); } if (type == UInt32::typeid) { return static_cast<unsigned int>(value); } if (type == Single::typeid) { return BitConverter::ToUInt32(BitConverter::GetBytes(static_cast<float>(value)), 0); } if (type == Double::typeid) { return BitConverter::ToUInt32(BitConverter::GetBytes(static_cast<float>(static_cast<double>(value))), 0); } if (type == IntPtr::typeid) { return static_cast<IntPtr>(value).ToInt64(); } if (type == String::typeid) { return ScriptDomain::CurrentDomain->PinString(static_cast<String ^>(value)).ToInt64(); } // Scripting types if (type == Model::typeid) { return static_cast<Model>(value).Hash; } if (IHandleable::typeid->IsAssignableFrom(type)) { return safe_cast<IHandleable ^>(value)->Handle; } throw gcnew InvalidCastException(String::Concat("Unable to cast object of type '", type->FullName, "' to native value")); } Object ^ObjectFromNative(Type ^type, UINT64 *value) { // Fundamental types if (type == Boolean::typeid) { return *reinterpret_cast<const int *>(value) != 0; } if (type == Int32::typeid) { return *reinterpret_cast<const int *>(value); } if (type == UInt32::typeid) { return *reinterpret_cast<const unsigned int *>(value); } if (type == Single::typeid) { return *reinterpret_cast<const float *>(value); } if (type == Double::typeid) { return static_cast<double>(*reinterpret_cast<const float *>(value)); } if (type == String::typeid) { if (*value != 0) { const auto size = static_cast<int>(strlen(reinterpret_cast<const char *>(*value))); const auto bytes = gcnew array<Byte>(size); Runtime::InteropServices::Marshal::Copy(static_cast<IntPtr>(static_cast<Int64>(*value)), bytes, 0, size); return Text::Encoding::UTF8->GetString(bytes); } else { return String::Empty; } } #pragma pack(push, 1) struct NativeVector3 { float x; DWORD _paddingx; float y; DWORD _paddingy; float z; DWORD _paddingz; }; #pragma pack(pop) // Math types if (type == Math::Vector2::typeid) { const auto vec = reinterpret_cast<NativeVector3 *>(value); return gcnew Math::Vector2(vec->x, vec->y); } if (type == Math::Vector3::typeid) { const auto vec = reinterpret_cast<NativeVector3 *>(value); return gcnew Math::Vector3(vec->x, vec->y, vec->z); } const int handle = *reinterpret_cast<int *>(value); // Scripting types if (type == Blip::typeid) { return gcnew Blip(handle); } if (type == Camera::typeid) { return gcnew Camera(handle); } if (type == Entity::typeid) { if (Function::Call<bool>(Hash::DOES_ENTITY_EXIST, handle)) { switch (Function::Call<int>(Hash::GET_ENTITY_TYPE, handle)) { case 1: return gcnew Ped(handle); case 2: return gcnew Vehicle(handle); case 3: return gcnew Prop(handle); } } return nullptr; } if (type == Ped::typeid) { return gcnew Ped(handle); } if (type == PedGroup::typeid) { return gcnew PedGroup(handle); } if (type == Player::typeid) { return gcnew Player(handle); } if (type == Prop::typeid) { return gcnew Prop(handle); } if (type == Rope::typeid) { return gcnew Rope(handle); } if (type == Vehicle::typeid) { return gcnew Vehicle(handle); } throw gcnew InvalidCastException(String::Concat("Unable to cast native value to object of type '", type->FullName, "'")); } } InputArgument::InputArgument(Object ^value) : _data(ObjectToNative(value)) { } OutputArgument::OutputArgument() : _storage(new unsigned char[24]()), InputArgument(IntPtr(_storage)) { } OutputArgument::OutputArgument(Object ^value) : OutputArgument() { *reinterpret_cast<UINT64 *>(_storage) = ObjectToNative(value); } OutputArgument::~OutputArgument() { this->!OutputArgument(); } OutputArgument::!OutputArgument() { delete[] _storage; } generic <typename T> T OutputArgument::GetResult() { return static_cast<T>(ObjectFromNative(T::typeid, reinterpret_cast<UINT64 *>(_data))); } generic <typename T> T Function::Call(Hash hash, ... array<InputArgument ^> ^arguments) { return Call<T>(static_cast<UInt64>(hash), arguments); } void Function::Call(Hash hash, ... array<InputArgument ^> ^arguments) { Call<int>(static_cast<UInt64>(hash), arguments); } generic <typename T> T Function::Call(UInt64 hash, ... array<InputArgument ^> ^arguments) { const auto task = gcnew NativeTask(); task->_hash = hash; task->_arguments = arguments; ScriptDomain::CurrentDomain->ExecuteTask(task); return static_cast<T>(ObjectFromNative(T::typeid, task->_result)); } } }
25.143369
125
0.629366
[ "object", "model" ]
f299e5d556c946426257c7b55a8babc49df4d065
3,506
hh
C++
RAVL2/GUI/DPDisplay3d/DPWindow3d.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/GUI/DPDisplay3d/DPWindow3d.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/GUI/DPDisplay3d/DPWindow3d.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2008, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here #ifndef RAVLGUI_DPWINDOW3D_HEADER #define RAVLGUI_DPWINDOW3D_HEADER 1 //////////////////////////////////////////////////////////////////// //! rcsid="$Id$" //! lib=RavlDPDisplay //! file="Ravl/GUI/DPDisplay3d/DPWindow3d.hh" //! author="Charles Galambos" //! docentry="Ravl.API.Graphics.3D Data Display" #include "Ravl/DP/Port.hh" #include "Ravl/GUI/Window.hh" #include "Ravl/GUI/DPDisplayView3d.hh" #include "Ravl/Threads/Mutex.hh" namespace RavlGUIN { class DPWindow3dC; //! userlevel=Develop //: DP Window base. class DPWindow3dBodyC : public RCBodyVC { public: DPWindow3dBodyC(const StringC &nname,const IndexRange2dC &nWinSize = IndexRange2dC(IndexC(100),IndexC(100))); //: Default constructor. const StringC &Name() const { return name; } //: Access window name. void Init(const IndexRange2dC &size); //: Construct widgets. bool AddObject(const DObject3DC &obj); //: Add object to the display list. bool ReplaceObject(const DObject3DC &obj,bool resetPosition = false); //: This clears the display list then adds 'obj'. bool Clear(); //: Clear the display list. bool Refresh(); //: Refresh the display. bool WindowClosed(); //: Called when window is closed. bool IsOpen() const { return view.IsValid(); } //: Test if view has been created. protected: StringC name; MutexC accessMutex; // Make sure window is only setup at once. WindowC win; IndexRange2dC winSize; DPDisplayView3dC view; UIntT m_layerCount; friend class DPWindow3dC; }; //! userlevel=Normal //: DP Window. class DPWindow3dC : public RCHandleC<DPWindow3dBodyC> { public: DPWindow3dC() {} //: Default constructor. // Creates an invalid handle. DPWindow3dC(const StringC &nname,const IndexRange2dC &nWinSize = IndexRange2dC(IndexC(100), IndexC(100))) : RCHandleC<DPWindow3dBodyC>(*new DPWindow3dBodyC(nname,nWinSize)) {} //: Construct a named window. protected: DPWindow3dC(DPWindow3dBodyC &body) : RCHandleC<DPWindow3dBodyC>(body) {} //: Body constructor. DPWindow3dBodyC &Body() { return RCHandleC<DPWindow3dBodyC>::Body(); } //: Access body. const DPWindow3dBodyC &Body() const { return RCHandleC<DPWindow3dBodyC>::Body(); } //: Access body. public: bool AddObject(const DObject3DC &obj) { return Body().AddObject(obj); } //: Add object to the display list. bool ReplaceObject(const DObject3DC &obj,bool resetPosition = false) { return Body().ReplaceObject(obj,resetPosition); } //: This clears the display list then adds 'obj'. bool Clear() { return Body().Clear(); } //: Clear the display list. bool Refresh() { return Body().Refresh(); } //: Refresh the display. bool WindowClosed() { return Body().WindowClosed(); } //: Called when window is closed. bool IsOpen() const { return Body().IsOpen(); } //: Test if view has been created. friend class DPWindow3dBodyC; }; } #endif
25.591241
113
0.635767
[ "object", "3d" ]
f29d41b41c61da1d4a931a2b2a5ccde3658c1e73
13,822
hpp
C++
Code/L3_Utils/vector.hpp
rishabh00/Catch_Me_If_You_Can
d4e43258a895e9d9984fa3c963d0f081a582a762
[ "Unlicense" ]
null
null
null
Code/L3_Utils/vector.hpp
rishabh00/Catch_Me_If_You_Can
d4e43258a895e9d9984fa3c963d0f081a582a762
[ "Unlicense" ]
null
null
null
Code/L3_Utils/vector.hpp
rishabh00/Catch_Me_If_You_Can
d4e43258a895e9d9984fa3c963d0f081a582a762
[ "Unlicense" ]
null
null
null
/* * SocialLedge.com - Copyright (C) 2013 * * This file is part of free software framework for embedded processors. * You can use it and/or distribute it as long as this copyright header * remains unmodified. The code is free for personal use and requires * permission to use in a commercial product. * * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. * I SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. * * You can reach the author of this software at : * p r e e t . w i k i @ g m a i l . c o m */ /** * @file vector.hpp * @brief Vector Class with a small footprint * @ingroup Utilities * * Version: 05172013 Added at() to ease element access when vector is a pointer. * Version: 06192012 Initial */ #ifndef _VECTOR_H__ #define _VECTOR_H__ #include <stdlib.h> /** * Vector class * @ingroup Utilities * * This vector class can by used as a dynamic array. * This can provide fast-index based retrieval of stored elements * and also provides fast methods to erase or rotate the elements. * The underlining storage uses pointer-based storage and entire * objects are not created or deleted when the vector contents change. * * Usage: * @code * VECTOR<int> intVec; * intVec += 1; * intVec += 2; * intVec += 3; * * intVec.remove(2); // Vector now: 1 3 * intVec.rotateLeft(); // 1 3 --> 3 1 * printf("%i %i", intVec[0], intVec[1]); // Prints: 3 1 * @endcode */ template <typename TYPE> class VECTOR { public: VECTOR(); ///< Default Constructor VECTOR(int initialCapacity); ///< Constructor with initial capacity as Vector size VECTOR(const VECTOR& copy); ///< Copy Constructor VECTOR& operator=(const VECTOR& copy); ///< =Operator to copy the vector. ~VECTOR(); ///< Destructor of the vector const TYPE& front(); ///< @returns the first(oldest) element of the vector (index 0). const TYPE& back(); ///< @returns the last added element of the vector. const TYPE& pop_front(); ///< Pops & returns the first(oldest) element of the vector (index 0). (SLOW) const TYPE& pop_back(); ///< Pops & returns the last element from the vector. (FAST) void push_back(const TYPE& element); ///< Pushes the element to the end of the vector. (FAST) void push_front(const TYPE& element); ///< Pushes the element at the 1st location (index 0). (SLOW) void reverse(); ///< Reverses the order of the vector contents. const TYPE& rotateRight(); ///< Rotates the vector right by 1 and @returns front() value const TYPE& rotateLeft(); ///< Rotates the vector left by 1 and @returns front() value const TYPE& eraseAt(unsigned int pos); ///< Erases the element at pos and returns it. All elements are shifted left from this pos. int getFirstIndexOf(const TYPE& find); ///< @returns the first index at which the element find is located at bool remove(const TYPE& element); ///< Removes the first Vector Element match from this vector, @returns true if successful int removeAll(const TYPE& element); ///< Removes all Vector Elements that match the given element, @returns number of elements removed bool replace(const TYPE& find, const TYPE& replace); ///< Replaces the first element "find" and replaces it with "replace" int replaceAll(const TYPE& find, const TYPE& replace); ///< Replaces all instances of "find" and replaces it with "replace" void fill(const TYPE& fillElement); ///< Fills the entire vector capacity with the given fillElement. void fillUnused(const TYPE& fillElement); ///< Fills the unused capacity of the vector with the given fillElement. unsigned int size() const; ///< @returns The size of the vector (actual usage) unsigned int capacity() const; ///< @returns The capacity of the vector (allocated memory) void reserve(unsigned int size); ///< Reserves the memory for the vector up front. void setGrowthFactor(int factor); ///< Changes the size the vector grows by. void clear(); ///< Clears the entire vector bool isEmpty(); ///< @returns True if the vector is empty TYPE& at(const unsigned int i); ///< Access element at given index TYPE& operator[](const unsigned int i ); ///< [] Operator for Left-hand-side. const TYPE& operator[](const unsigned int i ) const; ///< [] Operator of Right-hand-side. void operator+=(const TYPE& item) { push_back(item); } ///< += Operator which is same as push_back() of an item private: void changeCapacity(unsigned int newSize); ///< Changes the capacity of this vector to the new size and handles internal memory move TYPE* shiftLeftFromPosition(unsigned int pos); ///< @returns Pointer at the pos, and all pointers get shifted left from this pos TYPE* shiftRightFromPosition(unsigned int pos); ///< @returns Pointer at the last position, and all pointers get shifted right from ths pos unsigned int mGrowthRate; ///< Number of elements added when vector needs to grow unsigned int mVectorCapacity; ///< Capacity of this vector unsigned int mVectorSize; ///< Used size of this vector TYPE **mpObjPtrs; ///< Pointer array of TYPE TYPE mNullItem; ///< Null Item is returned when invalid vector element is accessed /// Initializes all member variables of this vector void init() { mGrowthRate = 4; mVectorCapacity = 0; mVectorSize = 0; mpObjPtrs = 0; } }; template <typename TYPE> VECTOR<TYPE>::VECTOR() { init(); } template <typename TYPE> VECTOR<TYPE>::VECTOR(int initialCapacity) { init(); changeCapacity(initialCapacity); } template <typename TYPE> VECTOR<TYPE>::VECTOR(const VECTOR& copy) { init(); *this = copy; // Call = Operator below to copy vector contents } template <typename TYPE> VECTOR<TYPE>& VECTOR<TYPE>::operator=(const VECTOR<TYPE>& copy) { if(this != &copy) { // Clear this vector and reserve enough for the vector to copy this->clear(); this->reserve(copy.capacity()); // Now copy other vectors contents into this vector for(unsigned int i = 0; i < copy.size(); i++) { *(this->mpObjPtrs[i]) = copy[i]; } } return *this; } template <typename TYPE> VECTOR<TYPE>::~VECTOR() { for(unsigned int i=0; i < mVectorCapacity; i++) { delete mpObjPtrs[i]; } delete [] mpObjPtrs; } template <typename TYPE> const TYPE& VECTOR<TYPE>::pop_back() { return (mVectorSize > 0) ? *mpObjPtrs[--mVectorSize] : mNullItem; } template <typename TYPE> const TYPE& VECTOR<TYPE>::pop_front() { return eraseAt(0); } template <typename TYPE> void VECTOR<TYPE>::push_back(const TYPE& element) { if(mVectorSize >= mVectorCapacity) { changeCapacity( (mVectorCapacity + mGrowthRate) ); } *mpObjPtrs[mVectorSize++] = element; } template <typename TYPE> void VECTOR<TYPE>::push_front(const TYPE& element) { if(mVectorSize >= mVectorCapacity) { changeCapacity( (mVectorCapacity + mGrowthRate) ); } // Make room to put new item at mpData[0] by moving free right-most pointer back to 0 if( mVectorSize++ >= 1) { mpObjPtrs[0] = shiftRightFromPosition(0); } // 1st element was moved to 2nd by shifting right, place new item at 1st location. *mpObjPtrs[0] = element; } template <typename TYPE> const TYPE& VECTOR<TYPE>::front() { return (*this)[0]; } template <typename TYPE> const TYPE& VECTOR<TYPE>::back() { return (*this)[mVectorSize-1]; } template <typename TYPE> unsigned int VECTOR<TYPE>::size() const { return mVectorSize; } template <typename TYPE> unsigned int VECTOR<TYPE>::capacity() const { return mVectorCapacity; } template <typename TYPE> void VECTOR<TYPE>::reserve(unsigned int theSize) { changeCapacity(theSize); } template <typename TYPE> void VECTOR<TYPE>::setGrowthFactor(int factor) { if(factor > 1) mGrowthRate = factor; } template <typename TYPE> int VECTOR<TYPE>::getFirstIndexOf(const TYPE& find) { for(unsigned int i = 0; i < mVectorSize; i++) { if(*mpObjPtrs[i] == find) { return i; } } return -1; } template <typename TYPE> const TYPE& VECTOR<TYPE>::eraseAt(unsigned int elementNumber) { TYPE* item = 0; if(elementNumber < mVectorSize && elementNumber >= 0) { // Must save the pointer even though we are erasing item = (mpObjPtrs[mVectorSize-1] = shiftLeftFromPosition(elementNumber)); mVectorSize--; } return 0 == item ? mNullItem : *item; } template <typename TYPE> bool VECTOR<TYPE>::remove(const TYPE& element) { const int index = getFirstIndexOf(element); const bool found = (index >= 0); if(found) { eraseAt(index); } return found; } template <typename TYPE> int VECTOR<TYPE>::removeAll(const TYPE& element) { // Optimize vector::removeAll() ??? int itemsRemoved = 0; while(remove(element)) { itemsRemoved++; } return itemsRemoved; } template <typename TYPE> bool VECTOR<TYPE>::replace(const TYPE& find, const TYPE& replaceWith) { const int index = getFirstIndexOf(find); const bool found = (index >= 0); if(found) { *mpObjPtrs[index] = replaceWith; } return found; } template <typename TYPE> int VECTOR<TYPE>::replaceAll(const TYPE& find, const TYPE& replaceWith) { int itemsReplaced = 0; for(unsigned int i = 0; i < mVectorSize; i++) { if(*mpObjPtrs[i] == find) { *mpObjPtrs[i] = replaceWith; itemsReplaced++; } } return itemsReplaced; } template <typename TYPE> void VECTOR<TYPE>::fill(const TYPE& fillElement) { for(unsigned int i = 0; i < mVectorCapacity; i++) { *mpObjPtrs[i] = fillElement; } mVectorSize = mVectorCapacity; } template <typename TYPE> void VECTOR<TYPE>::fillUnused(const TYPE& fillElement) { for(unsigned int i = mVectorSize; i < mVectorCapacity; i++) { *mpObjPtrs[i] = fillElement; } mVectorSize = mVectorCapacity; } template <typename TYPE> void VECTOR<TYPE>::clear() { mVectorSize = 0; } template <typename TYPE> bool VECTOR<TYPE>::isEmpty() { return (0 == mVectorSize); } template <typename TYPE> void VECTOR<TYPE>::reverse() { for(unsigned int i = 0; i < (mVectorSize/2); i++) { TYPE* temp = mpObjPtrs[i]; mpObjPtrs[i] = mpObjPtrs[ (mVectorSize-1-i) ]; mpObjPtrs[ (mVectorSize-1-i) ] = temp; } } template <typename TYPE> const TYPE& VECTOR<TYPE>::rotateLeft() { if(mVectorSize >= 2) { // Shift right and set shifted element to index 0 mpObjPtrs[0] = shiftRightFromPosition(0); } return (*this)[0]; } template <typename TYPE> const TYPE& VECTOR<TYPE>::rotateRight() { if(mVectorSize >= 2) { // Shift left, and set the last element to shifted element. mpObjPtrs[ (mVectorSize-1) ] = shiftLeftFromPosition(0); } return (*this)[0]; } template <typename TYPE> TYPE& VECTOR<TYPE>::at(const unsigned int i ) { return (*this)[i]; } template <typename TYPE> TYPE& VECTOR<TYPE>::operator[](const unsigned int i ) { return ( i >= 0 && i < mVectorSize) ? *mpObjPtrs[i] : mNullItem; } template <typename TYPE> const TYPE& VECTOR<TYPE>::operator[](const unsigned int i ) const { return ( i >= 0 && i < mVectorSize) ? *mpObjPtrs[i] : mNullItem; } // ******* PRIVATE FUNCTIONS: template <typename TYPE> void VECTOR<TYPE>::changeCapacity(unsigned int newSize) { if(newSize < mVectorCapacity) return; // This is slow code so it is #ifdef'd out #if 0 // Allocate new memory and call TYPE's default constructor TYPE **newData = new TYPE*[ (newSize) ]; for(unsigned int i = 0; i < newSize; i++) { newData[i] = new TYPE(); } // Copy old memory to new one & delete old memory if(mpObjPtrs) { for(unsigned int i = 0; i < mVectorSize; i++) { newData[i] = mpObjPtrs[i]; } delete [] mpObjPtrs; } // Point data to new memory mpObjPtrs = newData; #else // Allocate pointers of the datatype mpObjPtrs = (TYPE**)realloc(mpObjPtrs, sizeof(TYPE*)*newSize); // Allocate new objects ONLY at each of the new pointers for(unsigned int i = mVectorSize; i < newSize; i++) { mpObjPtrs[i] = new TYPE(); } #endif mVectorCapacity = newSize; } template <typename TYPE> TYPE* VECTOR<TYPE>::shiftLeftFromPosition(unsigned int pos) { TYPE* leftMostItem = mpObjPtrs[pos]; if(mVectorSize > 1 && (mVectorSize-pos) > 1) { // Shift elements left by one. for( unsigned int i = pos; i < (mVectorSize-1); i++) { mpObjPtrs[i] = mpObjPtrs[i+1]; } } return leftMostItem; } template <typename TYPE> TYPE* VECTOR<TYPE>::shiftRightFromPosition(unsigned int pos) { // Vector size must be at least 1 before calling this function TYPE* rightMostItem = mpObjPtrs[mVectorSize-1]; // Shift elements right by one. for( unsigned int i = mVectorSize-1; i > pos; i--) { mpObjPtrs[i] = mpObjPtrs[i-1]; } return rightMostItem; } #endif /* #ifndef _VECTOR_H__ */
28.557851
143
0.636015
[ "vector" ]
f2bb32016cb6e3c90acc6c608f0538629df6009a
88,829
cpp
C++
source/Company.cpp
Osumi-Akari/energytycoon
25d18a0ee4a9f8833e678af297734602918a92e9
[ "Unlicense" ]
null
null
null
source/Company.cpp
Osumi-Akari/energytycoon
25d18a0ee4a9f8833e678af297734602918a92e9
[ "Unlicense" ]
null
null
null
source/Company.cpp
Osumi-Akari/energytycoon
25d18a0ee4a9f8833e678af297734602918a92e9
[ "Unlicense" ]
null
null
null
#include "StdAfx.h" #include "Company.h" #include "GUI.h" #include "Map.h" #include "City.h" #include "Powerplant.h" #include "PowerNet.h" #include "GameObject.h" #include "ResourceBuilding.h" #include "CompanyBuilding.h" #include "Chart.h" /*-----------------------------------------------------------------------------------------------*/ Company::Company(std::string pMission, bool pSandbox, std::vector<boost::shared_ptr<City> > pCities, boost::shared_ptr<Map> pMap) : mMoney(cDefaultStartMoney), mCoal(cDefaultCoalStart), mGas(cDefaultGasStart), mUranium(cDefaultUraniumStart), mSandbox(pSandbox), mCities(pCities), mGlobalImage(50), mGlobalPrice(15), mGlobalAdvertising(15), mGlobalMaintenance(100), mCompleteCustomers(0), mName(StrLoc::get()->DefaultCompanyName()), mNetWorth(0), mExpenses(0), mIncome(0), mTraining(eNormalTraining), mCustomerSupport(eNormalSupport), mSafety(eNormalSafety), mContractTime(e12), mSupplyMaintenance(100), mEnvSupport(0), mHeadquartersBuilt(false), mResearchBuilt(false), mPRBuilt(false), mTaxFreeTrades(0), mWarActive(false), mPriceActive(false), mWasteActive(false), mBribeActive(false), mNoTrainingActive(false), mBankruptcyWarningIssued(false), mGasLastWeek(0), mCoalLastWeek(0), mUraniumLastWeek(0), mGasTrend(0), mCoalTrend(0), mUraniumTrend(0), mKeepPlaying(false), mMap(pMap) { mPowerNet.reset(new PowerNet()); REGISTER_CALLBACK(eChangeResource, Company::changeResource); REGISTER_CALLBACK(eDayPassed, Company::dayPassed); REGISTER_CALLBACK(eWeekPassed, Company::weekPassed); REGISTER_CALLBACK(eMonthPassed, Company::monthPassed); REGISTER_CALLBACK(eYearPassed, Company::yearPassed); REGISTER_CALLBACK(eUpdateFinanceChart, Company::updateFinanceChart); setupMissionParams(pMission); if(mSandbox) { mCoal = 50000; mGas = 50000; mUranium = 50000; } createNewTradeOffers(); mTradeChart.reset(new Chart("TradeChart", 290, 133, 512, 256, false)); mImageChart.reset(new Chart("ImageChart", 338, 185, 512, 256, true)); mFinanceChart.reset(new Chart("FinanceChart", 560, 294, 1024, 512, true, true, true)); std::vector<Ogre::ColourValue> lFinanceColours; lFinanceColours.push_back(Ogre::ColourValue(1.0, 0.0, 0.0)); lFinanceColours.push_back(Ogre::ColourValue(0.0, 1.0, 0.0)); lFinanceColours.push_back(Ogre::ColourValue(1.0, 1.0, 0.0)); lFinanceColours.push_back(Ogre::ColourValue(0.0, 0.0, 1.0)); mFinanceChart->setColourSet(lFinanceColours); mTradeChart->forceRepaint(); mImageChart->forceRepaint(); mFinanceChart->forceRepaint(); mGasPrice = rand() % 100; mCoalPrice = rand() % 100; mUraniumPrice = rand() % 100; } /*-----------------------------------------------------------------------------------------------*/ void Company::adjustResource(eResourceType pType, int pAmount) { if (pType == eCoal) { if ((mCoal == 0) && (pAmount > 0)) EventHandler::raiseEvent(eResourceGain, new EventArg<int>(eCoal)); if ((mCoal + pAmount) < 0) { mCoal = 0; EventHandler::raiseEvent(eResourceGone, new EventArg<int>(eCoal)); EventHandler::raiseEvent(eMinimapModeChange, new EventArg<int>(-1)); TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->CoalStockDepleted(); lMessage.mPointOfInterest = Ogre::Vector2(-1.0, -1.0); lMessage.mUrgent = true; lMessage.mDetail = StrLoc::get()->CoalStockDepletedDetail(); lMessage.mID = 0; EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); } else { mCoal += pAmount; } } else if (pType == eUranium) { if((mUranium == 0) && (pAmount > 0)) EventHandler::raiseEvent(eResourceGain, new EventArg<int>(eUranium)); if ((mUranium + pAmount) < 0) { mUranium = 0; EventHandler::raiseEvent(eResourceGone, new EventArg<int>(eUranium)); EventHandler::raiseEvent(eMinimapModeChange, new EventArg<int>(-1)); TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->UraniumStockDepleted(); lMessage.mPointOfInterest = Ogre::Vector2(-1.0, -1.0); lMessage.mUrgent = true; lMessage.mDetail = StrLoc::get()->UraniumStockDepletedDetail(); lMessage.mID = 0; EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); } else { mUranium += pAmount; } } else if (pType == eGas) { if((mGas == 0) && (pAmount > 0)) EventHandler::raiseEvent(eResourceGain, new EventArg<int>(eGas)); if((mGas + pAmount) < 0) { mGas = 0; EventHandler::raiseEvent(eResourceGone, new EventArg<int>(eGas)); EventHandler::raiseEvent(eMinimapModeChange, new EventArg<int>(-1)); TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->GasStockDepleted(); lMessage.mPointOfInterest = Ogre::Vector2(-1.0, -1.0); lMessage.mUrgent = true; lMessage.mDetail = StrLoc::get()->GasStockDepletedDetail(); lMessage.mID = 0; EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); } else { mGas += pAmount; } } } /*-----------------------------------------------------------------------------------------------*/ void Company::changeResource(EventData* pData) { if (!mSandbox) { eResourceType lType = (eResourceType)static_cast<EventArg<int>*>(pData)->mData1; int lAmount = static_cast<EventArg<int>*>(pData)->mData2; adjustResource(lType, lAmount); } } /*-----------------------------------------------------------------------------------------------*/ boost::shared_ptr<PowerNet> Company::getPowerNet(void) { return mPowerNet; } /*-----------------------------------------------------------------------------------------------*/ int Company::getMoney(void) { return mMoney; } /*-----------------------------------------------------------------------------------------------*/ bool Company::buyObject(eCompanyObjectType pType, bool pFree) { if (!mSandbox) { int lCost = GameConfig::getInt(GameConfig::cCOTS(pType), cCOVCost); if (pFree) lCost = 0; if (lCost <= mMoney) { mMoney -= lCost; mCurrentMonth.mBuilding -= lCost; mCurrentYear.mBuilding -= lCost; mNetWorth += lCost; mExpenses -= lCost; if (pType == eCOHeadquarters) { mHeadquartersBuilt = true; TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->HeadquartersBuilt(); lMessage.mDetail = StrLoc::get()->HeadquartersBuiltDetail(); lMessage.mPointOfInterest = Ogre::Vector2(-1.0, -1.0); lMessage.mUrgent = false; lMessage.mID = 0; EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); EventHandler::raiseEvent(eUpdateCOBuildingButtons); } else if (pType == eCOResearch) { mResearchBuilt = true; TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->ResearchBuilt(); lMessage.mDetail = StrLoc::get()->ResearchBuiltDetail(); lMessage.mPointOfInterest = Ogre::Vector2(-1.0, -1.0); lMessage.mUrgent = false; lMessage.mID = 0; EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); EventHandler::raiseEvent(eUpdateCOBuildingButtons); } else if (pType == eCOPublicRelations) { mPRBuilt = true; TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->PRBuilt(); lMessage.mDetail = StrLoc::get()->PRBuiltDetail(); lMessage.mPointOfInterest = Ogre::Vector2(-1.0, -1.0); lMessage.mUrgent = false; lMessage.mID = 0; EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); EventHandler::raiseEvent(eUpdateCOBuildingButtons); } return true; } else { return false; } } else { if (pType == eCOHeadquarters) mHeadquartersBuilt = true; else if (pType == eCOResearch) mResearchBuilt = true; else if (pType == eCOPublicRelations) mPRBuilt = true; return true; } } /*-----------------------------------------------------------------------------------------------*/ void Company::setupMissionParams(std::string pMission) { boost::shared_ptr<TiXmlDocument> lMission(new TiXmlDocument((cDataDirPre + "missions/" + pMission).c_str())); lMission->LoadFile(TIXML_ENCODING_UTF8); TiXmlNode* rootNode; rootNode = lMission->FirstChildElement("mission"); TiXmlNode* node = rootNode->FirstChildElement("trading_partner"); while (node) { TradingPartner lPartner; lPartner.mPrice = toNumber<int>(node->ToElement()->Attribute("price")); TiXmlNode* nameNode = node->FirstChildElement("name"); while (nameNode) { if (((std::string)nameNode->ToElement()->Attribute("language")) == StrLoc::get()->MyGUILanguage().asUTF8()) { lPartner.mName = Ogre::UTFString(nameNode->ToElement()->GetText()); break; } nameNode = nameNode->NextSiblingElement("name"); } if (lPartner.mPrice == 0) lPartner.mAvailable = true; else lPartner.mAvailable = false; mTradingPartners.push_back(lPartner); node = node->NextSiblingElement("trading_partner"); } node = rootNode->FirstChildElement("mission_goal"); while (node) { MissionGoal lTemp; TiXmlNode* textNode = node->FirstChildElement("text"); while (textNode) { if (((std::string)textNode->ToElement()->Attribute("language")) == StrLoc::get()->MyGUILanguage().asUTF8()) { lTemp.mText = textNode->ToElement()->GetText(); } textNode = textNode->NextSiblingElement("text"); } lTemp.mDone = false; std::string lType = node->ToElement()->Attribute("type"); if (lType == "freeplay") { lTemp.mType = eFreePlay; lTemp.mDone = true; lTemp.mValueNeeded = 0; } else if (lType == "money") { lTemp.mType = eMoney; lTemp.mValueNeeded = toNumber<int>(node->ToElement()->Attribute("value")); } else if (lType == "customers") { lTemp.mType = eCustomerCount; lTemp.mValueNeeded = toNumber<int>(node->ToElement()->Attribute("value")); } lTemp.mValueCurrent = 0; mMissionGoals.push_back(lTemp); node = node->NextSiblingElement("mission_goal"); } } /*-----------------------------------------------------------------------------------------------*/ void Company::serializeIntoXMLElement(TiXmlElement* pParentElement, boost::shared_ptr<GUI> pGUI) { TiXmlElement* lCompanySerialized = new TiXmlElement("company"); lCompanySerialized->SetAttribute("money", mMoney); lCompanySerialized->SetAttribute("gas", mGas); lCompanySerialized->SetAttribute("coal", mCoal); lCompanySerialized->SetAttribute("uranium", mUranium); lCompanySerialized->SetAttribute("global_price", mGlobalPrice); lCompanySerialized->SetAttribute("global_image", mGlobalImage); lCompanySerialized->SetAttribute("global_advertising", mGlobalAdvertising); lCompanySerialized->SetAttribute("global_maintenance", mGlobalMaintenance); lCompanySerialized->SetAttribute("gas_price", mGasPrice); lCompanySerialized->SetAttribute("coal_price", mCoalPrice); lCompanySerialized->SetAttribute("uranium_price", mUraniumPrice); lCompanySerialized->SetAttribute("customers_complete", mCompleteCustomers); lCompanySerialized->SetAttribute("contract_time", (int)mContractTime); lCompanySerialized->SetAttribute("safety", (int)mSafety); lCompanySerialized->SetAttribute("customer_support", (int)mCustomerSupport); lCompanySerialized->SetAttribute("training", (int)mTraining); lCompanySerialized->SetAttribute("env_support", mEnvSupport); lCompanySerialized->SetAttribute("supply_maintenance", mSupplyMaintenance); lCompanySerialized->SetAttribute("free_trades", mTaxFreeTrades); lCompanySerialized->SetAttribute("net_worth", mNetWorth); lCompanySerialized->SetAttribute("company_name", mName.c_str()); pParentElement->LinkEndChild(lCompanySerialized); for (size_t i = 0; i < mCurrentLoans.size(); ++i) { TiXmlElement* lLoanSerialized = new TiXmlElement("loan"); lLoanSerialized->SetAttribute("amount_left", mCurrentLoans[i].mAmountLeft); lLoanSerialized->SetAttribute("month_left", mCurrentLoans[i].mMonthLeft); lLoanSerialized->SetAttribute("monthly_rate", mCurrentLoans[i].mMonthlyRate); pParentElement->LinkEndChild(lLoanSerialized); } for (size_t j = 0; j < mExecutingOffers.size(); ++j) { TiXmlElement* lOfferSerialized = new TiXmlElement("trade_obligation"); lOfferSerialized->SetAttribute("partner", mExecutingOffers[j].mTradingPartner.c_str()); lOfferSerialized->SetAttribute("resource", (int)mExecutingOffers[j].mResource); lOfferSerialized->SetAttribute("amount", mExecutingOffers[j].mAmount); lOfferSerialized->SetAttribute("weeks", mExecutingOffers[j].mWeeks); lOfferSerialized->SetAttribute("discount", mExecutingOffers[j].mDiscount); lOfferSerialized->SetAttribute("fixed_price", mExecutingOffers[j].mFixedPrice); lOfferSerialized->SetAttribute("unique", mExecutingOffers[j].mUnique ? "true" : "false"); lOfferSerialized->SetAttribute("world_market", mExecutingOffers[j].mWorldMarket ? "true" : "false"); lOfferSerialized->SetAttribute("permanent", mExecutingOffers[j].mPermanent ? "true" : "false"); pParentElement->LinkEndChild(lOfferSerialized); } for (size_t k = 0; k < mTradingPartners.size(); ++k) { TiXmlElement* lTradingPartner = new TiXmlElement("trading_partner"); lTradingPartner->SetAttribute("name", mTradingPartners[k].mName.asUTF8_c_str()); lTradingPartner->SetAttribute("available", mTradingPartners[k].mAvailable ? "true" : "false"); pParentElement->LinkEndChild(lTradingPartner); } for (size_t l = 0; l < mCampaigns.size(); ++l) { TiXmlElement* lCampaign = new TiXmlElement("campaign"); lCampaign->SetAttribute("type", (int)mCampaigns[l].mType); lCampaign->SetAttribute("weeks_left", mCampaigns[l].mWeeksLeft); pParentElement->LinkEndChild(lCampaign); } for (size_t m = 0; m < mSpecialActions.size(); ++m) { TiXmlElement* lSpecialAction = new TiXmlElement("special_action"); lSpecialAction->SetAttribute("type", (int)mSpecialActions[m].mType); lSpecialAction->SetAttribute("trades_left", mSpecialActions[m].mTradesLeft); lSpecialAction->SetAttribute("month_left", mSpecialActions[m].mMonthLeft); lSpecialAction->SetAttribute("done", mSpecialActions[m].mDone ? "true" : "false"); pParentElement->LinkEndChild(lSpecialAction); } for (size_t n = 0; n < mCompanyBuildings.size(); ++n) { TiXmlElement* lCompanyBuilding = new TiXmlElement("company_building"); lCompanyBuilding->SetAttribute("pos_x", mCompanyBuildings[n]->getPosition().x); lCompanyBuilding->SetAttribute("pos_y", mCompanyBuildings[n]->getPosition().y); lCompanyBuilding->SetAttribute("type", (int)mCompanyBuildings[n]->getSubtype()); lCompanyBuilding->SetAttribute("id", mCompanyBuildings[n]->getID().c_str()); pParentElement->LinkEndChild(lCompanyBuilding); } for (size_t o = 0; o < mResourceBuildings.size(); ++o) { TiXmlElement* lResourceBuilding = new TiXmlElement("resource_building"); lResourceBuilding->SetAttribute("pos_x", mResourceBuildings[o]->getPosition().x); lResourceBuilding->SetAttribute("pos_y", mResourceBuildings[o]->getPosition().y); lResourceBuilding->SetAttribute("type", (int)mResourceBuildings[o]->getSubtype()); lResourceBuilding->SetAttribute("id", mResourceBuildings[o]->getID().c_str()); lResourceBuilding->SetAttribute("inherit", mResourceBuildings[o]->getInheritSettings() ? true : false); lResourceBuilding->SetAttribute("maintenance", mResourceBuildings[o]->getMaintenance()); lResourceBuilding->SetAttribute("counter", mResourceBuildings[o]->getCounter()); lResourceBuilding->SetAttribute("damaged", mResourceBuildings[o]->getDamaged() ? true : false); lResourceBuilding->SetAttribute("condition", mResourceBuildings[o]->getCondition()); pParentElement->LinkEndChild(lResourceBuilding); } TiXmlElement* lCurrentMonth = new TiXmlElement("finances_current_month"); lCurrentMonth->SetAttribute("advertising", mCurrentMonth.mAdvertising); lCurrentMonth->SetAttribute("building", mCurrentMonth.mBuilding); lCurrentMonth->SetAttribute("customer_income", mCurrentMonth.mCustomerIncome); lCurrentMonth->SetAttribute("environmental", mCurrentMonth.mEnvironmental); lCurrentMonth->SetAttribute("loan_payments", mCurrentMonth.mLoanPayments); lCurrentMonth->SetAttribute("maintenance", mCurrentMonth.mMaintenance); lCurrentMonth->SetAttribute("operation", mCurrentMonth.mOperation); lCurrentMonth->SetAttribute("research", mCurrentMonth.mResearch); lCurrentMonth->SetAttribute("special_expenses", mCurrentMonth.mSpecialExpenses); lCurrentMonth->SetAttribute("trade", mCurrentMonth.mTrade); lCurrentMonth->SetAttribute("training_safety", mCurrentMonth.mTrainingSafety); pParentElement->LinkEndChild(lCurrentMonth); TiXmlElement* lCurrentYear = new TiXmlElement("finances_current_year"); lCurrentYear->SetAttribute("advertising", mCurrentYear.mAdvertising); lCurrentYear->SetAttribute("building", mCurrentYear.mBuilding); lCurrentYear->SetAttribute("customer_income", mCurrentYear.mCustomerIncome); lCurrentYear->SetAttribute("environmental", mCurrentYear.mEnvironmental); lCurrentYear->SetAttribute("loan_payments", mCurrentYear.mLoanPayments); lCurrentYear->SetAttribute("maintenance", mCurrentYear.mMaintenance); lCurrentYear->SetAttribute("operation", mCurrentYear.mOperation); lCurrentYear->SetAttribute("research", mCurrentYear.mResearch); lCurrentYear->SetAttribute("special_expenses", mCurrentYear.mSpecialExpenses); lCurrentYear->SetAttribute("trade", mCurrentYear.mTrade); lCurrentYear->SetAttribute("training_safety", mCurrentYear.mTrainingSafety); pParentElement->LinkEndChild(lCurrentYear); TiXmlElement* lLastMonth = new TiXmlElement("finances_last_month"); lLastMonth->SetAttribute("advertising", mLastMonth.mAdvertising); lLastMonth->SetAttribute("building", mLastMonth.mBuilding); lLastMonth->SetAttribute("customer_income", mLastMonth.mCustomerIncome); lLastMonth->SetAttribute("environmental", mLastMonth.mEnvironmental); lLastMonth->SetAttribute("loan_payments", mLastMonth.mLoanPayments); lLastMonth->SetAttribute("maintenance", mLastMonth.mMaintenance); lLastMonth->SetAttribute("operation", mLastMonth.mOperation); lLastMonth->SetAttribute("research", mLastMonth.mResearch); lLastMonth->SetAttribute("special_expenses", mLastMonth.mSpecialExpenses); lLastMonth->SetAttribute("trade", mLastMonth.mTrade); lLastMonth->SetAttribute("training_safety", mLastMonth.mTrainingSafety); pParentElement->LinkEndChild(lLastMonth); TiXmlElement* lLastYear = new TiXmlElement("finances_last_year"); lLastYear->SetAttribute("advertising", mLastYear.mAdvertising); lLastYear->SetAttribute("building", mLastYear.mBuilding); lLastYear->SetAttribute("customer_income", mLastYear.mCustomerIncome); lLastYear->SetAttribute("environmental", mLastYear.mEnvironmental); lLastYear->SetAttribute("loan_payments", mLastYear.mLoanPayments); lLastYear->SetAttribute("maintenance", mLastYear.mMaintenance); lLastYear->SetAttribute("operation", mLastYear.mOperation); lLastYear->SetAttribute("research", mLastYear.mResearch); lLastYear->SetAttribute("special_expenses", mLastYear.mSpecialExpenses); lLastYear->SetAttribute("trade", mLastYear.mTrade); lLastYear->SetAttribute("training_safety", mLastYear.mTrainingSafety); pParentElement->LinkEndChild(lLastYear); for (size_t p = 0; p < 21; ++p) { TiXmlElement* lResearchSet = new TiXmlElement("research_set"); lResearchSet->SetAttribute("researched", mResearchSet.mResearched[p] ? "true" : "false"); lResearchSet->SetAttribute("started", mResearchSet.mStarted[p] ? "true" : "false"); lResearchSet->SetAttribute("price", mResearchSet.mPrice[p]); lResearchSet->SetAttribute("name", mResearchSet.mName[p].c_str()); lResearchSet->SetAttribute("weeks_left", mResearchSet.mWeeksLeft[p]); lResearchSet->SetAttribute("weeks_required", mResearchSet.mWeeks[p]); pParentElement->LinkEndChild(lResearchSet); } for (size_t q = 0; q < pGUI->getTickerArchive().size(); ++q) { TiXmlElement* lTickerMessage = new TiXmlElement("ticker_message"); lTickerMessage->SetAttribute("id", pGUI->getTickerArchive()[q].mID); lTickerMessage->SetAttribute("poi_x", pGUI->getTickerArchive()[q].mPointOfInterest.x); lTickerMessage->SetAttribute("poi_y", pGUI->getTickerArchive()[q].mPointOfInterest.y); lTickerMessage->SetAttribute("text", pGUI->getTickerArchive()[q].mMessage.c_str()); lTickerMessage->SetAttribute("detail", pGUI->getTickerArchive()[q].mDetail.c_str()); lTickerMessage->SetAttribute("urgent", pGUI->getTickerArchive()[q].mUrgent ? "true" : "false"); lTickerMessage->SetAttribute("date_time", pGUI->getTickerArchive()[q].mDateTime.c_str()); pParentElement->LinkEndChild(lTickerMessage); } mPowerNet->serializeIntoXMLElement(pParentElement); TiXmlElement* lTradeChart = new TiXmlElement("trade_chart"); mTradeChart->serializeIntoXMLElement(lTradeChart); pParentElement->LinkEndChild(lTradeChart); TiXmlElement* lImageChart = new TiXmlElement("image_chart"); mImageChart->serializeIntoXMLElement(lImageChart); pParentElement->LinkEndChild(lImageChart); TiXmlElement* lFinanceChart = new TiXmlElement("finance_chart"); mFinanceChart->serializeIntoXMLElement(lFinanceChart); pParentElement->LinkEndChild(lFinanceChart); } /*-----------------------------------------------------------------------------------------------*/ void Company::deserializeFromXMLElement(TiXmlNode* pParentNode, boost::shared_ptr<Map> pMap, Ogre::SceneManager* pSceneManager, boost::shared_ptr<Company> pCompany, boost::shared_ptr<GUI> pGUI) { TiXmlNode* lCompanyNode = pParentNode->FirstChildElement("company"); mMoney = toNumber<int>(lCompanyNode->ToElement()->Attribute("money")); mGas = toNumber<int>(lCompanyNode->ToElement()->Attribute("gas")); mCoal = toNumber<int>(lCompanyNode->ToElement()->Attribute("coal")); mUranium = toNumber<int>(lCompanyNode->ToElement()->Attribute("uranium")); mGlobalPrice = toNumber<int>(lCompanyNode->ToElement()->Attribute("global_price")); mGlobalImage = toNumber<int>(lCompanyNode->ToElement()->Attribute("global_image")); mGlobalAdvertising = toNumber<int>(lCompanyNode->ToElement()->Attribute("global_advertising")); mGlobalMaintenance = toNumber<int>(lCompanyNode->ToElement()->Attribute("global_maintenance")); mGasPrice = toNumber<int>(lCompanyNode->ToElement()->Attribute("gas_price")); mCoalPrice = toNumber<int>(lCompanyNode->ToElement()->Attribute("coal_price")); mUraniumPrice = toNumber<int>(lCompanyNode->ToElement()->Attribute("uranium_price")); mCompleteCustomers = toNumber<int>(lCompanyNode->ToElement()->Attribute("customers_complete")); mContractTime = (eContract)toNumber<int>(lCompanyNode->ToElement()->Attribute("contract_time")); mSafety = (eSafety)toNumber<int>(lCompanyNode->ToElement()->Attribute("safety")); mCustomerSupport = (eSupport)toNumber<int>(lCompanyNode->ToElement()->Attribute("customer_support")); mTraining = (eTraining)toNumber<int>(lCompanyNode->ToElement()->Attribute("training")); mEnvSupport = toNumber<int>(lCompanyNode->ToElement()->Attribute("env_support")); mSupplyMaintenance = toNumber<int>(lCompanyNode->ToElement()->Attribute("supply_maintenance")); mTaxFreeTrades = toNumber<int>(lCompanyNode->ToElement()->Attribute("free_trades")); mNetWorth = toNumber<int>(lCompanyNode->ToElement()->Attribute("net_worth")); mName = lCompanyNode->ToElement()->Attribute("company_name"); TiXmlNode* lLoanNode = pParentNode->FirstChildElement("loan"); while (lLoanNode) { Loan lTemp; lTemp.mMonthlyRate = toNumber<int>(lLoanNode->ToElement()->Attribute("monthly_rate")); lTemp.mMonthLeft = toNumber<int>(lLoanNode->ToElement()->Attribute("month_left")); lTemp.mAmountLeft = toNumber<int>(lLoanNode->ToElement()->Attribute("amount_left")); mCurrentLoans.push_back(lTemp); lLoanNode = lLoanNode->NextSiblingElement("loan"); } TiXmlNode* lTradeObligationNode = pParentNode->FirstChildElement("trade_obligation"); while (lTradeObligationNode) { TradingOffer lTemp; lTemp.mTradingPartner = lTradeObligationNode->ToElement()->Attribute("partner"); lTemp.mResource = (eResourceType)toNumber<int>(lTradeObligationNode->ToElement()->Attribute("resource")); lTemp.mAmount = toNumber<int>(lTradeObligationNode->ToElement()->Attribute("amount")); lTemp.mWeeks = toNumber<int>(lTradeObligationNode->ToElement()->Attribute("weeks")); lTemp.mDiscount = toNumber<int>(lTradeObligationNode->ToElement()->Attribute("discount")); lTemp.mFixedPrice = toNumber<int>(lTradeObligationNode->ToElement()->Attribute("fixed_price")); lTemp.mUnique = (((std::string)lTradeObligationNode->ToElement()->Attribute("unique")) == "false") ? false : true; lTemp.mWorldMarket = (((std::string)lTradeObligationNode->ToElement()->Attribute("world_market")) == "false") ? false : true; lTemp.mPermanent = (((std::string)lTradeObligationNode->ToElement()->Attribute("permanent")) == "false") ? false : true; mExecutingOffers.push_back(lTemp); lTradeObligationNode = lTradeObligationNode->NextSiblingElement("trade_obligation"); } TiXmlNode* lTradingPartnerNode = pParentNode->FirstChildElement("trading_partner"); while (lTradingPartnerNode) { std::string lName = lTradingPartnerNode->ToElement()->Attribute("name"); bool lAvailable = (((std::string)lTradingPartnerNode->ToElement()->Attribute("available")) == "false") ? false : true; for(size_t i = 0; i < mTradingPartners.size(); ++i) if(mTradingPartners[i].mName == lName) mTradingPartners[i].mAvailable = lAvailable; lTradingPartnerNode = lTradingPartnerNode->NextSiblingElement("trading_partner"); } TiXmlNode* lAdCampaignNode = pParentNode->FirstChildElement("campaign"); while (lAdCampaignNode) { AdCampaign lTemp; lTemp.mType = (eAdType)toNumber<int>(lAdCampaignNode->ToElement()->Attribute("type")); lTemp.mWeeksLeft = toNumber<int>(lAdCampaignNode->ToElement()->Attribute("weeks_left")); mCampaigns.push_back(lTemp); lAdCampaignNode = lAdCampaignNode->NextSiblingElement("campaign"); } TiXmlNode* lSpecialActionNode = pParentNode->FirstChildElement("special_action"); while (lSpecialActionNode) { SpecialAction lTemp; lTemp.mType = (eSpecialAction)toNumber<int>(lSpecialActionNode->ToElement()->Attribute("type")); lTemp.mMonthLeft = toNumber<int>(lSpecialActionNode->ToElement()->Attribute("month_left")); lTemp.mDone = (((std::string)lSpecialActionNode->ToElement()->Attribute("done")) == "false") ? false : true; lTemp.mTradesLeft = toNumber<int>(lSpecialActionNode->ToElement()->Attribute("trades_left")); mSpecialActions.push_back(lTemp); lSpecialActionNode = lSpecialActionNode->NextSiblingElement("special_action"); } TiXmlNode* lCompanyBuildingNode = pParentNode->FirstChildElement("company_building"); while (lCompanyBuildingNode) { Ogre::Vector2 lPosition; lPosition.x = toNumber<int>(lCompanyBuildingNode->ToElement()->Attribute("pos_x")); lPosition.y = toNumber<int>(lCompanyBuildingNode->ToElement()->Attribute("pos_y")); eCompanyObjectType lType = (eCompanyObjectType)toNumber<int>(lCompanyBuildingNode->ToElement()->Attribute("type")); boost::shared_ptr<CompanyBuilding> lNewBuilding; lNewBuilding.reset(new CompanyBuilding(lPosition, lType)); lNewBuilding->setID(toNumber<int>(lCompanyBuildingNode->ToElement()->Attribute("id"))); lNewBuilding->addToSceneManager(pSceneManager, pMap->getTerrain()); pMap->addCollidable(lNewBuilding, true); if (lType == eCOHeadquarters) mHeadquartersBuilt = true; else if (lType == eCOResearch) mResearchBuilt = true; else if (lType == eCOPublicRelations) mPRBuilt = true; mCompanyBuildings.push_back(lNewBuilding); lCompanyBuildingNode = lCompanyBuildingNode->NextSiblingElement("company_building"); } TiXmlNode* lResourceBuildingNode = pParentNode->FirstChildElement("resource_building"); while (lResourceBuildingNode) { Ogre::Vector2 lPosition; lPosition.x = toNumber<int>(lResourceBuildingNode->ToElement()->Attribute("pos_x")); lPosition.y = toNumber<int>(lResourceBuildingNode->ToElement()->Attribute("pos_y")); eCompanyObjectType lType = (eCompanyObjectType)toNumber<int>(lResourceBuildingNode->ToElement()->Attribute("type")); size_t lCounter = toNumber<int>(lResourceBuildingNode->ToElement()->Attribute("counter")); boost::shared_ptr<ResourceBuilding> lNewBuilding; lNewBuilding.reset(new ResourceBuilding(lPosition, lType, lCounter, pCompany)); lNewBuilding->setID(toNumber<int>(lResourceBuildingNode->ToElement()->Attribute("id"))); lNewBuilding->setInheritSettings((((std::string)lResourceBuildingNode->ToElement()->Attribute("inherit")) == "false") ? false : true); lNewBuilding->setMaintenance(toNumber<int>(lResourceBuildingNode->ToElement()->Attribute("maintenance"))); if (((std::string)lResourceBuildingNode->ToElement()->Attribute("damaged")) == "true") lNewBuilding->setDamaged(); lNewBuilding->setCondition(toNumber<int>(lResourceBuildingNode->ToElement()->Attribute("condition"))); lNewBuilding->addToSceneManager(pSceneManager, pMap->getTerrain()); pMap->addCollidable(lNewBuilding, true); mResourceBuildings.push_back(lNewBuilding); lResourceBuildingNode = lResourceBuildingNode->NextSiblingElement("resource_building"); } TiXmlNode* lCurrentMonthNode = pParentNode->FirstChildElement("finances_current_month"); mCurrentMonth.mAdvertising = toNumber<int>(lCurrentMonthNode->ToElement()->Attribute("advertising")); mCurrentMonth.mBuilding = toNumber<int>(lCurrentMonthNode->ToElement()->Attribute("building")); mCurrentMonth.mCustomerIncome = toNumber<int>(lCurrentMonthNode->ToElement()->Attribute("customer_income")); mCurrentMonth.mEnvironmental = toNumber<int>(lCurrentMonthNode->ToElement()->Attribute("environmental")); mCurrentMonth.mLoanPayments = toNumber<int>(lCurrentMonthNode->ToElement()->Attribute("loan_payments")); mCurrentMonth.mMaintenance = toNumber<int>(lCurrentMonthNode->ToElement()->Attribute("maintenance")); mCurrentMonth.mOperation = toNumber<int>(lCurrentMonthNode->ToElement()->Attribute("operation")); mCurrentMonth.mResearch = toNumber<int>(lCurrentMonthNode->ToElement()->Attribute("research")); mCurrentMonth.mSpecialExpenses = toNumber<int>(lCurrentMonthNode->ToElement()->Attribute("special_expenses")); mCurrentMonth.mTrade = toNumber<int>(lCurrentMonthNode->ToElement()->Attribute("trade")); mCurrentMonth.mTrainingSafety = toNumber<int>(lCurrentMonthNode->ToElement()->Attribute("training_safety")); TiXmlNode* lCurrentYearNode = pParentNode->FirstChildElement("finances_current_year"); mCurrentYear.mAdvertising = toNumber<int>(lCurrentYearNode->ToElement()->Attribute("advertising")); mCurrentYear.mBuilding = toNumber<int>(lCurrentYearNode->ToElement()->Attribute("building")); mCurrentYear.mCustomerIncome = toNumber<int>(lCurrentYearNode->ToElement()->Attribute("customer_income")); mCurrentYear.mEnvironmental = toNumber<int>(lCurrentYearNode->ToElement()->Attribute("environmental")); mCurrentYear.mLoanPayments = toNumber<int>(lCurrentYearNode->ToElement()->Attribute("loan_payments")); mCurrentYear.mMaintenance = toNumber<int>(lCurrentYearNode->ToElement()->Attribute("maintenance")); mCurrentYear.mOperation = toNumber<int>(lCurrentYearNode->ToElement()->Attribute("operation")); mCurrentYear.mResearch = toNumber<int>(lCurrentYearNode->ToElement()->Attribute("research")); mCurrentYear.mSpecialExpenses = toNumber<int>(lCurrentYearNode->ToElement()->Attribute("special_expenses")); mCurrentYear.mTrade = toNumber<int>(lCurrentYearNode->ToElement()->Attribute("trade")); mCurrentYear.mTrainingSafety = toNumber<int>(lCurrentYearNode->ToElement()->Attribute("training_safety")); TiXmlNode* lLastMonthNode = pParentNode->FirstChildElement("finances_last_month"); mLastMonth.mAdvertising = toNumber<int>(lLastMonthNode->ToElement()->Attribute("advertising")); mLastMonth.mBuilding = toNumber<int>(lLastMonthNode->ToElement()->Attribute("building")); mLastMonth.mCustomerIncome = toNumber<int>(lLastMonthNode->ToElement()->Attribute("customer_income")); mLastMonth.mEnvironmental = toNumber<int>(lLastMonthNode->ToElement()->Attribute("environmental")); mLastMonth.mLoanPayments = toNumber<int>(lLastMonthNode->ToElement()->Attribute("loan_payments")); mLastMonth.mMaintenance = toNumber<int>(lLastMonthNode->ToElement()->Attribute("maintenance")); mLastMonth.mOperation = toNumber<int>(lLastMonthNode->ToElement()->Attribute("operation")); mLastMonth.mResearch = toNumber<int>(lLastMonthNode->ToElement()->Attribute("research")); mLastMonth.mSpecialExpenses = toNumber<int>(lLastMonthNode->ToElement()->Attribute("special_expenses")); mLastMonth.mTrade = toNumber<int>(lLastMonthNode->ToElement()->Attribute("trade")); mLastMonth.mTrainingSafety = toNumber<int>(lLastMonthNode->ToElement()->Attribute("training_safety")); TiXmlNode* lLastYearNode = pParentNode->FirstChildElement("finances_last_year"); mLastYear.mAdvertising = toNumber<int>(lLastYearNode->ToElement()->Attribute("advertising")); mLastYear.mBuilding = toNumber<int>(lLastYearNode->ToElement()->Attribute("building")); mLastYear.mCustomerIncome = toNumber<int>(lLastYearNode->ToElement()->Attribute("customer_income")); mLastYear.mEnvironmental = toNumber<int>(lLastYearNode->ToElement()->Attribute("environmental")); mLastYear.mLoanPayments = toNumber<int>(lLastYearNode->ToElement()->Attribute("loan_payments")); mLastYear.mMaintenance = toNumber<int>(lLastYearNode->ToElement()->Attribute("maintenance")); mLastYear.mOperation = toNumber<int>(lLastYearNode->ToElement()->Attribute("operation")); mLastYear.mResearch = toNumber<int>(lLastYearNode->ToElement()->Attribute("research")); mLastYear.mSpecialExpenses = toNumber<int>(lLastYearNode->ToElement()->Attribute("special_expenses")); mLastYear.mTrade = toNumber<int>(lLastYearNode->ToElement()->Attribute("trade")); mLastYear.mTrainingSafety = toNumber<int>(lLastYearNode->ToElement()->Attribute("training_safety")); TiXmlNode* lResearchSetNode = pParentNode->FirstChildElement("research_set"); for (size_t j = 0; j < 21; ++j) { mResearchSet.mResearched[j] = ((((std::string)lResearchSetNode->ToElement()->Attribute("researched")) == "false") ? false : true); mResearchSet.mStarted[j] = ((((std::string)lResearchSetNode->ToElement()->Attribute("started")) == "false") ? false : true); mResearchSet.mPrice[j] = toNumber<int>(lResearchSetNode->ToElement()->Attribute("price")); mResearchSet.mName[j] = lResearchSetNode->ToElement()->Attribute("name"); mResearchSet.mWeeksLeft[j] = toNumber<int>(lResearchSetNode->ToElement()->Attribute("weeks_left")); mResearchSet.mWeeks[j] = toNumber<int>(lResearchSetNode->ToElement()->Attribute("weeks_required")); lResearchSetNode = lResearchSetNode->NextSiblingElement("research_set"); } std::vector<TickerMessage> lSerializedArchive; TiXmlNode* lTickerMessageNode = pParentNode->FirstChildElement("ticker_message"); while (lTickerMessageNode) { TickerMessage lTemp; lTemp.mID = toNumber<int>(lTickerMessageNode->ToElement()->Attribute("id")); lTemp.mPointOfInterest.x = toNumber<int>(lTickerMessageNode->ToElement()->Attribute("poi_x")); lTemp.mPointOfInterest.y = toNumber<int>(lTickerMessageNode->ToElement()->Attribute("poi_y")); lTemp.mMessage = lTickerMessageNode->ToElement()->Attribute("text"); lTemp.mDetail = lTickerMessageNode->ToElement()->Attribute("detail"); lTemp.mUrgent = (((std::string)lTickerMessageNode->ToElement()->Attribute("urgent")) == "false" ? false : true); lTemp.mDateTime = lTickerMessageNode->ToElement()->Attribute("date_time"); lSerializedArchive.push_back(lTemp); lTickerMessageNode = lTickerMessageNode->NextSiblingElement("ticker_message"); } pGUI->setTickerArchive(lSerializedArchive); mPowerNet->deserializeFromXMLElement(pParentNode, pMap, pSceneManager, pCompany); TiXmlNode* lTradeChart = pParentNode->FirstChildElement("trade_chart"); mTradeChart->deserializeFromXMLElement(lTradeChart); TiXmlNode* lImageChart = pParentNode->FirstChildElement("image_chart"); mImageChart->deserializeFromXMLElement(lImageChart); TiXmlNode* lFinanceChart = pParentNode->FirstChildElement("finance_chart"); mFinanceChart->deserializeFromXMLElement(lFinanceChart); } /*-----------------------------------------------------------------------------------------------*/ void Company::addResourceBuilding(boost::shared_ptr<ResourceBuilding> pBuilding) { mResourceBuildings.push_back(pBuilding); } /*-----------------------------------------------------------------------------------------------*/ bool Company::runAdCampaign(eAdType pType) { int lCost = 0; if (pType == eInternet) lCost = GameConfig::getInt("AdInternetCost"); else if (pType == eNewspaper) lCost = GameConfig::getInt("AdNewspaperCost"); else if (pType == eRadio) lCost = GameConfig::getInt("AdRadioCost"); else if (pType == eTV) lCost = GameConfig::getInt("AdTVCost"); if (mMoney >= lCost) { mMoney -= lCost; mCurrentMonth.mAdvertising -= lCost; mCurrentYear.mAdvertising -= lCost; AdCampaign lNewCampaign; lNewCampaign.mType = pType; lNewCampaign.mWeeksLeft = GameConfig::getInt("AdLenght"); mCampaigns.push_back(lNewCampaign); return true; } else { return false; } } /*-----------------------------------------------------------------------------------------------*/ std::vector<std::string> Company::getCityOpinions(int pCityIndex) { std::vector<std::string> lOpinions; if (mGlobalImage > 50.0 && randBool()) lOpinions.push_back(mName + StrLoc::get()->OpinionIsOK()); else if (randBool()) lOpinions.push_back(StrLoc::get()->OpinionDontLike1() + mName + StrLoc::get()->OpinionDontLike2()); if (mGlobalImage > 85.0 && randBool()) lOpinions.push_back(mName + StrLoc::get()->OpinionIsGreat()); if (mGlobalAdvertising > 20 && randBool()) lOpinions.push_back(StrLoc::get()->OpinionSawAd1() + mName + StrLoc::get()->OpinionSawAd2()); if (mGlobalPrice > 20 && randBool()) lOpinions.push_back(StrLoc::get()->OpinionPriceHigh1() + mName + StrLoc::get()->OpinionPriceHigh2()); else if (randBool()) lOpinions.push_back(StrLoc::get()->OpinionPriceOK1() + mName + StrLoc::get()->OpinionPriceOK2()); return lOpinions; } /*-----------------------------------------------------------------------------------------------*/ std::vector<std::string> Company::getCustomerOpinions(bool pAllCities, int pCityIndex) { std::vector<std::string> lOpinions; if (pAllCities) { for (size_t i = 0; i < mConnectedCities.size(); i++) { std::vector<std::string> lCityOpinions = getCityOpinions(-1); lOpinions.insert(lOpinions.end(), lCityOpinions.begin(), lCityOpinions.end()); } } else { lOpinions = getCityOpinions(-1); } return lOpinions; } /*-----------------------------------------------------------------------------------------------*/ void Company::dayPassed(EventData* pData) { mCoalPrice += (rand() % 6) * (((rand() % 2) == 0) ? -1 : 1); mGasPrice += (rand() % 6) * (((rand() % 2) == 0) ? -1 : 1); mUraniumPrice += (rand() % 6) * (((rand() % 2) == 0) ? -1 : 1); if (mCoalPrice > GameConfig::getInt("CoalUpperCap")) mCoalPrice = GameConfig::getInt("CoalUpperCap"); if (mGasPrice > GameConfig::getInt("GasUpperCap")) mGasPrice = GameConfig::getInt("GasUpperCap"); if (mUraniumPrice > GameConfig::getInt("UraniumUpperCap")) mUraniumPrice = GameConfig::getInt("UraniumUpperCap"); if (mCoalPrice < GameConfig::getInt("CoalLowerCap")) mCoalPrice = GameConfig::getInt("CoalLowerCap"); if (mGasPrice < GameConfig::getInt("GasLowerCap")) mGasPrice = GameConfig::getInt("GasLowerCap"); if (mUraniumPrice < GameConfig::getInt("UraniumLowerCap")) mUraniumPrice = GameConfig::getInt("UraniumLowerCap"); std::vector<int> lValuesTrade; lValuesTrade.push_back(mCoalPrice); lValuesTrade.push_back(mGasPrice); lValuesTrade.push_back(mUraniumPrice); mTradeChart->addValueSet(lValuesTrade); EventHandler::raiseEvent(eUpdateGUICompanyData); } /*-----------------------------------------------------------------------------------------------*/ std::vector<FinancialArchive> Company::getFinancialData(void) { std::vector<FinancialArchive> lData; mCurrentMonth.updateTotal(); mLastMonth.updateTotal(); mCurrentYear.updateTotal(); mLastYear.updateTotal(); lData.push_back(mCurrentMonth); lData.push_back(mLastMonth); lData.push_back(mCurrentYear); lData.push_back(mLastYear); return lData; } /*-----------------------------------------------------------------------------------------------*/ void Company::updateFinanceChart(EventData* pData) { FinanceChartSet lSet = static_cast<EventArg<FinanceChartSet>*>(pData)->mData1; std::vector<bool> lVisibleSet; lVisibleSet.push_back(lSet.mExpenses); lVisibleSet.push_back(lSet.mIncome); lVisibleSet.push_back(lSet.mFunds); lVisibleSet.push_back(lSet.mNetWorth); mFinanceChart->setValuesVisible(lVisibleSet); mFinanceChart->forceRepaint(); } /*-----------------------------------------------------------------------------------------------*/ void Company::weekPassed(EventData* pData) { handleAdCampaigns(); handleCustomers(); handleExecutingOffers(); handleSales(); handleRunningCosts(); handleAccidents(); updateResearch(); EventHandler::raiseEvent(eUpdateFinanceWindow); std::vector<int> lValuesFinance; lValuesFinance.push_back(mExpenses*8*-1); lValuesFinance.push_back(mIncome*8); lValuesFinance.push_back(mMoney); lValuesFinance.push_back(mNetWorth); mFinanceChart->addValueSet(lValuesFinance); std::vector<int> lValuesImage; lValuesImage.push_back((int)mGlobalImage); lValuesImage.push_back(mCompleteCustomers); mImageChart->addValueSet(lValuesImage); mIncome = 0; mExpenses = 0; handleMissionGoals(); if (mGasLastWeek > mGas) mGasTrend = 1; else if (mGasLastWeek < mGas) mGasTrend = -1; else mGasTrend = 0; if (mCoalLastWeek > mCoal) mCoalTrend = 1; else if (mCoalLastWeek < mCoal) mCoalTrend = -1; else mCoalTrend = 0; if (mUraniumLastWeek > mUranium) mUraniumTrend = 1; else if (mUraniumLastWeek < mUranium) mUraniumTrend = -1; else mUraniumTrend = 0; EventHandler::raiseEvent(eUpdateResourceTrend); mGasLastWeek = mGas; mCoalLastWeek = mCoal; mUraniumLastWeek = mUranium; } /*-----------------------------------------------------------------------------------------------*/ std::vector<int> Company::getResourceTrends(void) { std::vector<int> lTrends; lTrends.push_back(mCoalTrend); lTrends.push_back(mGasTrend); lTrends.push_back(mUraniumTrend); return lTrends; } /*-----------------------------------------------------------------------------------------------*/ void Company::handleRunningCosts(void) { std::vector<boost::shared_ptr<Powerplant> > lPowerplants = getAllPowerplants(); int lRunningCosts = 0; int lEnvironmentalCosts = 0; int lMaintenanceCost = 0; int lTrainingCosts = 0; int lSafetyCosts = 0; if (mTraining == eNoTraining) lTrainingCosts += ((lPowerplants.size()+mResourceBuildings.size()) *GameConfig::getInt("NoTrainingCostFactor")); else if (mTraining == eNormalTraining) lTrainingCosts += ((lPowerplants.size()+mResourceBuildings.size()) *GameConfig::getInt("NormalTrainingCostFactor")); else if (mTraining == eExtensiveTraining) lTrainingCosts += ((lPowerplants.size()+mResourceBuildings.size()) *GameConfig::getInt("ExtensiveTrainingCostFactor")); if (mSafety == eNoSafety) lSafetyCosts += ((lPowerplants.size()+mResourceBuildings.size()) *GameConfig::getInt("NoSafetyCostFactor")); else if (mSafety == eNormalSafety) lSafetyCosts += ((lPowerplants.size()+mResourceBuildings.size()) *GameConfig::getInt("NormalSafetyCostFactor")); else if (mSafety == eExtensiveSafety) lSafetyCosts += ((lPowerplants.size()+mResourceBuildings.size()) *GameConfig::getInt("ExtensiveSafetyCostFactor")); double lMaintenanceCostFactor = GameConfig::getDouble("MaintenanceCostFactor"); double lRunningCostFactor = GameConfig::getDouble("RunningCostFactor"); double lEnvCostFactor = GameConfig::getDouble("EnvCostFactor"); for (size_t i = 0; i < lPowerplants.size(); ++i) { lRunningCosts += lPowerplants[i]->getOperatingCosts()*lRunningCostFactor; lEnvironmentalCosts += lPowerplants[i]->getEnvironmentalCosts()*lEnvCostFactor; if (lPowerplants[i]->getInheritSettings()) lMaintenanceCost += (lPowerplants[i]-> getOperatingCosts()*0.5*(mGlobalMaintenance/100))*lMaintenanceCostFactor; else lMaintenanceCost += (lPowerplants[i]-> getOperatingCosts()*0.5*((float)lPowerplants[i]->getMaintenance()/100.0)) *lMaintenanceCostFactor; } for (size_t j = 0; j < mResourceBuildings.size(); ++j) { lRunningCosts += mResourceBuildings[j]->getOperatingCosts()*lRunningCostFactor; lEnvironmentalCosts += mResourceBuildings[j]->getEnvironmentalCosts()*lEnvCostFactor; if(mResourceBuildings[j]->getInheritSettings()) lMaintenanceCost += (mResourceBuildings[j]-> getOperatingCosts()*0.5*(mGlobalMaintenance/100))*lMaintenanceCostFactor; else lMaintenanceCost += (mResourceBuildings[j]-> getOperatingCosts()*0.5*((float)mResourceBuildings[j]-> getMaintenance()/100.0))*lMaintenanceCostFactor; } lMaintenanceCost += (mPowerNet->getLargePoleCount()*300* ((float)mSupplyMaintenance/100.0))*lMaintenanceCostFactor; lMaintenanceCost += (mPowerNet->getSmallPoleCount()*150* ((float)mSupplyMaintenance/100.0))*lMaintenanceCostFactor; if (mNoTrainingActive) lRunningCosts *= GameConfig::getDouble("NoTrainingCostReduction"); if (mWasteActive) lRunningCosts *= GameConfig::getDouble("WasteDumpingCostReduction"); if (mBribeActive) lEnvironmentalCosts *= GameConfig::getDouble("BribeCostReduction"); if (mResearchSet.mResearched[11]) lRunningCosts *= GameConfig::getDouble("ResearchedRunningCost"); if (mResearchSet.mResearched[13]) lEnvironmentalCosts *= GameConfig::getDouble("CO2ReductionEnvCost"); mMoney -= lRunningCosts; mMoney -= lEnvironmentalCosts; mMoney -= lMaintenanceCost; mMoney -= (lTrainingCosts+lSafetyCosts); mExpenses -= lRunningCosts; mExpenses -= lEnvironmentalCosts; mExpenses -= lMaintenanceCost; mExpenses -= (lTrainingCosts+lSafetyCosts); mCurrentMonth.mOperation -= lRunningCosts; mCurrentYear.mOperation -= lRunningCosts; mCurrentMonth.mEnvironmental -= lEnvironmentalCosts; mCurrentYear.mEnvironmental -= lEnvironmentalCosts; mCurrentMonth.mMaintenance -= lMaintenanceCost; mCurrentYear.mMaintenance -= lMaintenanceCost; mCurrentMonth.mTrainingSafety -= (lTrainingCosts+lSafetyCosts); mCurrentYear.mTrainingSafety -= (lTrainingCosts+lSafetyCosts); } /*-----------------------------------------------------------------------------------------------*/ void Company::handleSales(void) { int lAdvertisingThreshold = GameConfig::getDouble("AdvertisingThreshold"); if (mResearchSet.mResearched[2]) lAdvertisingThreshold = GameConfig::getDouble("AdvertisingResearchedThreshold"); mGlobalImage += ((float)mGlobalAdvertising - lAdvertisingThreshold) / 20.0; if (mAdBoost != 0) mGlobalImage += mAdBoost; int lSafetyFactor = 0; if (mTraining == eNoTraining) lSafetyFactor += GameConfig::getInt("SafetyFactorNoTraining"); else if (mTraining == eNormalTraining) lSafetyFactor += GameConfig::getInt("SafetyFactorNormalTraining"); else if (mTraining == eExtensiveTraining) lSafetyFactor += GameConfig::getInt("SafetyFactorExtensiveTraining"); if (mSafety == eNoSafety) lSafetyFactor += GameConfig::getInt("SafetyFactorNoSafety"); else if (mSafety == eNormalSafety) lSafetyFactor += GameConfig::getInt("SafetyFactorNormalSafety"); else if (mSafety == eExtensiveSafety) lSafetyFactor += GameConfig::getInt("SafetyFactorExtensiveSafety"); // compute accidents by safety factor if (mCustomerSupport == eNoSupport) mGlobalImage += GameConfig::getInt("NoSupportImageInf"); else if (mCustomerSupport == eExtensiveSupport) mGlobalImage += GameConfig::getInt("ExtensvieSupportImageInf"); if (mContractTime == eNoTime) mGlobalImage += GameConfig::getInt("NoTimeImageInf"); else if (mContractTime == e24) mGlobalImage += GameConfig::getInt("24TimeImageInf"); double lEnvSupportInf = GameConfig::getDouble("EnvSupportImageInf"); mGlobalImage += mEnvSupport / 40 * lEnvSupportInf; // buildings image influence { double lBuildingImageScaleFactor = GameConfig::getDouble("BuildingImageScaleFactor"); std::vector<boost::shared_ptr<Powerplant> > lPowerplants = getAllPowerplants(); std::vector<boost::shared_ptr<ResourceBuilding> > lResourceBuildings = getResourceBuildings(); for(size_t i = 0; i < lPowerplants.size(); ++i) mGlobalImage += GameConfig::getDouble(GameConfig::cCOTS(lPowerplants[i]->getSubtype()), cCOVImage)/lBuildingImageScaleFactor; for(size_t j = 0; j < lResourceBuildings.size(); ++j) mGlobalImage += GameConfig::getDouble(GameConfig::cCOTS(lResourceBuildings[j]->getSubtype()), cCOVImage)/lBuildingImageScaleFactor; if(mResearchBuilt) mGlobalImage += GameConfig::getDouble("COResearch_Image")/lBuildingImageScaleFactor; if(mPRBuilt) mGlobalImage += GameConfig::getDouble("COPublicRelations_Image")/lBuildingImageScaleFactor; if(mHeadquartersBuilt) mGlobalImage += GameConfig::getDouble("COHeadquarters_Image")/lBuildingImageScaleFactor; } if(mGlobalImage < 0.0) mGlobalImage = 0.0; if(mGlobalImage > 100.0) mGlobalImage = 100.0; mMoney -= mGlobalAdvertising * mConnectedCities.size(); mCurrentYear.mAdvertising -= mGlobalAdvertising * mConnectedCities.size(); mCurrentMonth.mAdvertising -= mGlobalAdvertising * mConnectedCities.size(); mExpenses -= mGlobalAdvertising * mConnectedCities.size(); } /*-----------------------------------------------------------------------------------------------*/ std::vector<boost::shared_ptr<City> > Company::getConnectedCities(bool pForceUpdate) { std::vector<boost::shared_ptr<City> > lConnectedCities; if (pForceUpdate) { for (size_t j = 0; j < mPowerNet->getSubnetCount(); j++) { std::vector<boost::shared_ptr<City> > lSubnetCities = mPowerNet->getSubnetCities(j); for (size_t k = 0; k < lSubnetCities.size(); k++) lConnectedCities.push_back(lSubnetCities[k]); } mConnectedCities = lConnectedCities; } else { lConnectedCities = mConnectedCities; } return lConnectedCities; } /*-----------------------------------------------------------------------------------------------*/ void Company::handleCustomers(void) { EventHandler::raiseEvent(eUpdatePowerNet); mCompleteCustomers = 0; std::vector<boost::shared_ptr<City> > lConnectedCities = getConnectedCities(true); for (size_t i = 0; i < lConnectedCities.size(); i++) { int lMaxCustomers = lConnectedCities[i]->getResidentCount(); int lCurrentCustomers = lConnectedCities[i]->getCustomers(); int lPossibleCustomers = lMaxCustomers - lCurrentCustomers; int lNewCustomers = 0; double lImageScaleFactor = GameConfig::getDouble("ImageScaleFactor"); double lPriceScaleFactor = GameConfig::getDouble("PriceScaleFactor"); double lAdvertisingScaleFactor = GameConfig::getDouble("AdvertisingScaleFactor"); double lPowerScaleFactor = GameConfig::getDouble("PowerScaleFactor"); float lImageScaler = lImageScaleFactor * ((mGlobalImage - 25.0)) / 100 * 0.002; float lPriceScaler = lPriceScaleFactor * ((mGlobalPrice - 20.0) * -1) / 100 * 0.004; float lAdvertisingScaler = lAdvertisingScaleFactor * ((mGlobalAdvertising) / 100 * 0.002); float lPowerScaler = 0; if (lConnectedCities[i]->getCustomers() > 0) if (lConnectedCities[i]->getConsumption() > lConnectedCities[i]->getCurrentSupply()) lPowerScaler = -0.004 * lPowerScaleFactor; if ((lImageScaler*lPriceScaler*lAdvertisingScaler*lPowerScaler) < 0.0) { lNewCustomers = (lImageScaler * (float)lCurrentCustomers) + (lPriceScaler * (float)lCurrentCustomers) + (lAdvertisingScaler * (float)lCurrentCustomers) + (lPowerScaler * (float)lCurrentCustomers); } else { lNewCustomers = (lImageScaler * (float)lPossibleCustomers) + (lPriceScaler * (float)lPossibleCustomers) + (lAdvertisingScaler * (float)lPossibleCustomers) + (lPowerScaler * (float)lPossibleCustomers); } if ((lCurrentCustomers + lNewCustomers) >= 0) lConnectedCities[i]->setCustomers(lCurrentCustomers + lNewCustomers); else lConnectedCities[i]->setCustomers(0); mCompleteCustomers += lConnectedCities[i]->getCustomers(); } float lPriceRigging = 1.0; if (mPriceActive) lPriceRigging = GameConfig::getDouble("PriceRiggingIncomeBoost"); float lIncomeMultiplicator = GameConfig::getDouble("DefaultIncomeMultiplicator"); if (mCustomerSupport == eNoSupport) lIncomeMultiplicator = GameConfig::getDouble("NoSupportIncomeFactor"); else if (mCustomerSupport == eNormalSupport) lIncomeMultiplicator = GameConfig::getDouble("NormalSupportIncomeFactor"); else if (mCustomerSupport == eExtensiveSupport) lIncomeMultiplicator = GameConfig::getDouble("ExtensiveSupportIncomeFactor"); if (mContractTime == eNoTime) lIncomeMultiplicator *= GameConfig::getDouble("PriceRiggingIncomeBoost"); else if (mContractTime == e12) lIncomeMultiplicator *= GameConfig::getDouble("12TimeIncomeFactor"); else if (mContractTime == e24) lIncomeMultiplicator *= GameConfig::getDouble("24TimeIncomeFactor"); mMoney += mGlobalPrice * (((float)mCompleteCustomers * GameConfig::getDouble("AverageCustomerDemand")) / 1000) * lIncomeMultiplicator * lPriceRigging; mCurrentMonth.mCustomerIncome += mGlobalPrice * (((float)mCompleteCustomers * GameConfig::getDouble("AverageCustomerDemand")) / 1000) * lIncomeMultiplicator * lPriceRigging; mCurrentYear.mCustomerIncome += mGlobalPrice * (((float)mCompleteCustomers * GameConfig::getDouble("AverageCustomerDemand")) / 1000) * lIncomeMultiplicator * lPriceRigging; mIncome += mGlobalPrice * (((float)mCompleteCustomers * GameConfig::getDouble("AverageCustomerDemand")) / 1000) * lIncomeMultiplicator * lPriceRigging; } /*-----------------------------------------------------------------------------------------------*/ void Company::handleExecutingOffers(void) { std::vector<TradingOffer>::iterator it = mExecutingOffers.begin(); bool lCancel = false; bool lReport = false; bool lMoney = false; while (it != mExecutingOffers.end()) { EventHandler::raiseEvent(eUpdateObligations); if ((*it).mWorldMarket) { if ((*it).mResource == eCoal) (*it).mFixedPrice = mCoalPrice; if ((*it).mResource == eGas) (*it).mFixedPrice = mGasPrice; if ((*it).mResource == eUranium) (*it).mFixedPrice = mUraniumPrice; } int lCheckFunds = (*it).mFixedPrice; if ((*it).mAmount > 0) lCheckFunds = (*it).mFixedPrice * -1; else if (mWarActive) (*it).mFixedPrice = (*it).mFixedPrice * 0.5; if ((mMoney - lCheckFunds * 1000) >= 0) { mMoney -= lCheckFunds * 1000; mCurrentMonth.mTrade -= lCheckFunds * 1000; mCurrentYear.mTrade -= lCheckFunds * 1000; if (lCheckFunds > 0) mExpenses -= lCheckFunds * 1000; else mIncome -= lCheckFunds * 1000; if ((*it).mResource == eCoal) { if ((mCoal - (*it).mAmount) >= 0) { adjustResource((*it).mResource, (*it).mAmount*-1); } else { lCancel = true; lMoney = false; lReport = true; } } if ((*it).mResource == eGas) { if ((mGas - (*it).mAmount) >= 0) { adjustResource((*it).mResource, (*it).mAmount*-1); } else { lCancel = true; lMoney = false; lReport = true; } } if ((*it).mResource == eUranium) { if ((mUranium - (*it).mAmount) >= 0) { adjustResource((*it).mResource, (*it).mAmount*-1); } else { lCancel = true; lMoney = false; lReport = true; } } } else { lCancel = true; lMoney = true; lReport = true; } (*it).mWeeks--; if ((((*it).mWeeks <= 0) && ((*it).mPermanent == false)) || (lCancel == true)) { if (lReport) contractCanceled(lMoney, "", "", ""); it = mExecutingOffers.erase(it); } else { it++; } } } /*-----------------------------------------------------------------------------------------------*/ void Company::contractCanceled(bool pMoney, std::string pPartner, std::string pBuySell, std::string pResource) { TickerMessage lMessage; if (pMoney) { lMessage.mMessage = StrLoc::get()->ContractCanceledMoney(); lMessage.mDetail = StrLoc::get()->ContractCanceledMoneyDetail(); } else { lMessage.mMessage = StrLoc::get()->ContractCanceledResources(); lMessage.mDetail = StrLoc::get()->ContractCanceledResourcesDetail(); } EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); EventHandler::raiseEvent(eUpdateObligations); } /*-----------------------------------------------------------------------------------------------*/ void Company::monthPassed(EventData* pData) { handleSpecialActions(); createNewTradeOffers(); handleLoans(); mMoney -= (mEnvSupport * 1000); mCurrentMonth.mEnvironmental -= (mEnvSupport * 1000); mCurrentYear.mEnvironmental -= (mEnvSupport * 1000); mExpenses -= (mEnvSupport * 1000); mLastMonth = mCurrentMonth; mCurrentMonth = FinancialArchive(); Weather lNewWeather; EventHandler::raiseEvent(eNewWeather, new EventArg<Weather>(lNewWeather)); } void Company::yearPassed(EventData* pData) { mLastYear = mCurrentYear; mCurrentYear = FinancialArchive(); if ((mBankruptcyWarningIssued) && (mMoney >= GameConfig::getInt("MaxDebtAfterWarning"))) mBankruptcyWarningIssued = false; if (mMoney < GameConfig::getInt("MaxDebtAfterWarning")) { if (mBankruptcyWarningIssued) { EventHandler::raiseEvent(eBankruptcy); } else { if (mMoney < GameConfig::getInt("MinDebtForWarning")) { EventHandler::raiseEvent(eBankruptcyWarning); mBankruptcyWarningIssued = true; } } } TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->NewYear(); lMessage.mPointOfInterest = Ogre::Vector2(-1.0, -1.0); lMessage.mUrgent = false; lMessage.mID = 0; EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); } /*-----------------------------------------------------------------------------------------------*/ std::string TradingOffer::formatted(void) { std::string lFormatted; if (mAmount < 0) lFormatted += StrLoc::get()->BuyF() + toString(mAmount*-1); else lFormatted += StrLoc::get()->SellF() + toString(mAmount); lFormatted += " " + getResourceUnit(mResource) + " " + resourceString(mResource); if (mAmount < 0) lFormatted += StrLoc::get()->From(); else lFormatted += StrLoc::get()->To(); lFormatted += mTradingPartner; if (mPermanent) { if (!mWorldMarket) lFormatted += ", " + StrLoc::get()->EveryWeek() + " (" + StrLoc::get()->PriceT() + ": " + toString(mFixedPrice) + L"k€" + StrLoc::get()->TooltipPerWeek() + ")"; else lFormatted += ", " + StrLoc::get()->EveryWeek() + " (" + StrLoc::get()->PriceT() + ": " + StrLoc::get()->WorldMarket() + " - " + toString(mDiscount + 1) + "%)"; } else { if (!mUnique) { if(!mWorldMarket) { lFormatted += StrLoc::get()->For() + toString(mWeeks) + " " + StrLoc::get()->Weeks() + " (" + StrLoc::get()->PriceT() + ": " + toString(mFixedPrice) + L"k€" + StrLoc::get()->TooltipPerWeek() + ")"; } else { if (mDiscount > 20) lFormatted += StrLoc::get()->For() + toString(mWeeks) + " " + StrLoc::get()->Weeks() + " (" + StrLoc::get()->PriceT() + ": " + StrLoc::get()->WorldMarket() + " - " + toString(mDiscount) + "%)"; else lFormatted += StrLoc::get()->For() + toString(mWeeks) + " " + StrLoc::get()->Weeks() + " (" + StrLoc::get()->PriceT() + ": " + StrLoc::get()->WorldMarket() + ")"; } } else { lFormatted += " (" + StrLoc::get()->PriceT() + ": " + toString(mFixedPrice) + L"k€)"; } } return lFormatted; } /*-----------------------------------------------------------------------------------------------*/ std::string TradingOffer::formattedCurrent(void) { std::string lFormatted; if (mAmount < 0) lFormatted += StrLoc::get()->BuyF() + toString(mAmount*-1); else lFormatted += StrLoc::get()->SellF() + toString(mAmount); lFormatted += " " + getResourceUnit(mResource) + " " + resourceString(mResource); if (mAmount < 0) lFormatted += StrLoc::get()->From(); else lFormatted += StrLoc::get()->To(); lFormatted += mTradingPartner; if (mPermanent) { if (!mWorldMarket) lFormatted += " (" + StrLoc::get()->EveryWeekS() + ", " + StrLoc::get()->PriceT() + ": " + toString(mFixedPrice) + L"k€" + StrLoc::get()->TooltipPerWeek() + ")"; else lFormatted += " (" + StrLoc::get()->EveryWeekS() + ", " + StrLoc::get()->PriceT() + ": " + StrLoc::get()->WorldMarket() + " - " + toString(mDiscount + 1) + "%)"; } else { if (!mWorldMarket) lFormatted += " (" + toString(mWeeks) + " " + StrLoc::get()->WeeksRemaining() + ", " + StrLoc::get()->PriceT() + ": " + toString(mFixedPrice) + L"k€" + StrLoc::get()->TooltipPerWeek() + ")"; else lFormatted += " (" + toString(mWeeks) + " " + StrLoc::get()->WeeksRemaining() + ", " + StrLoc::get()->PriceT() + ": " + StrLoc::get()->WorldMarket() + " - " + toString(mDiscount + 1) + "%)"; } return lFormatted; } /*-----------------------------------------------------------------------------------------------*/ void Company::createNewTradeOffers(void) { mTradingOffers.clear(); for (size_t i = 0; i < mTradingPartners.size(); i++) { if (mTradingPartners[i].mAvailable) { int lNumberOffers = (rand() % 4); for (int j = 0; j < lNumberOffers; j++) { TradingOffer lNewOffer; lNewOffer.mTradingPartner = mTradingPartners[i].mName; lNewOffer.mWorldMarket = randPercent(GameConfig::getDouble("WorldMarketProbability")); lNewOffer.mUnique = randPercent(GameConfig::getDouble("UniqueProbability")); lNewOffer.mDiscount = rand() % 51; lNewOffer.mResource = (eResourceType)(rand() % 3); lNewOffer.mWeeks = rand() % 27; int lPermanent = rand() % 5; if (lPermanent == 4) lNewOffer.mPermanent = true; else lNewOffer.mPermanent = false; if (lNewOffer.mUnique) lNewOffer.mAmount = (rand() % 5000) - 2500; else lNewOffer.mAmount = (rand() % 500) - 250; if (lNewOffer.mPermanent) lNewOffer.mAmount = (rand() % 500) - 250; if ((lNewOffer.mAmount > 100) || (lNewOffer.mAmount < -100)) { double lTradePriceFactor = GameConfig::getDouble("TradePriceFactor"); lNewOffer.mFixedPrice = (rand() % (lNewOffer.mAmount * 2)) * lTradePriceFactor; if (!lNewOffer.mUnique) { if (lNewOffer.mWeeks > 3) { mTradingOffers.push_back(lNewOffer); } } else { mTradingOffers.push_back(lNewOffer); } } } } } EventHandler::raiseEvent(eUpdateTradeWindow); } /*-----------------------------------------------------------------------------------------------*/ bool Company::acceptTradingOffer(std::string pName) { int lIndex; for (size_t i = 0; i < mTradingOffers.size(); i++) { if (pName == mTradingOffers[i].formatted()) { lIndex = i; break; } } if ((mTradingOffers[lIndex].mUnique) && (!mTradingOffers[lIndex].mPermanent)) { if (mTradingOffers[lIndex].mAmount > 0) { mTradingOffers[lIndex].mFixedPrice *= -1; } else { if (mTaxFreeTrades > 0) { mTradingOffers[lIndex].mFixedPrice = mTradingOffers[lIndex].mFixedPrice * 0.5; mTaxFreeTrades--; TickerMessage lMessage; if (mTaxFreeTrades > 1) lMessage.mMessage = toString(mTaxFreeTrades) + StrLoc::get()->FreeTradesLeft(); else if (mTaxFreeTrades == 1) lMessage.mMessage = toString(mTaxFreeTrades) + StrLoc::get()->FreeTradesLeft(); else lMessage.mMessage = StrLoc::get()->FreeTradesGone(); lMessage.mPointOfInterest = Ogre::Vector2(-1,-1); lMessage.mDetail = StrLoc::get()->FreeTradesDetail(); lMessage.mUrgent = false; EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); } if (mWarActive) mTradingOffers[lIndex].mFixedPrice = mTradingOffers[lIndex].mFixedPrice * 0.5; } if ((mMoney - mTradingOffers[lIndex].mFixedPrice * 1000) >= 0) { mMoney -= mTradingOffers[lIndex].mFixedPrice * 1000; mCurrentYear.mTrade -= mTradingOffers[lIndex].mFixedPrice * 1000; mCurrentMonth.mTrade -= mTradingOffers[lIndex].mFixedPrice * 1000; if (mTradingOffers[lIndex].mFixedPrice > 0) mExpenses -= mTradingOffers[lIndex].mFixedPrice * 1000; else mIncome -= mTradingOffers[lIndex].mFixedPrice * 1000; if (mTradingOffers[lIndex].mResource == eCoal) if ((mCoal - mTradingOffers[lIndex].mAmount) >= 0) adjustResource(mTradingOffers[lIndex].mResource, mTradingOffers[lIndex].mAmount*-1); else return false; if (mTradingOffers[lIndex].mResource == eGas) if ((mGas - mTradingOffers[lIndex].mAmount) >= 0) adjustResource(mTradingOffers[lIndex].mResource, mTradingOffers[lIndex].mAmount*-1); else return false; if (mTradingOffers[lIndex].mResource == eUranium) if ((mUranium - mTradingOffers[lIndex].mAmount) >= 0) adjustResource(mTradingOffers[lIndex].mResource, mTradingOffers[lIndex].mAmount*-1); else return false; mTradingOffers.erase(mTradingOffers.begin() + lIndex); return true; } } else { mExecutingOffers.push_back(mTradingOffers[lIndex]); mTradingOffers.erase(mTradingOffers.begin() + lIndex); return true; } return false; } /*-----------------------------------------------------------------------------------------------*/ bool Company::buyTradingPartner(std::string pName) { for (size_t i = 0; i < mTradingPartners.size(); i++) { if (mTradingPartners[i].mName.find(pName) != -1) { if (mMoney >= (mTradingPartners[i].mPrice*1000)) { mMoney -= mTradingPartners[i].mPrice*1000; mCurrentMonth.mTrade -= mTradingPartners[i].mPrice*1000; mCurrentYear.mTrade -= mTradingPartners[i].mPrice*1000; mTradingPartners[i].mAvailable = true; mExpenses -= mTradingPartners[i].mPrice*1000; return true; } } } return false; } /*-----------------------------------------------------------------------------------------------*/ void Company::addCompanyBuilding(boost::shared_ptr<CompanyBuilding> pBuilding) { mCompanyBuildings.push_back(pBuilding); } /*-----------------------------------------------------------------------------------------------*/ void Company::updateAnimations(float pElapsedTime) { for (size_t j = 0; j < mPowerNet->getSubnetCount(); j++) { std::vector<boost::shared_ptr<Powerplant> > lSubnetPowerplants = mPowerNet-> getSubnetPowerplants(j); for (size_t k = 0; k < lSubnetPowerplants.size(); k++) lSubnetPowerplants[k]->updateAnimations(pElapsedTime); } } /*-----------------------------------------------------------------------------------------------*/ std::vector<boost::shared_ptr<Powerplant> > Company::getAllPowerplants(void) { std::vector<boost::shared_ptr<Powerplant> > lReturn; for (size_t j = 0; j < mPowerNet->getSubnetCount(); j++) { std::vector<boost::shared_ptr<Powerplant> > lSubnetPowerplants = mPowerNet-> getSubnetPowerplants(j); for (size_t k = 0; k < lSubnetPowerplants.size(); k++) lReturn.push_back(lSubnetPowerplants[k]); } return lReturn; } /*-----------------------------------------------------------------------------------------------*/ void Company::handleLoans(void) { std::vector<Loan>::iterator it = mCurrentLoans.begin(); while (it != mCurrentLoans.end()) { (*it).mMonthLeft--; (*it).mAmountLeft -= (*it).mMonthlyRate; mMoney -= (*it).mMonthlyRate; mCurrentMonth.mLoanPayments -= (*it).mMonthlyRate; mCurrentYear.mLoanPayments -= (*it).mMonthlyRate; mExpenses -= (*it).mMonthlyRate; if ((*it).mMonthLeft <= 0) it = mCurrentLoans.erase(it); else it++; } EventHandler::raiseEvent(eUpdateLoans); } /*-----------------------------------------------------------------------------------------------*/ bool Company::takeOutLoan(Loan pLoan) { mMoney += pLoan.mAmountLeft; pLoan.mAmountLeft = pLoan.mMonthLeft * pLoan.mMonthlyRate; mCurrentLoans.push_back(pLoan); return true; } /*-----------------------------------------------------------------------------------------------*/ std::vector<Loan> Company::getLoans(void) { return mCurrentLoans; } /*-----------------------------------------------------------------------------------------------*/ bool Company::unscheduledRepayment(int pLoanIndex, int pAmount) { if (mMoney >= pAmount) { mMoney -= pAmount; mExpenses -= pAmount; mCurrentMonth.mLoanPayments -= pAmount; mCurrentYear.mLoanPayments -= pAmount; mCurrentLoans[pLoanIndex].mAmountLeft -= pAmount; mCurrentLoans[pLoanIndex].mMonthlyRate = mCurrentLoans[pLoanIndex].mAmountLeft / mCurrentLoans[pLoanIndex].mMonthLeft; if (mCurrentLoans[pLoanIndex].mAmountLeft <= 1001) mCurrentLoans.erase(mCurrentLoans.begin() + pLoanIndex); return true; } return false; } /*-----------------------------------------------------------------------------------------------*/ std::string Loan::formatted(void) { return StrLoc::get()->LoanFormattedA() + toString(mAmountLeft/1000) + StrLoc::get()->LoanFormattedB() + toString(mMonthlyRate/1000) + StrLoc::get()->LoanFormattedC() + toString(mMonthLeft) + StrLoc::get()->LoanFormattedD(); } /*-----------------------------------------------------------------------------------------------*/ ResearchSet::ResearchSet(void) { for (int i = 0; i < 21; i ++) { mStarted[i] = false; mResearched[i] = false; } mName[0] = StrLoc::get()->Re1(); mPrice[0] = GameConfig::getInt("Re0Price"); mWeeks[0] = GameConfig::getInt("Re0Duration"); mResearched[0] = false; mStarted[0] = false; mWeeksLeft[0] = 0; mPrerequesit[0] = -1; mName[1] = StrLoc::get()->Re2(); mPrice[1] = GameConfig::getInt("Re1Price"); mWeeks[1] = GameConfig::getInt("Re1Duration"); mResearched[1] = false; mStarted[1] = false; mWeeksLeft[1] = 0; mPrerequesit[1] = -1; mName[2] = StrLoc::get()->Re3(); mPrice[2] = GameConfig::getInt("Re2Price"); mWeeks[2] = GameConfig::getInt("Re2Duration"); mResearched[2] = false; mStarted[2] = false; mWeeksLeft[2] = 0; mPrerequesit[2] = -1; mName[3] = StrLoc::get()->Re4(); mPrice[3] = GameConfig::getInt("Re3Price"); mWeeks[3] = GameConfig::getInt("Re3Duration"); mResearched[3] = false; mStarted[3] = false; mWeeksLeft[3] = 0; mPrerequesit[3] = 1; mName[4] = StrLoc::get()->Re5(); mPrice[4] = GameConfig::getInt("Re4Price"); mWeeks[4] = GameConfig::getInt("Re4Duration"); mResearched[4] = false; mStarted[4] = false; mWeeksLeft[4] = 0; mPrerequesit[4] = 6; mName[5] = StrLoc::get()->Re6(); mPrice[5] = GameConfig::getInt("Re5Price"); mWeeks[5] = GameConfig::getInt("Re5Duration"); mResearched[5] = false; mStarted[5] = false; mWeeksLeft[5] = 0; mPrerequesit[5] = 0; mName[6] = StrLoc::get()->Re7(); mPrice[6] = GameConfig::getInt("Re6Price"); mWeeks[6] = GameConfig::getInt("Re6Duration"); mResearched[6] = false; mStarted[6] = false; mWeeksLeft[6] = 0; mPrerequesit[6] = 1; mName[7] = StrLoc::get()->Re8(); mPrice[7] = GameConfig::getInt("Re7Price"); mWeeks[7] = GameConfig::getInt("Re7Duration"); mResearched[7] = false; mStarted[7] = false; mWeeksLeft[7] = 0; mPrerequesit[7] = 9; mName[8] = StrLoc::get()->Re9(); mPrice[8] = GameConfig::getInt("Re8Price"); mWeeks[8] = GameConfig::getInt("Re8Duration"); mResearched[8] = false; mStarted[8] = false; mWeeksLeft[8] = 0; mPrerequesit[8] = 9; mName[9] = StrLoc::get()->Re10(); mPrice[9] = GameConfig::getInt("Re9Price"); mWeeks[9] = GameConfig::getInt("Re9Duration"); mResearched[9] = false; mStarted[9] = false; mWeeksLeft[9] = 0; mPrerequesit[9] = 0; mName[10] = StrLoc::get()->Re11(); mPrice[10] = GameConfig::getInt("Re10Price"); mWeeks[10] = GameConfig::getInt("Re10Duration"); mResearched[10] = false; mStarted[10] = false; mWeeksLeft[10] = 0; mPrerequesit[10] = 0; mName[11] = StrLoc::get()->Re12(); mPrice[11] = GameConfig::getInt("Re11Price"); mWeeks[11] = GameConfig::getInt("Re11Duration"); mResearched[11] = false; mStarted[11] = false; mWeeksLeft[11] = 0; mPrerequesit[11] = 2; mName[12] = StrLoc::get()->Re13(); mPrice[12] = GameConfig::getInt("Re12Price"); mWeeks[12] = GameConfig::getInt("Re12Duration"); mResearched[12] = false; mStarted[12] = false; mWeeksLeft[12] = 0; mPrerequesit[12] = 9; mName[13] = StrLoc::get()->Re14(); mPrice[13] = GameConfig::getInt("Re13Price"); mWeeks[13] = GameConfig::getInt("Re13Duration"); mResearched[13] = false; mStarted[13] = false; mWeeksLeft[13] = 0; mPrerequesit[13] = 11; mName[14] = StrLoc::get()->Re15(); mPrice[14] = GameConfig::getInt("Re14Price"); mWeeks[14] = GameConfig::getInt("Re14Duration"); mResearched[14] = false; mStarted[14] = false; mWeeksLeft[14] = 0; mPrerequesit[14] = 18; mName[15] = StrLoc::get()->Re16(); mPrice[15] = GameConfig::getInt("Re15Price"); mWeeks[15] = GameConfig::getInt("Re15Duration"); mResearched[15] = false; mStarted[15] = false; mWeeksLeft[15] = 0; mPrerequesit[15] = 3; mName[16] = StrLoc::get()->Re17(); mPrice[16] = GameConfig::getInt("Re16Price"); mWeeks[16] = GameConfig::getInt("Re16Duration"); mResearched[16] = false; mStarted[16] = false; mWeeksLeft[16] = 0; mPrerequesit[16] = 15; mName[17] = StrLoc::get()->Re18(); mPrice[17] = GameConfig::getInt("Re17Price"); mWeeks[17] = GameConfig::getInt("Re17Duration"); mResearched[17] = false; mStarted[17] = false; mWeeksLeft[17] = 0; mPrerequesit[17] = 15; mName[18] = StrLoc::get()->Re19(); mPrice[18] = GameConfig::getInt("Re18Price"); mWeeks[18] = GameConfig::getInt("Re18Duration"); mResearched[18] = false; mStarted[18] = false; mWeeksLeft[18] = 0; mPrerequesit[18] = 8; mName[19] = StrLoc::get()->Re20(); mPrice[19] = GameConfig::getInt("Re19Price"); mWeeks[19] = GameConfig::getInt("Re19Duration"); mResearched[19] = false; mStarted[19] = false; mWeeksLeft[19] = 0; mPrerequesit[19] = 18; mName[20] = StrLoc::get()->Re21(); mPrice[20] = GameConfig::getInt("Re20Price"); mWeeks[20] = GameConfig::getInt("Re20Duration"); mResearched[20] = false; mStarted[20] = false; mWeeksLeft[20] = 0; mPrerequesit[20] = 18; } /*-----------------------------------------------------------------------------------------------*/ std::string Company::getCurrentResearch(int &oPercentageCompleted) { for (int i = 0; i < 21; i++) { if (mResearchSet.mStarted[i] == true) { oPercentageCompleted = ((float)(mResearchSet.mWeeks[i] - mResearchSet.mWeeksLeft[i])/(float)mResearchSet.mWeeks[i])*99; return mResearchSet.mName[i]; } } oPercentageCompleted = 0; return StrLoc::get()->Nothing(); } /*-----------------------------------------------------------------------------------------------*/ bool Company::isAvailableInTree(size_t pResearchIndex) { if (mResearchSet.mPrerequesit[pResearchIndex] == -1) { return true; } else { if (mResearchSet.mResearched[mResearchSet.mPrerequesit[pResearchIndex]]) return true; else return false; } } /*-----------------------------------------------------------------------------------------------*/ void Company::handleAdCampaigns(void) { mAdBoost = 0; std::vector<AdCampaign>::iterator it = mCampaigns.begin(); while (it != mCampaigns.end()) { (*it).mWeeksLeft--; if ((*it).mType == eInternet) mAdBoost += GameConfig::getDouble("ImageBoostInternetAd"); else if ((*it).mType == eNewspaper) mAdBoost += GameConfig::getDouble("ImageBoostNewspaperAd"); else if ((*it).mType == eRadio) mAdBoost += GameConfig::getDouble("ImageBoostRadioAd"); else if ((*it).mType == eTV) mAdBoost += GameConfig::getDouble("ImageBoostTVAd"); if ((*it).mWeeksLeft <= 0) it = mCampaigns.erase(it); else it++; } } /*-----------------------------------------------------------------------------------------------*/ bool Company::startResearch(int pIndex) { if (mMoney >= mResearchSet.mPrice[pIndex]*1000) { mMoney -= mResearchSet.mPrice[pIndex]*1000; mCurrentMonth.mResearch -= mResearchSet.mPrice[pIndex]*1000; mCurrentYear.mResearch -= mResearchSet.mPrice[pIndex]*1000; mResearchSet.mStarted[pIndex] = true; mResearchSet.mWeeksLeft[pIndex] = mResearchSet.mWeeks[pIndex]; TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->ResearchStartedA() + mResearchSet.mName[pIndex] + StrLoc::get()->ResearchStartedB(); lMessage.mPointOfInterest = Ogre::Vector2(-1,-1); lMessage.mUrgent = false; EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); return true; } else { return false; } } /*-----------------------------------------------------------------------------------------------*/ void Company::updateResearch(void) { for (int i = 0; i < 21; i++) { if (mResearchSet.mStarted[i] == true) { mResearchSet.mWeeksLeft[i]--; if(mResearchSet.mWeeksLeft[i] <= 0) { mResearchSet.mResearched[i] = true; mResearchSet.mStarted[i] = false; TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->ResearchFinishedA() + mResearchSet.mName[i] + StrLoc::get()->ResearchFinishedB(); lMessage.mPointOfInterest = Ogre::Vector2(-1, -1); lMessage.mUrgent = false; if(i == 20) EventHandler::raiseEvent(eShowNewspaper, new EventArg<std::string>("np_fusion.png", StrLoc::get()->NPFusion(), mName + " " + StrLoc::get()->NPFusionDetail())); EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); EventHandler::raiseEvent(eUpdateResearchableButtons); EventHandler::raiseEvent(eUpdateCOBuildingButtons); } } } } /*-----------------------------------------------------------------------------------------------*/ bool Company::runSpecialAction(eSpecialAction pType) { int lPrice = 0; SpecialAction lSpecialAction; lSpecialAction.mType = pType; enum eSpecialAction { eBribe, eWar, ePrice, eEmployee, eTaxfraud, eWaste }; if (pType == eBribe) { lSpecialAction.mDone = false; lSpecialAction.mMonthLeft = 8; lSpecialAction.mTradesLeft = 1; lPrice = GameConfig::getInt("PriceBribe"); } else if (pType == ePrice) { lSpecialAction.mDone = false; lSpecialAction.mMonthLeft = 6; lSpecialAction.mTradesLeft = 0; lPrice = GameConfig::getInt("PricePriceRigging"); } else if (pType == eWar) { lSpecialAction.mDone = false; lSpecialAction.mMonthLeft = 12; lSpecialAction.mTradesLeft = 0; lPrice = GameConfig::getInt("PriceWarSupport"); } else if (pType == eEmployee) { lSpecialAction.mDone = false; lSpecialAction.mMonthLeft = 6; lSpecialAction.mTradesLeft = 0; lPrice = GameConfig::getInt("PriceNoTraining"); } else if (pType == eWaste) { lSpecialAction.mDone = false; lSpecialAction.mMonthLeft = 6; lSpecialAction.mTradesLeft = 0; lPrice = GameConfig::getInt("PriceWasteDumping"); } else if (pType == eTaxfraud) { lPrice = GameConfig::getInt("PriceTaxFraud"); } if(mMoney >= lPrice) { mMoney -= lPrice; mCurrentMonth.mSpecialExpenses -= lPrice; mCurrentYear.mSpecialExpenses -= lPrice; } else { return false; } if (pType == eTaxfraud) mTaxFreeTrades += 4; else mSpecialActions.push_back(lSpecialAction); return true; EventHandler::raiseEvent(eUpdateSpecialActions); } /*-----------------------------------------------------------------------------------------------*/ void Company::handleSpecialActions(void) { std::vector<SpecialAction>::iterator it = mSpecialActions.begin(); while (it != mSpecialActions.end()) { if ((*it).mType == eBribe) { (*it).mMonthLeft--; if ((*it).mTradesLeft == 1) // running mBribeActive = true; if ((*it).mMonthLeft <= 0) { if ((*it).mTradesLeft == 1) { (*it).mTradesLeft = 0; (*it).mMonthLeft = 48; if (randPercent(GameConfig::getDouble("ExposeProbBribe"))) { EventHandler::raiseEvent(eShowNewspaper, new EventArg<std::string>("np_bribe.png", StrLoc::get()->NPBribe(), mName + " " + StrLoc::get()->NPBribeDetail())); if (mGlobalImage >= GameConfig::getInt("ImageHitBribe")) mGlobalImage -= GameConfig::getInt("ImageHitBribe"); else mGlobalImage = 0; (*it).mDone = true; } } else { (*it).mDone = true; } } } else if ((*it).mType == ePrice) { (*it).mMonthLeft--; if ((*it).mMonthLeft <= 0) { mPriceActive = false; (*it).mDone = true; } else { mPriceActive = true; if (randPercent(GameConfig::getDouble("ExposeProbPriceRigging"))) { EventHandler::raiseEvent(eShowNewspaper, new EventArg<std::string>("np_price.png", StrLoc::get()->NPPriceRigging(), mName + " " + StrLoc::get()->NPPriceRiggingDetail())); if (mGlobalImage >= GameConfig::getInt("ImageHitPriceRigging")) mGlobalImage -= GameConfig::getInt("ImageHitPriceRigging"); else mGlobalImage = 0; (*it).mDone = true; mPriceActive = false; } } } else if ((*it).mType == eWar) { (*it).mMonthLeft--; if ((*it).mMonthLeft <= 0) { mWarActive = false; (*it).mDone = true; } else { mWarActive = true; if (randPercent(GameConfig::getDouble("ExposeProbWarSupport"))) { EventHandler::raiseEvent(eShowNewspaper, new EventArg<std::string>("np_war.png", StrLoc::get()->NPWar(), mName + " " + StrLoc::get()->NPWarDetail())); if (mGlobalImage >= GameConfig::getInt("ImageHitWarSupport")) mGlobalImage -= GameConfig::getInt("ImageHitWarSupport"); else mGlobalImage = 0; (*it).mDone = true; mWarActive = false; } } } else if ((*it).mType == eWaste) { (*it).mMonthLeft--; if ((*it).mMonthLeft <= 0) { mWasteActive = false; (*it).mDone = true; } else { mWasteActive = true; if (randPercent(GameConfig::getDouble("ExposeProbWasteDumping"))) { EventHandler::raiseEvent(eShowNewspaper, new EventArg<std::string>("np_waste.png", StrLoc::get()->NPWasteDumping(), mName + " " + StrLoc::get()->NPWasteDumpingDetail())); if (mGlobalImage >= GameConfig::getInt("ImageHitWasteDumping")) mGlobalImage -= GameConfig::getInt("ImageHitWasteDumping"); else mGlobalImage = 0; (*it).mDone = true; mWasteActive = false; } } } else if ((*it).mType == eEmployee) { (*it).mMonthLeft--; if ((*it).mMonthLeft <= 0) { mNoTrainingActive = false; (*it).mDone = true; } else { mNoTrainingActive = true; if (randPercent(GameConfig::getDouble("ExposeProbNoTraining"))) { EventHandler::raiseEvent(eShowNewspaper, new EventArg<std::string>("np_training.png", StrLoc::get()->NPNoTraining(), mName + " " + StrLoc::get()->NPNoTrainingDetail())); if (mGlobalImage >= GameConfig::getInt("ImageHitNoTraining")) mGlobalImage -= GameConfig::getInt("ImageHitNoTraining"); else mGlobalImage = 0; (*it).mDone = true; mNoTrainingActive = false; } } } if ((*it).mDone) { it = mSpecialActions.erase(it); EventHandler::raiseEvent(eUpdateSpecialActions); } else { it++; } } } /*-----------------------------------------------------------------------------------------------*/ void Company::removeResourceBuilding(boost::shared_ptr<Collidable> pObject) { std::vector<boost::shared_ptr<ResourceBuilding> >::iterator it = mResourceBuildings.begin(); while (it != mResourceBuildings.end()) { if ((*it)->getID() == pObject->getID()) it = mResourceBuildings.erase(it); else it++; } } /*-----------------------------------------------------------------------------------------------*/ void Company::handleMissionGoals(void) { bool mAllDone = true; for (size_t i = 0; i < mMissionGoals.size(); ++i) { if (mMissionGoals[i].mType != eFreePlay) { if (mMissionGoals[i].mType == eMoney) mMissionGoals[i].mValueCurrent = mMoney; if (mMissionGoals[i].mType == eCustomerCount) mMissionGoals[i].mValueCurrent = mCompleteCustomers; if (mMissionGoals[i].mValueCurrent >= mMissionGoals[i].mValueNeeded) mMissionGoals[i].mDone = true; if (!mMissionGoals[i].mDone) mAllDone = false; } else { mAllDone = false; } } if(mAllDone && !mKeepPlaying) EventHandler::raiseEvent(eMissionDone); } /*-----------------------------------------------------------------------------------------------*/ bool Company::isSpecialActionRunning(eSpecialAction pType) { for (size_t i = 0; i < mSpecialActions.size(); ++i) if (mSpecialActions[i].mType == pType) return true; if ((pType == eTaxfraud) && (mTaxFreeTrades > 0)) return true; return false; } /*-----------------------------------------------------------------------------------------------*/ int Company::getTaxFreeTradesLeft(void) { return mTaxFreeTrades; } /*-----------------------------------------------------------------------------------------------*/ void Company::handleAccidents(void) { if (randPercent(GameConfig::getDouble("PoleCollapseProbability")/(mSupplyMaintenance+1))) mPowerNet->destroyRandomPole(mMap); std::vector<boost::shared_ptr<Powerplant> > lPowerplants = getAllPowerplants(); for (size_t i = 0; i < lPowerplants.size(); ++i) { if ((randPercent(GameConfig::getDouble("PPShutdownProbability")/ (lPowerplants[i]->getCondition()+1))) && (lPowerplants[i]->getCondition() < 70)) { if (!lPowerplants[i]->getDamaged()) { lPowerplants[i]->setDamaged(); TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->DamagedPPMessageA() + lPowerplants[i]->getName() + StrLoc::get()->DamagedPPMessageB(); lMessage.mPointOfInterest = lPowerplants[i]->getPosition(); lMessage.mUrgent = false; lMessage.mID = 0; lMessage.mDetail = StrLoc::get()->DamagedDetail(); EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); } } } // random accidents { bool lAccident = false; if (mSafety == eNoSafety) if (randPercent(GameConfig::getDouble("PPAccidentProbabilityNoSafety"))) lAccident = true; else if (mSafety == eNormalSafety) if (randPercent(GameConfig::getDouble("PPAccidentProbabilityNormalSafety"))) lAccident = true; else if (mSafety == eExtensiveSafety) if (randPercent(GameConfig::getDouble("PPAccidentProbabilityExtensiveSafety"))) lAccident = true; if (lAccident) { int lPowerplantAffected = rand() % lPowerplants.size(); EventHandler::raiseEvent(eShowNewspaper, new EventArg<std::string>("np_accident.png", StrLoc::get()->Accident(), StrLoc::get()->AccidentDetail1() + lPowerplants[lPowerplantAffected]->getName() + StrLoc::get()->AccidentDetail2())); TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->PPShutdown1() + lPowerplants[lPowerplantAffected]->getName() + StrLoc::get()->PPShutdown2(); lMessage.mPointOfInterest = lPowerplants[lPowerplantAffected]->getPosition(); lMessage.mDetail = StrLoc::get()->PPAccidentDetail(); EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); lPowerplants[lPowerplantAffected]->setDamaged(); } } for (size_t j = 0; j < mResourceBuildings.size(); ++j) { if ((randPercent(GameConfig::getDouble("REShutdownProbability")/ (mResourceBuildings[j]->getCondition()+1))) && (mResourceBuildings[j]->getCondition() < 70)) { if (!mResourceBuildings[j]->getDamaged()) { mResourceBuildings[j]->setDamaged(); TickerMessage lMessage; lMessage.mMessage = StrLoc::get()->DamagedResourceMessageA() + mResourceBuildings[j]->getName() + StrLoc::get()->DamagedResourceMessageB(); lMessage.mPointOfInterest = mResourceBuildings[j]->getPosition(); lMessage.mUrgent = false; lMessage.mID = 0; lMessage.mDetail = StrLoc::get()->DamagedDetail(); EventHandler::raiseEvent(eTickerMessage, new EventArg<TickerMessage>(lMessage)); } } } } /*-----------------------------------------------------------------------------------------------*/ void Company::dump(std::string pFilename) { } /*-----------------------------------------------------------------------------------------------*/ bool Company::isCreditworthy(int pAmount, std::string& pWhyNot) { if ((int)mCurrentLoans.size() >= GameConfig::getInt("LoanMaxCount")) { pWhyNot = StrLoc::get()->TooManyLoans(); return false; } int lBaseVolume = GameConfig::getInt("LoanBaseVolume"); int lNetWorthFactor = GameConfig::getInt("LoanNetWorthFactor"); int lCompleteCreditVolume = 0; for (size_t i = 0; i < mCurrentLoans.size(); ++i) lCompleteCreditVolume += mCurrentLoans[i].mAmountLeft; int lCompleteK = (lCompleteCreditVolume + pAmount) / 1000; int lCreditMaxK = (lNetWorthFactor*mNetWorth + lBaseVolume) / 1000; int lNetWorthNeededK = ((lCompleteCreditVolume + pAmount - lBaseVolume)/lNetWorthFactor)/1000; if (lCompleteK > lCreditMaxK) { pWhyNot = StrLoc::get()->NotEnoughNetWorth() + StrLoc::get()->NetWorthNeeded() + toString(lNetWorthNeededK) + L"k€" + StrLoc::get()->NetWorthHave() + toString(mNetWorth/1000) + L"k€"; return false; } return true; }
36.88912
136
0.675207
[ "vector" ]
f2c51b8cda4603935541d655281e33184aaa04e9
604
cpp
C++
PatternProblems/PyramidPatternProblem/C++/PyramidPatternProblem1.cpp
riship99/codeWith-hacktoberfest
f16fa9dc9a2af0009dea3dea3220e3eaa43d3d2b
[ "MIT" ]
29
2020-10-03T17:41:46.000Z
2021-10-04T17:59:22.000Z
PatternProblems/PyramidPatternProblem/C++/PyramidPatternProblem1.cpp
riship99/codeWith-hacktoberfest
f16fa9dc9a2af0009dea3dea3220e3eaa43d3d2b
[ "MIT" ]
117
2020-10-03T15:39:39.000Z
2021-10-06T08:21:37.000Z
PatternProblems/PyramidPatternProblem/C++/PyramidPatternProblem1.cpp
riship99/codeWith-hacktoberfest
f16fa9dc9a2af0009dea3dea3220e3eaa43d3d2b
[ "MIT" ]
160
2020-10-03T15:39:23.000Z
2021-10-13T09:07:05.000Z
//Solid rectangular star pattern: //Number of rows: 3 //Number of columns: 5 //* * * * * //* * * * * //* * * * * //Program to print solid rectangular star pattern #include <iostream> using namespace std; /* Function to print solid rectangle*/ void solid_rectangle(int n, int m) { int i, j; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { cout << “*”; } cout << endl; } } int main() { int rows, columns; cout << “nEnter the number of rows : “; cin >> rows; cout << “nEnter the number of columns : “; cin >> columns; cout << endl; solid_rectangle(rows, columns); return 0; }
10.237288
49
0.57947
[ "solid" ]
f2c7cab561788cc7a5606f5012b56f050c215d50
16,093
cpp
C++
src/rhombicToricLattice.cpp
MikeVasmer/Sweep-Decoder-Boundaries
5acd1d94303333fda0d2a1e206ee884f9b372fe9
[ "MIT" ]
null
null
null
src/rhombicToricLattice.cpp
MikeVasmer/Sweep-Decoder-Boundaries
5acd1d94303333fda0d2a1e206ee884f9b372fe9
[ "MIT" ]
2
2020-04-03T00:33:11.000Z
2021-12-02T20:22:57.000Z
src/rhombicToricLattice.cpp
MikeVasmer/Sweep-Decoder-Boundaries
5acd1d94303333fda0d2a1e206ee884f9b372fe9
[ "MIT" ]
1
2021-02-22T19:48:24.000Z
2021-02-22T19:48:24.000Z
#include "rhombicToricLattice.h" #include "lattice.h" #include <string> #include <iostream> #include <cmath> #include <algorithm> #include <map> RhombicToricLattice::RhombicToricLattice(const int length) : Lattice(length) { if (length % 2 != 0) { throw std::invalid_argument("Lattice length l must be even for rhombic toric lattices."); } faceToVertices.reserve(3 * l * l * l); faceToEdges.reserve(3 * l * l * l); // Not all vertices present in this lattice, but all w=1 faces // are present, so the possible vertex indices go from // 0 to l^3 -1 vertexToFaces.assign(2 * l * l * l, {}); vertexToEdges.assign(2 * l * l * l, {}); } int RhombicToricLattice::neighbour(const int vertexIndex, const std::string &direction, const int sign) { if (!(sign == 1 || sign == -1)) { throw std::invalid_argument("Sign must be either 1 or -1."); } if (!(direction == "xy" || direction == "xz" || direction == "yz" || direction == "xyz")) { throw std::invalid_argument("Direction must be one of 'xy', 'xz', 'yz' or 'xyz'."); } cartesian4 coordinate; coordinate = indexToCoordinate(vertexIndex); // if (direction == "x") // coordinate.x = (coordinate.x + sign + l) % l; // if (direction == "y") // coordinate.y = (coordinate.y + sign + l) % l; // if (direction == "z") // coordinate.z = (coordinate.z + sign + l) % l; if (coordinate.w == 1) { if (direction == "xy") { coordinate.x = (coordinate.x + (sign > 0)) % l; coordinate.y = (coordinate.y + (sign > 0)) % l; coordinate.z = (coordinate.z + (sign < 0)) % l; coordinate.w = 0; } if (direction == "xz") { coordinate.x = (coordinate.x + (sign > 0)) % l; coordinate.z = (coordinate.z + (sign > 0)) % l; coordinate.y = (coordinate.y + (sign < 0)) % l; coordinate.w = 0; } if (direction == "yz") { coordinate.y = (coordinate.y + (sign > 0)) % l; coordinate.z = (coordinate.z + (sign > 0)) % l; coordinate.x = (coordinate.x + (sign < 0)) % l; coordinate.w = 0; } if (direction == "xyz") { coordinate.x = (coordinate.x + (sign > 0)) % l; coordinate.y = (coordinate.y + (sign > 0)) % l; coordinate.z = (coordinate.z + (sign > 0)) % l; coordinate.w = 0; } } else { if (direction == "xy") { coordinate.x = (coordinate.x - (sign < 0) + l) % l; coordinate.y = (coordinate.y - (sign < 0) + l) % l; coordinate.z = (coordinate.z - (sign > 0) + l) % l; coordinate.w = 1; } if (direction == "xz") { coordinate.x = (coordinate.x - (sign < 0) + l) % l; coordinate.z = (coordinate.z - (sign < 0) + l) % l; coordinate.y = (coordinate.y - (sign > 0) + l) % l; coordinate.w = 1; } if (direction == "yz") { coordinate.y = (coordinate.y - (sign < 0) + l) % l; coordinate.z = (coordinate.z - (sign < 0) + l) % l; coordinate.x = (coordinate.x - (sign > 0) + l) % l; coordinate.w = 1; } if (direction == "xyz") { coordinate.x = (coordinate.x - (sign < 0) + l) % l; coordinate.y = (coordinate.y - (sign < 0) + l) % l; coordinate.z = (coordinate.z - (sign < 0) + l) % l; coordinate.w = 1; } } return coordinateToIndex(coordinate); } void RhombicToricLattice::createFaces() { int faceIndex = 0; for (int vertexIndex = 0; vertexIndex < l * l * l; ++vertexIndex) { cartesian4 coordinate = indexToCoordinate(vertexIndex); if ((coordinate.x + coordinate.y + coordinate.z) % 2 == 0) { vint signs = {1, 1, 1, 1}; addFace(vertexIndex, faceIndex, {"xyz", "yz", "yz", "xyz"}, signs); ++faceIndex; addFace(vertexIndex, faceIndex, {"xyz", "xz", "xz", "xyz"}, signs); ++faceIndex; addFace(vertexIndex, faceIndex, {"xyz", "xy", "xy", "xyz"}, signs); ++faceIndex; signs = {1, -1, -1, 1}; addFace(vertexIndex, faceIndex, {"xy", "xz", "xz", "xy"}, signs); ++faceIndex; addFace(vertexIndex, faceIndex, {"xy", "yz", "yz", "xy"}, signs); ++faceIndex; addFace(vertexIndex, faceIndex, {"xz", "yz", "yz", "xz"}, signs); ++faceIndex; } } } void RhombicToricLattice::createUpEdgesMap() { std::vector<std::string> directionList = {"xyz", "xy", "xz", "yz", "-xyz", "-xy", "-xz", "-yz"}; for (const auto &direction : directionList) { vvint vertexToUpEdges; vertexToUpEdges.assign(2 * l * l * l, {}); for (int vertexIndex = 0; vertexIndex < 2 * l * l * l; ++vertexIndex) { cartesian4 coordinate = indexToCoordinate(vertexIndex); if (coordinate.w == 0) { if ((coordinate.x + coordinate.y + coordinate.z) % 2 == 0) { if (direction == "xyz") { // Third argument is sign vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", 1)); } else if (direction == "yz") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", -1)); } else if (direction == "xz") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", -1)); } else if (direction == "xy") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", -1)); } else if (direction == "-xyz") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", -1)); } else if (direction == "-yz") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", -1)); } else if (direction == "-xz") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", -1)); } else if (direction == "-xy") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", -1)); } } } else { if ((coordinate.x + coordinate.y + coordinate.z) % 2 == 0) { if (direction == "xy" || direction == "xz" || direction == "yz" || direction == "-xyz") { // Only one up edge, so return an empty vector as no sweep will happen here. } else { if (direction == "xyz") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", 1)); } else if (direction == "-xy") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", 1)); } else if (direction == "-xz") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", 1)); } else if (direction == "-yz") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", 1)); } } } else { if (direction == "-xy" || direction == "-xz" || direction == "-yz" || direction == "xyz") { // Only one up edge, so return an empty vector as no sweep will happen here. } else { if (direction == "-xyz") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", -1)); } else if (direction == "xy") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", -1)); } else if (direction == "xz") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", -1)); } else if (direction == "yz") { vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", 1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", -1)); vertexToUpEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", -1)); } } } } } upEdgesMap.insert(std::pair<std::string, vvint>(direction, vertexToUpEdges)); } } void RhombicToricLattice::createVertexToEdges() { for (int vertexIndex = 0; vertexIndex < 2 * l * l * l; ++vertexIndex) { cartesian4 coordinate = indexToCoordinate(vertexIndex); if (coordinate.w == 0) { if ((coordinate.x + coordinate.y + coordinate.z) % 2 == 0) { int sign = 1; vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", sign)); vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", sign)); vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", sign)); vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", sign)); sign = -1; vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", sign)); vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", sign)); vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", sign)); vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", sign)); } } else { if ((coordinate.x + coordinate.y + coordinate.z) % 2 == 0) { int sign = 1; vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", sign)); vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", sign)); vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", sign)); sign = -1; vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", sign)); } else { int sign = -1; vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xy", sign)); vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xz", sign)); vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "yz", sign)); sign = 1; vertexToEdges[vertexIndex].push_back(edgeIndex(vertexIndex, "xyz", sign)); } } } }
48.327327
110
0.47791
[ "vector" ]
f2d97affb56b228cf24ea4c7d2cfecf919ffae95
5,479
cpp
C++
gcommon/source/gscenenodecomponentcollision.cpp
DavidCoenFish/ancient-code-0
243fb47b9302a77f9b9392b6e3f90bba2ef3c228
[ "Unlicense" ]
null
null
null
gcommon/source/gscenenodecomponentcollision.cpp
DavidCoenFish/ancient-code-0
243fb47b9302a77f9b9392b6e3f90bba2ef3c228
[ "Unlicense" ]
null
null
null
gcommon/source/gscenenodecomponentcollision.cpp
DavidCoenFish/ancient-code-0
243fb47b9302a77f9b9392b6e3f90bba2ef3c228
[ "Unlicense" ]
null
null
null
// // GSceneNodeComponentCollision.cpp // // Created by David Coen on 2011 02 18 // Copyright 2010 Pleasure seeking morons. All rights reserved. // #include "GSceneNodeComponentCollision.h" #include "GSceneNode.h" #include "GSceneNodeComponentCollisionLoad.h" #include "GSceneNodeComponentCollisionDataLoad.h" #include "GSceneNodeComponentCollisionDataBase.h" #include "GSceneNodeComponentCollisionResult.h" #include "GSceneType.h" #include "GMatrix9Float.h" #include "GStringUtility.h" //static public methods /*static*/ GSceneNodeComponentCollision::TPointerSceneNodeComponentBase GSceneNodeComponentCollision::Factory( GScene& inout_scene, //access to mesh/ material manager TPointerSceneNode& inout_owner, //pain, some components may want access to owner. means we need to create components after node, so node needs ablity to add component TArrayScenePostLoadCallback& inout_arrayPostLoadCallback, const void* const in_componentData ) { TPointerSceneNodeComponentBase pointer; if (!in_componentData) { return pointer; } const GSceneNodeComponentCollisionLoad& componentLoad = *((GSceneNodeComponentCollisionLoad*)in_componentData); TArrayPointerSceneNodeComponentCollisionDataBase arrayCollisionDataBase; for (int index = 0; index < componentLoad.GetCollisionDataCount(); ++index) { const GSceneNodeComponentCollisionDataLoad& dataLoad = componentLoad.GetArrayCollisionData()[index]; TPointerSceneNodeComponentCollisionDataBase pointerData = dataLoad.Factory(); if (pointerData) { arrayCollisionDataBase.push_back(pointerData); } } pointer.reset(new GSceneNodeComponentCollision( *inout_owner, componentLoad.GetMaterialId(), GStringUtility::SafeString(componentLoad.GetData()), arrayCollisionDataBase, componentLoad.GetFlagActive() )); return pointer; } /*static*/ const unsigned int GSceneNodeComponentCollision::GetComponentFlag() { return GSceneType::TComponentFlag::TCollision; } //constructor GSceneNodeComponentCollision::GSceneNodeComponentCollision( GSceneNode& in_parentSceneNode, const int in_materialId, const std::string& in_data, TArrayPointerSceneNodeComponentCollisionDataBase& in_arrayData, //WARN: transfer ownership const bool in_active ) : GSceneNodeComponentBase(GetComponentFlag()) , mParentSceneNode(in_parentSceneNode) , mMaterialId(in_materialId) , mData(in_data) , mArrayData(in_arrayData) , mActive(in_active) { return; } GSceneNodeComponentCollision::~GSceneNodeComponentCollision() { return; } //public methods void GSceneNodeComponentCollision::CollideRay( TArrayPointerSceneNodeComponentCollisionResult& inout_collisionResult, TWeakSceneNodeComponentCollision& in_weakOwner, const bool in_wantHitSurfaceNormalObjectSpace, const bool in_wantHitSurfaceNormalWorldSpace, const GVector3Float& in_worldSpaceRayOrigin, const GVector3Float& in_worldSpaceRayDirection ) { const GMatrix16Float& worldTransform = mParentSceneNode.GetWorldTransform(); const GMatrix9Float rotation = worldTransform.GetRotation(); GMatrix9Float invertRotation(rotation); invertRotation.TransposeSelf(); const GVector3Float objectSpaceRayOrigin = (in_worldSpaceRayOrigin - worldTransform.GetPosition()) * invertRotation; const GVector3Float objectSpaceRayDirection = in_worldSpaceRayDirection * invertRotation; for (TArrayPointerSceneNodeComponentCollisionDataBase::iterator iterator = mArrayData.begin(); iterator != mArrayData.end(); ++iterator) { (*iterator)->CollideRay( inout_collisionResult, in_weakOwner, (in_wantHitSurfaceNormalObjectSpace || in_wantHitSurfaceNormalWorldSpace), objectSpaceRayOrigin, objectSpaceRayDirection ); } if (in_wantHitSurfaceNormalWorldSpace) { for (TArrayPointerSceneNodeComponentCollisionResult::iterator iterator = inout_collisionResult.begin(); iterator != inout_collisionResult.end(); ++iterator) { (*iterator)->PutNormalIntoWorldSpace(rotation); } } return; } void GSceneNodeComponentCollision::CollideCone( TArrayPointerSceneNodeComponentCollisionResult& inout_collisionResult, TWeakSceneNodeComponentCollision& in_weakOwner, const bool in_wantHitSurfaceNormalObjectSpace, const bool in_wantHitSurfaceNormalWorldSpace, const GVector3Float& in_worldSpaceRayOrigin, const GVector3Float& in_worldSpaceRayDirection, const float in_coneLength, const float in_radiusOne, const float in_radiusTwo ) { const GMatrix16Float& worldTransform = mParentSceneNode.GetWorldTransform(); const GMatrix9Float rotation = worldTransform.GetRotation(); GMatrix9Float invertRotation(rotation); invertRotation.TransposeSelf(); const GVector3Float objectSpaceRayOrigin = (in_worldSpaceRayOrigin - worldTransform.GetPosition()) * invertRotation; const GVector3Float objectSpaceRayDirection = in_worldSpaceRayDirection * invertRotation; for (TArrayPointerSceneNodeComponentCollisionDataBase::iterator iterator = mArrayData.begin(); iterator != mArrayData.end(); ++iterator) { (*iterator)->CollideCone( inout_collisionResult, in_weakOwner, (in_wantHitSurfaceNormalObjectSpace || in_wantHitSurfaceNormalWorldSpace), objectSpaceRayOrigin, objectSpaceRayDirection, in_coneLength, in_radiusOne, in_radiusTwo ); } if (in_wantHitSurfaceNormalWorldSpace) { for (TArrayPointerSceneNodeComponentCollisionResult::iterator iterator = inout_collisionResult.begin(); iterator != inout_collisionResult.end(); ++iterator) { (*iterator)->PutNormalIntoWorldSpace(rotation); } } return; }
32.808383
167
0.81493
[ "mesh" ]
f2e277eb368dd1c454010e91dac470c49e176713
3,107
cxx
C++
vital/algo/integrate_depth_maps.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
1
2020-10-14T18:22:42.000Z
2020-10-14T18:22:42.000Z
vital/algo/integrate_depth_maps.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
vital/algo/integrate_depth_maps.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +29 * Copyright 2017-2019 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither name of Kitware, Inc. 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 COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file * \brief Instantiation of \link * kwiver::vital::algo::algorithm_def algorithm_def<T> \endlink for \link * kwiver::vital::algo::integrate_depth_maps integrate_depth_maps \endlink */ #include <vital/algo/integrate_depth_maps.h> #include <vital/algo/algorithm.txx> namespace kwiver { namespace vital { namespace algo { integrate_depth_maps ::integrate_depth_maps() { attach_logger( "algo.integrate_depth_maps" ); } /// Integrate multiple depth maps into a common volume /** * * \param [in] minpt_bound the min point of the bounding region * \param [in] maxpt_bound the max point of the bounding region * \param [in] depth_maps the set of floating point depth map images * \param [in] cameras the set of cameras, one for each depth map * \param [in,out] volume the fused volumetric data * \param [out] spacing the spacing between voxels in each dimension */ void integrate_depth_maps ::integrate(vector_3d const& minpt_bound, vector_3d const& maxpt_bound, std::vector<image_container_sptr> const& depth_maps, std::vector<camera_perspective_sptr> const& cameras, image_container_sptr& volume, vector_3d &spacing) const { // call the weighted version, but leave the weights empty this->integrate(minpt_bound, maxpt_bound, depth_maps, {}, cameras, volume, spacing); } } } } /// \cond DoxygenSuppress INSTANTIATE_ALGORITHM_DEF(kwiver::vital::algo::integrate_depth_maps); /// \endcond
38.8375
81
0.731574
[ "vector" ]
f2e97c61ed8c15756fa092050eefcbdd01be9984
4,769
cpp
C++
AString/AString/main.cpp
Milo-Shen/Data-Structure-Course
20366fb9583694e33f3f57273362b1e677541729
[ "MIT" ]
1
2021-09-21T07:53:59.000Z
2021-09-21T07:53:59.000Z
AString/AString/main.cpp
Milo-Shen/Data-Structure-Course
20366fb9583694e33f3f57273362b1e677541729
[ "MIT" ]
null
null
null
AString/AString/main.cpp
Milo-Shen/Data-Structure-Course
20366fb9583694e33f3f57273362b1e677541729
[ "MIT" ]
null
null
null
// // main.cpp // AString // // Created by Sllimen on 2021/10/6. // #include <string.h> #include <iostream> using namespace std; const int defaultSize = 128; class AString { private: char* ch; int curLength; int maxSize; public: AString(int size = defaultSize) { maxSize = size; ch = new char[maxSize + 1]; if (ch == NULL) { cerr << "Allocation Error !" << endl; exit(1); } curLength = 0; ch[0] = '\0'; } AString(const char* init) { int len = (int)strlen(init); maxSize = len > maxSize ? len : maxSize; ch = new char[maxSize + 1]; if (ch == NULL) { cerr << "Allocation Error !" << endl; exit(1); } curLength = len; strcpy(ch, init); } AString(const AString& obj) { maxSize = obj.maxSize; curLength = obj.curLength; ch = new char[maxSize + 1]; if (ch == NULL) { cerr << "Allocation Error !" << endl; exit(1); } strcpy(ch, obj.ch); cout << "Copy Constructor has been called !" << endl; } ~AString() { delete[] ch; ch = NULL; } int Length() { return curLength; } // Copy Constructor will be called if we return AString& // Warning: Reference to stack memory associated with local variable 'temp' // returned ( AString& ) AString operator()(int pos, int len) { AString temp; if (pos < 0 || len < 0 || pos + len - 1 >= maxSize) { temp.curLength = 0; temp.ch[0] = '\0'; } else { if (pos + len - 1 >= curLength) len = curLength - pos; temp.curLength = len; for (int i = 0, j = pos; i < len; i++, j++) { temp.ch[i] = ch[j]; } temp.ch[len] = '\0'; } return temp; } int operator==(const AString& obj) const { return strcmp(ch, obj.ch) == 0; } int operator!=(const AString& obj) const { return strcmp(ch, obj.ch) != 0; } int operator!() const { return curLength == 0; } // To avoid: error for object 0x100766ab0: pointer being freed was not // allocated If & is missing: Copy Constructor has been called ! AString& operator=(const AString& obj) { if (&obj != this) { if (ch != NULL) delete[] ch; ch = new char[obj.maxSize]; if (ch == NULL) { cerr << "Allocation Error !" << endl; exit(1); } curLength = obj.curLength; strcpy(ch, obj.ch); } else cerr << "Error assigning the string itself !" << endl; cout << "overload operator = has been called !" << endl; return *this; } // If & is missing: Copy Constructor has been called ! AString& operator+=(const AString& obj) { char* temp = ch; int curLen = curLength + obj.curLength; int finalLen = curLen >= maxSize ? curLen : maxSize; ch = new char[finalLen]; if (ch == NULL) { cerr << "Allocation Error !" << endl; exit(1); } maxSize = finalLen; curLength = curLen; strcpy(ch, temp); strcat(ch, obj.ch); delete[] temp; temp = NULL; cout << "overload operator += has been called !" << endl; return *this; } char* getCH() { return ch; } char& operator[](int i) { if (i <= 0 || i > curLength) { cout << "out of boundary !" << endl; } return ch[i]; } friend ostream& operator<<(ostream& out, AString& M) { out << M.ch; return out; } }; int main(int argc, const char* argv[]) { cout << "Hello World" << endl; AString a("I am Hubery"); // Test operator: () AString b = a(5, 6); AString empty; // Test operator: == cout << (a == b ? "true" : "false") << endl; // Test operator: != cout << (a != b ? "true" : "false") << endl; // Test operator: ! cout << (!empty ? "true" : "false") << endl; // Test operator: = AString c; c = a; cout << static_cast<void*>(&a.getCH()[0]) << endl; cout << static_cast<void*>(&c.getCH()[0]) << endl; // Test: Copy Constructor AString d = c; cout << d << endl; cout << static_cast<void*>(&c.getCH()[0]) << endl; cout << static_cast<void*>(&d.getCH()[0]) << endl; // Test operator: += AString e("I Like: "); // Const variable can only call const functions const AString f("C++"); e += f; cout << e << endl; // Test operator: [] cout << e[2] << endl; return 0; }
27.408046
80
0.487524
[ "object" ]
f2edee29ef0cd5c2d129d1387b3850f95558284a
2,435
cpp
C++
ch04/CallbackSample/javacaller.cpp
argama147/qt-android
ca9e5a7d5b35bd9d81e6d12455b8c9d296e2e880
[ "MIT" ]
null
null
null
ch04/CallbackSample/javacaller.cpp
argama147/qt-android
ca9e5a7d5b35bd9d81e6d12455b8c9d296e2e880
[ "MIT" ]
null
null
null
ch04/CallbackSample/javacaller.cpp
argama147/qt-android
ca9e5a7d5b35bd9d81e6d12455b8c9d296e2e880
[ "MIT" ]
null
null
null
#include "javacaller.h" #include <QQuickItem> #include <QMetaObject> std::function<void(int data)> gCallbackInt; std::function<void(const QString& message)> gCallbackString; JavaCaller::JavaCaller(QObject *root, QObject *parent) : QObject(parent) { QQuickItem *button = root->findChild<QQuickItem *>("callJavaButton"); connect(button, SIGNAL(clicked()), this, SLOT(callJava())); registerNativeMethods(); gCallbackInt = std::bind(&JavaCaller::receiveFromJavaInt, this, std::placeholders::_1); gCallbackString = std::bind(&JavaCaller::receiveFromJavaString, this, std::placeholders::_1); } void JavaCaller::receiveFromJavaInt(int data) { qDebug() << __FUNCTION__ << data; } void JavaCaller::receiveFromJavaString(const QString& message) { qDebug() << __FUNCTION__ << message; } void JavaCaller::fromJavaInt(JNIEnv *env, jobject thiz, jint x) { Q_UNUSED(env) Q_UNUSED(thiz) gCallbackInt(x); } void JavaCaller::fromJavaString(JNIEnv *env, jobject thiz, jstring str) { Q_UNUSED(env) Q_UNUSED(thiz) QAndroidJniObject obj(str); gCallbackString(obj.toString()); } void JavaCaller::callJava() { callJavaMethod(); } void JavaCaller::registerNativeMethods() { JNINativeMethod methods[] { {"callNativeInt", "(I)V", reinterpret_cast<void *>(fromJavaInt)}, {"callNativeString", "(Ljava/lang/String;)V", reinterpret_cast<void *>(fromJavaString)}}; QAndroidJniObject javaClass("com/eugo/example/callbacksample/MyClass"); QAndroidJniEnvironment env; jclass objectClass = env->GetObjectClass(javaClass.object<jobject>()); env->RegisterNatives(objectClass, methods, sizeof(methods) / sizeof(methods[0])); env->DeleteLocalRef(objectClass); } void JavaCaller::callJavaMethod() { QAndroidJniObject::callStaticMethod<void>("com/eugo/example/callbacksample/MyClass", "method1", "(I)V", 10); QString str = "Test"; QAndroidJniObject::callStaticMethod<void>("com/eugo/example/callbacksample/MyClass", "method2", "(Ljava/lang/String;)V", QAndroidJniObject::fromString(str).object<jstring>()); }
29.695122
100
0.619302
[ "object" ]
f2ee42aaec4d469f6a06ada5b39904fb75812acc
6,861
cpp
C++
GunBird - CodedDreams/ModuleEnemies.cpp
Adria-F/Gunbird-Coded-Dreams
9a65ae346507a0db20e9d682081b08a0b8d31c43
[ "Info-ZIP", "CECILL-B" ]
null
null
null
GunBird - CodedDreams/ModuleEnemies.cpp
Adria-F/Gunbird-Coded-Dreams
9a65ae346507a0db20e9d682081b08a0b8d31c43
[ "Info-ZIP", "CECILL-B" ]
9
2017-05-02T09:58:30.000Z
2017-05-15T20:33:19.000Z
GunBird - CodedDreams/ModuleEnemies.cpp
Adria-F/Gunbird-Coded-Dreams
9a65ae346507a0db20e9d682081b08a0b8d31c43
[ "Info-ZIP", "CECILL-B" ]
null
null
null
#include "Application.h" #include "ModuleInput.h" #include "ModuleRender.h" #include "ModuleEnemies.h" #include "ModuleParticles.h" #include "ModuleTextures.h" #include "ModuleSceneMine.h" #include "Enemy.h" //Include all enemies #include "Enemy_Balloon.h" #include "Enemy_Torpedo.h" #include "Enemy_Tank.h" #include "Enemy_Flying_Machine.h" #include "Enemy_Miners.h" #include "Enemy_Drone.h" #include "Enemy_Trump.h" #include "Enemy_Falling_Drone.h" #include "Enemy_Barrel.h" #include "Enemy_Megaman.h" #include "Enemy_General_Turret.h" #include "Enemy_Antiaircraft_left.h" #include "Enemy_Antiaircraft_right.h" #include "Enemy_Boss1_Base.h" #include "Enemy_CentralSide.h" #include "Enemy_LeftSide.h" #include "Enemy_RightSide.h" #define SPAWN_MARGIN 75 ModuleEnemies::ModuleEnemies() { for(uint i = 0; i < MAX_ENEMIES; ++i) enemies[i] = nullptr; } // Destructor ModuleEnemies::~ModuleEnemies() { } bool ModuleEnemies::Start() { // Create a prototype for each enemy available so we can copy them around //sprites = App->textures->Load("rtype/enemies.png"); return true; } update_status ModuleEnemies::PreUpdate() { // check camera position to decide what to spawn for(uint i = 0; i < MAX_ENEMIES; ++i) { if(queue[i].type != ENEMY_TYPES::NO_TYPE) { if(-queue[i].y < App->render->camera.y + SPAWN_MARGIN) { SpawnEnemy(queue[i]); queue[i].type = ENEMY_TYPES::NO_TYPE; LOG("Spawning enemy at %d", queue[i].y * SCREEN_SIZE); } } } return UPDATE_CONTINUE; } // Called before render is available update_status ModuleEnemies::Update() { if (draw_underlayed) { for (uint i = 0; i < MAX_ENEMIES; ++i) if (enemies[i] != nullptr && (enemies[i]->lower_level)) enemies[i]->Draw(enemies[i]->sprites); } else { for (uint i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] != nullptr && App->scene_mine->lost == false) { if (enemies[i]->die) enemies[i]->DeadAnim(); else enemies[i]->Move(); } } for (uint i = 0; i < MAX_ENEMIES; ++i) if (enemies[i] != nullptr && (enemies[i]->collider == nullptr) && (enemies[i]->lower_level == false)) enemies[i]->Draw(enemies[i]->sprites); for (uint i = 0; i < MAX_ENEMIES; ++i) if (enemies[i] != nullptr && (enemies[i]->collider != nullptr) && (enemies[i]->collider->type == COLLIDER_DECORATION) && (enemies[i]->lower_level == false)) enemies[i]->Draw(enemies[i]->sprites); for (uint i = 0; i < MAX_ENEMIES; ++i) if (enemies[i] != nullptr && (enemies[i]->collider != nullptr) && (enemies[i]->collider->type == COLLIDER_ENEMY) && (enemies[i]->lower_level == false)) enemies[i]->Draw(enemies[i]->sprites); for (uint i = 0; i < MAX_ENEMIES; ++i) if (enemies[i] != nullptr && (enemies[i]->collider != nullptr) && (enemies[i]->collider->type == COLLIDER_NONE) && (enemies[i]->lower_level == false)) enemies[i]->Draw(enemies[i]->sprites); for (uint i = 0; i < MAX_ENEMIES; ++i) if (enemies[i] != nullptr && (enemies[i]->collider != nullptr) && (enemies[i]->collider->type == COLLIDER_AIR_ENEMY) && (enemies[i]->lower_level == false)) enemies[i]->Draw(enemies[i]->sprites); } return UPDATE_CONTINUE; } update_status ModuleEnemies::PostUpdate() { // check camera position to decide what to despawn for(uint i = 0; i < MAX_ENEMIES; ++i) { if(enemies[i] != nullptr) { if (enemies[i]->position.x < -(SPAWN_MARGIN + 1) || enemies[i]->position.x >(SCREEN_WIDTH + (SPAWN_MARGIN + 1)) || enemies[i]->position.y > (-App->render->camera.y + SCREEN_HEIGHT + (SPAWN_MARGIN + 1)) || enemies[i]->position.y < (-App->render->camera.y - (SPAWN_MARGIN + 1))) //if ((abs((int)App->render->camera.y) + SCREEN_HEIGHT + SPAWN_MARGIN) < enemies[i]->position.y) { LOG("DeSpawning enemy at %d", enemies[i]->position.y * SCREEN_SIZE); delete enemies[i]; enemies[i] = nullptr; } } } return UPDATE_CONTINUE; } // Called before quitting bool ModuleEnemies::CleanUp() { LOG("Freeing all enemies"); for(uint i = 0; i < MAX_ENEMIES; ++i) { if(enemies[i] != nullptr) { delete enemies[i]; enemies[i] = nullptr; } if (queue[i].type != NO_TYPE) { queue[i].type = NO_TYPE; } } return true; } bool ModuleEnemies::AddEnemy(ENEMY_TYPES type, int x, int y, int wave, int id) { bool ret = false; for(uint i = 0; i < MAX_ENEMIES; ++i) { if(queue[i].type == ENEMY_TYPES::NO_TYPE) { queue[i].type = type; queue[i].x = x; queue[i].y = y; queue[i].wave = wave; queue[i].id = id; ret = true; break; } } return ret; } void ModuleEnemies::SpawnEnemy(const EnemyInfo& info) { // find room for the new enemy uint i = 0; for(; enemies[i] != nullptr && i < MAX_ENEMIES; ++i); if(i != MAX_ENEMIES) { switch (info.type) { case ENEMY_TYPES::TANK: enemies[i] = new Enemy_Tank(info.x, info.y, info.wave); break; case ENEMY_TYPES::TORPEDO: enemies[i] = new Enemy_Torpedo(info.x, info.y, info.wave); break; case ENEMY_TYPES::MINER: enemies[i] = new Enemy_Miners(info.x, info.y, info.wave, info.id); break; case ENEMY_TYPES::TRUMP: enemies[i] = new Enemy_Trump(info.x, info.y, info.wave, info.id); break; case ENEMY_TYPES::BALLON: enemies[i] = new Enemy_Balloon(info.x, info.y); break; case ENEMY_TYPES::FLYING_MACHINE: enemies[i] = new Enemy_Flying_Machine(info.x, info.y); break; case ENEMY_TYPES::DRONE: enemies[i] = new Enemy_Drone(info.x, info.y, info.wave, info.id); break; case ENEMY_TYPES::FALLING_DRONE: enemies[i] = new Enemy_Faling_Drone(info.x, info.y, info.wave, info.id); break; case ENEMY_TYPES::BARREL: enemies[i] = new Enemy_Barrel(info.x, info.y); break; case ENEMY_TYPES::MEGAMAN: enemies[i] = new Enemy_Megaman(info.x, info.y); break; case ENEMY_TYPES::GENERAL_TURRET: enemies[i] = new Enemy_General_Turret(info.x, info.y, info.wave, info.id); break; case ENEMY_TYPES::RIGHTSIDE: enemies[i] = new Enemy_RightSide(info.x, info.y); break; case ENEMY_TYPES::LEFTSIDE: enemies[i] = new Enemy_LeftSide(info.x, info.y); break; case ENEMY_TYPES::CENTRALSIDE: enemies[i] = new Enemy_CentralSide(info.x, info.y); break; case ENEMY_TYPES::BOSS1_BASE: enemies[i] = new Enemy_Boss1_Base(info.x, info.y, info.wave, info.id); break; case ENEMY_TYPES::ANTIAIRCRAFT_LEFT: enemies[i] = new Enemy_Antiaircraft_left(info.x, info.y, info.id); break; case ENEMY_TYPES::ANTIAIRCRAFT_RIGHT: enemies[i] = new Enemy_Antiaircraft_right(info.x, info.y, info.id); break; } } } void ModuleEnemies::OnCollision(Collider* c1, Collider* c2) { for(uint i = 0; i < MAX_ENEMIES; ++i) { if (enemies[i] != nullptr && enemies[i]->GetCollider() == c1) { enemies[i]->OnCollision(c2); if (enemies[i]->lives <= 0 && enemies[i]->die == false) { enemies[i]->collider->to_delete = true; enemies[i]->collider = nullptr; } break; } } }
27.22619
279
0.65661
[ "render" ]
f2f148ed6ac31bddf9d888a9a2bb3f1b21c35244
19,523
cc
C++
grad3/unit_test/outcar_test.cc
Ionizing/usefultools-for-vasp
b13e821fb5f4024a45b3d16176033b9577e1cf31
[ "MIT" ]
8
2019-03-18T08:21:24.000Z
2021-07-20T07:56:39.000Z
grad3/unit_test/outcar_test.cc
Ionizing/usefultools-for-vasp
b13e821fb5f4024a45b3d16176033b9577e1cf31
[ "MIT" ]
9
2019-01-22T16:30:55.000Z
2021-02-08T13:16:45.000Z
grad3/unit_test/outcar_test.cc
IonizingRadiation/usefultools-for-vasp
b13e821fb5f4024a45b3d16176033b9577e1cf31
[ "MIT" ]
4
2019-03-06T03:29:54.000Z
2020-03-14T04:24:03.000Z
#define CATCH_CONFIG_MAIN #define UNIT_TEST // #define OUTCAR_DEBUG #include <outcar.hpp> #include <catch.hpp> using namespace ionizing; OUTCAR outcar("./test4/OUTCAR"); TEST_CASE("parse_elems debug") { VecStr str_vec { " POTCAR: PAW_PBE O 08Apr2002 ", " POTCAR: PAW_PBE Ti_pv 07Sep2000 ", " POTCAR: PAW_PBE Ba_sv 06Sep2000 " }; VecStr result { "O", "Ti", "Ba" }; VecStr parse_result; for (size_t i=0; i!=str_vec.size(); ++i) { string tmp = split(str_vec[i])[2]; if (tmp.length() > 2) { tmp.erase(2, string::npos); } parse_result.emplace_back(std::move(tmp)); } REQUIRE(parse_result == result); } TEST_CASE("parse_elems test") { VecStr str_vec { " POTCAR: PAW_PBE O 08Apr2002 ", " POTCAR: PAW_PBE Ti_pv 07Sep2000 ", " POTCAR: PAW_PBE Ba_sv 06Sep2000 " }; VecStr result { "O", "Ti", "Ba" }; REQUIRE(result == outcar.parse_elems(str_vec)); } TEST_CASE("Read OUTCAR to one string and VecStr") { std::ifstream ifs("./test1/OUTCAR"); string content = outcar.file_to_string(ifs); WHEN("into one string") { string tail(content.end() - 7, content.end()); string head(content.begin(), content.begin() + 10); REQUIRE(tail == "125489\n"); REQUIRE(head == " vasp.5.3."); } WHEN("into VecStr") { VecStr vec_str = outcar.string_to_vecstr(content); string head {" vasp.5.3.5 31Mar14 (build Nov 09 2015 12:05:13) complex "}; string tail {" Voluntary context switches: 125489"}; REQUIRE(vec_str.front() == head); REQUIRE(vec_str.back() == tail); } WHEN("from raw file") { std::ifstream ifs2("./test3/OUTCAR"); VecStr elem_name { "Cu", "C", "H" }; std::vector<int> ions_per_type {100, 2, 2}; string content = outcar.file_to_string(ifs2); VecStr contentVector = outcar.string_to_vecstr(content); REQUIRE(outcar.parseElems(contentVector) == elem_name); REQUIRE(outcar._atomsPerElem == ions_per_type); } } TEST_CASE("Parse Lattice Vector") { VecStr raw_lines { " A1 = ( 9.0750000000, -9.0750000000, 0.0000000000)", " A2 = ( 9.0750000000, 9.0750000000, 0.0000000000)", " A3 = ( 0.0000000000, 0.0000000000, 29.0400000000)" }; Mat33d result; result << 9.0750000000, -9.0750000000, 0.0000000000, 9.0750000000, 9.0750000000, 0.0000000000, 0.0000000000, 0.0000000000, 29.0400000000; WHEN("private member") { REQUIRE(outcar.parse_lattice_vectors(raw_lines) == result); VecStr broken_lines_1 {raw_lines}; VecStr broken_lines_2 {raw_lines}; broken_lines_1.pop_back(); broken_lines_2[2][1] = 'a'; REQUIRE_THROWS(outcar.parse_lattice_vectors(broken_lines_1)); REQUIRE_THROWS(outcar.parse_lattice_vectors(broken_lines_2)); } WHEN("from raw file") { std::ifstream ifs("./test3/OUTCAR"); string content = outcar.file_to_string(ifs); VecStr contentVector = outcar.string_to_vecstr(content); REQUIRE(outcar.parseLatticeVectors(contentVector) == result); } } TEST_CASE("Parse KPoints") { string NKPTS_line = " k-points NKPTS = 20 k-points in BZ NKDIM = 20 number of bands NBANDS= 81"; VecStr KPoints_lines { "0.06250000 0.06250000 0.06250000 0.016", "0.18750000 0.06250000 0.06250000 0.047", "0.31250000 0.06250000 0.06250000 0.047", "0.43750000 0.06250000 0.06250000 0.047", "0.18750000 0.18750000 0.06250000 0.047", "0.31250000 0.18750000 0.06250000 0.094", "0.43750000 0.18750000 0.06250000 0.094", "0.31250000 0.31250000 0.06250000 0.047", "0.43750000 0.31250000 0.06250000 0.094", "0.43750000 0.43750000 0.06250000 0.047", "0.18750000 0.18750000 0.18750000 0.016", "0.31250000 0.18750000 0.18750000 0.047", "0.43750000 0.18750000 0.18750000 0.047", "0.31250000 0.31250000 0.18750000 0.047", "0.43750000 0.31250000 0.18750000 0.094", "0.43750000 0.43750000 0.18750000 0.047", "0.31250000 0.31250000 0.31250000 0.016", "0.43750000 0.31250000 0.31250000 0.047", "0.43750000 0.43750000 0.31250000 0.047", "0.43750000 0.43750000 0.43750000 0.016", }; MatX3d kpoint_result; kpoint_result.resize(20, 3); kpoint_result << 0.06250000, 0.06250000, 0.06250000, 0.18750000, 0.06250000, 0.06250000, 0.31250000, 0.06250000, 0.06250000, 0.43750000, 0.06250000, 0.06250000, 0.18750000, 0.18750000, 0.06250000, 0.31250000, 0.18750000, 0.06250000, 0.43750000, 0.18750000, 0.06250000, 0.31250000, 0.31250000, 0.06250000, 0.43750000, 0.31250000, 0.06250000, 0.43750000, 0.43750000, 0.06250000, 0.18750000, 0.18750000, 0.18750000, 0.31250000, 0.18750000, 0.18750000, 0.43750000, 0.18750000, 0.18750000, 0.31250000, 0.31250000, 0.18750000, 0.43750000, 0.31250000, 0.18750000, 0.43750000, 0.43750000, 0.18750000, 0.31250000, 0.31250000, 0.31250000, 0.43750000, 0.31250000, 0.31250000, 0.43750000, 0.43750000, 0.31250000, 0.43750000, 0.43750000, 0.43750000; WHEN("Normal case") { REQUIRE(outcar.parse_nkpts(NKPTS_line) == 20); REQUIRE(outcar._incar._NKPTS == 20); REQUIRE(outcar.parse_kpoints(KPoints_lines) == kpoint_result); } WHEN("Negative NKPTS") { const string line = " k-points NKPTS = -8 k-points in BZ NKDIM = 20 number of bands NBANDS= 81"; REQUIRE_THROWS(outcar.parse_nkpts(line)); REQUIRE(-1 == outcar._incar._NKPTS); } WHEN("Invalid NKPTS line prefix") { const string line = " k-points NKPTS = -8 k-points in BZ NKDIM = 20 number of bands NBANDS= 81"; REQUIRE_THROWS(outcar.parse_nkpts(line)); REQUIRE(-1 == outcar._incar._NKPTS); } WHEN("Missing NKPTS data") { const string line = " k-points NKPTS = "; REQUIRE_THROWS(outcar.parse_nkpts(line)); REQUIRE(-1 == outcar._incar._NKPTS); } WHEN("KPoint array damaged") { outcar.parse_nkpts(NKPTS_line); KPoints_lines.pop_back(); REQUIRE_THROWS(outcar.parse_kpoints(KPoints_lines)); } WHEN("KPoint array contains invalid charactor") { KPoints_lines[19][11] = 'a'; outcar.parse_nkpts(NKPTS_line); REQUIRE_THROWS(outcar.parse_kpoints(KPoints_lines)); } WHEN("from raw file") { std::ifstream ifs("./test2/OUTCAR"); string content = outcar.file_to_string(ifs); VecStr contentVector = outcar.string_to_vecstr(content); REQUIRE(kpoint_result == outcar.parseKPoints(contentVector)); } } TEST_CASE("INCAR Parameters in OUTCAR") { string ediff_line = " EDIFF = 0.1E-05 stopping-criterion for ELM"; string ediffg_line = " EDIFFG = -.3E-01 stopping-criterion for IOM"; string encut_line = " ENCUT = 500.0 eV 36.75 Ry 6.06 a.u. 30.47 23.11 54.70*2*pi/ulx,y,z "; string ibrion_line = " IBRION = 1 ionic relax: 0-MD 1-quasi-New 2-CG"; string isif_line = " ISIF = 3 stress and relaxation"; string ispin_line = " ISPIN = 1 spin polarized calculation?"; string lnoncollinear_line = " LNONCOLLINEAR = F non collinear calculations"; string lsorbit_line = " LSORBIT = F spin-orbit coupling"; string lorbit_line = " LORBIT = 0 0 simple, 1 ext, 2 COOP (PROOUT)"; string nbands_line = " k-points NKPTS = 9 k-points in BZ NKDIM = 9 number of bands NBANDS= 98"; string nelmin_line = " NELM = 60; NELMIN= 6; NELMDL= -5 # of ELM steps"" NELM = 60; NELMIN= 6; NELMDL= -5 # of ELM steps"; string nions_line = " number of dos NEDOS = 301 number of ions NIONS = 27"; string nsw_line = " NSW = 200 number of steps for IOM"; string nkpts_line = nbands_line; WHEN("parse_ediff") { REQUIRE(1e-6 == outcar.parse_ediff(ediff_line)); REQUIRE(1e-6 == outcar._incar._EDIFF); } WHEN("parse_ediffg") { REQUIRE(-3e-2 == outcar.parse_ediffg(ediffg_line)); REQUIRE(-3e-2 == outcar._incar._EDIFFG); } WHEN("parse_encut") { REQUIRE(500.0 == outcar.parse_encut(encut_line)); REQUIRE(500.0 == outcar._incar._ENCUT); } WHEN("parse_ibrion") { REQUIRE(1 == outcar.parse_ibrion(ibrion_line)); REQUIRE(1 == outcar._incar._IBRION); } WHEN("parse_isif") { REQUIRE(3 == outcar.parse_isif(isif_line)); REQUIRE(3 == outcar._incar._ISIF); } WHEN("parse_ispin") { REQUIRE(1 == outcar.parse_ispin(ispin_line)); REQUIRE(1 == outcar._incar._ISPIN); } WHEN("parse_lnoncollinear") { REQUIRE(0 == outcar.parse_lnoncollinear(lnoncollinear_line)); REQUIRE(0 == outcar._incar._LNONCOLLINEAR); } WHEN("parse_lsorbit") { REQUIRE(0 == outcar.parse_lsorbit(lsorbit_line)); REQUIRE(0 == outcar._incar._LSORBIT); } WHEN("parse_lorbit") { REQUIRE(0 == outcar.parse_lorbit(lorbit_line)); REQUIRE(0 == outcar._incar._LORBIT); } WHEN("parse_nbands") { REQUIRE(98 == outcar.parse_nbands(nbands_line)); REQUIRE(98 == outcar._incar._NBANDS); } WHEN("parse_nelmin") { REQUIRE(6 == outcar.parse_nelmin(nelmin_line)); REQUIRE(6 == outcar._incar._NELMIN); } WHEN("parse_nions") { REQUIRE(27 == outcar.parse_nions(nions_line)); REQUIRE(27 == outcar._incar._NIONS); } WHEN("parse_nsw") { REQUIRE(200 == outcar.parse_nsw(nsw_line)); REQUIRE(200 == outcar._incar._NSW); } WHEN("parse_nkpts") { REQUIRE(9 == outcar.parse_nkpts(nkpts_line)); REQUIRE(9 == outcar._incar._NKPTS); } std::ifstream ifs("./test2/OUTCAR"); string content = outcar.file_to_string(ifs); VecStr contentVector = outcar.string_to_vecstr(content); outcar.parseINCAR(contentVector); INCAR incar_result; incar_result._EDIFF = 1e-6; incar_result._EDIFFG = -1e-2; incar_result._ENCUT = 400.0; incar_result._IBRION = 1; incar_result._ISIF = 3; incar_result._ISPIN = 1; incar_result._LNONCOLLINEAR = 0; incar_result._LORBIT = 0; incar_result._LSORBIT = 0; incar_result._NBANDS = 81; incar_result._NELMIN = 2; incar_result._NIONS = 32; incar_result._NSW = 100; incar_result._NKPTS = 20; WHEN("EDIFF") REQUIRE(incar_result._EDIFF == outcar._incar._EDIFF ); WHEN("EDIFFG") REQUIRE(incar_result._EDIFFG == outcar._incar._EDIFFG ); WHEN("ENCUT") REQUIRE(incar_result._ENCUT == outcar._incar._ENCUT ); WHEN("IBRION") REQUIRE(incar_result._IBRION == outcar._incar._IBRION ); WHEN("ISIF") REQUIRE(incar_result._ISIF == outcar._incar._ISIF ); WHEN("ISPIN") REQUIRE(incar_result._ISPIN == outcar._incar._ISPIN ); WHEN("LNONCOLLINEAR") REQUIRE(incar_result._LNONCOLLINEAR == outcar._incar._LNONCOLLINEAR); WHEN("LORBIT") REQUIRE(incar_result._LORBIT == outcar._incar._LORBIT ); WHEN("LSORBIT") REQUIRE(incar_result._LSORBIT == outcar._incar._LSORBIT ); WHEN("NBANDS") REQUIRE(incar_result._NBANDS == outcar._incar._NBANDS ); WHEN("NELMIN") REQUIRE(incar_result._NELMIN == outcar._incar._NELMIN ); WHEN("NIONS") REQUIRE(incar_result._NIONS == outcar._incar._NIONS ); WHEN("NSW") REQUIRE(incar_result._NSW == outcar._incar._NSW ); WHEN("NKPTS") REQUIRE(incar_result._NKPTS == outcar._incar._NKPTS ); } TEST_CASE("Parse Initial Position") { VecStr lines { " position of ions in fractional coordinates (direct lattice) ", " 0.64620000 0.57360000 0.50000000", " 0.50000000 0.35470000 0.50000000", " 0.35380000 0.57360000 0.50000000", " 0.50000000 0.50000000 0.50000000", "", " position of ions in cartesian coordinates (Angst):", " 3.87720000 4.01520000 4.00000000", " 3.00000000 2.48290000 4.00000000", " 2.12280000 4.01520000 4.00000000", " 3.00000000 3.50000000 4.00000000" }; WHEN("Parsing Initial Positions") { outcar._incar._NIONS = 4; REQUIRE_NOTHROW(outcar.parseInitialPositions(lines)); REQUIRE(0 != outcar._initialPosition_cart.size()); REQUIRE(outcar._initialPosition_cart.size() == outcar._initialPosition_cart.size()); REQUIRE(outcar._initialPosition_dire(0, 0) == 0.64620000); REQUIRE(outcar._initialPosition_cart(3, 2) == 4.00000000); outcar._incar._NIONS = 0; REQUIRE_THROWS(outcar.parseInitialPositions(lines)); } } TEST_CASE("Parse Iteration") { outcar._incar._NIONS = 32; WHEN("parse_magmom") { const char* magmom_str = " number of electron 1026.0000000 magnetization 135.0000000"; const char* magmom_err = " number of electron 1026.0000000 magnetization"; REQUIRE_THROWS(outcar.parse_magmom(magmom_str)); outcar._incar._ISPIN = 2; REQUIRE(135.00 == outcar.parse_magmom(magmom_str)); REQUIRE(135.00 == outcar.tmpIteration._magmom); REQUIRE_THROWS(outcar.parse_magmom(magmom_err)); } WHEN("parse_lattice_volume") { const char* volume_str = " volume of cell : 425.26"; const char* voluem_err = " volume of cell :"; REQUIRE(425.26 == outcar.parse_lattice_volume(volume_str)); REQUIRE(425.26 == outcar.tmpIteration._volume); REQUIRE_THROWS(outcar.parse_lattice_volume(voluem_err)); } WHEN("parse_lattice") { VecStr lattice_vecstr { " 7.519999981 0.000000000 0.000000000 0.132978724 0.000000000 0.000000000", " 0.000000000 7.519999981 0.000000000 0.000000000 0.132978724 0.000000000", " 0.000000000 0.000000000 7.519999981 0.000000000 0.000000000 0.132978724" }; Mat33d lattice_result; lattice_result << 7.519999981, 0.000000000, 0.000000000, 0.000000000, 7.519999981, 0.000000000, 0.000000000, 0.000000000, 7.519999981; REQUIRE(lattice_result == outcar.parse_lattice(lattice_vecstr)); } WHEN("parse_atom_force_pos") { VecStr forcepos_vec { " 0.52935 0.52935 0.52935 0.000716 0.000716 0.000716", " 6.96491 3.21778 4.27649 -0.000716 -0.000716 0.000716", " 3.21778 4.27649 6.96491 -0.000716 0.000716 -0.000716", " 4.27649 6.96491 3.21778 0.000716 -0.000716 -0.000716"}; MatX3d force_res; force_res.resize(4, 3); force_res << 0.000716, 0.000716, 0.000716, -0.000716, -0.000716, 0.000716, -0.000716, 0.000716, -0.000716, 0.000716, -0.000716, -0.000716; REQUIRE_THROWS(outcar.parse_atom_force_pos(forcepos_vec)); outcar._incar._NIONS = 4; REQUIRE(force_res == outcar.parse_atom_force_pos(forcepos_vec)); } WHEN("parse_toten_0") { const char* toten_str = " energy without entropy= -1059.00022771 energy(sigma->0) = -1059.00022771"; const char* toten_err = " energy without entropy= -1059.00022771 energy(sigma->0) ="; REQUIRE(-1059.00022771 == outcar.parse_toten_0(toten_str)); REQUIRE(-1059.00022771 == outcar.tmpIteration._totalEnergy_sigma_0); REQUIRE_THROWS(outcar.parse_toten_0(toten_err)); } WHEN("parse_cpu_time") { const char* cputime_str = " LOOP+: cpu time 428.5440: real time 468.0720"; const char* cputime_err = " LOOP+: cpu tim 428.5440: real time 468.0720"; REQUIRE(428.5440 == outcar.parse_cpu_time(cputime_str)); REQUIRE(428.5440 == outcar.tmpIteration._cpuTime); REQUIRE_THROWS(outcar.parse_cpu_time(cputime_err)); } WHEN("calc_atom_force") { Mat33d atom_force_dirs; atom_force_dirs << 1, 2, 3, 4, 5, 6, 7, 8, 9; Vecd atom_force_res; atom_force_res.resize(3); for (long i=0 ;i!=atom_force_dirs.rows(); ++i) { atom_force_res(i) = atom_force_dirs.row(i).norm(); } REQUIRE(atom_force_res == outcar.calc_atom_force(atom_force_dirs)); } std::ifstream ifs("./test6/OUTCAR"); string content = outcar.file_to_string(ifs); VecStr contentVector = outcar.string_to_vecstr(content); WHEN("parse_iteration") { int it_begin = 0; int it_end = contentVector.size(); static const string IT_START_PREFIX = "--------------------------------------- Iteration"; static const string IT_END_PREFIX = " LOOP+"; for (size_t i=0; i!=contentVector.size(); ++i) { if (0 == it_begin and is_start_with(contentVector[i], IT_START_PREFIX)) { it_begin = i; continue; } else if (is_start_with(contentVector[i], IT_END_PREFIX)) { it_end = i + 1; break; } else {} } VecStr it_lines { contentVector.begin() + it_begin, contentVector.begin() + it_end }; REQUIRE(it_lines.size() == 7791); outcar._incar._NIONS = 135; outcar._incar._ISPIN = 2; OUTCAR::IonIteration iteration; REQUIRE_NOTHROW(iteration = outcar.parse_iteration(it_lines)); REQUIRE( -0.0000203 == iteration._magmom); REQUIRE( 4553.41 == iteration._volume); REQUIRE( 2094.2404 == iteration._cpuTime); REQUIRE( -1059.00022771 == iteration._totalEnergy); REQUIRE( 36 == iteration._nSCF); REQUIRE( -1059.00022771 == iteration._deltaE); } WHEN("parse_iteration_vec") { OUTCAR::VecIt it_vec_result; outcar._incar._NIONS = 135; outcar._incar._ISPIN = 2; REQUIRE_NOTHROW(it_vec_result = outcar.parseIterationVec(contentVector)); REQUIRE(17 == it_vec_result.size()); REQUIRE(it_vec_result.back()._cpuTime == 428.5440); REQUIRE(it_vec_result.back()._totalEnergy == -1062.01695778); } outcar.parseElems(contentVector); OUTCAR::VecIt it_vec = outcar.parseIterationVec(contentVector); WHEN("save_as_molden") { REQUIRE_NOTHROW(outcar.saveAsMolden(it_vec)); REQUIRE_THROWS(outcar.saveAsMolden(it_vec, "animate.molden", -1)); REQUIRE_THROWS(outcar.saveAsMolden(it_vec, "animate.molden", 17)); } WHEN("save_one_frame_as_poscar") { REQUIRE(true == outcar.save_one_frame_as_poscar(it_vec.back(), "POSCAR_frame_direct")); REQUIRE(true == outcar.save_one_frame_as_poscar(it_vec.back(), "POSCAR_frame_cartesian", false)); REQUIRE_THROWS(outcar.save_one_frame_as_poscar(it_vec.back(), "./no_dir/POSCAR_frame")); } WHEN("save_as_poscar") { REQUIRE(true == outcar.saveAsPoscar(it_vec)); } } TEST_CASE("Parsing vibration modes") { std::ifstream ifs("./test7/OUTCAR"); REQUIRE(ifs.good()); OUTCAR outcar{ifs}; REQUIRE(outcar._initialPosition_cart.size() !=0 ); const VecStr& lines = outcar._contentVector; REQUIRE_NOTHROW(outcar.parseVibration(lines)); REQUIRE_NOTHROW(outcar.saveAsXsf(outcar._vibrations)); REQUIRE_NOTHROW(outcar.saveAsMol(outcar._vibrations)); }
37.11597
161
0.622753
[ "vector" ]
f2f7b00475822e1b8abd19d53f2ba754946ef2fb
3,557
cpp
C++
problemsets/Codejam/2020/Qual/e_01.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codejam/2020/Qual/e_01.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codejam/2020/Qual/e_01.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <bits/stdc++.h> using namespace std; template<typename T = int> vector<T> create(size_t n){ return vector<T>(n); } template<typename T, typename... Args> auto create(size_t n, Args... args){ return vector<decltype(create<T>(args...))>(n, create<T>(args...)); } struct hopcroft{ vector<int> dist, pair_l, pair_r; vector<bool> seen; vector<vector<int>> to; int n1, n2; hopcroft(int n1, int n2) : n1(n1), n2(n2){ to.resize(n1); pair_l.assign(n1, -1); pair_r.assign(n2, -1); dist.resize(n1); seen.resize(n1); } void add_edge(int u, int v){ to[u].push_back(v); } bool bfs(){ fill(dist.begin(), dist.end(), -1); queue<int> q; for (int i = 0; i < n1; i++){ if (pair_l[i] == -1){ dist[i] = 0; q.push(i); } } bool reach_minus = false; while (!q.empty()){ int u = q.front(); q.pop(); for (int adj : to[u]){ int radj = pair_r[adj]; if (radj == -1){ reach_minus = true; } else if (dist[radj] == -1){ dist[radj] = dist[u] + 1; q.push(radj); } } } return reach_minus; } bool dfs(int u){ seen[u] = true; for (int adj : to[u]){ int radj = pair_r[adj]; if (radj == -1 || (!seen[radj] && dist[radj] == dist[u] + 1 && dfs(radj))){ pair_l[u] = adj; pair_r[adj] = u; return true; } } return false; } int max_matching(){ int res = 0; while (bfs()){ fill(seen.begin(), seen.end(), false); for (int i = 0; i < n1; i++) if (pair_l[i] == -1 && dfs(i)) res++; } return res; } }; int main(){ ios::sync_with_stdio(false); cin.tie(0); int tt; cin >> tt; for(int _ = 1; _ <= tt; _++){ cout << "Case #" << _ << ":"; int n, k; cin >> n >> k; k -= n; auto g = create<int>(n, n); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) g[i][j] = 1; auto rg = g; bool found = false; for(int iter = 0; iter < 200; iter++){ g = rg; for(int j = 0; j < k; j++){ vector<int> pos; for(int z = 0; z < n; z++) if(g[z][z] < n) pos.push_back(z); int p = pos[rand() % pos.size()]; g[p][p]++; } bool bad = false; for(int j = 0; j < n; j++){ int take = g[j][j] - 1; hopcroft hop(n, n); for(int i = 0; i < n; i++){ if(j == i){ } else { vector<int> good(n, 1); good[take] = 0; good[g[i][i] - 1] = 0; for(int k = 0; k < j; k++) good[g[i][k] - 1] = 0; for(int k = 0; k < n; k++){ if(good[k]){ hop.add_edge(k, i); } } } } int c = hop.max_matching(); // cout << "ma " << c << endl; if(c == n - 1){ for(int k = 0; k < n; k++) if(k != take){ // cout << hop.pair_l[k] << ' ' << j << ' ' << k << endl; g[hop.pair_l[k]][j] += k; } } else { bad = true; break; } } if(bad){ continue; } found = true; cout << " POSSIBLE\n"; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cout << g[i][j] << " \n"[j + 1 == n]; } } break; } if(!found) cout << " IMPOSSIBLE\n"; } return 0; }
25.22695
145
0.414394
[ "vector" ]
8406c3905c76633ac190103a3c55ec67ddefcca1
809
cpp
C++
External/libigl-2.1.0/tests/include/igl/per_face_normals.cpp
RokKos/eol-cloth
b9c6f55f25ba17f33532ea5eefa41fedd29c5206
[ "MIT" ]
null
null
null
External/libigl-2.1.0/tests/include/igl/per_face_normals.cpp
RokKos/eol-cloth
b9c6f55f25ba17f33532ea5eefa41fedd29c5206
[ "MIT" ]
null
null
null
External/libigl-2.1.0/tests/include/igl/per_face_normals.cpp
RokKos/eol-cloth
b9c6f55f25ba17f33532ea5eefa41fedd29c5206
[ "MIT" ]
null
null
null
#include <test_common.h> #include <igl/per_face_normals.h> #include <Eigen/Geometry> TEST_CASE("per_face_normals: dot", "[igl]") { const auto test_case = [](const std::string &param) { Eigen::MatrixXd V,N; Eigen::MatrixXi F; // Load example mesh: GetParam() will be name of mesh file test_common::load_mesh(param, V, F); igl::per_face_normals(V,F,N); REQUIRE (N.rows() == F.rows()); for(int f = 0;f<N.rows();f++) { for(int c = 0;c<3;c++) { // Every half-edge dot the normal should be 0 REQUIRE(std::abs((V.row(F(f,c))-V.row(F(f,(c+1)%3))).dot(N.row(f))) < 1e-12); } } // REQUIRE (b == a); // REQUIRE (a==b); // ASSERT_NEAR(a,b,1e-15) // REQUIRE (1e-12 > a); }; test_common::run_test_cases(test_common::all_meshes(), test_case); }
25.28125
84
0.587145
[ "mesh", "geometry" ]
840e2c7b4caf832b9f8c3ff3b8854c39711117f3
5,638
cpp
C++
graphic/showtile.cpp
MihailJP/MiHaJong
b81168ab2696dd29af5c400b84c870a9b8a2f01e
[ "MIT" ]
13
2016-01-20T02:10:52.000Z
2022-03-08T15:51:36.000Z
graphic/showtile.cpp
MihailJP/MiHaJong
b81168ab2696dd29af5c400b84c870a9b8a2f01e
[ "MIT" ]
13
2020-09-28T12:57:52.000Z
2022-02-20T19:20:57.000Z
graphic/showtile.cpp
MihailJP/MiHaJong
b81168ab2696dd29af5c400b84c870a9b8a2f01e
[ "MIT" ]
4
2016-09-19T13:44:10.000Z
2022-02-18T08:13:37.000Z
#include "showtile.h" #include "resource.h" #include "loadtex.h" #include "geometry.h" #include "sprite.h" #include "rule.h" namespace mihajong_graphic { ShowTile::ShowTile(DevicePtr device) { myDevice = device; LoadTexture(myDevice, &TileTexture, preferences::blackTile ? MAKEINTRESOURCE(IDB_PNG_TILE_BLACK) : MAKEINTRESOURCE(IDB_PNG_TILE)); } ShowTile::~ShowTile() { #if defined(_WIN32) && defined(WITH_DIRECTX) if (TileTexture) TileTexture->Release(); #endif } /* 新規の牌オブジェクトを作成する */ void ShowTile::NewTile(unsigned int ID, Tile tile, int x, int y, TileDirection direction, TileSide side, ArgbColor filterCol) { constexpr TileDescriptor empty = {false, Tile(), 0, 0, TileDirection::portrait, TileSide::obverse, 0xffffffff}; if (mySprites.size() <= ID) mySprites.resize(static_cast<std::size_t>(ID) + 1, empty); // 配列の拡張 mySprites[ID].exist = true; mySprites[ID].tile = tile; mySprites[ID].X = x; mySprites[ID].Y = y; mySprites[ID].direction = direction; mySprites[ID].side = side; mySprites[ID].color = filterCol; } /* 牌オブジェクトの後始末 */ void ShowTile::DelTile(unsigned int ID) { if (mySprites.size() > ID) { mySprites[ID].exist = false; } } /* レンダリング */ void ShowTile::RenderTile(const TileDescriptor* tile, const RECT* rect, int CenterX, int CenterY) { SpriteRenderer::instantiate(myDevice)->ShowSprite(TileTexture, tile->X, tile->Y, CenterX*2, CenterY*2, tile->color, rect, CenterX, CenterY); } void ShowTile::RenderVert(const TileDescriptor* tile, const RECT* rect) { RenderTile(tile, rect, VertTileWidth/2, VertTileHeight/2); } void ShowTile::RenderHori(const TileDescriptor* tile, const RECT* rect) { RenderTile(tile, rect, HoriTileWidth/2, HoriTileHeight/2); } void ShowTile::RenderSide(const TileDescriptor* tile, const RECT* rect) { RenderTile(tile, rect, SideTileWidth/2, SideTileHeight/2); } void ShowTile::Render() { for (auto& k : mySprites) { const int32_t kVal = static_cast<int>(k.tile.tile) + static_cast<int>(k.tile.red) * TileNonflowerMax; if (k.exist) { if ((k.direction == TileDirection::portrait) || (k.direction == TileDirection::upsideDown)) { /* TileDirection::portrait alignment */ RECT rect = { static_cast<int32_t>((kVal % 10) * (VertTileWidth + TexturePadding)), static_cast<int32_t>((kVal / 10) * (VertTileHeight + TexturePadding)), static_cast<int32_t>((kVal % 10 + 1) * (VertTileWidth + TexturePadding) - TexturePadding), static_cast<int32_t>((kVal / 10 + 1) * (VertTileHeight + TexturePadding) - TexturePadding), }; RECT rectrev = { (static_cast<int>(TileCode::backSide) % 10) * (VertTileWidth + TexturePadding), (static_cast<int>(TileCode::backSide) / 10) * (VertTileHeight + TexturePadding), (static_cast<int>(TileCode::backSide) % 10 + 1) * (VertTileWidth + TexturePadding) - TexturePadding, (static_cast<int>(TileCode::backSide) / 10 + 1) * (VertTileHeight + TexturePadding) - TexturePadding, }; switch (k.side) { case TileSide::obverse: if (k.direction == TileDirection::upsideDown) { rect.left += (VertTileWidth + TexturePadding) * TileCols; rect.right += (VertTileWidth + TexturePadding) * TileCols; } RenderVert(&k, &rect); break; case TileSide::upright: if (k.direction == TileDirection::upsideDown) { rectrev.left += (VertTileWidth + TexturePadding) * TileCols * 2; rectrev.right += (VertTileWidth + TexturePadding) * TileCols * 2; RenderVert(&k, &rectrev); } else { rect.left += (VertTileWidth + TexturePadding) * TileCols * 2; rect.right += (VertTileWidth + TexturePadding) * TileCols * 2; RenderVert(&k, &rect); } break; case TileSide::reverse: RenderVert(&k, &rectrev); break; } } else { /* Landscape alignment */ RECT rect = { static_cast<int32_t>((kVal % 10) * (HoriTileWidth + TexturePadding)), static_cast<int32_t>((kVal / 10) * (HoriTileHeight + TexturePadding) + (VertTileHeight + TexturePadding) * TileRows), static_cast<int32_t>((kVal % 10 + 1) * (HoriTileWidth + TexturePadding) - TexturePadding), static_cast<int32_t>((kVal / 10 + 1) * (HoriTileHeight + TexturePadding) + (VertTileHeight + TexturePadding) * TileRows - TexturePadding), }; RECT rectrev = { (static_cast<int>(TileCode::backSide) % 10) * (HoriTileWidth + TexturePadding), (static_cast<int>(TileCode::backSide) / 10) * (HoriTileHeight + TexturePadding) + (VertTileHeight + TexturePadding) * TileRows, (static_cast<int>(TileCode::backSide) % 10 + 1) * (HoriTileWidth + TexturePadding) - TexturePadding, (static_cast<int>(TileCode::backSide) / 10 + 1) * (HoriTileHeight + TexturePadding) + (VertTileHeight + TexturePadding) * TileRows - TexturePadding, }; RECT rectside = { 2 * TileCols * (HoriTileWidth + TexturePadding), (VertTileHeight + TexturePadding) * TileRows, 2 * TileCols * (HoriTileWidth + TexturePadding) + SideTileWidth, (VertTileHeight + TexturePadding) * TileRows + SideTileHeight, }; switch (k.side) { case TileSide::obverse: if (k.direction == TileDirection::clockwise) { rect.left += (HoriTileWidth + TexturePadding) * TileCols; rect.right += (HoriTileWidth + TexturePadding) * TileCols; } RenderHori(&k, &rect); break; case TileSide::upright: if (k.direction == TileDirection::clockwise) { rectside.left += SideTileWidth + TexturePadding; rectside.right += SideTileWidth + TexturePadding; } RenderSide(&k, &rectside); break; case TileSide::reverse: RenderHori(&k, &rectrev); break; } } } } } }
40.271429
153
0.677368
[ "geometry", "render" ]
84111458735e4a241c625728df30a476dfd426c2
2,044
cpp
C++
Kattis/cetvrta.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
3
2021-02-19T17:01:11.000Z
2021-03-11T16:50:19.000Z
Kattis/cetvrta.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
Kattis/cetvrta.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
// // https://open.kattis.com/problems/cetvrta #include <iostream> #include <cmath> #include <algorithm> #include <string> #include <iomanip> #include <sstream> #include <vector> #include <iomanip> #include <map> using namespace std; struct Point { int x, y; Point(int a, int b) : x(a), y(b) {} Point() : x(0), y(0) {} int LenPow() const { return x * x + y * y; } double Len() const { return pow(LenPow(), 0.5); } friend Point operator*(int d, const Point& p) { return Point(d * p.x, d * p.y); } friend Point operator+(const Point& p1, const Point& p2) { return Point(p1.x + p2.x, p1.y + p2.y); } friend Point operator-(const Point& p1, const Point& p2) { return Point(p1.x - p2.x, p1.y - p2.y); } friend bool operator==(const Point& p1, const Point& p2) { return p1.x == p2.x && p1.y == p2.y; } friend double Dis(const Point& p1, const Point& p2) { return (p1 - p2).Len(); } friend istream& operator>>(istream& in, Point& p) { in >> p.x >> p.y; return in; } friend ostream& operator<<(ostream& out, Point& p) { out << p.x << ' ' << p.y; return out; } }; bool cmp(Point& p1, Point& p2) { if (p1.x == p2.x) return p1.y < p2.y; return p1.x < p2.x; } bool isRec(vector<Point> p) { sort(p.begin(), p.end(), cmp); // cout << p[0] << ' ' << p[1] << ' ' << p[2] << ' ' << p[3] << '\n'; return (p[0] + p[3]) == (p[1] + p[2]); } int main() { Point tmp; vector<Point> p; for (int i = 0; i < 3; i++) { cin >> tmp; p.push_back(tmp); } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Point cur(p[i].x, p[j].y); // cout << "cur = " << cur << '\n'; p.push_back(cur); if (isRec(p)) { cout << cur << '\n'; return 0; } else { p.pop_back(); } } } return 0; }
21.744681
73
0.46184
[ "vector" ]
841810b7b28cfde57e82f6069db1af6fb6954281
2,895
hpp
C++
sdo/Parsers.hpp
rgottwald/libsdo
6937784258672e3a2d4252107242796b95f026aa
[ "MIT" ]
null
null
null
sdo/Parsers.hpp
rgottwald/libsdo
6937784258672e3a2d4252107242796b95f026aa
[ "MIT" ]
null
null
null
sdo/Parsers.hpp
rgottwald/libsdo
6937784258672e3a2d4252107242796b95f026aa
[ "MIT" ]
null
null
null
#ifndef _MDL_PARSERS_HPP_ #define _MDL_PARSERS_HPP_ #include <string> #include "VopFile.hpp" #include "ExpressionGraph.hpp" #include "Objective.hpp" namespace sdo { /** * \brief Parses a vop file. * * The path's used to specify model, objective and control files * inside the file are made absolute. * * \param fileName the vop file given by its filename * \return The sdo::VopFile object representing the contents of the vop file * \throw std::ifstream::failure if the file cannot be read * \throw sdo::parse_error if an error occured while parsing the file */ VopFile parse_vop_file(const std::string &fileName); /** * \brief Parses a mdl file. * * The mdl file is parsed and the information contained is stored in the given expression * graph. Thus it is possible to parse multiple controls into the same expression graph. * * It is very important that voc files are parsed before the mdl files or else the controls * and changes in the time step are not recognized since a symbol definition will not * get overwritten once it is contained in the expression graph. * * \param fileName the voc file given by its filename * \param exprGraph a reference to the expression graph where the information in the file is stored * \throw std::ifstream::failure if the file cannot be read * \throw sdo::parse_error if an error occured while parsing the file */ void parse_mdl_file(const std::string &fileName, ExpressionGraph &exprGraph); /** * \brief Parses a voc file. * * The vocfile is parsed and the information contained is stored in the given expression * graph. Thus it is possible to parse multiple controls into the same expression graph. * * It is very important that voc files are parsed before the mdl files or else the controls * and changes in the time step are not recognized since a symbol definition will not * get overwritten once it is contained in the expression graph. * * \param fileName the voc file given by its filename * \param exprGraph a reference to the sdo::ExpressionGraph where the information in the file is stored * \throw std::ifstream::failure if the file cannot be read * \throw sdo::parse_error if an error occured while parsing the file */ void parse_voc_file(const std::string &fileName, ExpressionGraph &exprGraph); /** * \brief Parse a vpd file. * * The vpd file is parsed and the information contained is stored in the given sdo::Objective. * Thus it is possible to parse multiple objective files into the same sdo::Objective instance. * * \param fileName the voc file given by its filename * \param obj a reference to the sdo::Objective where the information in the file is stored * \throw std::ifstream::failure if the file cannot be read * \throw sdo::parse_error if an error occured while parsing the file */ void parse_vpd_file(const std::string &fileName, Objective& obj); } #endif
36.64557
103
0.752677
[ "object", "model" ]
8430ba31a52976a5a6c594d38a501cad21374da8
6,500
cpp
C++
src/asiAlgo/points/asiAlgo_PlaneOnPoints.cpp
sasobadovinac/AnalysisSitus
304d39c64258d4fcca888eb8e68144eca50e785a
[ "BSD-3-Clause" ]
3
2021-11-04T01:36:56.000Z
2022-03-10T07:11:01.000Z
src/asiAlgo/points/asiAlgo_PlaneOnPoints.cpp
sasobadovinac/AnalysisSitus
304d39c64258d4fcca888eb8e68144eca50e785a
[ "BSD-3-Clause" ]
null
null
null
src/asiAlgo/points/asiAlgo_PlaneOnPoints.cpp
sasobadovinac/AnalysisSitus
304d39c64258d4fcca888eb8e68144eca50e785a
[ "BSD-3-Clause" ]
1
2021-09-25T18:14:30.000Z
2021-09-25T18:14:30.000Z
//----------------------------------------------------------------------------- // Created on: 03 December 2016 //----------------------------------------------------------------------------- // Copyright (c) 2017, Sergey Slyadnev // 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 copyright holder(s) nor the // names of all contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- // Own include #include <asiAlgo_PlaneOnPoints.h> // Eigen includes #pragma warning(disable : 4701 4702) #include <Eigen/Dense> #pragma warning(default : 4701 4702) #undef COUT_DEBUG #if defined COUT_DEBUG #pragma message("===== warning: COUT_DEBUG is enabled") #endif //----------------------------------------------------------------------------- bool compare(const std::pair<double, int>& p1, const std::pair<double, int>& p2) { return p1.first > p2.first; } //----------------------------------------------------------------------------- asiAlgo_PlaneOnPoints::asiAlgo_PlaneOnPoints(ActAPI_ProgressEntry progress, ActAPI_PlotterEntry plotter) : ActAPI_IAlgorithm(progress, plotter) {} //----------------------------------------------------------------------------- bool asiAlgo_PlaneOnPoints::Build(const std::vector<gp_XYZ>& points, gp_Pln& result) const { return this->internalBuild(points, result); } //----------------------------------------------------------------------------- bool asiAlgo_PlaneOnPoints::Build(const Handle(asiAlgo_BaseCloud<double>)& points, gp_Pln& result) const { // Repack point cloud to a vector. std::vector<gp_XYZ> pointsVec; // for ( int k = 0; k < points->GetNumberOfElements(); ++k ) pointsVec.push_back( points->GetElement(k) ); return this->internalBuild(pointsVec, result); } //----------------------------------------------------------------------------- bool asiAlgo_PlaneOnPoints::internalBuild(const std::vector<gp_XYZ>& points, gp_Pln& result) const { const int nPts = (int) points.size(); /* ====================== * Calculate mean point * ====================== */ gp_XYZ mu; for ( size_t i = 0; i < points.size(); ++i ) { mu += points[i]; } mu /= nPts; /* ========================= * Build covariance matrix * ========================= */ Eigen::Matrix3d C; for ( int j = 1; j <= 3; ++j ) { for ( int k = 1; k <= 3; ++k ) { C(j-1, k-1) = 0.0; // TODO: is that necessary? } } for ( size_t i = 0; i < points.size(); ++i ) { const gp_XYZ& p = points[i]; gp_XYZ p_dash = p - mu; for ( int j = 1; j <= 3; ++j ) { for ( int k = 1; k <= 3; ++k ) { C(j-1, k-1) += ( p_dash.Coord(j)*p_dash.Coord(k) ); } } } for ( int j = 1; j <= 3; ++j ) { for ( int k = 1; k <= 3; ++k ) { C(j-1, k-1) /= nPts; } } Eigen::EigenSolver<Eigen::Matrix3d> EigenSolver(C); #if defined COUT_DEBUG std::cout << "\tCovariance matrix: " << std::endl << C << std::endl; std::cout << "\tThe eigen values of C are:" << std::endl << EigenSolver.eigenvalues() << std::endl; std::cout << "\tThe matrix of eigenvectors, V, is:" << std::endl << EigenSolver.eigenvectors() << std::endl << std::endl; #endif Eigen::Vector3cd v1 = EigenSolver.eigenvectors().col(0); Eigen::Vector3cd v2 = EigenSolver.eigenvectors().col(1); Eigen::Vector3cd v3 = EigenSolver.eigenvectors().col(2); gp_Vec V[3] = { gp_Vec( v1.x().real(), v1.y().real(), v1.z().real() ), gp_Vec( v2.x().real(), v2.y().real(), v2.z().real() ), gp_Vec( v3.x().real(), v3.y().real(), v3.z().real() ) }; // std::vector< std::pair<double, int> > lambda { std::pair<double, int>( EigenSolver.eigenvalues()(0).real(), 0 ), std::pair<double, int>( EigenSolver.eigenvalues()(1).real(), 1 ), std::pair<double, int>( EigenSolver.eigenvalues()(2).real(), 2 ) }; // std::sort(lambda.begin(), lambda.end(), compare); // gp_Ax1 ax_X(mu, V[lambda[0].second]); gp_Ax1 ax_Y(mu, V[lambda[1].second]); gp_Ax1 ax_Z(mu, V[lambda[2].second]); // gp_Vec vec_X( ax_X.Direction() ); gp_Vec vec_Y( ax_Y.Direction() ); gp_Vec vec_Z( ax_Z.Direction() ); // if ( (vec_X ^ vec_Y).Magnitude() < gp::Resolution() || (vec_X ^ vec_Z).Magnitude() < gp::Resolution() || (vec_Y ^ vec_Z).Magnitude() < gp::Resolution() ) { std::cout << "Warning: degenerated normal" << std::endl; return false; // Degenerated normal } // Check if the system is right-handed const double ang = ax_X.Direction().AngleWithRef( ax_Y.Direction(), ax_Z.Direction() ); if ( ang < 0 ) { gp_Ax1 tmp = ax_X; ax_X = ax_Y; ax_Y = tmp; } // Store results gp_Ax3 ax3( gp_Pnt(mu), ax_Z.Direction(), ax_X.Direction() ); result.SetPosition(ax3); // return true; }
34.759358
123
0.548462
[ "vector" ]
8430c8589986139c8bc3bcd744b6f9d2f2511c97
4,113
cpp
C++
src/DEX/parser/dex_strings.cpp
Fare9/KUNAI-static-analyzer
3b711de554d8e712cf17672d0adb2e303fdae750
[ "MIT" ]
48
2021-12-25T11:19:32.000Z
2022-01-25T14:43:47.000Z
src/DEX/parser/dex_strings.cpp
Fare9/KUNAI-static-analyzer
3b711de554d8e712cf17672d0adb2e303fdae750
[ "MIT" ]
5
2021-12-25T13:36:25.000Z
2022-01-21T20:02:54.000Z
src/DEX/parser/dex_strings.cpp
Fare9/KUNAI-static-analyzer
3b711de554d8e712cf17672d0adb2e303fdae750
[ "MIT" ]
5
2021-12-25T14:14:09.000Z
2022-01-16T06:52:18.000Z
#include "dex_strings.hpp" namespace KUNAI { namespace DEX { DexStrings::DexStrings(std::ifstream& input_file, std::uint64_t file_size, std::uint32_t number_of_strings, std::uint32_t strings_offsets) : number_of_strings (number_of_strings), offset (strings_offsets) { if (!parse_strings(input_file, file_size)) throw exceptions::ParserReadingException("Error reading DEX strings"); } DexStrings::~DexStrings() { if (!strings.empty()) strings.clear(); } std::string* DexStrings::get_string_from_offset(std::uint32_t offset) { if (this->strings.find(offset) == this->strings.end()) return nullptr; return &(this->strings[offset]); } std::string* DexStrings::get_string_from_order(std::uint32_t pos) { if (pos >= this->strings.size()) return nullptr; return ordered_strings[pos]; } std::vector<std::string> DexStrings::get_all_strings() { std::vector<std::string> all_strings; for (auto it = this->strings.begin(); it != this->strings.end(); it++) all_strings.push_back(it->second); return all_strings; } /** * Private methods */ bool DexStrings::parse_strings(std::ifstream& input_file, std::uint64_t file_size) { auto current_offset = input_file.tellg(); size_t i; // string values std::uint32_t str_offset; std::string str; // move to offset where are the string ids input_file.seekg(this->offset); // go one by one reading offset and string for (i = 0; i < this->number_of_strings; i++) { if (!KUNAI::read_data_file<std::uint32_t>(str_offset, sizeof(std::uint32_t), input_file)) return false; if (str_offset > file_size) throw exceptions::OutOfBoundException("Error offset from string out of file bound"); str = KUNAI::read_dex_string(input_file, str_offset); this->strings.insert(std::pair<std::uint32_t, std::string>(str_offset, str)); ordered_strings.push_back(&this->strings[str_offset]); } input_file.seekg(current_offset); return true; } /** * friend methods */ std::ostream& operator<<(std::ostream& os, const DexStrings& entry) { size_t i = 0; os << std::hex; os << std::setw(30) << std::left << std::setfill(' ') << "=========== DEX Strings ===========" << std::endl; for (auto it = entry.strings.begin(); it != entry.strings.end(); it++) { os << std::left << std::setfill(' ') << "String (" << std::dec << i++ << std::hex << "): " << it->first << "->\"" << it->second << "\"" << std::endl; } return os; } std::fstream& operator<<(std::fstream& fos, const DexStrings& entry) { std::stringstream stream; stream << std::hex; stream << "<strings>" << std::endl; for (auto it = entry.strings.begin(); it != entry.strings.end(); it++) { stream << "\t<string>" << std::endl; stream << "\t\t<offset>" << it->first << "</offset>" << std::endl; stream << "\t\t<value>" << it->second << "</value>" << std::endl; stream << "\t</string>" << std::endl; } stream << "</strings>" << std::endl; fos.write(stream.str().c_str(), stream.str().size()); return fos; } } }
33.991736
165
0.474836
[ "vector" ]
843b541e773db1c38cb77c1704436975991806aa
1,427
cpp
C++
Common01/Source/Common/DrawSystem/Geometry/GeometryGeneric.cpp
DavidCoenFish/game02
3011cf2fe069b579759aa95333cb406a8ff52d53
[ "Unlicense" ]
null
null
null
Common01/Source/Common/DrawSystem/Geometry/GeometryGeneric.cpp
DavidCoenFish/game02
3011cf2fe069b579759aa95333cb406a8ff52d53
[ "Unlicense" ]
null
null
null
Common01/Source/Common/DrawSystem/Geometry/GeometryGeneric.cpp
DavidCoenFish/game02
3011cf2fe069b579759aa95333cb406a8ff52d53
[ "Unlicense" ]
null
null
null
#include "CommonPCH.h" #include "Common/DrawSystem/Geometry/GeometryGeneric.h" #include "Common/DrawSystem/Geometry/IGeometry.h" GeometryGeneric::GeometryGeneric( DrawSystem* const pDrawSystem, const D3D_PRIMITIVE_TOPOLOGY primitiveTopology, const std::vector< D3D12_INPUT_ELEMENT_DESC >& inputElementDescArray, const std::vector< float >& vertexDataRaw, const int floatPerVertex ) : IResource( pDrawSystem) , m_primitiveTopology(primitiveTopology) , m_inputElementDescArray(inputElementDescArray) , m_vertexRawData(vertexDataRaw) , m_floatPerVertex(floatPerVertex) , m_pVertexBuffer() , m_vertexBufferView{} { //nop } void GeometryGeneric::Draw(ID3D12GraphicsCommandList* const pCommandList) { IGeometry::DrawImplementation( pCommandList, (UINT)(m_vertexRawData.size() / m_floatPerVertex), m_primitiveTopology, m_vertexBufferView ); } void GeometryGeneric::OnDeviceLost() { IGeometry::DeviceLostImplementation(m_pVertexBuffer); } void GeometryGeneric::OnDeviceRestored( ID3D12GraphicsCommandList* const pCommandList, ID3D12Device2* const pDevice ) { IGeometry::DeviceRestoredImplementation( m_pDrawSystem, pCommandList, pDevice, (int)(m_vertexRawData.size() / m_floatPerVertex), sizeof(float) * m_floatPerVertex, m_pVertexBuffer, m_vertexBufferView, m_vertexRawData.data() ); }
26.425926
73
0.742116
[ "geometry", "vector" ]
e0fc80601d579672347799624d313e44648fdff8
5,707
cpp
C++
smatrix/src/myModel.cpp
talismanbrandi/SMatrix
1307fe786a18d2684806c3ec6bf8bcee306a4891
[ "MIT" ]
null
null
null
smatrix/src/myModel.cpp
talismanbrandi/SMatrix
1307fe786a18d2684806c3ec6bf8bcee306a4891
[ "MIT" ]
null
null
null
smatrix/src/myModel.cpp
talismanbrandi/SMatrix
1307fe786a18d2684806c3ec6bf8bcee306a4891
[ "MIT" ]
null
null
null
/* * Copyright (C) 2015 HEPfit Collaboration * All rights reserved. * * For the licensing terms see doc/COPYING. */ #include "myModel.h" /* Define mandatory model parameters here. */ const std::string myModel::myModelvars[NmyModelvars] = {"Api0", "Api2", "AK0", "A4pi0", "Aetet_r", "Aetetp_r", "Aetet_i", "Aetetp_i", "delta1", "delta2", "n1r", "n1r", "n3r", "n4r", "n5r", "n1i", "n2i", "n3i", "n4i", "n5i", "nd1", "nd2"}; myModel::myModel() : StandardModel() { /* Define all the parameters here and port them as observables too */ ModelParamMap.insert(std::make_pair("Api0", std::cref(Api0))); ModelParamMap.insert(std::make_pair("Api2", std::cref(Api2))); ModelParamMap.insert(std::make_pair("AK0", std::cref(AK0))); ModelParamMap.insert(std::make_pair("A4pi0", std::cref(A4pi0))); ModelParamMap.insert(std::make_pair("Aetet_r", std::cref(Aetet_r))); ModelParamMap.insert(std::make_pair("Aetetp_r", std::cref(Aetetp_r))); ModelParamMap.insert(std::make_pair("Aetet_i", std::cref(Aetet_i))); ModelParamMap.insert(std::make_pair("Aetetp_i", std::cref(Aetetp_i))); ModelParamMap.insert(std::make_pair("delta1", std::cref(delta1))); ModelParamMap.insert(std::make_pair("delta2", std::cref(delta2))); ModelParamMap.insert(std::make_pair("n1r", std::cref(n1r))); ModelParamMap.insert(std::make_pair("n2r", std::cref(n2r))); ModelParamMap.insert(std::make_pair("n3r", std::cref(n3r))); ModelParamMap.insert(std::make_pair("n4r", std::cref(n4r))); ModelParamMap.insert(std::make_pair("n5r", std::cref(n5r))); ModelParamMap.insert(std::make_pair("n1i", std::cref(n1i))); ModelParamMap.insert(std::make_pair("n2i", std::cref(n2i))); ModelParamMap.insert(std::make_pair("n3i", std::cref(n3i))); ModelParamMap.insert(std::make_pair("n4i", std::cref(n4i))); ModelParamMap.insert(std::make_pair("n5i", std::cref(n5i))); ModelParamMap.insert(std::make_pair("nd1", std::cref(nd1))); ModelParamMap.insert(std::make_pair("nd2", std::cref(nd2))); } myModel::~myModel() { if (IsModelInitialized()) { /* Destroy whatever you want, e.g. potentially dangerous pointers. */ } } /* Initialize model here */ bool myModel::InitializeModel() { condition = false; setModelInitialized(StandardModel::InitializeModel()); return(true); } bool myModel::Init(const std::map<std::string, double>& DPars) { return(StandardModel::Init(DPars)); } /* Do whatever is necessary before parameters are updated by the MCMC. */ bool myModel::PreUpdate() { if(!StandardModel::PreUpdate()) return (false); return (true); } /* Model update method used be the MCMC to update the model parameters. */ bool myModel::Update(const std::map<std::string, double>& DPars) { if(!PreUpdate()) return (false); UpdateError = false; for (std::map<std::string, double>::const_iterator it = DPars.begin(); it != DPars.end(); it++) setParameter(it->first, it->second); if (UpdateError) return (false); if(!PostUpdate()) return (false); return (true); return (true); } /* Postupdate method to update whatever is needed after the model parameters are updated */ bool myModel::PostUpdate() { if(!StandardModel::PostUpdate()) return (false); return (true); } /* Model parameters and their derived quantities can be set here. */ void myModel::setParameter(const std::string name, const double& value) { if(name.compare("Api0") == 0) Api0 = value; else if(name.compare("Api2") == 0) Api2 = value; else if(name.compare("AK0") == 0) AK0 = value; else if(name.compare("A4pi0") == 0) A4pi0 = value; else if(name.compare("Aetet_r") == 0) Aetet_r = value; else if(name.compare("Aetetp_r") == 0) Aetetp_r = value; else if(name.compare("Aetet_i") == 0) Aetet_i = value; else if(name.compare("Aetetp_i") == 0) Aetetp_i = value; else if(name.compare("delta1") == 0) delta1 = value; else if(name.compare("delta2") == 0) delta2 = value; else if(name.compare("n1r") == 0) n1r = value; else if(name.compare("n2r") == 0) n2r = value; else if(name.compare("n3r") == 0) n3r = value; else if(name.compare("n4r") == 0) n4r = value; else if(name.compare("n5r") == 0) n5r = value; else if(name.compare("n1i") == 0) n1i = value; else if(name.compare("n2i") == 0) n2i = value; else if(name.compare("n3i") == 0) n3i = value; else if(name.compare("n4i") == 0) n4i = value; else if(name.compare("n5i") == 0) n5i = value; else if(name.compare("nd1") == 0) nd1 = value; else if(name.compare("nd2") == 0) nd2 = value; else StandardModel::setParameter(name,value); } bool myModel::CheckParameters(const std::map<std::string, double>& DPars) { for (int i = 0; i < NmyModelvars; i++) { if (DPars.find(myModelvars[i]) == DPars.end()) { std::cout << "missing mandatory myModel parameter " << myModelvars[i] << std::endl; return false; } } return(StandardModel::CheckParameters(DPars)); } /* Model Flags can be set here. */ bool myModel::setFlag(const std::string name, const bool value) { bool res = false; if(name.compare("condition") == 0){ condition = value; res = true; } else { res = StandardModel::setFlag(name,value); } return(res); }
32.426136
125
0.602243
[ "model" ]
e0fce2381b43b832250a1604c36843d3ec8c88d9
3,213
cpp
C++
src/action.cpp
shivaang12/Smart-AGV
480dadd570ec09d19adf8380c5bcfcc7704d01ae
[ "MIT" ]
null
null
null
src/action.cpp
shivaang12/Smart-AGV
480dadd570ec09d19adf8380c5bcfcc7704d01ae
[ "MIT" ]
null
null
null
src/action.cpp
shivaang12/Smart-AGV
480dadd570ec09d19adf8380c5bcfcc7704d01ae
[ "MIT" ]
null
null
null
/******************************************************************** * MIT License * * Copyright (c) 2018 Shivang Patel * * 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. ********************************************************************/ /** @file action.cpp * @brief Implementation of class Action * * This file contains implementation of class Action which performs actions * requested from console input. * * @author Shivang Patel */ #include <ros/ros.h> #include <geometry_msgs/Pose.h> #include <string> #include <smartAGV/navigation.hpp> #include <smartAGV/action.hpp> #include <smartAGV/location.hpp> void Action::initialize(ros::NodeHandle &n) { nodeHandle = n; nav.initialize(nodeHandle); } void Action::execute(int act, const std::string &arg) { action = act; ROS_INFO_STREAM("Action::" << action << " arg::" << arg); navigate(action, arg); return; } void Action::navigate(int act, const std::string &arg) { geometry_msgs::Pose goal; struct Location locationA(std::string("rest pos"), 0.0, 0.0, 0.0, 0.0, 0.0, 0.950, 0.312); struct Location locationB(std::string("storage"), -1.38, 4.43, 0.0, 0.0, 0.0, 0.73, 0.68); struct Location locationC(std::string("shop"), 3.60, 4.07, 0.0, 0.0, 0.0, 0.80, 0.59); std::vector<Location> locations; locations.push_back(locationA); locations.push_back(locationB); locations.push_back(locationC); if (action == ACT_MOVETO) { for (int i = 0; i < locations.size(); ++i) { if (arg.find(locations[i].loc) != std::string::npos) { ROS_INFO_STREAM("Action:: navigate move to " << locations[i].loc); goal.position.x = locations[i].pointX; goal.position.y = locations[i].pointY; goal.position.z = locations[i].pointZ; goal.orientation.x = locations[i].orientationX; goal.orientation.y = locations[i].orientationY; goal.orientation.z = locations[i].orientationZ; goal.orientation.w = locations[i].orientationW; nav.goTO(goal); break; } } } else { nav.abortMove(); } return; }
36.101124
82
0.639278
[ "vector" ]
e0ff123891bdcb51d41f856d2e7ede7b45e48b56
29,599
hpp
C++
mars/boost/mpl/vector/aux_/preprocessed/plain/vector20.hpp
habbyge/mars
f30884ab41599780c51eb57a19dc1e0662cbc98a
[ "BSD-2-Clause", "Apache-2.0" ]
1
2020-09-17T06:29:28.000Z
2020-09-17T06:29:28.000Z
mars/boost/mpl/vector/aux_/preprocessed/plain/vector20.hpp
habbyge/mars
f30884ab41599780c51eb57a19dc1e0662cbc98a
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
mars/boost/mpl/vector/aux_/preprocessed/plain/vector20.hpp
habbyge/mars
f30884ab41599780c51eb57a19dc1e0662cbc98a
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
// Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Preprocessed version of "boost/mpl/vector/vector20.hpp" header // -- DO NOT modify by hand! namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost { namespace mpl { template< typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10 > struct vector11 { typedef aux::vector_tag<11> tag; typedef vector11 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef T9 item9; typedef T10 item10; typedef void_ item11; typedef T10 back; typedef v_iter<type, 0> begin; typedef v_iter<type, 11> end; }; template<> struct push_front_impl<aux::vector_tag < 10> > { template<typename Vector, typename T> struct apply { typedef vector11< T, typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9 > type; }; }; template<> struct pop_front_impl<aux::vector_tag < 11> > { template<typename Vector> struct apply { typedef vector10< typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10 > type; }; }; template<> struct push_back_impl<aux::vector_tag < 10> > { template<typename Vector, typename T> struct apply { typedef vector11< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, T > type; }; }; template<> struct pop_back_impl<aux::vector_tag < 11> > { template<typename Vector> struct apply { typedef vector10< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9 > type; }; }; template<typename V> struct v_at<V, 11> { typedef typename V::item11 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11 > struct vector12 { typedef aux::vector_tag<12> tag; typedef vector12 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef T9 item9; typedef T10 item10; typedef T11 item11; typedef void_ item12; typedef T11 back; typedef v_iter<type, 0> begin; typedef v_iter<type, 12> end; }; template<> struct push_front_impl<aux::vector_tag < 11> > { template<typename Vector, typename T> struct apply { typedef vector12< T, typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10 > type; }; }; template<> struct pop_front_impl<aux::vector_tag < 12> > { template<typename Vector> struct apply { typedef vector11< typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11 > type; }; }; template<> struct push_back_impl<aux::vector_tag < 11> > { template<typename Vector, typename T> struct apply { typedef vector12< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, T > type; }; }; template<> struct pop_back_impl<aux::vector_tag < 12> > { template<typename Vector> struct apply { typedef vector11< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10 > type; }; }; template<typename V> struct v_at<V, 12> { typedef typename V::item12 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12 > struct vector13 { typedef aux::vector_tag<13> tag; typedef vector13 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef T9 item9; typedef T10 item10; typedef T11 item11; typedef T12 item12; typedef void_ item13; typedef T12 back; typedef v_iter<type, 0> begin; typedef v_iter<type, 13> end; }; template<> struct push_front_impl<aux::vector_tag < 12> > { template<typename Vector, typename T> struct apply { typedef vector13< T, typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11 > type; }; }; template<> struct pop_front_impl<aux::vector_tag < 13> > { template<typename Vector> struct apply { typedef vector12< typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12 > type; }; }; template<> struct push_back_impl<aux::vector_tag < 12> > { template<typename Vector, typename T> struct apply { typedef vector13< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, T > type; }; }; template<> struct pop_back_impl<aux::vector_tag < 13> > { template<typename Vector> struct apply { typedef vector12< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11 > type; }; }; template<typename V> struct v_at<V, 13> { typedef typename V::item13 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13 > struct vector14 { typedef aux::vector_tag<14> tag; typedef vector14 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef T9 item9; typedef T10 item10; typedef T11 item11; typedef T12 item12; typedef T13 item13; typedef void_ item14; typedef T13 back; typedef v_iter<type, 0> begin; typedef v_iter<type, 14> end; }; template<> struct push_front_impl<aux::vector_tag < 13> > { template<typename Vector, typename T> struct apply { typedef vector14< T, typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12 > type; }; }; template<> struct pop_front_impl<aux::vector_tag < 14> > { template<typename Vector> struct apply { typedef vector13< typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13 > type; }; }; template<> struct push_back_impl<aux::vector_tag < 13> > { template<typename Vector, typename T> struct apply { typedef vector14< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, T > type; }; }; template<> struct pop_back_impl<aux::vector_tag < 14> > { template<typename Vector> struct apply { typedef vector13< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12 > type; }; }; template<typename V> struct v_at<V, 14> { typedef typename V::item14 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14 > struct vector15 { typedef aux::vector_tag<15> tag; typedef vector15 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef T9 item9; typedef T10 item10; typedef T11 item11; typedef T12 item12; typedef T13 item13; typedef T14 item14; typedef void_ item15; typedef T14 back; typedef v_iter<type, 0> begin; typedef v_iter<type, 15> end; }; template<> struct push_front_impl<aux::vector_tag < 14> > { template<typename Vector, typename T> struct apply { typedef vector15< T, typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13 > type; }; }; template<> struct pop_front_impl<aux::vector_tag < 15> > { template<typename Vector> struct apply { typedef vector14< typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14 > type; }; }; template<> struct push_back_impl<aux::vector_tag < 14> > { template<typename Vector, typename T> struct apply { typedef vector15< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, T > type; }; }; template<> struct pop_back_impl<aux::vector_tag < 15> > { template<typename Vector> struct apply { typedef vector14< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13 > type; }; }; template<typename V> struct v_at<V, 15> { typedef typename V::item15 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15 > struct vector16 { typedef aux::vector_tag<16> tag; typedef vector16 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef T9 item9; typedef T10 item10; typedef T11 item11; typedef T12 item12; typedef T13 item13; typedef T14 item14; typedef T15 item15; typedef void_ item16; typedef T15 back; typedef v_iter<type, 0> begin; typedef v_iter<type, 16> end; }; template<> struct push_front_impl<aux::vector_tag < 15> > { template<typename Vector, typename T> struct apply { typedef vector16< T, typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14 > type; }; }; template<> struct pop_front_impl<aux::vector_tag < 16> > { template<typename Vector> struct apply { typedef vector15< typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15 > type; }; }; template<> struct push_back_impl<aux::vector_tag < 15> > { template<typename Vector, typename T> struct apply { typedef vector16< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, T > type; }; }; template<> struct pop_back_impl<aux::vector_tag < 16> > { template<typename Vector> struct apply { typedef vector15< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14 > type; }; }; template<typename V> struct v_at<V, 16> { typedef typename V::item16 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16 > struct vector17 { typedef aux::vector_tag<17> tag; typedef vector17 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef T9 item9; typedef T10 item10; typedef T11 item11; typedef T12 item12; typedef T13 item13; typedef T14 item14; typedef T15 item15; typedef T16 item16; typedef void_ item17; typedef T16 back; typedef v_iter<type, 0> begin; typedef v_iter<type, 17> end; }; template<> struct push_front_impl<aux::vector_tag < 16> > { template<typename Vector, typename T> struct apply { typedef vector17< T, typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15 > type; }; }; template<> struct pop_front_impl<aux::vector_tag < 17> > { template<typename Vector> struct apply { typedef vector16< typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16 > type; }; }; template<> struct push_back_impl<aux::vector_tag < 16> > { template<typename Vector, typename T> struct apply { typedef vector17< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, T > type; }; }; template<> struct pop_back_impl<aux::vector_tag < 17> > { template<typename Vector> struct apply { typedef vector16< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15 > type; }; }; template<typename V> struct v_at<V, 17> { typedef typename V::item17 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17 > struct vector18 { typedef aux::vector_tag<18> tag; typedef vector18 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef T9 item9; typedef T10 item10; typedef T11 item11; typedef T12 item12; typedef T13 item13; typedef T14 item14; typedef T15 item15; typedef T16 item16; typedef T17 item17; typedef void_ item18; typedef T17 back; typedef v_iter<type, 0> begin; typedef v_iter<type, 18> end; }; template<> struct push_front_impl<aux::vector_tag < 17> > { template<typename Vector, typename T> struct apply { typedef vector18< T, typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16 > type; }; }; template<> struct pop_front_impl<aux::vector_tag < 18> > { template<typename Vector> struct apply { typedef vector17< typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16, typename Vector::item17 > type; }; }; template<> struct push_back_impl<aux::vector_tag < 17> > { template<typename Vector, typename T> struct apply { typedef vector18< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16, T > type; }; }; template<> struct pop_back_impl<aux::vector_tag < 18> > { template<typename Vector> struct apply { typedef vector17< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16 > type; }; }; template<typename V> struct v_at<V, 18> { typedef typename V::item18 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18 > struct vector19 { typedef aux::vector_tag<19> tag; typedef vector19 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef T9 item9; typedef T10 item10; typedef T11 item11; typedef T12 item12; typedef T13 item13; typedef T14 item14; typedef T15 item15; typedef T16 item16; typedef T17 item17; typedef T18 item18; typedef void_ item19; typedef T18 back; typedef v_iter<type, 0> begin; typedef v_iter<type, 19> end; }; template<> struct push_front_impl<aux::vector_tag < 18> > { template<typename Vector, typename T> struct apply { typedef vector19< T, typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16, typename Vector::item17 > type; }; }; template<> struct pop_front_impl<aux::vector_tag < 19> > { template<typename Vector> struct apply { typedef vector18< typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16, typename Vector::item17, typename Vector::item18 > type; }; }; template<> struct push_back_impl<aux::vector_tag < 18> > { template<typename Vector, typename T> struct apply { typedef vector19< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16, typename Vector::item17, T > type; }; }; template<> struct pop_back_impl<aux::vector_tag < 19> > { template<typename Vector> struct apply { typedef vector18< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16, typename Vector::item17 > type; }; }; template<typename V> struct v_at<V, 19> { typedef typename V::item19 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19 > struct vector20 { typedef aux::vector_tag<20> tag; typedef vector20 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef T9 item9; typedef T10 item10; typedef T11 item11; typedef T12 item12; typedef T13 item13; typedef T14 item14; typedef T15 item15; typedef T16 item16; typedef T17 item17; typedef T18 item18; typedef T19 item19; typedef void_ item20; typedef T19 back; typedef v_iter<type, 0> begin; typedef v_iter<type, 20> end; }; template<> struct push_front_impl<aux::vector_tag < 19> > { template<typename Vector, typename T> struct apply { typedef vector20< T, typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16, typename Vector::item17, typename Vector::item18 > type; }; }; template<> struct pop_front_impl<aux::vector_tag < 20> > { template<typename Vector> struct apply { typedef vector19< typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16, typename Vector::item17, typename Vector::item18, typename Vector::item19 > type; }; }; template<> struct push_back_impl<aux::vector_tag < 19> > { template<typename Vector, typename T> struct apply { typedef vector20< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16, typename Vector::item17, typename Vector::item18, T > type; }; }; template<> struct pop_back_impl<aux::vector_tag < 20> > { template<typename Vector> struct apply { typedef vector19< typename Vector::item0, typename Vector::item1, typename Vector::item2, typename Vector::item3, typename Vector::item4, typename Vector::item5, typename Vector::item6, typename Vector::item7, typename Vector::item8, typename Vector::item9, typename Vector::item10, typename Vector::item11, typename Vector::item12, typename Vector::item13, typename Vector::item14, typename Vector::item15, typename Vector::item16, typename Vector::item17, typename Vector::item18 > type; }; }; template<typename V> struct v_at<V, 20> { typedef typename V::item20 type; }; }}
36.052375
471
0.722254
[ "vector" ]
46040532d78ad3b818fcf5cdd6463ed7751f6a5c
35,764
cpp
C++
src/storage.cpp
wjakob/layerlab
3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3
[ "BSD-2-Clause" ]
89
2015-07-31T05:20:17.000Z
2022-02-05T13:21:33.000Z
src/storage.cpp
wjakob/layerlab
3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3
[ "BSD-2-Clause" ]
2
2015-08-17T20:50:32.000Z
2019-10-07T11:27:04.000Z
src/storage.cpp
wjakob/layerlab
3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3
[ "BSD-2-Clause" ]
23
2015-08-03T01:09:55.000Z
2021-12-25T15:45:42.000Z
/* This file is part of Mitsuba, a physically based rendering system. Copyright (c) 2007-2012 by Wenzel Jakob and others. Mitsuba is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. Mitsuba 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 <layer/storage.h> #include <layer/spline.h> #include <layer/fourier.h> #include <layer/log.h> #include <layer/simd.h> #include <tbb/tbb.h> #include <atomic> #if defined(__MSVC__) # include <intrin.h> #else # include <immintrin.h> #endif NAMESPACE_BEGIN(layer) #define BSDF_STORAGE_HEADER_ID "SCATFUN" #define BSDF_STORAGE_VERSION 1 #define BSDF_STORAGE_FLAGS_EXTRAPOLATED 2 #define BSDF_STORAGE_FLAGS_BSDF 1 #define BSDF_STORAGE_HEADER_SIZE 64 static const float __basisCoeffsDefault[3] = { 1.0, 1.0, 1.0 }; BSDFStorage::BSDFStorage(const fs::path &filename, size_t nNodes, size_t nChannels, size_t nMaxOrder, size_t nCoeffs, size_t nBases, size_t nParameters, const size_t *paramSampleCounts, const float **paramSamplePositions, bool extrapolate, const std::string &metadata) : m_header(nullptr), m_reciprocals(nullptr), m_filename(filename), m_paramSamplePositionsNested(nullptr) { if (nChannels != 1 && nChannels != 3) Error("Only 1 and 3-channel files are supported!"); if (extrapolate && nMaxOrder != 3) Error("Only three Fourier orders should be specified " "for the extrapolated storage format!"); size_t nBasesPred = 1, nParameterValues = 0; for (size_t i=0; i<nParameters; ++i) { nParameterValues += paramSampleCounts[i]; nBasesPred *= paramSampleCounts[i]; } if (nBasesPred != nBases) Error("BSDFStorage::BSDFStorage(): provided an invalid number of basis functions"); size_t size = BSDF_STORAGE_HEADER_SIZE + // Header sizeof(float)*nNodes + // Node locations sizeof(uint32_t)*nParameters + // Parameter sample counts sizeof(float)*nParameterValues + // Parameter sample positions sizeof(float)*nNodes*nNodes*nBases + // CDF in \mu sizeof(OffsetType)*nNodes*nNodes*2 + // Offset + size table sizeof(float)*nCoeffs + // Fourier coefficients metadata.size(); // Metadata size_t uncompressedSize = size - sizeof(float)*nCoeffs + nNodes*nNodes*nChannels*nBases*nMaxOrder*sizeof(float); Log("Creating sparse BSDF storage file \"%s\":", filename.str()); Log(" Discretizations in mu : %d", nNodes); if (!extrapolate) Log(" Max. Fourier orders : %d", nMaxOrder); else Log(" Harmonic extrapolation : yes"); Log(" Color channels : %d", nChannels); Log(" Textured parameters : %d", nParameters); Log(" Basis functions : %d", nBases); Log(" Uncompressed size : %s", memString(uncompressedSize)); Log(" Actual size : %s (reduced to %.2f%%)", memString(size), 100 * size / (Float) uncompressedSize); m_mmap = new MemoryMappedFile(filename, size); m_header = (Header *) m_mmap->data(); const char *id = BSDF_STORAGE_HEADER_ID; const size_t len = strlen(BSDF_STORAGE_HEADER_ID); for (size_t i=0; i<len; ++i) m_header->identifier[i] = id[i]; m_header->version = BSDF_STORAGE_VERSION; m_header->flags = 0; m_header->flags |= BSDF_STORAGE_FLAGS_BSDF; if (extrapolate) m_header->flags |= BSDF_STORAGE_FLAGS_EXTRAPOLATED; m_header->nNodes = (uint32_t) nNodes; m_header->nParameters = (uint16_t) nParameters; m_header->nMaxOrder = (uint32_t) nMaxOrder; m_header->nChannels = (uint32_t) nChannels; m_header->nBases = (uint32_t) nBases; m_header->nParameterValues = (uint16_t) nParameterValues; m_header->nCoeffs = (uint32_t) nCoeffs; m_header->nMetadataBytes = (uint32_t) metadata.size(); m_header->eta = 1.0f; // default m_nodes = m_header->data; m_paramSampleCounts = (uint32_t *) (m_nodes + nNodes); m_paramSamplePositions = (float *) (m_paramSampleCounts + nParameters); m_cdfMu = m_paramSamplePositions + nParameterValues; m_offsetTable = (OffsetType *) (m_cdfMu + nNodes*nNodes*nBases); m_coeffs = (float *) (m_offsetTable + nNodes*nNodes*2); size_t idx = 0; m_paramSamplePositionsNested = new float*[nParameters]; for (size_t i=0; i<nParameters; ++i) { m_paramSampleCounts[i] = (uint32_t) paramSampleCounts[i]; m_paramSamplePositionsNested[i] = m_paramSamplePositions + idx; for (size_t j = 0; j<m_paramSampleCounts[i]; ++j) m_paramSamplePositions[idx++] = (float) paramSamplePositions[i][j]; } memcpy(m_coeffs + nCoeffs, metadata.c_str(), metadata.size()); m_metadata = metadata; int extra = LANE_WIDTH + LANE_WIDTH-1; m_reciprocals = (double *) simd::malloc((nMaxOrder+extra) * sizeof(double)); memset(m_reciprocals, 0, sizeof(double) * (nMaxOrder+extra)); m_reciprocals += LANE_WIDTH-1; for (uint32_t i=0; i<nMaxOrder+LANE_WIDTH; ++i) m_reciprocals[i] = 1.0 / (double) i; } BSDFStorage::BSDFStorage(const fs::path &filename, bool readOnly) : m_header(nullptr), m_reciprocals(nullptr), m_filename(filename), m_paramSamplePositionsNested(nullptr) { static_assert(sizeof(Header) == BSDF_STORAGE_HEADER_SIZE, "Header size mismatch!"); m_mmap = new MemoryMappedFile(filename, readOnly); if (m_mmap->size() < sizeof(Header)) Error("BSDF storage file \"%s\" has a truncated header!", filename.str()); m_header = (Header *) m_mmap->data(); const char *id = BSDF_STORAGE_HEADER_ID; const size_t len = strlen(BSDF_STORAGE_HEADER_ID); if (memcmp(id, m_header->identifier, len) != 0) Error("BSDF storage file \"%s\" has a corrupt header!", filename.str().c_str()); size_t nNodes = m_header->nNodes, nMaxOrder = m_header->nMaxOrder, nChannels = m_header->nChannels, nBases = m_header->nBases, nParameters = m_header->nParameters, nCoeffs = m_header->nCoeffs, nParameterValues = m_header->nParameterValues, nMetadataBytes = m_header->nMetadataBytes; size_t size = BSDF_STORAGE_HEADER_SIZE + // Header sizeof(float)*nNodes + // Node locations sizeof(uint32_t)*nParameters + // Parameter sample counts sizeof(float)*nParameterValues + // Parameter sample positions sizeof(float)*nNodes*nNodes*nBases + // CDF in \mu sizeof(OffsetType)*nNodes*nNodes*2 + // Offset + size table sizeof(float)*nCoeffs + // Fourier coeff nMetadataBytes; // Metadata size_t uncompressedSize = size - sizeof(float)*nCoeffs + nNodes*nNodes*nChannels*nBases*nMaxOrder*sizeof(float); if (m_mmap->size() != size) Error("BSDF storage file \"%s\" has an invalid size! (it" " is potentially truncated)", filename.str()); Log("Mapped sparse BSDF storage file \"%s\" into memory:", filename.str()); Log(" Discretizations in mu : %d", nNodes); if (!extrapolated()) Log(" Max. Fourier orders : %d", nMaxOrder); else Log(" Harmonic extrapolation : yes"); Log(" Color channels : %d", nChannels); Log(" Textured parameters : %d", nParameters); Log(" Basis functions : %d", nBases); Log(" Uncompressed size : %s", memString(uncompressedSize)); Log(" Actual size : %s (reduced to %.2f%%)", memString(size), 100 * size / (Float) uncompressedSize); m_nodes = m_header->data; m_paramSampleCounts = (uint32_t *) (m_nodes + nNodes); m_paramSamplePositions = (float *) (m_paramSampleCounts + nParameters); m_cdfMu = m_paramSamplePositions + nParameterValues; m_offsetTable = (OffsetType *) (m_cdfMu + nNodes*nNodes*nBases); m_coeffs = (float *) (m_offsetTable + nNodes*nNodes*2); size_t idx = 0; m_paramSamplePositionsNested = new float*[nParameters]; for (size_t i=0; i<nParameters; ++i) { m_paramSamplePositionsNested[i] = m_paramSamplePositions + idx; idx += m_paramSampleCounts[i]; } m_metadata.resize(nMetadataBytes); memcpy(&m_metadata[0], m_coeffs + nCoeffs, nMetadataBytes); int extra = LANE_WIDTH + LANE_WIDTH-1; m_reciprocals = (double *) simd::malloc((nMaxOrder+extra) * sizeof(double)); memset(m_reciprocals, 0, sizeof(double) * (nMaxOrder+extra)); m_reciprocals += LANE_WIDTH-1; for (uint32_t i=0; i<nMaxOrder+LANE_WIDTH; ++i) m_reciprocals[i] = 1.0 / (double) i; } BSDFStorage::~BSDFStorage() { if (m_mmap) delete m_mmap; if (m_reciprocals) simd::free(m_reciprocals - (LANE_WIDTH-1)); if (m_paramSamplePositionsNested) delete[] m_paramSamplePositionsNested; } Float integrateCubicInterp1DN(size_t idx, const Float *nodes, const Float *values, size_t size) { Float f0 = values[idx], f1 = values[idx+1], width = nodes[idx+1] - nodes[idx], d0, d1; /* Approximate the derivatives */ if (idx > 0) d0 = width * (f1 - values[idx-1]) / (nodes[idx+1] - nodes[idx-1]); else d0 = f1 - f0; if (idx + 2 < size) d1 = width * (values[idx+2] - f0) / (nodes[idx+2] - nodes[idx]); else d1 = f1 - f0; return ((d0-d1) * (Float) (1.0 / 12.0) + (f0+f1) * 0.5f) * width; } BSDFStorage *BSDFStorage::fromLayerGeneral(const fs::path &filename, const Layer **layers, size_t nChannels, size_t nBases, size_t nParameters, const size_t *paramSampleCounts, const float **paramSamplePositions, bool extrapolate, const std::string &metadata) { const Layer &layer = *layers[0]; size_t n = layer.resolution(), h = n/2; /* Insert an explicit mu=0 node to simplify the evaluation / sampling code */ VectorX nodes = (VectorX(n + 2) << layer.nodes().head(h).reverse(), 0, 0, layer.nodes().tail(h)).finished(); Log("BSDFStorage::fromLayerGeneral(): merging %d layers into \"%s\" " "- analyzing sparsity pattern..", nBases * nChannels, filename.str()); /* Do a huge matrix transpose */ size_t maxCoeffs = nodes.size()*nodes.size()*nBases*nChannels* (extrapolate ? 3 : layer.fourierOrders()); size_t nNodes = (size_t) nodes.size(); std::atomic<size_t> m(0); OffsetType *offsetTable = new OffsetType[nodes.size()*nodes.size()*2]; tbb::parallel_for( tbb::blocked_range<size_t>(0, nNodes), [&](const tbb::blocked_range<size_t> &range) { for (size_t i = range.begin(); i != range.end(); ++i) { for (size_t o = 0; o < nNodes; ++o) { MatrixS::Index ip, op; size_t offset = (o + i * nNodes) * 2; if (i == h || i == h+1 || o == h || o == h+1) { offsetTable[offset + 0] = 0; offsetTable[offset + 1] = 0; continue; } ip = (MatrixS::Index) (i < h ? (h-i-1) : (i-2)); op = (MatrixS::Index) (o < h ? (h-o-1) : (o-2)); size_t nCoeffs = 0; for (size_t basis=0; basis<nBases; ++basis) { for (size_t ch=0; ch<nChannels; ++ch) { size_t sparseSize = 0; float ref = std::abs((float) (*layers[basis*nChannels+ch])[0].coeff(op, ip)); float partialSum = 0; if (ref != 0) { sparseSize = (size_t) layer.fourierOrders(); for (size_t j=(size_t) layer.fourierOrders()-1; j>=1; --j) { float value = (float) (*layers[basis*nChannels+ch])[j].coeff(op, ip); partialSum += std::abs(value); if (partialSum <= ref * ERROR_GOAL || value == 0) sparseSize = j; } nCoeffs = std::max(nCoeffs, sparseSize); } } } if (extrapolate && nCoeffs > 0) nCoeffs = 3; do { size_t m_cur = m; if (nCoeffs <= m_cur || m.compare_exchange_strong(m_cur, nCoeffs)) break; } while(true); offsetTable[offset + 0] = 0; offsetTable[offset + 1] = (OffsetType) nCoeffs; } } }); if (extrapolate) m = 3; /* Compute the offset table */ size_t totalCoeffs = 0; for (size_t i=0; i<nNodes*nNodes; ++i) { offsetTable[2*i] = (OffsetType) totalCoeffs; totalCoeffs += offsetTable[2*i + 1] * nBases*nChannels; } Log("Done. Number of coeff: %d" " / %d" ", sparsity=%.2f%%", totalCoeffs, maxCoeffs, 100 * (Float) totalCoeffs / (Float) maxCoeffs); BSDFStorage *storage = new BSDFStorage(filename, nNodes, nChannels, m, totalCoeffs, nBases, nParameters, paramSampleCounts, paramSamplePositions, extrapolate, metadata); Log("Copying data into sparse BSDF file .."); for (size_t i=0; i<nNodes; ++i) storage->m_nodes[i] = (float) nodes[i]; memcpy(storage->offsetTable(), offsetTable, nNodes*nNodes*2*sizeof(OffsetType)); /* Do a huge matrix transpose */ for (size_t i=0; i<nNodes; ++i) { for (size_t o=0; o<nNodes; ++o) { std::pair<float *, OffsetType> coeffsAndCount = storage->coeffAndCount(o, i); float *coeffs = coeffsAndCount.first; OffsetType size = coeffsAndCount.second; MatrixS::Index ip, op; if (i == h || o == h) { assert(size == 0); continue; } ip = (MatrixS::Index) (i < h ? (h-i-1) : (i-2)); op = (MatrixS::Index) (o < h ? (h-o-1) : (o-2)); float weight = (float) std::abs(nodes[o] / (math::Pi * nodes[i] * layer.weights()[ip])); if (nChannels == 1) { for (size_t basis=0; basis<nBases; ++basis) { for (OffsetType j=0; j<size; ++j) { float value = (float) (*layers[basis])[j].coeff(op, ip) * weight * (j == 0 ? 0.5f : 1.0f); if (!std::isfinite(value)) Warn("Encountered invalid data: %f", value); *coeffs++ = value; } } } else if (nChannels == 3) { float *coeffsY = coeffs; float *coeffsR = coeffsY + size*nBases; float *coeffsB = coeffsR + size*nBases; for (size_t basis=0; basis<nBases; ++basis) { for (OffsetType j=0; j<size; ++j) { float weight2 = weight * (j == 0 ? 0.5f : 1.0f); float R = (float) (*layers[basis*nChannels+0])[j].coeff(op, ip) * weight2; float G = (float) (*layers[basis*nChannels+1])[j].coeff(op, ip) * weight2; float B = (float) (*layers[basis*nChannels+2])[j].coeff(op, ip) * weight2; float Y = R * 0.212671f + G * 0.715160f + B * 0.072169f; if (!std::isfinite(Y)) Warn("Encountered invalid data: %f", Y); *coeffsY++ = Y; *coeffsR++ = R; *coeffsB++ = B; } } } } } Log("Computing cumulative distributions for importance sampling .."); /* Create an importance sampling CDF */ VectorX splineValues(nNodes), cdf(nNodes); for (size_t i = 0; i < nNodes; ++i) { for (size_t basis = 0; basis < nBases; ++basis) { for (size_t o = 0; o < nNodes; ++o) { auto c = storage->coeffAndCount(o, i, basis, 0); splineValues[o] = c.second > 0 ? *c.first : 0; } spline::integrate1D(nodes.data(), splineValues.data(), nNodes, cdf.data()); float *cdf_ptr = storage->cdf(i) + basis; for (size_t k=0; k<nNodes; ++k) cdf_ptr[k * nBases] = (float) cdf[k]; } } #if 0 if (extrapolate) { Log("Performing harmonic extrapolation .."); SAssert(totalCoeffs % 3 == 0); for (size_t i=0; i<totalCoeffs; i += 3) HarmonicExtrapolation::transform(storage->m_coeffs + i, storage->m_coeffs + i); } #endif Log("BSDFStorage::fromLayerGeneral(): Done."); return storage; } size_t BSDFStorage::size() const { if (!m_mmap) return 0; return m_mmap->size(); } bool BSDFStorage::extrapolated() const { return m_header->flags & BSDF_STORAGE_FLAGS_EXTRAPOLATED; } Color3 BSDFStorage::eval(Float mu_i, Float mu_o, Float phi_d, const float *basisCoeffs) const { if (!basisCoeffs) { assert(basisCount() == 1); basisCoeffs = __basisCoeffsDefault; } ssize_t knotOffsetO, knotOffsetI; float knotWeightsO[4], knotWeightsI[4]; spline::evalSplineWeights(m_nodes, m_header->nNodes, (float) mu_o, knotOffsetO, knotWeightsO); spline::evalSplineWeights(m_nodes, m_header->nNodes, (float) mu_i, knotOffsetI, knotWeightsI); size_t nChannels = channelCount(), nBases = basisCount(); OffsetType nCoeffs = 0; float *coeffs[3]; for (size_t i=0; i<nChannels; ++i) coeffs[i] = fourier_aligned_alloca(maxOrder() * sizeof(float)); for (int i=0; i<4; ++i) { for (int o=0; o<4; ++o) { float weight = knotWeightsO[o] * knotWeightsI[i]; if (weight == 0) continue; std::pair<const float *, OffsetType> coeffAndCount = this->coeffAndCount(knotOffsetO + o, knotOffsetI + i); const float *source = coeffAndCount.first; OffsetType count = coeffAndCount.second; if (count == 0) continue; nCoeffs = std::max(nCoeffs, count); for (size_t channel=0; channel<nChannels; ++channel) { for (size_t basis=0; basis<nBases; ++basis) { float interpWeight = weight * basisCoeffs[channel*nBases+basis]; if (interpWeight == 0) { source += count; continue; } float *target = coeffs[channel]; OffsetType remainder = count; #if MTS_FOURIER_VECTORIZED == 1 /* Copy first (unaligned) element using scalar arithmetic */ *target++ += *source++ * interpWeight; --remainder; /* Copy as many elements as possible using AVX */ __m256 weight_vec = _mm256_set1_ps(interpWeight); OffsetType simdCount = remainder & ~7; for (OffsetType k=0; k<simdCount; k += 8) _mm256_store_ps(target+k, _mm256_add_ps(_mm256_load_ps(target+k), _mm256_mul_ps(_mm256_loadu_ps(source+k), weight_vec))); source += simdCount; target += simdCount; remainder -= simdCount; #endif for (OffsetType k=0; k<remainder; ++k) *target++ += *source++ * interpWeight; } } } } Color3 result; if (nCoeffs == 0 || coeffs[0][0] == 0.0f) { result = Color3(0.0f); #if 0 } else if (m_header->flags & BSDF_STORAGE_FLAGS_EXTRAPOLATED) { float phi_d_sp = (float) phi_d; for (size_t ch=0; ch<nChannels; ++ch) { coeffs[ch][0] = std::max(0.0f, coeffs[ch][0]); coeffs[ch][1] = std::max(0.0f, std::min(1.0f, coeffs[ch][1])); coeffs[ch][2] = std::max(1e-6f,coeffs[ch][2]); } if (nChannels == 1) { result = Color3((Float) HarmonicExtrapolation::eval(coeffs[0], phi_d_sp)); } else { Float Y = HarmonicExtrapolation::eval(coeffs[0], phi_d_sp); Float R = HarmonicExtrapolation::eval(coeffs[1], phi_d_sp); Float B = HarmonicExtrapolation::eval(coeffs[2], phi_d_sp); Float G = 1.39829f*Y - 0.100913f*B - 0.297375f*R; result.fromLinearRGB(R, G, B); } #endif } else if (nChannels == 1) { result = Color3(std::max((Float) 0, (Float) evalFourier(coeffs[0], nCoeffs, phi_d))); } else { result = evalFourier3(coeffs, nCoeffs, phi_d); } result.clamp(); return result; } Float BSDFStorage::pdf(Float mu_i, Float mu_o, Float phi_d, const float *basisCoeffs) const { if (!basisCoeffs) { assert(basisCount() == 1); basisCoeffs = __basisCoeffsDefault; } ssize_t knotOffsetO, knotOffsetI; float knotWeightsO[4], knotWeightsI[4]; spline::evalSplineWeights(m_nodes, m_header->nNodes, (float) mu_o, knotOffsetO, knotWeightsO); spline::evalSplineWeights(m_nodes, m_header->nNodes, (float) mu_i, knotOffsetI, knotWeightsI); size_t nBases = basisCount(); OffsetType nCoeffs = 0; float *coeffs = fourier_aligned_alloca(maxOrder() * sizeof(float)); for (int i=0; i<4; ++i) { for (int o=0; o<4; ++o) { float weight = knotWeightsO[o] * knotWeightsI[i]; if (weight == 0) continue; std::pair<const float *, OffsetType> coeffAndCount = this->coeffAndCount(knotOffsetO + o, knotOffsetI + i); const float *source = coeffAndCount.first; OffsetType count = coeffAndCount.second; if (count == 0) continue; nCoeffs = std::max(nCoeffs, count); for (size_t basis=0; basis<nBases; ++basis) { float interpWeight = weight * basisCoeffs[basis]; if (interpWeight == 0) { source += count; continue; } float *target = coeffs; OffsetType remainder = count; #if MTS_FOURIER_VECTORIZED == 1 /* Copy first (unaligned) element using scalar arithmetic */ *target++ += *source++ * interpWeight; --remainder; /* Copy as many elements as possible using AVX */ __m256 weight_vec = _mm256_set1_ps(interpWeight); OffsetType simdCount = remainder & ~7; for (OffsetType k=0; k<simdCount; k += 8) _mm256_store_ps(target+k, _mm256_add_ps(_mm256_load_ps(target+k), _mm256_mul_ps(_mm256_loadu_ps(source+k), weight_vec))); source += simdCount; target += simdCount; remainder -= simdCount; #endif for (OffsetType k=0; k<remainder; ++k) *target++ += *source++ * interpWeight; } } } Float pdfMu = coeffs[0] / evalLatitudinalCDF(knotOffsetI, knotWeightsI, nodeCount()-1, basisCoeffs); if (nCoeffs == 0 || coeffs[0] == 0.0f) { return 0.0f; #if 0 } else if (m_header->flags & BSDF_STORAGE_FLAGS_EXTRAPOLATED) { coeffs[0] = std::max(0.0f, coeffs[0]); coeffs[1] = std::max(0.0f, std::min(1.0f, coeffs[1])); coeffs[2] = std::max(1e-6f,coeffs[2]); return HarmonicExtrapolation::pdf(coeffs, (float) phi_d) * pdfMu; #endif } else { return std::max((Float) 0, pdfFourier(coeffs, nCoeffs, phi_d) * pdfMu); } } #if 0 Color3 BSDFStorage::sample(Float mu_i, Float &mu_o, Float &phi_d, Float &pdf, const Point2 &sample, const float *basisCoeffs) const { if (!basisCoeffs) { assert(basisCount() == 1); basisCoeffs = __basisCoeffsDefault; } size_t knotOffsetI, n = nodeCount(); float knotWeightsI[4]; /* Lookup spline nodes and weights for mu_i */ spline::evalSplineWeights(m_nodes, m_header->nNodes, (float) mu_i, knotOffsetI, knotWeightsI); /* Account for energy loss */ float normalization = evalLatitudinalCDF(knotOffsetI, knotWeightsI, n-1, basisCoeffs); float sample_y = (float) sample.y * normalization; /* Binary search for the spline segment containing the outgoing angle */ size_t first = 0, len = n; while (len > 0) { ssize_t half = len >> 1, middle = first + half; if (evalLatitudinalCDF(knotOffsetI, knotWeightsI, middle, basisCoeffs) < sample_y) { first = middle + 1; len -= half + 1; } else { len = half; } } size_t index = std::min(n-2, std::max((size_t) 0, first-1)); /* The spline segment to be sampled has been chosen. Determine the values of its nodes and then use the inversion method to sample an exact position within the segment */ float cdf0 = evalLatitudinalCDF(knotOffsetI, knotWeightsI, index, basisCoeffs), cdf1 = evalLatitudinalCDF(knotOffsetI, knotWeightsI, index+1, basisCoeffs), f0 = evalLatitudinalAverage(knotOffsetI, knotWeightsI, index, basisCoeffs), f1 = evalLatitudinalAverage(knotOffsetI, knotWeightsI, index+1, basisCoeffs), width = m_nodes[index+1] - m_nodes[index], d0, d1; /* Catmull-Rom spline: approximate the derivatives at the endpoints using finite differences */ if (index > 0) { d0 = width / (m_nodes[index+1] - m_nodes[index-1]) * (f1 - evalLatitudinalAverage(knotOffsetI, knotWeightsI, index-1, basisCoeffs)); } else { d0 = f1 - f0; } if (index + 2 < n) { d1 = width / (m_nodes[index+2] - m_nodes[index]) * (evalLatitudinalAverage(knotOffsetI, knotWeightsI, index+2, basisCoeffs) - f0); } else { d1 = f1 - f0; } /* Bracketing interval and starting guess */ float a = 0, c = 1, b; b = (sample_y-cdf0) / (cdf1-cdf0); sample_y = (sample_y-cdf0) / width; if (f0 != f1) /* Importance sample linear interpolant */ b = (f0-math::safe_sqrt(f0*f0 + b * (f1*f1-f0*f0))) / (f0-f1); /* Invert CDF using Newton-Bisection */ int it = 0; while (true) { if (!(b >= a && b <= c)) b = 0.5f * (a + c); /* CDF and PDF in Horner form */ float value = b*(f0 + b*(.5f*d0 + b*((1.0f/3.0f) * (-2*d0-d1) + f1 - f0 + b*(0.25f*(d0 + d1) + 0.5f * (f0 - f1))))) - sample_y; float deriv = f0 + b*(d0 + b*(-2*d0 - d1 + 3*(f1-f0) + b*(d0 + d1 + 2*(f0 - f1)))); if (std::abs(value) < 1e-6f * deriv || ++it > 10) { mu_o = m_nodes[index] + width*b; break; } if (value > 0) c = b; else a = b; b -= value / deriv; } /* Outgoing zenith angle has been sampled -- interpolate Fourier coeff and sample the series */ ssize_t knotOffsetO; float knotWeightsO[4]; spline::evalSplineWeights(m_nodes, m_header->nNodes, (float) mu_o, knotOffsetO, knotWeightsO); size_t nChannels = channelCount(), nBases = basisCount(); OffsetType nCoeffs = 0; float *coeffs[3]; for (size_t i=0; i<nChannels; ++i) coeffs[i] = fourier_aligned_alloca(maxOrder() * sizeof(float)); for (int i=0; i<4; ++i) { for (int o=0; o<4; ++o) { float weight = knotWeightsO[o] * knotWeightsI[i]; if (weight == 0) continue; std::pair<const float *, OffsetType> coeffAndCount = coeffAndCount(knotOffsetO + o, knotOffsetI + i); const float *source = coeffAndCount.first; OffsetType count = coeffAndCount.second; if (count == 0) continue; nCoeffs = std::max(nCoeffs, count); for (size_t channel=0; channel<nChannels; ++channel) { for (size_t basis=0; basis<nBases; ++basis) { float interpWeight = weight * basisCoeffs[channel*nBases+basis]; if (interpWeight == 0) { source += count; continue; } float *target = coeffs[channel]; OffsetType remainder = count; #if MTS_FOURIER_VECTORIZED == 1 /* Copy first (unaligned) element using scalar arithmetic */ *target++ += *source++ * interpWeight; --remainder; /* Copy as many elements as possible using AVX */ __m256 weight_vec = _mm256_set1_ps(interpWeight); OffsetType simdCount = remainder & ~7; for (OffsetType k=0; k<simdCount; k += 8) _mm256_store_ps(target+k, _mm256_add_ps(_mm256_load_ps(target+k), _mm256_mul_ps(_mm256_loadu_ps(source+k), weight_vec))); source += simdCount; target += simdCount; remainder -= simdCount; #endif for (OffsetType k=0; k<remainder; ++k) *target++ += *source++ * interpWeight; } } } } Float pdfMu = coeffs[0][0] / normalization; Float pdfPhi = 0; Color3 weight; if (coeffs[0][0] == 0) { weight = Color3(0.0f); } else if (m_header->flags & BSDF_STORAGE_FLAGS_EXTRAPOLATED) { for (size_t ch=0; ch<nChannels; ++ch) { coeffs[ch][0] = std::max(0.0f, coeffs[ch][0]); coeffs[ch][1] = std::max(0.0f, std::min(1.0f, coeffs[ch][1])); coeffs[ch][2] = std::max(1e-6f,coeffs[ch][2]); } Float phiWeight = HarmonicExtrapolation::sample(coeffs[0], phi_d, sample.x); float phi_d_sp = (float) phi_d; pdfPhi = HarmonicExtrapolation::pdf(coeffs[0], phi_d_sp); if (nChannels == 1) { weight = Color3(phiWeight * 2 * M_PI / pdfMu); } else { Float Y = HarmonicExtrapolation::eval(coeffs[0], phi_d_sp); Float R = HarmonicExtrapolation::eval(coeffs[1], phi_d_sp); Float B = HarmonicExtrapolation::eval(coeffs[2], phi_d_sp); Float G = 1.39829f*Y - 0.100913f*B - 0.297375f*R; weight.fromLinearRGB(R, G, B); weight /= pdfPhi * pdfMu; } } else if (nChannels == 1) { weight = Color3(std::max((Float) 0.0f, sampleFourier(coeffs[0], m_reciprocals, nCoeffs, (float) sample.x, pdfPhi, phi_d) / pdfMu)); } else { weight = sampleFourier3(coeffs, m_reciprocals, nCoeffs, (float) sample.x, pdfPhi, phi_d) / pdfMu; } weight.clamp(); pdf = std::max((Float) 0, pdfPhi * pdfMu); #if 1 if (!std::isfinite(phi_d) || !std::isfinite(weight.getLuminance())) { cout << "Coeffs: "; for (size_t i=0; i<nCoeffs; ++i) { cout << coeffs[0][i] << ", "; } cout << "Sample=" << sample.toString() << endl; cout << "phi_d=" << phi_d << endl; cout << "pdfMu=" << pdfMu << endl; cout << "weight=" << weight.toString() << endl; cout << endl; Error("Internal error while sampling: phi_d: %f, weight: %s", phi_d, weight.toString().c_str()); } #endif return weight; } #endif void BSDFStorage::interpolateSeries(Float mu_i, Float mu_o, int basis, int channel, float *coeffs) const { ssize_t knotOffsetO, knotOffsetI; float knotWeightsO[4], knotWeightsI[4]; spline::evalSplineWeights(m_nodes, m_header->nNodes, (float) mu_o, knotOffsetO, knotWeightsO); spline::evalSplineWeights(m_nodes, m_header->nNodes, (float) mu_i, knotOffsetI, knotWeightsI); memset(coeffs, 0, sizeof(float) * maxOrder()); for (int i=0; i<4; ++i) { for (int o=0; o<4; ++o) { float weight = knotWeightsO[o] * knotWeightsI[i]; if (weight == 0) continue; std::pair<const float *, OffsetType> coeffAndCount = this->coeffAndCount(knotOffsetO + o, knotOffsetI + i, basis, channel); const float *source = coeffAndCount.first; OffsetType count = coeffAndCount.second; float *target = coeffs; for (OffsetType k=0; k<count; ++k) *target++ += *source++ * weight; } } } std::string BSDFStorage::stats() const { std::ostringstream oss; size_t nNodes = m_header->nNodes, nMaxOrder = m_header->nMaxOrder, nChannels = m_header->nChannels, nBases = m_header->nBases, nParameters = m_header->nParameters, nCoeffs = m_header->nCoeffs, nParameterValues = m_header->nParameterValues, nMetadataBytes = m_header->nMetadataBytes; size_t size = BSDF_STORAGE_HEADER_SIZE + // Header sizeof(float)*nNodes + // Node locations sizeof(uint32_t)*nParameters + // Parameter sample counts sizeof(float)*nParameterValues + // Parameter sample positions sizeof(float)*nNodes*nNodes*nBases + // CDF in \mu sizeof(OffsetType)*nNodes*nNodes*2 + // Offset + size table sizeof(float)*nCoeffs + // Fourier coeff nMetadataBytes; // Metadata size_t uncompressedSize = size - sizeof(float)*nCoeffs + nNodes*nNodes*nChannels*nBases*nMaxOrder*sizeof(float); oss.precision(2); oss << " Discretizations in mu : " << nNodes << std::endl; if (!extrapolated()) oss << " Max. Fourier orders : " << nMaxOrder << std::endl; else oss << " Harmonic extrapolation : yes" << std::endl; oss << " Color channels : " << nChannels << std::endl; oss << " Textured parameters : " << nParameters << std::endl; oss << " Basis functions : " << nBases << std::endl; oss << " Uncompressed size : " << memString(uncompressedSize) << std::endl; oss << " Actual size : " << memString(size); oss << " (reduced to " << (100 * size / (Float) uncompressedSize) << "%)"; return oss.str(); } std::string BSDFStorage::toString() const { std::ostringstream oss; oss << "BSDFStorage[" << std::endl << " mmap = " << m_mmap->toString() << "," << std::endl; if (m_header) { oss << " nNodes = " << m_header->nNodes << "," << std::endl << " nMaxOrder = " << m_header->nMaxOrder << "," << std::endl << " nChannels = " << m_header->nChannels << "," << std::endl << " nBases = " << m_header->nBases << "," << std::endl << " eta = " << m_header->eta << std::endl; } oss << "]"; return oss.str(); } NAMESPACE_END(layer)
38.958606
113
0.557069
[ "transform" ]
4604edb76f1e2cac71ae6e1a85c20dae6bb921cc
2,520
cc
C++
influxdb/src/connector.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
40
2015-03-10T07:55:39.000Z
2021-06-11T10:13:56.000Z
influxdb/src/connector.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
297
2015-04-30T10:02:04.000Z
2022-03-09T13:31:54.000Z
influxdb/src/connector.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
29
2015-08-03T10:04:15.000Z
2021-11-25T12:21:00.000Z
/* ** Copyright 2011-2017, 2021 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #include "com/centreon/broker/influxdb/connector.hh" #include "com/centreon/broker/influxdb/stream.hh" #include "com/centreon/broker/persistent_cache.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::influxdb; /************************************** * * * Public Methods * * * **************************************/ /** * Default constructor. */ connector::connector() : io::endpoint(false) {} /** * Destructor. */ connector::~connector() {} /** * Set connection parameters. * */ void connector::connect_to(std::string const& user, std::string const& passwd, std::string const& addr, unsigned short port, std::string const& db, uint32_t queries_per_transaction, std::string const& status_ts, std::vector<column> const& status_cols, std::string const& metric_ts, std::vector<column> const& metric_cols, std::shared_ptr<persistent_cache> const& cache) { _user = user; _password = passwd; _addr = addr; _port = port, _db = db; _queries_per_transaction = queries_per_transaction; _status_ts = status_ts; _status_cols = status_cols; _metric_ts = metric_ts; _metric_cols = metric_cols; _cache = cache; } /** * @brief Connect to an influxdb DB. * * @return An Influxdb connection object. */ std::unique_ptr<io::stream> connector::open() { return std::unique_ptr<stream>( new stream(_user, _password, _addr, _port, _db, _queries_per_transaction, _status_ts, _status_cols, _metric_ts, _metric_cols, _cache)); }
31.898734
79
0.594048
[ "object", "vector" ]
460546bd1c2ae31891ea4e55b7f4c7e21091289b
3,852
cpp
C++
src/gpd/src/tests/test_occlusion.cpp
iiisrobotics/bulldog_ws
5bf3c48fd9c51fdee7c36705ce99e59e4abd96ed
[ "MIT" ]
null
null
null
src/gpd/src/tests/test_occlusion.cpp
iiisrobotics/bulldog_ws
5bf3c48fd9c51fdee7c36705ce99e59e4abd96ed
[ "MIT" ]
null
null
null
src/gpd/src/tests/test_occlusion.cpp
iiisrobotics/bulldog_ws
5bf3c48fd9c51fdee7c36705ce99e59e4abd96ed
[ "MIT" ]
null
null
null
#include <gpg/candidates_generator.h> #include <gpg/cloud_camera.h> #include <gpg/grasp.h> #include <gpg/plot.h> #include <gpd/learning.h> int main(int argc, char* argv[]) { // View point from which the camera sees the point cloud. Eigen::Matrix3Xd view_points(3,1); view_points.setZero(); // Load point cloud from file // std::string filename = "/media/andreas/2a9b7d00-f8c3-4849-9ddc-283f5b7c206a/data/object_datasets/bb_onesource/pcd/vo5_tea_therapy_healthful_green_tea_smoothing_shampoo_1_bin.pcd"; std::string filename = "/home/andreas/data/bigbird/3m_high_track_spray_adhesive/clouds/NP1_0.pcd"; // std::string filename = "/home/baxter/data/bigbird/3m_high_tack_spray_adhesive/clouds/NP1_0.pcd"; CloudCamera cloud_cam(filename, view_points); if (cloud_cam.getCloudOriginal()->size() == 0) { std::cout << "Input point cloud is empty or does not exist!\n"; return (-1); } // Use a custom sample. Eigen::Matrix3Xd samples(3,1); samples << -0.0129, 0.0515, 0.7042; cloud_cam.setSamples(samples); // Create objects to store parameters. CandidatesGenerator::Parameters generator_params; HandSearch::Parameters hand_search_params; // Hand geometry parameters hand_search_params.finger_width_ = 0.01; hand_search_params.hand_outer_diameter_ = 0.12; hand_search_params.hand_depth_ = 0.06; hand_search_params.hand_height_ = 0.02; hand_search_params.init_bite_ = 0.015; // Local hand search parameters hand_search_params.nn_radius_frames_ = 0.01; hand_search_params.num_orientations_ = 8; hand_search_params.num_samples_ = 1; hand_search_params.num_threads_ = 1; hand_search_params.rotation_axis_ = 2; // General parameters generator_params.num_samples_ = hand_search_params.num_samples_; generator_params.num_threads_ = hand_search_params.num_threads_; generator_params.plot_grasps_ = true; // Preprocessing parameters generator_params.remove_statistical_outliers_ = false; generator_params.voxelize_ = false; generator_params.workspace_.resize(6); generator_params.workspace_[0] = -1.0; generator_params.workspace_[1] = 1.0; generator_params.workspace_[2] = -1.0; generator_params.workspace_[3] = 1.0; generator_params.workspace_[4] = -1.0; generator_params.workspace_[5] = 1.0; // Image parameters Learning::ImageParameters image_params; image_params.depth_ = 0.06; image_params.height_ = 0.02; image_params.outer_diameter_ = 0.10; image_params.size_ = 60; image_params.num_channels_ = 15; // Calculate surface normals. cloud_cam.calculateNormals(4); // Plot the normals. Plot plot; plot.plotNormals(cloud_cam.getCloudProcessed(), cloud_cam.getNormals()); // Manually construct a grasp candidate. Eigen::Matrix3d frame; frame << 0.9317, 0.3561, 0.0717, 0.0968, -0.0533, -0.9939, -0.3501, 0.9329, -0.0841; Eigen::Vector3d sample = samples.col(0); FingerHand fh(hand_search_params.finger_width_, hand_search_params.hand_outer_diameter_, hand_search_params.hand_depth_); fh.setBottom(-0.0150); fh.setTop(0.0450); fh.setSurface(-0.0180); fh.setLeft(-0.0511); fh.setRight(0.0489); fh.setCenter(-0.0011); Grasp hand(sample, frame, fh); hand.print(); std::vector<Grasp> hands; hands.push_back(hand); GraspSet hand_set; hand_set.setHands(hands); hand_set.setSample(sample); std::vector<GraspSet> hand_set_list; hand_set_list.push_back(hand_set); // Create the image for this grasp candidate. Learning learn(image_params, 1, hand_search_params.num_orientations_, true, false); std::vector<cv::Mat> images = learn.createImages(cloud_cam, hand_set_list); std::cout << "------------\n" << images[0].rows << " x " << images[0].cols << " x " << images[0].channels() << "\n"; // Predict if the grasp candidate is a good grasp or not. return 0; }
33.206897
185
0.731828
[ "geometry", "vector" ]
4608ddde74b7d2631c1ce2939ee31598e2fe2321
676
cpp
C++
daily/4.cpp
tuket/challenges
456979020c78dfcae2f8681245000bb64a6aaf38
[ "Unlicense" ]
null
null
null
daily/4.cpp
tuket/challenges
456979020c78dfcae2f8681245000bb64a6aaf38
[ "Unlicense" ]
null
null
null
daily/4.cpp
tuket/challenges
456979020c78dfcae2f8681245000bb64a6aaf38
[ "Unlicense" ]
null
null
null
#include <iostream> #include <vector> using namespace std; template <typename T> void debugPrint(const vector<T>& v) { for(const T& x : v) cerr << x << " "; cerr << endl; } int minMissingPositive(vector<int>& a) { const int n = a.size(); for(int i=0; i<n; ) { int ai = a[i]; if(ai > 0 && ai <= n && ai != i+1) swap(a[i], a[ai-1]); else i++; } for(int i=0; i<n; i++) { if(a[i] != i+1) return i+1; } return n+1; } int main() { //vector<int> a = {3, 4, -1, 1}; vector<int> a = {1, 2, 0}; debugPrint(a); cout << minMissingPositive(a) << endl; }
17.333333
42
0.454142
[ "vector" ]
460973c771a97f01854e17fe3b4e581770fe96cf
2,478
cpp
C++
Analysis/utest/OptArgs_Test.cpp
konradotto/TS
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
[ "Apache-2.0" ]
125
2015-01-22T05:43:23.000Z
2022-03-22T17:15:59.000Z
Analysis/utest/OptArgs_Test.cpp
konradotto/TS
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
[ "Apache-2.0" ]
59
2015-02-10T09:13:06.000Z
2021-11-11T02:32:38.000Z
Analysis/utest/OptArgs_Test.cpp
konradotto/TS
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
[ "Apache-2.0" ]
98
2015-01-17T01:25:10.000Z
2022-03-18T17:29:42.000Z
/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */ #include <gtest/gtest.h> #include "OptArgs.h" #include "Utils.h" using namespace std; TEST(OptArgs_Test, BasicTest) { const char *argv[] = {"test-prog", "--mult-double", "0.0,1.0", "--mult-int", "1,-10,0", "--hello", "world", "-b", "true", "-d", "2.0", "-i", "5", "--unchecked","fun","trailing1", "trailing2"}; int argc = ArraySize(argv); OptArgs opts; opts.ParseCmdLine(argc, argv); string hello = "junk"; int i = -1; double d = -1.0; bool b = false; string notCalled = "non-specified"; vector<string> unchecked; vector<double> multDouble; vector<int> multInt; opts.GetOption(hello, "junk", 's', "hello"); opts.GetOption(i, "-1", 'i', "int-opt"); opts.GetOption(d, "-1.0", 'd', "double-opt"); opts.GetOption(b, "false", 'b', "bool-opt"); opts.GetOption(multDouble, "", '-', "mult-double"); opts.GetOption(multInt, "", '-', "mult-int"); opts.GetUncheckedOptions(unchecked); EXPECT_EQ(hello, "world"); EXPECT_EQ(multDouble.size(), 2); EXPECT_EQ(multDouble[0], 0.0); EXPECT_EQ(multDouble[1], 1.0); EXPECT_EQ(multInt.size(), 3); EXPECT_EQ(multInt[0], 1); EXPECT_EQ(multInt[1], -10); EXPECT_EQ(multInt[2], 0); EXPECT_EQ(b, true); EXPECT_EQ(d, 2.0); EXPECT_EQ(i, 5); EXPECT_EQ(unchecked[0], "unchecked"); vector<string> leftover; opts.GetLeftoverArguments(leftover); ASSERT_EQ(leftover.size(), 2); EXPECT_EQ(leftover[0], "trailing1"); EXPECT_EQ(leftover[1], "trailing2"); } TEST(OptArgs_DeathTest, BadTypesTest) { const char *argv[] = {"test-prog", "--mult-double", "0.0a,1.0,", "--hello", "world", "-b", "bad", "-d", "true", "-i", "x", "--unchecked","fun","trailing1", "trailing2"}; int argc = ArraySize(argv); OptArgs opts; opts.ParseCmdLine(argc, argv); string hello = "junk"; int i = -1; double d = -1.0; bool b = false; string notCalled = "non-specified"; vector<double> multDouble; opts.GetOption(hello, "junk", 's', "hello"); EXPECT_DEATH(opts.GetOption(i, "-1", 'i', "int-opt"), ".*"); EXPECT_DEATH(opts.GetOption(d, "-1.0", 'd', "double-opt"), ".*"); EXPECT_DEATH(opts.GetOption(b, "false", 'b', "bool-opt"), ".*"); EXPECT_DEATH(opts.GetOption(multDouble, "", '-', "mult-double"), ".*"); EXPECT_EQ(hello, "world"); vector<string> leftover; opts.GetLeftoverArguments(leftover); ASSERT_EQ(leftover.size(), 2); EXPECT_EQ(leftover[0], "trailing1"); EXPECT_EQ(leftover[1], "trailing2"); }
34.416667
194
0.62954
[ "vector" ]
46209c5bab6143f423098003e4d38f3d8d0aeaf6
49,195
cpp
C++
CesiumGltfReader/generated/GeneratedJsonHandlers.cpp
zrkcode/cesium-native
5265a65053542fe02928c272762c6b89fa2b29bb
[ "Apache-2.0" ]
null
null
null
CesiumGltfReader/generated/GeneratedJsonHandlers.cpp
zrkcode/cesium-native
5265a65053542fe02928c272762c6b89fa2b29bb
[ "Apache-2.0" ]
null
null
null
CesiumGltfReader/generated/GeneratedJsonHandlers.cpp
zrkcode/cesium-native
5265a65053542fe02928c272762c6b89fa2b29bb
[ "Apache-2.0" ]
null
null
null
// This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/KHR_draco_mesh_compression.h" #include "KHR_draco_mesh_compressionJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; KHR_draco_mesh_compressionJsonHandler::KHR_draco_mesh_compressionJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _bufferView(), _attributes() {} void KHR_draco_mesh_compressionJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, KHR_draco_mesh_compression* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* KHR_draco_mesh_compressionJsonHandler::readObjectKey( const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyKHR_draco_mesh_compression( KHR_draco_mesh_compression::TypeName, str, *this->_pObject); } void KHR_draco_mesh_compressionJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, ExtensibleObject& o, const std::string_view& extensionName) { std::any& value = o.extensions.emplace(extensionName, KHR_draco_mesh_compression()) .first->second; this->reset( pParentHandler, &std::any_cast<KHR_draco_mesh_compression&>(value)); } CesiumJsonReader::IJsonHandler* KHR_draco_mesh_compressionJsonHandler::readObjectKeyKHR_draco_mesh_compression( const std::string& objectType, const std::string_view& str, KHR_draco_mesh_compression& o) { using namespace std::string_literals; if ("bufferView"s == str) return property("bufferView", this->_bufferView, o.bufferView); if ("attributes"s == str) return property("attributes", this->_attributes, o.attributes); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/Model.h" #include "ModelJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; ModelJsonHandler::ModelJsonHandler(const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _extensionsUsed(), _extensionsRequired(), _accessors(context), _animations(context), _asset(context), _buffers(context), _bufferViews(context), _cameras(context), _images(context), _materials(context), _meshes(context), _nodes(context), _samplers(context), _scene(), _scenes(context), _skins(context), _textures(context) {} void ModelJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Model* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* ModelJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyModel(Model::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* ModelJsonHandler::readObjectKeyModel( const std::string& objectType, const std::string_view& str, Model& o) { using namespace std::string_literals; if ("extensionsUsed"s == str) return property("extensionsUsed", this->_extensionsUsed, o.extensionsUsed); if ("extensionsRequired"s == str) return property( "extensionsRequired", this->_extensionsRequired, o.extensionsRequired); if ("accessors"s == str) return property("accessors", this->_accessors, o.accessors); if ("animations"s == str) return property("animations", this->_animations, o.animations); if ("asset"s == str) return property("asset", this->_asset, o.asset); if ("buffers"s == str) return property("buffers", this->_buffers, o.buffers); if ("bufferViews"s == str) return property("bufferViews", this->_bufferViews, o.bufferViews); if ("cameras"s == str) return property("cameras", this->_cameras, o.cameras); if ("images"s == str) return property("images", this->_images, o.images); if ("materials"s == str) return property("materials", this->_materials, o.materials); if ("meshes"s == str) return property("meshes", this->_meshes, o.meshes); if ("nodes"s == str) return property("nodes", this->_nodes, o.nodes); if ("samplers"s == str) return property("samplers", this->_samplers, o.samplers); if ("scene"s == str) return property("scene", this->_scene, o.scene); if ("scenes"s == str) return property("scenes", this->_scenes, o.scenes); if ("skins"s == str) return property("skins", this->_skins, o.skins); if ("textures"s == str) return property("textures", this->_textures, o.textures); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/Texture.h" #include "TextureJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; TextureJsonHandler::TextureJsonHandler(const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _sampler(), _source() {} void TextureJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Texture* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* TextureJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyTexture(Texture::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* TextureJsonHandler::readObjectKeyTexture( const std::string& objectType, const std::string_view& str, Texture& o) { using namespace std::string_literals; if ("sampler"s == str) return property("sampler", this->_sampler, o.sampler); if ("source"s == str) return property("source", this->_source, o.source); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/Skin.h" #include "SkinJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; SkinJsonHandler::SkinJsonHandler(const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _inverseBindMatrices(), _skeleton(), _joints() {} void SkinJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Skin* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* SkinJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeySkin(Skin::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* SkinJsonHandler::readObjectKeySkin( const std::string& objectType, const std::string_view& str, Skin& o) { using namespace std::string_literals; if ("inverseBindMatrices"s == str) return property( "inverseBindMatrices", this->_inverseBindMatrices, o.inverseBindMatrices); if ("skeleton"s == str) return property("skeleton", this->_skeleton, o.skeleton); if ("joints"s == str) return property("joints", this->_joints, o.joints); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/Scene.h" #include "SceneJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; SceneJsonHandler::SceneJsonHandler(const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _nodes() {} void SceneJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Scene* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* SceneJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyScene(Scene::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* SceneJsonHandler::readObjectKeyScene( const std::string& objectType, const std::string_view& str, Scene& o) { using namespace std::string_literals; if ("nodes"s == str) return property("nodes", this->_nodes, o.nodes); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/Sampler.h" #include "SamplerJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; SamplerJsonHandler::SamplerJsonHandler(const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _magFilter(), _minFilter(), _wrapS(), _wrapT() {} void SamplerJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Sampler* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* SamplerJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeySampler(Sampler::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* SamplerJsonHandler::readObjectKeySampler( const std::string& objectType, const std::string_view& str, Sampler& o) { using namespace std::string_literals; if ("magFilter"s == str) return property("magFilter", this->_magFilter, o.magFilter); if ("minFilter"s == str) return property("minFilter", this->_minFilter, o.minFilter); if ("wrapS"s == str) return property("wrapS", this->_wrapS, o.wrapS); if ("wrapT"s == str) return property("wrapT", this->_wrapT, o.wrapT); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/Node.h" #include "NodeJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; NodeJsonHandler::NodeJsonHandler(const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _camera(), _children(), _skin(), _matrix(), _mesh(), _rotation(), _scale(), _translation(), _weights() {} void NodeJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Node* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* NodeJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyNode(Node::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* NodeJsonHandler::readObjectKeyNode( const std::string& objectType, const std::string_view& str, Node& o) { using namespace std::string_literals; if ("camera"s == str) return property("camera", this->_camera, o.camera); if ("children"s == str) return property("children", this->_children, o.children); if ("skin"s == str) return property("skin", this->_skin, o.skin); if ("matrix"s == str) return property("matrix", this->_matrix, o.matrix); if ("mesh"s == str) return property("mesh", this->_mesh, o.mesh); if ("rotation"s == str) return property("rotation", this->_rotation, o.rotation); if ("scale"s == str) return property("scale", this->_scale, o.scale); if ("translation"s == str) return property("translation", this->_translation, o.translation); if ("weights"s == str) return property("weights", this->_weights, o.weights); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/Mesh.h" #include "MeshJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; MeshJsonHandler::MeshJsonHandler(const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _primitives(context), _weights() {} void MeshJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Mesh* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* MeshJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyMesh(Mesh::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* MeshJsonHandler::readObjectKeyMesh( const std::string& objectType, const std::string_view& str, Mesh& o) { using namespace std::string_literals; if ("primitives"s == str) return property("primitives", this->_primitives, o.primitives); if ("weights"s == str) return property("weights", this->_weights, o.weights); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/MeshPrimitive.h" #include "MeshPrimitiveJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; MeshPrimitiveJsonHandler::MeshPrimitiveJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _attributes(), _indices(), _material(), _mode(), _targets() {} void MeshPrimitiveJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, MeshPrimitive* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* MeshPrimitiveJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyMeshPrimitive( MeshPrimitive::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* MeshPrimitiveJsonHandler::readObjectKeyMeshPrimitive( const std::string& objectType, const std::string_view& str, MeshPrimitive& o) { using namespace std::string_literals; if ("attributes"s == str) return property("attributes", this->_attributes, o.attributes); if ("indices"s == str) return property("indices", this->_indices, o.indices); if ("material"s == str) return property("material", this->_material, o.material); if ("mode"s == str) return property("mode", this->_mode, o.mode); if ("targets"s == str) return property("targets", this->_targets, o.targets); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/Material.h" #include "MaterialJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; MaterialJsonHandler::MaterialJsonHandler(const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _pbrMetallicRoughness(context), _normalTexture(context), _occlusionTexture(context), _emissiveTexture(context), _emissiveFactor(), _alphaMode(), _alphaCutoff(), _doubleSided() {} void MaterialJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Material* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* MaterialJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyMaterial(Material::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* MaterialJsonHandler::readObjectKeyMaterial( const std::string& objectType, const std::string_view& str, Material& o) { using namespace std::string_literals; if ("pbrMetallicRoughness"s == str) return property( "pbrMetallicRoughness", this->_pbrMetallicRoughness, o.pbrMetallicRoughness); if ("normalTexture"s == str) return property("normalTexture", this->_normalTexture, o.normalTexture); if ("occlusionTexture"s == str) return property( "occlusionTexture", this->_occlusionTexture, o.occlusionTexture); if ("emissiveTexture"s == str) return property( "emissiveTexture", this->_emissiveTexture, o.emissiveTexture); if ("emissiveFactor"s == str) return property("emissiveFactor", this->_emissiveFactor, o.emissiveFactor); if ("alphaMode"s == str) return property("alphaMode", this->_alphaMode, o.alphaMode); if ("alphaCutoff"s == str) return property("alphaCutoff", this->_alphaCutoff, o.alphaCutoff); if ("doubleSided"s == str) return property("doubleSided", this->_doubleSided, o.doubleSided); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } void MaterialJsonHandler::AlphaModeJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParent, Material::AlphaMode* pEnum) { JsonHandler::reset(pParent); this->_pEnum = pEnum; } CesiumJsonReader::IJsonHandler* MaterialJsonHandler::AlphaModeJsonHandler::readString( const std::string_view& str) { using namespace std::string_literals; assert(this->_pEnum); if ("OPAQUE"s == str) *this->_pEnum = Material::AlphaMode::OPAQUE; else if ("MASK"s == str) *this->_pEnum = Material::AlphaMode::MASK; else if ("BLEND"s == str) *this->_pEnum = Material::AlphaMode::BLEND; else return nullptr; return this->parent(); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/TextureInfo.h" #include "TextureInfoJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; TextureInfoJsonHandler::TextureInfoJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _index(), _texCoord() {} void TextureInfoJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, TextureInfo* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* TextureInfoJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyTextureInfo( TextureInfo::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* TextureInfoJsonHandler::readObjectKeyTextureInfo( const std::string& objectType, const std::string_view& str, TextureInfo& o) { using namespace std::string_literals; if ("index"s == str) return property("index", this->_index, o.index); if ("texCoord"s == str) return property("texCoord", this->_texCoord, o.texCoord); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/MaterialOcclusionTextureInfo.h" #include "MaterialOcclusionTextureInfoJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; MaterialOcclusionTextureInfoJsonHandler:: MaterialOcclusionTextureInfoJsonHandler( const ReaderContext& context) noexcept : TextureInfoJsonHandler(context), _strength() {} void MaterialOcclusionTextureInfoJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, MaterialOcclusionTextureInfo* pObject) { TextureInfoJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* MaterialOcclusionTextureInfoJsonHandler::readObjectKey( const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyMaterialOcclusionTextureInfo( MaterialOcclusionTextureInfo::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* MaterialOcclusionTextureInfoJsonHandler:: readObjectKeyMaterialOcclusionTextureInfo( const std::string& objectType, const std::string_view& str, MaterialOcclusionTextureInfo& o) { using namespace std::string_literals; if ("strength"s == str) return property("strength", this->_strength, o.strength); return this->readObjectKeyTextureInfo(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/MaterialNormalTextureInfo.h" #include "MaterialNormalTextureInfoJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; MaterialNormalTextureInfoJsonHandler::MaterialNormalTextureInfoJsonHandler( const ReaderContext& context) noexcept : TextureInfoJsonHandler(context), _scale() {} void MaterialNormalTextureInfoJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, MaterialNormalTextureInfo* pObject) { TextureInfoJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* MaterialNormalTextureInfoJsonHandler::readObjectKey( const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyMaterialNormalTextureInfo( MaterialNormalTextureInfo::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* MaterialNormalTextureInfoJsonHandler::readObjectKeyMaterialNormalTextureInfo( const std::string& objectType, const std::string_view& str, MaterialNormalTextureInfo& o) { using namespace std::string_literals; if ("scale"s == str) return property("scale", this->_scale, o.scale); return this->readObjectKeyTextureInfo(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/MaterialPBRMetallicRoughness.h" #include "MaterialPBRMetallicRoughnessJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; MaterialPBRMetallicRoughnessJsonHandler:: MaterialPBRMetallicRoughnessJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _baseColorFactor(), _baseColorTexture(context), _metallicFactor(), _roughnessFactor(), _metallicRoughnessTexture(context) {} void MaterialPBRMetallicRoughnessJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, MaterialPBRMetallicRoughness* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* MaterialPBRMetallicRoughnessJsonHandler::readObjectKey( const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyMaterialPBRMetallicRoughness( MaterialPBRMetallicRoughness::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* MaterialPBRMetallicRoughnessJsonHandler:: readObjectKeyMaterialPBRMetallicRoughness( const std::string& objectType, const std::string_view& str, MaterialPBRMetallicRoughness& o) { using namespace std::string_literals; if ("baseColorFactor"s == str) return property( "baseColorFactor", this->_baseColorFactor, o.baseColorFactor); if ("baseColorTexture"s == str) return property( "baseColorTexture", this->_baseColorTexture, o.baseColorTexture); if ("metallicFactor"s == str) return property("metallicFactor", this->_metallicFactor, o.metallicFactor); if ("roughnessFactor"s == str) return property( "roughnessFactor", this->_roughnessFactor, o.roughnessFactor); if ("metallicRoughnessTexture"s == str) return property( "metallicRoughnessTexture", this->_metallicRoughnessTexture, o.metallicRoughnessTexture); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CesiumGltf/Image.h" #include "ImageJsonHandler.h" #include <cassert> #include <string> using namespace CesiumGltf; ImageJsonHandler::ImageJsonHandler(const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _uri(), _mimeType(), _bufferView() {} void ImageJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Image* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* ImageJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyImage(Image::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* ImageJsonHandler::readObjectKeyImage( const std::string& objectType, const std::string_view& str, Image& o) { using namespace std::string_literals; if ("uri"s == str) return property("uri", this->_uri, o.uri); if ("mimeType"s == str) return property("mimeType", this->_mimeType, o.mimeType); if ("bufferView"s == str) return property("bufferView", this->_bufferView, o.bufferView); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } void ImageJsonHandler::MimeTypeJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParent, Image::MimeType* pEnum) { JsonHandler::reset(pParent); this->_pEnum = pEnum; } CesiumJsonReader::IJsonHandler* ImageJsonHandler::MimeTypeJsonHandler::readString(const std::string_view& str) { using namespace std::string_literals; assert(this->_pEnum); if ("image/jpeg"s == str) *this->_pEnum = Image::MimeType::image_jpeg; else if ("image/png"s == str) *this->_pEnum = Image::MimeType::image_png; else return nullptr; return this->parent(); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CameraJsonHandler.h" #include "CesiumGltf/Camera.h" #include <cassert> #include <string> using namespace CesiumGltf; CameraJsonHandler::CameraJsonHandler(const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _orthographic(context), _perspective(context), _type() {} void CameraJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Camera* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* CameraJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyCamera(Camera::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* CameraJsonHandler::readObjectKeyCamera( const std::string& objectType, const std::string_view& str, Camera& o) { using namespace std::string_literals; if ("orthographic"s == str) return property("orthographic", this->_orthographic, o.orthographic); if ("perspective"s == str) return property("perspective", this->_perspective, o.perspective); if ("type"s == str) return property("type", this->_type, o.type); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } void CameraJsonHandler::TypeJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParent, Camera::Type* pEnum) { JsonHandler::reset(pParent); this->_pEnum = pEnum; } CesiumJsonReader::IJsonHandler* CameraJsonHandler::TypeJsonHandler::readString(const std::string_view& str) { using namespace std::string_literals; assert(this->_pEnum); if ("perspective"s == str) *this->_pEnum = Camera::Type::perspective; else if ("orthographic"s == str) *this->_pEnum = Camera::Type::orthographic; else return nullptr; return this->parent(); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CameraPerspectiveJsonHandler.h" #include "CesiumGltf/CameraPerspective.h" #include <cassert> #include <string> using namespace CesiumGltf; CameraPerspectiveJsonHandler::CameraPerspectiveJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _aspectRatio(), _yfov(), _zfar(), _znear() {} void CameraPerspectiveJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, CameraPerspective* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* CameraPerspectiveJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyCameraPerspective( CameraPerspective::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* CameraPerspectiveJsonHandler::readObjectKeyCameraPerspective( const std::string& objectType, const std::string_view& str, CameraPerspective& o) { using namespace std::string_literals; if ("aspectRatio"s == str) return property("aspectRatio", this->_aspectRatio, o.aspectRatio); if ("yfov"s == str) return property("yfov", this->_yfov, o.yfov); if ("zfar"s == str) return property("zfar", this->_zfar, o.zfar); if ("znear"s == str) return property("znear", this->_znear, o.znear); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "CameraOrthographicJsonHandler.h" #include "CesiumGltf/CameraOrthographic.h" #include <cassert> #include <string> using namespace CesiumGltf; CameraOrthographicJsonHandler::CameraOrthographicJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _xmag(), _ymag(), _zfar(), _znear() {} void CameraOrthographicJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, CameraOrthographic* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* CameraOrthographicJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyCameraOrthographic( CameraOrthographic::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* CameraOrthographicJsonHandler::readObjectKeyCameraOrthographic( const std::string& objectType, const std::string_view& str, CameraOrthographic& o) { using namespace std::string_literals; if ("xmag"s == str) return property("xmag", this->_xmag, o.xmag); if ("ymag"s == str) return property("ymag", this->_ymag, o.ymag); if ("zfar"s == str) return property("zfar", this->_zfar, o.zfar); if ("znear"s == str) return property("znear", this->_znear, o.znear); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "BufferViewJsonHandler.h" #include "CesiumGltf/BufferView.h" #include <cassert> #include <string> using namespace CesiumGltf; BufferViewJsonHandler::BufferViewJsonHandler( const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _buffer(), _byteOffset(), _byteLength(), _byteStride(), _target() {} void BufferViewJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, BufferView* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* BufferViewJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyBufferView( BufferView::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* BufferViewJsonHandler::readObjectKeyBufferView( const std::string& objectType, const std::string_view& str, BufferView& o) { using namespace std::string_literals; if ("buffer"s == str) return property("buffer", this->_buffer, o.buffer); if ("byteOffset"s == str) return property("byteOffset", this->_byteOffset, o.byteOffset); if ("byteLength"s == str) return property("byteLength", this->_byteLength, o.byteLength); if ("byteStride"s == str) return property("byteStride", this->_byteStride, o.byteStride); if ("target"s == str) return property("target", this->_target, o.target); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "BufferJsonHandler.h" #include "CesiumGltf/Buffer.h" #include <cassert> #include <string> using namespace CesiumGltf; BufferJsonHandler::BufferJsonHandler(const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _uri(), _byteLength() {} void BufferJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Buffer* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* BufferJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyBuffer(Buffer::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* BufferJsonHandler::readObjectKeyBuffer( const std::string& objectType, const std::string_view& str, Buffer& o) { using namespace std::string_literals; if ("uri"s == str) return property("uri", this->_uri, o.uri); if ("byteLength"s == str) return property("byteLength", this->_byteLength, o.byteLength); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "AssetJsonHandler.h" #include "CesiumGltf/Asset.h" #include <cassert> #include <string> using namespace CesiumGltf; AssetJsonHandler::AssetJsonHandler(const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _copyright(), _generator(), _version(), _minVersion() {} void AssetJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Asset* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* AssetJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyAsset(Asset::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* AssetJsonHandler::readObjectKeyAsset( const std::string& objectType, const std::string_view& str, Asset& o) { using namespace std::string_literals; if ("copyright"s == str) return property("copyright", this->_copyright, o.copyright); if ("generator"s == str) return property("generator", this->_generator, o.generator); if ("version"s == str) return property("version", this->_version, o.version); if ("minVersion"s == str) return property("minVersion", this->_minVersion, o.minVersion); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "AnimationJsonHandler.h" #include "CesiumGltf/Animation.h" #include <cassert> #include <string> using namespace CesiumGltf; AnimationJsonHandler::AnimationJsonHandler( const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _channels(context), _samplers(context) {} void AnimationJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Animation* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* AnimationJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyAnimation( Animation::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* AnimationJsonHandler::readObjectKeyAnimation( const std::string& objectType, const std::string_view& str, Animation& o) { using namespace std::string_literals; if ("channels"s == str) return property("channels", this->_channels, o.channels); if ("samplers"s == str) return property("samplers", this->_samplers, o.samplers); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "AnimationSamplerJsonHandler.h" #include "CesiumGltf/AnimationSampler.h" #include <cassert> #include <string> using namespace CesiumGltf; AnimationSamplerJsonHandler::AnimationSamplerJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _input(), _interpolation(), _output() {} void AnimationSamplerJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, AnimationSampler* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* AnimationSamplerJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyAnimationSampler( AnimationSampler::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* AnimationSamplerJsonHandler::readObjectKeyAnimationSampler( const std::string& objectType, const std::string_view& str, AnimationSampler& o) { using namespace std::string_literals; if ("input"s == str) return property("input", this->_input, o.input); if ("interpolation"s == str) return property("interpolation", this->_interpolation, o.interpolation); if ("output"s == str) return property("output", this->_output, o.output); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } void AnimationSamplerJsonHandler::InterpolationJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParent, AnimationSampler::Interpolation* pEnum) { JsonHandler::reset(pParent); this->_pEnum = pEnum; } CesiumJsonReader::IJsonHandler* AnimationSamplerJsonHandler::InterpolationJsonHandler::readString( const std::string_view& str) { using namespace std::string_literals; assert(this->_pEnum); if ("LINEAR"s == str) *this->_pEnum = AnimationSampler::Interpolation::LINEAR; else if ("STEP"s == str) *this->_pEnum = AnimationSampler::Interpolation::STEP; else if ("CUBICSPLINE"s == str) *this->_pEnum = AnimationSampler::Interpolation::CUBICSPLINE; else return nullptr; return this->parent(); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "AnimationChannelJsonHandler.h" #include "CesiumGltf/AnimationChannel.h" #include <cassert> #include <string> using namespace CesiumGltf; AnimationChannelJsonHandler::AnimationChannelJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _sampler(), _target(context) {} void AnimationChannelJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, AnimationChannel* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* AnimationChannelJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyAnimationChannel( AnimationChannel::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* AnimationChannelJsonHandler::readObjectKeyAnimationChannel( const std::string& objectType, const std::string_view& str, AnimationChannel& o) { using namespace std::string_literals; if ("sampler"s == str) return property("sampler", this->_sampler, o.sampler); if ("target"s == str) return property("target", this->_target, o.target); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "AnimationChannelTargetJsonHandler.h" #include "CesiumGltf/AnimationChannelTarget.h" #include <cassert> #include <string> using namespace CesiumGltf; AnimationChannelTargetJsonHandler::AnimationChannelTargetJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _node(), _path() {} void AnimationChannelTargetJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, AnimationChannelTarget* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* AnimationChannelTargetJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyAnimationChannelTarget( AnimationChannelTarget::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* AnimationChannelTargetJsonHandler::readObjectKeyAnimationChannelTarget( const std::string& objectType, const std::string_view& str, AnimationChannelTarget& o) { using namespace std::string_literals; if ("node"s == str) return property("node", this->_node, o.node); if ("path"s == str) return property("path", this->_path, o.path); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } void AnimationChannelTargetJsonHandler::PathJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParent, AnimationChannelTarget::Path* pEnum) { JsonHandler::reset(pParent); this->_pEnum = pEnum; } CesiumJsonReader::IJsonHandler* AnimationChannelTargetJsonHandler::PathJsonHandler::readString( const std::string_view& str) { using namespace std::string_literals; assert(this->_pEnum); if ("translation"s == str) *this->_pEnum = AnimationChannelTarget::Path::translation; else if ("rotation"s == str) *this->_pEnum = AnimationChannelTarget::Path::rotation; else if ("scale"s == str) *this->_pEnum = AnimationChannelTarget::Path::scale; else if ("weights"s == str) *this->_pEnum = AnimationChannelTarget::Path::weights; else return nullptr; return this->parent(); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "AccessorJsonHandler.h" #include "CesiumGltf/Accessor.h" #include <cassert> #include <string> using namespace CesiumGltf; AccessorJsonHandler::AccessorJsonHandler(const ReaderContext& context) noexcept : NamedObjectJsonHandler(context), _bufferView(), _byteOffset(), _componentType(), _normalized(), _count(), _type(), _max(), _min(), _sparse(context) {} void AccessorJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, Accessor* pObject) { NamedObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* AccessorJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyAccessor(Accessor::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* AccessorJsonHandler::readObjectKeyAccessor( const std::string& objectType, const std::string_view& str, Accessor& o) { using namespace std::string_literals; if ("bufferView"s == str) return property("bufferView", this->_bufferView, o.bufferView); if ("byteOffset"s == str) return property("byteOffset", this->_byteOffset, o.byteOffset); if ("componentType"s == str) return property("componentType", this->_componentType, o.componentType); if ("normalized"s == str) return property("normalized", this->_normalized, o.normalized); if ("count"s == str) return property("count", this->_count, o.count); if ("type"s == str) return property("type", this->_type, o.type); if ("max"s == str) return property("max", this->_max, o.max); if ("min"s == str) return property("min", this->_min, o.min); if ("sparse"s == str) return property("sparse", this->_sparse, o.sparse); return this->readObjectKeyNamedObject(objectType, str, *this->_pObject); } void AccessorJsonHandler::TypeJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParent, Accessor::Type* pEnum) { JsonHandler::reset(pParent); this->_pEnum = pEnum; } CesiumJsonReader::IJsonHandler* AccessorJsonHandler::TypeJsonHandler::readString(const std::string_view& str) { using namespace std::string_literals; assert(this->_pEnum); if ("SCALAR"s == str) *this->_pEnum = Accessor::Type::SCALAR; else if ("VEC2"s == str) *this->_pEnum = Accessor::Type::VEC2; else if ("VEC3"s == str) *this->_pEnum = Accessor::Type::VEC3; else if ("VEC4"s == str) *this->_pEnum = Accessor::Type::VEC4; else if ("MAT2"s == str) *this->_pEnum = Accessor::Type::MAT2; else if ("MAT3"s == str) *this->_pEnum = Accessor::Type::MAT3; else if ("MAT4"s == str) *this->_pEnum = Accessor::Type::MAT4; else return nullptr; return this->parent(); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "AccessorSparseJsonHandler.h" #include "CesiumGltf/AccessorSparse.h" #include <cassert> #include <string> using namespace CesiumGltf; AccessorSparseJsonHandler::AccessorSparseJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _count(), _indices(context), _values(context) {} void AccessorSparseJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, AccessorSparse* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* AccessorSparseJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyAccessorSparse( AccessorSparse::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* AccessorSparseJsonHandler::readObjectKeyAccessorSparse( const std::string& objectType, const std::string_view& str, AccessorSparse& o) { using namespace std::string_literals; if ("count"s == str) return property("count", this->_count, o.count); if ("indices"s == str) return property("indices", this->_indices, o.indices); if ("values"s == str) return property("values", this->_values, o.values); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "AccessorSparseValuesJsonHandler.h" #include "CesiumGltf/AccessorSparseValues.h" #include <cassert> #include <string> using namespace CesiumGltf; AccessorSparseValuesJsonHandler::AccessorSparseValuesJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _bufferView(), _byteOffset() {} void AccessorSparseValuesJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, AccessorSparseValues* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* AccessorSparseValuesJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyAccessorSparseValues( AccessorSparseValues::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* AccessorSparseValuesJsonHandler::readObjectKeyAccessorSparseValues( const std::string& objectType, const std::string_view& str, AccessorSparseValues& o) { using namespace std::string_literals; if ("bufferView"s == str) return property("bufferView", this->_bufferView, o.bufferView); if ("byteOffset"s == str) return property("byteOffset", this->_byteOffset, o.byteOffset); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); } // This file was generated by generate-gltf-classes. // DO NOT EDIT THIS FILE! #include "AccessorSparseIndicesJsonHandler.h" #include "CesiumGltf/AccessorSparseIndices.h" #include <cassert> #include <string> using namespace CesiumGltf; AccessorSparseIndicesJsonHandler::AccessorSparseIndicesJsonHandler( const ReaderContext& context) noexcept : ExtensibleObjectJsonHandler(context), _bufferView(), _byteOffset(), _componentType() {} void AccessorSparseIndicesJsonHandler::reset( CesiumJsonReader::IJsonHandler* pParentHandler, AccessorSparseIndices* pObject) { ExtensibleObjectJsonHandler::reset(pParentHandler, pObject); this->_pObject = pObject; } CesiumJsonReader::IJsonHandler* AccessorSparseIndicesJsonHandler::readObjectKey(const std::string_view& str) { assert(this->_pObject); return this->readObjectKeyAccessorSparseIndices( AccessorSparseIndices::TypeName, str, *this->_pObject); } CesiumJsonReader::IJsonHandler* AccessorSparseIndicesJsonHandler::readObjectKeyAccessorSparseIndices( const std::string& objectType, const std::string_view& str, AccessorSparseIndices& o) { using namespace std::string_literals; if ("bufferView"s == str) return property("bufferView", this->_bufferView, o.bufferView); if ("byteOffset"s == str) return property("byteOffset", this->_byteOffset, o.byteOffset); if ("componentType"s == str) return property("componentType", this->_componentType, o.componentType); return this->readObjectKeyExtensibleObject(objectType, str, *this->_pObject); }
30.49907
80
0.731863
[ "mesh", "model" ]
4624dc27a401c915208c74ee7ac0c0846a989c19
7,968
cpp
C++
sound_system.cpp
ud1/ud1_arkanoid
af6d7d44ca7db3d90316fafc6e7b7b5905ae1020
[ "BSD-3-Clause" ]
null
null
null
sound_system.cpp
ud1/ud1_arkanoid
af6d7d44ca7db3d90316fafc6e7b7b5905ae1020
[ "BSD-3-Clause" ]
null
null
null
sound_system.cpp
ud1/ud1_arkanoid
af6d7d44ca7db3d90316fafc6e7b7b5905ae1020
[ "BSD-3-Clause" ]
null
null
null
// http://www.gamedev.ru/code/articles/OpenAL #include "sound_system.h" #include <fstream> #include <istream> #include <vector> #include <cassert> #include <ogg/ogg.h> #include <vorbis/codec.h> #include <vorbis/vorbisfile.h> #include <AL/al.h> #include <AL/alc.h> const size_t DYN_BUF_NUMBER = 3; // number buffers in queue const size_t DYN_BUF_SIZE = 44000*5; // Buffer size size_t ReadOgg(void *ptr, size_t size, size_t nmemb, void *datasource) { std::istream *File = reinterpret_cast<std::istream*>(datasource); File->read((char *)ptr, size * nmemb); return (size_t) File->gcount(); } int SeekOgg(void *datasource, ogg_int64_t offset, int whence) { std::istream *file = reinterpret_cast<std::istream*>(datasource); std::ios_base::seekdir dir; file->clear(); switch (whence) { case SEEK_SET: dir = std::ios::beg; break; case SEEK_CUR: dir = std::ios::cur; break; case SEEK_END: dir = std::ios::end; break; default: return -1; } file->seekg((std::streamoff)offset, dir); return (file->fail() ? -1 : 0); } long TellOgg(void *datasource) { std::istream *file = reinterpret_cast<std::istream*>(datasource); return (long) file->tellg(); } int CloseOgg(void *datasource) { return 0; } struct FileCallbacks : public ov_callbacks { FileCallbacks() { close_func = CloseOgg; read_func = ReadOgg; seek_func = SeekOgg; tell_func = TellOgg; } }; struct Sound { Sound() { vrb_file = NULL; source_setted = false; looped = false; opened = false; } ~Sound() { Reset(); } void Reset() { if (file.is_open()) { file.close(); } file.clear(); if (vrb_file) { ov_clear(vrb_file); delete vrb_file; } if (buffers.size()) { Stop(); alDeleteBuffers(buffers.size(), &buffers[0]); buffers.clear(); } vrb_file = NULL; source_setted = false; looped = false; opened = false; } bool Open(const std::string &filename, bool streamed_) { Reset(); streamed = streamed_; file.open(filename.c_str(), std::ios_base::in | std::ios_base::binary); if (!file) return false; vrb_file = new OggVorbis_File; if (ov_open_callbacks(&file, vrb_file, NULL, -1, FileCallbacks()) < 0) { return false; } vrb_info = ov_info(vrb_file, -1); format = (vrb_info->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16; if (streamed) { block_size = DYN_BUF_SIZE; dyn_bufs = DYN_BUF_NUMBER; } else { block_size = (size_t) (ov_pcm_total(vrb_file, -1)*2*vrb_info->channels); dyn_bufs = 1; } for (size_t i = 0; i < dyn_bufs; ++i) { ALuint bufferId; alGenBuffers(1, &bufferId); if (ReadOggBlock(bufferId, block_size)) { buffers.push_back(bufferId); } else { return false; } } opened = true; return true; } bool ReadOggBlock(ALuint buf_id, size_t size) { if (size < 1) return false; std::vector<char> PCM; PCM.resize(size); size_t total = 0; long ret; while (total < size) { ret = ov_read(vrb_file, &PCM[total], size - total, 0, 2, 1, NULL); if (!ret) break; total += ret; } if (total) { alBufferData(buf_id, format, &PCM[0], total, vrb_info->rate); } return total > 0; } void PlayOnSource(ALuint source_id_, bool looped_) { if (!opened) return; looped = looped_; if (streamed) { source_id = source_id_; source_setted = true; alSourceQueueBuffers(source_id_, buffers.size(), &buffers[0]); } else { alSourceStop(source_id_); alSourcei(source_id_, AL_BUFFER, buffers[0]); } alSourcePlay(source_id_); } void Update() { if (!source_setted) return; ALint processed = 0; alGetSourcei(source_id, AL_BUFFERS_PROCESSED, &processed); while (processed--) { ALuint buf_id; alSourceUnqueueBuffers(source_id, 1, &buf_id); if (ReadOggBlock(buf_id, DYN_BUF_SIZE)) { alSourceQueueBuffers(source_id, 1, &buf_id); } else { ov_pcm_seek(vrb_file, 0); if (ReadOggBlock(buf_id, DYN_BUF_SIZE)) { alSourceQueueBuffers(source_id, 1, &buf_id); } } } } void Stop() { if (!source_setted) return; alSourceStop(source_id); } std::ifstream file; OggVorbis_File *vrb_file; vorbis_info *vrb_info; size_t dyn_bufs, block_size; ALenum format; std::vector<ALuint> buffers; bool streamed, source_setted, looped, opened; ALuint source_id; }; const size_t SOURCE_NUMBER = 5; struct SoundSystem::SoundSystemImpl { SoundSystemImpl() { initialized = false; device = NULL; context = NULL; source_to_play_ind = 0; } ~SoundSystemImpl() { Clear(); if (sources.size()) alDeleteSources(sources.size(), &sources[0]); alDeleteSources(1, &backgound_source); alDeleteSources(1, &snd_source); sources.clear(); alcMakeContextCurrent(NULL); alcDestroyContext(context); alcCloseDevice(device); } bool Initialize() { device = alcOpenDevice(NULL); // open default device if (!device) return false; context = alcCreateContext(device,NULL); // create context if (!context) { alcCloseDevice(device); return false; } alcMakeContextCurrent(context); // set active context alDistanceModel(AL_NONE); sources.resize(SOURCE_NUMBER); alGenSources(SOURCE_NUMBER, &sources[0]); alGenSources(1, &backgound_source); alGenSources(1, &snd_source); initialized = true; return true; } void Clear() { for (size_t i = 0; i < sounds.size(); ++i) { delete sounds[i]; } sounds.clear(); } void SetSndNumber(size_t count) { if (!initialized) return; Clear(); sounds.reserve(count); for (size_t i = 0; i < count; ++i) { sounds.push_back(new Sound); } } bool Load(size_t n, const std::string &filename) { if (!initialized) return false; assert(n < sounds.size()); return sounds[n]->Open(filename, false); } void Play(size_t n, float volume) { if (!initialized) return; if (volume < 0.05f) return; ALuint source = sources[source_to_play_ind]; source_to_play_ind = (source_to_play_ind + 1) % sources.size(); alSourcef(source, AL_GAIN, volume); sounds[n]->PlayOnSource(source, false); } bool Play(const std::string &filename, float volume) { if (!initialized) return false; if (snd.Open(filename, false)) { alSourcef(snd_source, AL_GAIN, volume); snd.PlayOnSource(snd_source, false); return true; } return false; } bool PlayBackground(const std::string &filename, float volume) { if (!initialized) return false; if (!backgound.Open(filename, true)) return false; alSourcef(backgound_source, AL_GAIN, volume); backgound.PlayOnSource(backgound_source, true); return true; } void Update() { if (!initialized) return; backgound.Update(); } protected: std::vector<Sound *> sounds; Sound backgound, snd; std::vector<ALuint> sources; ALuint backgound_source, snd_source; size_t source_to_play_ind; bool initialized; ALCdevice *device; ALCcontext *context; }; SoundSystem::SoundSystem() { pimpl = new SoundSystemImpl; } SoundSystem::~SoundSystem() { delete pimpl; } bool SoundSystem::Initialize() { return pimpl->Initialize(); } void SoundSystem::SetSndNumber(size_t count) { pimpl->SetSndNumber(count); } bool SoundSystem::Load(size_t n, const std::string &filename) { return pimpl->Load(n, filename); } void SoundSystem::Play(size_t n, float volume) { pimpl->Play(n, volume); } bool SoundSystem::Play(const std::string &filename, float volume) { return pimpl->Play(filename, volume); } bool SoundSystem::PlayBackground(const std::string &filename, float volume) { return pimpl->PlayBackground(filename, volume); } void SoundSystem::Update() { pimpl->Update(); }
21.135279
78
0.641441
[ "vector" ]
46315e14a0fc60fc5b358bd22508d642280e5854
2,565
hpp
C++
include/tokenaizer.hpp
Newlifer/address-parser
b04364132822168815752b4eecf71c469c7279b8
[ "MIT" ]
2
2016-09-15T14:03:02.000Z
2016-09-16T05:36:47.000Z
include/tokenaizer.hpp
Newlifer/address-parser
b04364132822168815752b4eecf71c469c7279b8
[ "MIT" ]
1
2016-09-16T05:38:14.000Z
2016-09-16T05:38:14.000Z
include/tokenaizer.hpp
Newlifer/address-parser
b04364132822168815752b4eecf71c469c7279b8
[ "MIT" ]
null
null
null
#pragma once #include "string_utils.hpp" namespace fappy { enum class TOKEN_TYPE : unsigned int { none = 0 }; template <typename StringType> class token { using string_type_t = StringType; public: token() = delete; token(const string_type_t& str, TOKEN_TYPE tt) : str_(str) , tt_(tt) { } token(string_type_t&& str, TOKEN_TYPE tt) : str_(std::move(str)) , tt_(tt) { } token(const token&) = default; token(token&&) = default; private: string_type_t str_; TOKEN_TYPE tt_; }; template <typename StringType> class tokenaizer { using string_type_t = StringType; using string_vec_t = std::vector<token<string_type_t>>; public: tokenaizer() = delete; explicit tokenaizer(const string_type_t&) { } explicit tokenaizer(string_type_t&&) { } explicit tokenaizer(const tokenaizer&) { } tokenaizer(tokenaizer&&) { } string_vec_t make_tokens() const { std::vector<token<string_type_t>> ret; std::size_t last_pos = 0u; for (std::size_t i = 0; i < str_.size(); ++i) { if(is_space(str_[i])) continue; else ret.emplace_back("ololo", TOKEN_TYPE::none); } return ret; } void tokenize() { this->tokens_ = this->make_tokens(); } const string_vec_t& tokens() const { return this->tokens_; } string_vec_t& tokens() { return this->tokens_; } private: string_type_t str_; string_vec_t tokens_; }; }
26.173469
84
0.361404
[ "vector" ]
463edd82407a8b6b6f20387597cb6bc415d9d513
10,660
cpp
C++
sources/libcore/scheduler.cpp
Gaeldrin/cage
6399a5cdcb3932e8d422901ce7d72099dc09273c
[ "MIT" ]
null
null
null
sources/libcore/scheduler.cpp
Gaeldrin/cage
6399a5cdcb3932e8d422901ce7d72099dc09273c
[ "MIT" ]
null
null
null
sources/libcore/scheduler.cpp
Gaeldrin/cage
6399a5cdcb3932e8d422901ce7d72099dc09273c
[ "MIT" ]
null
null
null
#include <cage-core/scheduler.h> #include <cage-core/timer.h> #include <cage-core/math.h> // max #include <cage-core/concurrent.h> // threadSleep #include <cage-core/variableSmoothingBuffer.h> #include <vector> #include <algorithm> #include <atomic> #include <optick.h> namespace cage { namespace { struct SchedStats : private Immovable { VariableSmoothingBuffer<uint64, Schedule::StatisticsWindowSize> delays; VariableSmoothingBuffer<uint64, Schedule::StatisticsWindowSize> durations; uint64 totalDelay = 0; uint64 totalDuration = 0; uint64 maxDelay = 0; uint64 maxDuration = 0; uint32 runs = 0; void add(uint64 delay, uint64 duration) { delays.add(delay); durations.add(duration); totalDelay += delay; totalDuration += duration; maxDelay = max(maxDelay, delay); maxDuration = max(maxDuration, duration); runs++; } }; class SchedulerImpl; class ScheduleImpl : public Schedule { public: const ScheduleCreateConfig conf; SchedulerImpl *const schr; Holder<SchedStats> stats; uint64 sched = m; sint32 pri = 0; std::atomic<bool> active = false; explicit ScheduleImpl(SchedulerImpl *schr, const ScheduleCreateConfig &config) : conf(config), schr(schr) { if (conf.type != ScheduleTypeEnum::Once) stats = systemArena().createHolder<SchedStats>(); } }; class SchedulerImpl : public Scheduler { public: const SchedulerCreateConfig conf; std::vector<Holder<ScheduleImpl>> scheds; std::vector<ScheduleImpl*> tmp; Holder<Timer> realTimer; uint64 realDrift = 0; // offset for the real timer, this happens when switching lockstep mode uint64 t = 0; // current time for scheduling events uint64 lastTime = 0; // time at which the last schedule was run sint32 lastPriority = 0; std::atomic<bool> stopping = false; bool lockstepApi = false; bool lockstepEffective = false; explicit SchedulerImpl(const SchedulerCreateConfig &config) : conf(config) { realTimer = newTimer(); } void reset() { realTimer->reset(); realDrift = 0; t = 0; lastTime = 0; lastPriority = 0; for (const auto &it : scheds) { it->sched = m; it->active = it->conf.type == ScheduleTypeEnum::Empty; } } void checkNewSchedules() { for (const auto &it : scheds) { if (it->sched == m) { it->sched = t + it->conf.delay; it->pri = it->conf.priority; } } } void activateAllEmpty() { for (const auto &it : scheds) { if (it->conf.type == ScheduleTypeEnum::Empty) it->active = true; } } void filterAvailableSchedules() { for (const auto &it : scheds) { if (it->conf.type == ScheduleTypeEnum::Empty) continue; if (it->sched > t) continue; if (it->conf.type == ScheduleTypeEnum::External && !it->active) continue; tmp.push_back(+it); } if (!tmp.empty()) { activateAllEmpty(); return; } for (const auto &it : scheds) { if (it->conf.type != ScheduleTypeEnum::Empty) continue; if (it->sched > t) continue; if (!it->active) continue; tmp.push_back(+it); } } uint64 adjustedRealTime() { return realTimer->microsSinceStart() + realDrift; } uint64 currentTime() { return lockstepEffective ? t : adjustedRealTime(); } uint64 minimalScheduleTime() { uint64 res = m; for (const auto &it : scheds) { if (it->conf.type == ScheduleTypeEnum::Empty) continue; if (it->conf.type == ScheduleTypeEnum::External && !it->active) continue; res = min(res, it->sched); } return res; } void goSleep() { OPTICK_EVENT("scheduler sleep"); activateAllEmpty(); uint64 s = minimalScheduleTime() - t; s = min(s, conf.maxSleepDuration); s = max(s, (uint64)1000); // some systems do not have higher precision sleeps; this will prevent busy looping //CAGE_LOG(SeverityEnum::Info, "scheduler", stringizer() + "scheduler is going to sleep for " + s + " us"); threadSleep(s); } void sortSchedulesByPriority() { for (const auto &it : tmp) it->pri++; std::stable_sort(tmp.begin(), tmp.end(), [](const ScheduleImpl *a, const ScheduleImpl *b) { return a->pri > b->pri; // higher priority goes first }); } void runSchedule() { ScheduleImpl *s = tmp[0]; //CAGE_LOG(SeverityEnum::Info, "scheduler", stringizer() + "running schedule: " + s->conf.name); lastTime = s->sched; lastPriority = s->pri; s->pri = s->conf.priority; s->active = false; const uint64 start = currentTime(); s->run(); // likely to throw const uint64 end = currentTime(); if (s->stats) s->stats->add(start - s->sched, end - start); switch (s->conf.type) { case ScheduleTypeEnum::Once: return s->destroy(); case ScheduleTypeEnum::SteadyPeriodic: { const uint64 skip = (end - s->sched) / s->conf.period; if (skip >= s->conf.maxSteadyPeriods) { CAGE_LOG(SeverityEnum::Warning, "scheduler", stringizer() + "schedule '" + s->conf.name + "' cannot keep up and will skip " + skip + " iterations"); s->sched += skip * s->conf.period; } else s->sched += s->conf.period; } break; case ScheduleTypeEnum::FreePeriodic: s->sched = end + s->conf.period; break; } } void runIteration() { CAGE_ASSERT(!scheds.empty()); tmp.clear(); tmp.reserve(scheds.size()); if (lockstepEffective != lockstepApi) { if (!lockstepApi) { realDrift = t; realTimer->reset(); } lockstepEffective = lockstepApi; } t = lockstepEffective ? minimalScheduleTime() : adjustedRealTime(); //CAGE_LOG_DEBUG(SeverityEnum::Info, "scheduler", stringizer() + "current time: " + t); checkNewSchedules(); filterAvailableSchedules(); if (tmp.empty()) return goSleep(); sortSchedulesByPriority(); runSchedule(); } void run() { reset(); checkNewSchedules(); stopping = false; while (!stopping && !scheds.empty()) runIteration(); } }; } void Schedule::trigger() { ScheduleImpl *impl = (ScheduleImpl *)this; CAGE_ASSERT(impl->conf.type == ScheduleTypeEnum::External); CAGE_ASSERT(impl->sched != m); if (!impl->active) { // sched is updated to ensure meaningful delay statistics impl->sched = max(impl->sched, impl->schr->currentTime()); // the schedule cannot be run before its initial delay is expired // potential race condition here; i think it does not hurt impl->active = true; // the atomic is updated last to commit memory barrier } } void Schedule::run() { ScheduleImpl *impl = (ScheduleImpl *)this; OPTICK_EVENT_DYNAMIC(impl->conf.name.c_str()); if (!impl->conf.action) return; try { impl->conf.action(); } catch (...) { CAGE_LOG_THROW(stringizer() + "exception in schedule '" + impl->conf.name + "'"); throw; } } void Schedule::destroy() { ScheduleImpl *impl = (ScheduleImpl *)this; auto &vec = impl->schr->scheds; auto it = std::find_if(vec.begin(), vec.end(), [&](const auto &a) { return a.get() == impl; }); CAGE_ASSERT(it != vec.end()); vec.erase(it); } void Schedule::period(uint64 p) { ScheduleImpl *impl = (ScheduleImpl *)this; CAGE_ASSERT(impl->conf.type == ScheduleTypeEnum::SteadyPeriodic || impl->conf.type == ScheduleTypeEnum::FreePeriodic); const_cast<ScheduleCreateConfig &>(impl->conf).period = p; } uint64 Schedule::period() const { const ScheduleImpl *impl = (const ScheduleImpl *)this; CAGE_ASSERT(impl->conf.type == ScheduleTypeEnum::SteadyPeriodic || impl->conf.type == ScheduleTypeEnum::FreePeriodic); return impl->conf.period; } void Schedule::priority(sint32 p) { ScheduleImpl *impl = (ScheduleImpl *)this; impl->pri = p; } sint32 Schedule::priority() const { const ScheduleImpl *impl = (const ScheduleImpl *)this; return impl->pri; } uint64 Schedule::time() const { const ScheduleImpl *impl = (const ScheduleImpl *)this; return impl->sched; } const VariableSmoothingBuffer<uint64, Schedule::StatisticsWindowSize> &Schedule::statsDelay() const { const ScheduleImpl *impl = (const ScheduleImpl *)this; return impl->stats->delays; } const VariableSmoothingBuffer<uint64, Schedule::StatisticsWindowSize> &Schedule::statsDuration() const { const ScheduleImpl *impl = (const ScheduleImpl *)this; return impl->stats->durations; } uint64 Schedule::statsDelayMax() const { const ScheduleImpl *impl = (const ScheduleImpl *)this; return impl->stats->maxDelay; } uint64 Schedule::statsDelaySum() const { const ScheduleImpl *impl = (const ScheduleImpl *)this; return impl->stats->totalDelay; } uint64 Schedule::statsDurationMax() const { const ScheduleImpl *impl = (const ScheduleImpl *)this; return impl->stats->maxDuration; } uint64 Schedule::statsDurationSum() const { const ScheduleImpl *impl = (const ScheduleImpl *)this; return impl->stats->totalDuration; } uint32 Schedule::statsRunCount() const { const ScheduleImpl *impl = (const ScheduleImpl *)this; return impl->stats->runs; } void Scheduler::run() { SchedulerImpl *impl = (SchedulerImpl *)this; impl->run(); } void Scheduler::stop() { SchedulerImpl *impl = (SchedulerImpl *)this; impl->stopping = true; } Schedule *Scheduler::newSchedule(const ScheduleCreateConfig &config) { SchedulerImpl *impl = (SchedulerImpl *)this; auto sch = systemArena().createHolder<ScheduleImpl>(impl, config); auto res = sch.get(); impl->scheds.push_back(std::move(sch)); return res; } void Scheduler::clear() { SchedulerImpl *impl = (SchedulerImpl *)this; impl->scheds.clear(); } void Scheduler::setLockstep(bool lockstep) { SchedulerImpl *impl = (SchedulerImpl *)this; if (impl->lockstepApi == lockstep) return; CAGE_LOG(SeverityEnum::Warning, "scheduler", stringizer() + "scheduler lockstep mode: " + lockstep); impl->lockstepApi = lockstep; } bool Scheduler::isLockstep() const { const SchedulerImpl *impl = (const SchedulerImpl *)this; return impl->lockstepApi; } uint64 Scheduler::latestTime() const { const SchedulerImpl *impl = (const SchedulerImpl *)this; return impl->lastTime; } sint32 Scheduler::latestPriority() const { const SchedulerImpl *impl = (const SchedulerImpl *)this; return impl->lastPriority; } Holder<Scheduler> newScheduler(const SchedulerCreateConfig &config) { return systemArena().createImpl<Scheduler, SchedulerImpl>(config); } }
24.906542
154
0.649812
[ "vector" ]
463ede54ba6632c3a3ab3f56a169d05883c969c4
2,399
hpp
C++
extension/json/include/json_functions.hpp
nbenn/duckdb
a7493fec044a3d652389039fc942a3d331cf2c16
[ "MIT" ]
1
2021-12-13T06:00:18.000Z
2021-12-13T06:00:18.000Z
extension/json/include/json_functions.hpp
nbenn/duckdb
a7493fec044a3d652389039fc942a3d331cf2c16
[ "MIT" ]
32
2021-09-24T23:50:09.000Z
2022-03-29T09:37:26.000Z
extension/json/include/json_functions.hpp
nbenn/duckdb
a7493fec044a3d652389039fc942a3d331cf2c16
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // DuckDB // // json_functions.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/parser/parsed_data/create_scalar_function_info.hpp" namespace duckdb { class JSONFunctions { public: static vector<CreateScalarFunctionInfo> GetFunctions() { vector<CreateScalarFunctionInfo> functions; // Extract functions AddAliases({"json_extract", "json_extract_path"}, GetExtractFunction(), functions); AddAliases({"json_extract_string", "json_extract_path_text", "->>"}, GetExtractStringFunction(), functions); // Create functions functions.push_back(GetArrayFunction()); functions.push_back(GetObjectFunction()); AddAliases({"to_json", "json_quote"}, GetToJSONFunction(), functions); functions.push_back(GetArrayToJSONFunction()); functions.push_back(GetRowToJSONFunction()); // Structure/Transform functions.push_back(GetStructureFunction()); AddAliases({"json_transform", "from_json"}, GetTransformFunction(), functions); AddAliases({"json_transform_strict", "from_json_strict"}, GetTransformStrictFunction(), functions); // Other functions.push_back(GetArrayLengthFunction()); functions.push_back(GetTypeFunction()); functions.push_back(GetValidFunction()); return functions; } private: static CreateScalarFunctionInfo GetExtractFunction(); static CreateScalarFunctionInfo GetExtractStringFunction(); static CreateScalarFunctionInfo GetArrayFunction(); static CreateScalarFunctionInfo GetObjectFunction(); static CreateScalarFunctionInfo GetToJSONFunction(); static CreateScalarFunctionInfo GetArrayToJSONFunction(); static CreateScalarFunctionInfo GetRowToJSONFunction(); static CreateScalarFunctionInfo GetStructureFunction(); static CreateScalarFunctionInfo GetTransformFunction(); static CreateScalarFunctionInfo GetTransformStrictFunction(); static CreateScalarFunctionInfo GetArrayLengthFunction(); static CreateScalarFunctionInfo GetTypeFunction(); static CreateScalarFunctionInfo GetValidFunction(); static void AddAliases(vector<string> names, CreateScalarFunctionInfo fun, vector<CreateScalarFunctionInfo> &functions) { for (auto &name : names) { fun.name = name; functions.push_back(fun); } } }; } // namespace duckdb
33.319444
110
0.726553
[ "vector", "transform" ]
464187cf662c04c80585593869491b1d25a42635
418
cpp
C++
test/kth_to_last_unittest.cpp
Rokugatsu/leetcode
f868c494a9d23ac6519c94374281781f209fb19c
[ "MIT" ]
null
null
null
test/kth_to_last_unittest.cpp
Rokugatsu/leetcode
f868c494a9d23ac6519c94374281781f209fb19c
[ "MIT" ]
null
null
null
test/kth_to_last_unittest.cpp
Rokugatsu/leetcode
f868c494a9d23ac6519c94374281781f209fb19c
[ "MIT" ]
null
null
null
/** * @file kth_to_last_unittest.cpp * @author lipingan (lipingan.dev@outlook.com) * @brief * @version 0.1 * @date 2022-01-11 * * @copyright Copyright (c) 2022 * */ #include "kth_to_last.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace leetcode { TEST(kth_to_last, case_0) { ListNode *head = spawnList(std::vector{1, 2, 3, 4, 5}); std::cout << kthToLast(head, 1); } } // namespace leetcode
19.904762
57
0.662679
[ "vector" ]
465f5ecd33ad0ced0fa66dbecb166c505025a44b
485
hh
C++
inc/obiekt.hh
KPO-2020-2021/zad5_3-AdamDomachowski
1d3e1af48e948989937a9cdb206198b7de32f428
[ "Unlicense" ]
null
null
null
inc/obiekt.hh
KPO-2020-2021/zad5_3-AdamDomachowski
1d3e1af48e948989937a9cdb206198b7de32f428
[ "Unlicense" ]
null
null
null
inc/obiekt.hh
KPO-2020-2021/zad5_3-AdamDomachowski
1d3e1af48e948989937a9cdb206198b7de32f428
[ "Unlicense" ]
null
null
null
#pragma once #include <string> #include <memory> class obiekt { public: /*! \brief zwraca promien obiektu*/ virtual bool kolizja_info(shared_ptr <obiekt> object)=0; /*! \brief zczytuje nazwe obiektu*/ virtual std::string zczytaj_nazwe_obiektu() const=0; /*! \brief zapisuje obiekt*/ virtual void zapisz()=0; /*! \brief zczytuje wspolrzedne srodka obiektu*/ virtual Vector3D zczytaj_srodek_obiektu() const=0; /*! \brief zwraca promien obiektu*/ virtual double promien()=0; };
17.321429
56
0.731959
[ "object" ]
4661ce3b51035b66b94e1b63bc885527298781e0
2,341
cpp
C++
Examples/CPP/WorkingWithProjects/WorkingWithProjectProperties/SetAttributesForNewTasks.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2022-03-16T14:31:36.000Z
2022-03-16T14:31:36.000Z
Examples/CPP/WorkingWithProjects/WorkingWithProjectProperties/SetAttributesForNewTasks.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
null
null
null
Examples/CPP/WorkingWithProjects/WorkingWithProjectProperties/SetAttributesForNewTasks.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2020-07-01T01:26:17.000Z
2020-07-01T01:26:17.000Z
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference when the project is build. Please check https:// Docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from https://www.nuget.org/packages/Aspose.Tasks/, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using https://forum.aspose.com/c/tasks */ #include "WorkingWithProjects/WorkingWithProjectProperties/SetAttributesForNewTasks.h" #include <system/type_info.h> #include <system/string.h> #include <system/shared_ptr.h> #include <system/reflection/method_base.h> #include <system/object.h> #include <system/console.h> #include <saving/Enums/SaveFileFormat.h> #include <Project.h> #include <Prj.h> #include <Key.h> #include <enums/TaskStartDateType.h> #include <enums/PrjKey.h> #include "RunExamples.h" using namespace Aspose::Tasks::Saving; namespace Aspose { namespace Tasks { namespace Examples { namespace CPP { namespace WorkingWithProjects { namespace WorkingWithProjectProperties { RTTI_INFO_IMPL_HASH(1552159925u, ::Aspose::Tasks::Examples::CPP::WorkingWithProjects::WorkingWithProjectProperties::SetAttributesForNewTasks, ThisTypeBaseTypesInfo); void SetAttributesForNewTasks::Run() { // ExStart:SetAttributesForNewTasks // The path to the documents directory. System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName()); // Create a project instance Set new task property and Save the project as XML project file System::SharedPtr<Project> project = System::MakeObject<Project>(); project->Set<TaskStartDateType>(Prj::NewTaskStartDate(), Aspose::Tasks::TaskStartDateType::CurrentDate); project->Save(dataDir + u"SetAttributesForNewTasks_out.xml", Aspose::Tasks::Saving::SaveFileFormat::XML); // Display Status. System::Console::WriteLine(u"New Task created with start date successfully."); // ExEnd:SetAttributesForNewTasks } } // namespace WorkingWithProjectProperties } // namespace WorkingWithProjects } // namespace CPP } // namespace Examples } // namespace Tasks } // namespace Aspose
37.15873
165
0.77531
[ "object" ]
46674b5d6bfc3ed925ec220090ce7a9c45242d44
6,544
hpp
C++
geometry.hpp
rsenn/qjs-opencv
8035073ad8360636b816700325d92f4934e47e63
[ "MIT" ]
null
null
null
geometry.hpp
rsenn/qjs-opencv
8035073ad8360636b816700325d92f4934e47e63
[ "MIT" ]
null
null
null
geometry.hpp
rsenn/qjs-opencv
8035073ad8360636b816700325d92f4934e47e63
[ "MIT" ]
null
null
null
#ifndef GEOMETRY_HPP #define GEOMETRY_HPP #include <opencv2/core/matx.hpp> #include <opencv2/core/types.hpp> #include "psimpl.hpp" #include <cmath> #include <stddef.h> #include <iomanip> #include <iterator> #include <sstream> #include <string> #include <vector> template<class T> struct point { typedef T value_type; typedef cv::Point_<T> type; typedef std::vector<type> vector_type; }; template<class T> struct point_list { typedef std::vector<typename point<T>::type> type; }; template<class T> struct contour { typedef T coord_type; typedef typename point<T>::type point_type; typedef std::vector<point_type> type; }; template<class T> struct contour_list { typedef T coord_type; typedef typename contour<T>::point_type point_type; typedef typename contour<T>::type contour_type; typedef std::vector<contour_type> type; }; template<class T> using point_type = typename point<T>::type; template<class T> using point_vector = typename point_list<T>::type; template<class T> using contour_type = typename contour<T>::type; template<class T> using contour_vector = typename contour_list<T>::type; typedef std::vector<cv::Vec4i> vec4i_vector; // Function that calculates the area given a // std::vector of vertices in the XY plane. template<class P> inline double polygon_area(std::vector<P> list) { if(list.size() < 3) return 0; double area = 0; // Total Area double diff = 0; // Difference Of Y{i + 1} - Y{i - 1} unsigned int last = list.size() - 1; // Size Of Vector - 1 /* Given vertices from 1 to n, we first loop through the vertices 2 to n - 1. We will take into account vertex 1 and vertex n sepereately */ for(size_t i = 1; i < last; i++) { diff = list[i + 1].y - list[i - 1].y; area += list[i].x * diff; } /* Now We Consider The Vertex 1 And The Vertex N */ diff = list[1].y - list[last].y; area += list[0].x * diff; // Vertex 1 diff = list[0].y - list[last - 1].y; area += list[last].x * diff; // Vertex N /* Calculate The Final Answer */ area = 0.5 * fabs(area); return area; // Return The Area } point_vector<float> get_mass_centers(std::vector<point_vector<int>> contours); template<class T, class Char = char> inline std::basic_string<Char> to_string(const cv::Point_<T>& point) { const int pad = 3; std::basic_ostringstream<Char> os; os << "{x:" << std::setfill(' ') << std::setw(pad) << point.x << ",y:" << std::setfill(' ') << std::setw(pad) << point.y << "}"; return os.str(); } template<class ValueT, template<typename> class Container = std::vector, class Char = char> inline std::basic_string<Char> to_string(const Container<cv::Point_<ValueT>>& points) { typedef typename Container<cv::Point_<ValueT>>::const_iterator iterator_type; typedef cv::Point_<ValueT> value_type; std::basic_string<Char> ret; iterator_type end = points.cend(); for(iterator_type it = points.cbegin(); it != end; ++it) { if(ret.length()) ret += ","; ret += to_string<ValueT, Char>(*it); } return "[" + ret + "]"; } template<class T> inline T* coord_pointer(cv::Point_<T>* point_ptr) { return reinterpret_cast<T*>(point_ptr); } template<class T> inline const T* coord_pointer(const cv::Point_<T>* point_ptr) { return reinterpret_cast<const T*>(point_ptr); } template<class T> inline std::vector<cv::Point_<T>> simplify_polyline(const std::vector<cv::Point_<T>>& points) { typedef T coord_type; typedef cv::Point_<T> point_type; typedef std::vector<point_type> vector_type; vector_type ret; ret.resize(points.size()); psimpl::PolylineSimplification<2, const coord_type*, coord_type*> psimpl; auto output = coord_pointer(ret.data()); // auto end = psimpl.nth_point(coord_pointer(points.data()), // coord_pointer(&points.data()[points.size()]), 20, output); auto end = // psimpl.radial_distance(coord_pointer(points.data()), // coord_pointer(&points.data()[points.size()]), 10, output); auto end = psimpl.Opheim(coord_pointer(points.data()), coord_pointer(&points.data()[points.size()]), 4, 30, output); size_t outn = std::distance(output, end) / 2; // logfile << "simplification 1:" << ((double)points.size() / outn) << // std::endl; ret.resize(outn); return ret; } // helper function: // finds a cosine of angle between vectors // from pt0->pt1 and from pt0->pt2 template<class T> inline double angle(cv::Point_<T> pt1, cv::Point_<T> pt2, cv::Point_<T> pt0) { T dx1 = pt1.x - pt0.x; T dy1 = pt1.y - pt0.y; T dx2 = pt2.x - pt0.x; T dy2 = pt2.y - pt0.y; return (dx1 * dx2 + dy1 * dy2) / sqrt((dx1 * dx1 + dy1 * dy1) * (dx2 * dx2 + dy2 * dy2) + 1e-10); } template<class T> inline cv::Point_<T> difference(const cv::Point_<T>& a, const cv::Point_<T>& b) { return cv::Point_<T>(b.x - a.x, b.y - a.y); } template<class T> inline double distance(const cv::Point_<T>& p) { return std::sqrt(p.x * p.x + p.y * p.y); } template<class T> inline double distance(const cv::Point_<T>& a, const cv::Point_<T>& b) { return distance(difference(a, b)); } template<class To, class From> inline void convert_points(const typename point_list<From>::type& from, typename point_list<To>::type& to) { std::transform(from.cbegin(), from.cend(), std::back_inserter(to), [](cv::Point_<From> p) -> cv::Point_<To> { return cv::Point_<To>(p.x, p.y); }); } template<class To, class From> inline typename point_list<To>::type transform_points(const typename point_list<From>::type& from) { typename point_list<To>::type ret; convert_points<To, From>(from, ret); return ret; } template<class InputIterator, class OutputIterator> inline OutputIterator transform_points(InputIterator s, InputIterator e, OutputIterator o) { typedef typename std::iterator_traits<InputIterator>::value_type input_type; typedef typename std::iterator_traits<OutputIterator>::value_type output_type; o = std::transform(s, e, o, [](const input_type& p) -> output_type { return output_type(p.x, p.y); }); return o; } template<class InputIterator, class OutputIterator> inline OutputIterator transform_contours(InputIterator s, InputIterator e, OutputIterator o) { typedef typename std::iterator_traits<InputIterator>::value_type input_type; typedef typename std::iterator_traits<OutputIterator>::value_type output_type; o = std::transform(s, e, o, [](const input_type& p) -> output_type { output_type ret; ret.resize(p.size()); transform_points(p.cbegin(), p.cend(), ret.begin()); return ret; }); return o; } #endif // defined GEOMETRY_HPP
31.613527
148
0.684444
[ "vector", "transform" ]
4668020bbd551ce400ea89888fc979a901da6f18
1,413
cpp
C++
Code/Enemy_Pixel.cpp
ofaura/AndroDunos
98a8d54443df0bb3f9bd2b3ceb2017b3dafda489
[ "MIT" ]
2
2018-05-17T21:41:48.000Z
2018-12-27T21:46:00.000Z
Code/Enemy_Pixel.cpp
ofaura/AndroDunos
98a8d54443df0bb3f9bd2b3ceb2017b3dafda489
[ "MIT" ]
2
2018-05-15T19:03:18.000Z
2018-06-25T11:28:04.000Z
Code/Enemy_Pixel.cpp
ofaura/AndroDunos
98a8d54443df0bb3f9bd2b3ceb2017b3dafda489
[ "MIT" ]
null
null
null
#include "Application.h" #include "Enemy_GreenBall.h" #include "ModuleCollision.h" #include "ModulePlayer.h" #include "ModuleParticles.h" #include "ModuleUserInterface.h" #include "ModuleEnemies.h" #include "ModuleRender.h" #include "ModulePlayer.h" #include "ModuleTextures.h" #include "Enemy_Pixel.h" #include "ModuleAudio.h" Enemy_Pixel::Enemy_Pixel(int x, int y) : Enemy(x, y) { fly_1.PushBack({ 0, 0, 1, 1 }); fly_1.loop = false; collider = App->collision->AddCollider({ 0, 0, 1, 1 }, COLLIDER_TYPE::COLLIDER_ENEMY, (Module*)App->enemies); original_x = (App->render->camera.x / SCREEN_SIZE) + SCREEN_WIDTH - 1; //abs(App->render->camera.x) / SCREEN_SIZE + SCREEN_WIDTH; original_y = (App->render->camera.y / SCREEN_SIZE) + (SCREEN_HEIGHT / 2); HP = 1; } void Enemy_Pixel::Move() { position.x = (App->render->camera.x / SCREEN_SIZE) + SCREEN_WIDTH - 1; //abs(App->render->camera.x) / SCREEN_SIZE + SCREEN_WIDTH; position.y = (App->render->camera.y / SCREEN_SIZE) + (SCREEN_HEIGHT / 2); } bool Enemy_Pixel::CleanUp() { LOG("Unloading Powerup"); App->textures->Unload(graphics); return true; } void Enemy_Pixel::OnCollision(Collider* collider) { if (collider->type == COLLIDER_PLAYER_SHOT) { App->enemies->AddEnemy(ENEMY_TYPES::PIXEL, position.x, position.y); } if (collider->type == COLLIDER_PLAYER2_SHOT) { App->enemies->AddEnemy(ENEMY_TYPES::PIXEL, position.x, position.y); } }
27.705882
130
0.707006
[ "render" ]
467050bf39f54efacd5c36b857c666be6ca70775
2,393
cxx
C++
smtk/bridge/discrete/operation/vtkSelectionSplitOperatorBase.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
smtk/bridge/discrete/operation/vtkSelectionSplitOperatorBase.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
smtk/bridge/discrete/operation/vtkSelectionSplitOperatorBase.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "vtkSelectionSplitOperatorBase.h" #include "vtkDiscreteModel.h" #include "vtkDiscreteModelFace.h" #include "vtkIdTypeArray.h" #include "vtkObjectFactory.h" #include "vtkSmartPointer.h" vtkStandardNewMacro(vtkSelectionSplitOperatorBase); vtkSelectionSplitOperatorBase::vtkSelectionSplitOperatorBase() { this->ModifiedPairIDs = vtkIdTypeArray::New(); this->ModifiedPairIDs->SetNumberOfComponents(2); this->ModifiedPairIDs->SetNumberOfTuples(0); this->CompletelySelectedIDs = vtkIdTypeArray::New(); this->CompletelySelectedIDs->SetNumberOfComponents(1); this->CompletelySelectedIDs->SetNumberOfTuples(0); this->CurrentExistingFaceId = -1; } vtkSelectionSplitOperatorBase::~vtkSelectionSplitOperatorBase() { if(this->ModifiedPairIDs) { ModifiedPairIDs->Delete(); ModifiedPairIDs = 0; } if(this->CompletelySelectedIDs) { CompletelySelectedIDs->Delete(); CompletelySelectedIDs = 0; } } void vtkSelectionSplitOperatorBase::AddModifiedPair( vtkIdType SourceID, vtkIdType TargetID) { vtkIdType Ids[2] = {SourceID, TargetID}; this->ModifiedPairIDs->InsertNextTupleValue(Ids); } bool vtkSelectionSplitOperatorBase::GetModifiedPair( vtkIdType index, vtkIdType & SourceID, vtkIdType & TargetID) { if(index < 0 || index >= this->ModifiedPairIDs->GetNumberOfTuples()) { return 0; } SourceID = this->ModifiedPairIDs->GetValue(index*2); TargetID = this->ModifiedPairIDs->GetValue(index*2+1); return 1; } bool vtkSelectionSplitOperatorBase::AbleToOperate(vtkDiscreteModel* Model) { if(!Model) { vtkErrorMacro("Passed in a null model."); return 0; } return 1; } void vtkSelectionSplitOperatorBase::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "ModifiedPairIDs: " << this->ModifiedPairIDs << endl; os << indent << "CompletelySelectedIDs: " << this->CompletelySelectedIDs << endl; }
28.488095
83
0.696197
[ "model" ]
4676708e5e8abc75b9bb5729248a780ed413247d
6,381
cpp
C++
src/bind/refl/c.cpp
alecnunn/mud
9e204e2dc65f4a8ab52da3d11e6a261ff279d353
[ "Zlib" ]
1
2019-03-28T20:45:32.000Z
2019-03-28T20:45:32.000Z
src/bind/refl/c.cpp
alecnunn/mud
9e204e2dc65f4a8ab52da3d11e6a261ff279d353
[ "Zlib" ]
null
null
null
src/bind/refl/c.cpp
alecnunn/mud
9e204e2dc65f4a8ab52da3d11e6a261ff279d353
[ "Zlib" ]
null
null
null
#include <infra/Api.h> #include <type/Api.h> #include <pool/Api.h> #include <refl/Api.h> #ifdef MUD_PLATFORM_EMSCRIPTEN #include <emscripten.h> #define DECL EMSCRIPTEN_KEEPALIVE #else #define DECL #endif extern "C" { // Call mud::Type* DECL mud_Call__type() { return &mud::type<mud::Call>(); } mud::Call* DECL mud_Call_Call_0() { return new mud::Call(); } mud::Call* DECL mud_Call_Call_2(const mud::Callable* callable, std::vector<mud::Var>* arguments) { return new mud::Call(*callable, *arguments); } mud::Var* DECL mud_Call__get_result(mud::Call* self) { return &self->m_result; } void DECL mud_Call__destroy(mud::Call* self) { delete self; } // Callable mud::Type* DECL mud_Callable__type() { return &mud::type<mud::Callable>(); } void DECL mud_Callable__destroy(mud::Callable* self) { delete self; } // Class mud::Type* DECL mud_Class__type() { return &mud::type<mud::Class>(); } void DECL mud_Class__destroy(mud::Class* self) { delete self; } // Convert mud::Type* DECL mud_Convert__type() { return &mud::type<mud::Convert>(); } void DECL mud_Convert__destroy(mud::Convert* self) { delete self; } // Creator mud::Type* DECL mud_Creator__type() { return &mud::type<mud::Creator>(); } mud::Type* DECL mud_Creator__get_type(mud::Creator* self) { return &self->m_type; } bool DECL mud_Creator__get_construct(mud::Creator* self) { return self->m_construct; } void DECL mud_Creator__set_construct(mud::Creator* self, bool value) { self->m_construct = value; } mud::Type* DECL mud_Creator__get_prototype(mud::Creator* self) { return self->m_prototype; } void DECL mud_Creator__set_prototype(mud::Creator* self, mud::Type* value) { self->m_prototype = value; } mud::Injector* DECL mud_Creator__get_injector(mud::Creator* self) { return &self->injector(); } void DECL mud_Creator__destroy(mud::Creator* self) { delete self; } // Enum mud::Type* DECL mud_Enum__type() { return &mud::type<mud::Enum>(); } void DECL mud_Enum__destroy(mud::Enum* self) { delete self; } // Member mud::Type* DECL mud_Member__type() { return &mud::type<mud::Member>(); } void DECL mud_Member__destroy(mud::Member* self) { delete self; } // Meta mud::Type* DECL mud_Meta__type() { return &mud::type<mud::Meta>(); } void DECL mud_Meta__destroy(mud::Meta* self) { delete self; } // Module mud::Type* DECL mud_Module__type() { return &mud::type<mud::Module>(); } const char* DECL mud_Module__get_name(mud::Module* self) { return self->m_name; } void DECL mud_Module__set_name(mud::Module* self, const char* value) { self->m_name = value; } const char* DECL mud_Module__get_path(mud::Module* self) { return self->m_path; } void DECL mud_Module__set_path(mud::Module* self, const char* value) { self->m_path = value; } void DECL mud_Module__destroy(mud::Module* self) { delete self; } // Namespace mud::Type* DECL mud_Namespace__type() { return &mud::type<mud::Namespace>(); } void DECL mud_Namespace__destroy(mud::Namespace* self) { delete self; } // Operator mud::Type* DECL mud_Operator__type() { return &mud::type<mud::Operator>(); } mud::Operator* DECL mud_Operator_Operator_0() { return new mud::Operator(); } mud::Function* DECL mud_Operator__get_function(mud::Operator* self) { return self->m_function; } void DECL mud_Operator__set_function(mud::Operator* self, mud::Function* value) { self->m_function = value; } mud::Type* DECL mud_Operator__get_type(mud::Operator* self) { return self->m_type; } void DECL mud_Operator__set_type(mud::Operator* self, mud::Type* value) { self->m_type = value; } const char* DECL mud_Operator__get_name(mud::Operator* self) { return self->m_name; } void DECL mud_Operator__set_name(mud::Operator* self, const char* value) { self->m_name = value; } const char* DECL mud_Operator__get_sign(mud::Operator* self) { return self->m_sign; } void DECL mud_Operator__set_sign(mud::Operator* self, const char* value) { self->m_sign = value; } void DECL mud_Operator__destroy(mud::Operator* self) { delete self; } // Param mud::Type* DECL mud_Param__type() { return &mud::type<mud::Param>(); } void DECL mud_Param__destroy(mud::Param* self) { delete self; } // Signature mud::Type* DECL mud_Signature__type() { return &mud::type<mud::Signature>(); } void DECL mud_Signature__destroy(mud::Signature* self) { delete self; } // Static mud::Type* DECL mud_Static__type() { return &mud::type<mud::Static>(); } void DECL mud_Static__destroy(mud::Static* self) { delete self; } // System mud::Type* DECL mud_System__type() { return &mud::type<mud::System>(); } void DECL mud_System__destroy(mud::System* self) { delete self; } // Constructor mud::Type* DECL mud_Constructor__type() { return &mud::type<mud::Constructor>(); } void DECL mud_Constructor__destroy(mud::Constructor* self) { delete self; } // CopyConstructor mud::Type* DECL mud_CopyConstructor__type() { return &mud::type<mud::CopyConstructor>(); } void DECL mud_CopyConstructor__destroy(mud::CopyConstructor* self) { delete self; } // Destructor mud::Type* DECL mud_Destructor__type() { return &mud::type<mud::Destructor>(); } void DECL mud_Destructor__destroy(mud::Destructor* self) { delete self; } // Function mud::Type* DECL mud_Function__type() { return &mud::type<mud::Function>(); } void DECL mud_Function__destroy(mud::Function* self) { delete self; } // Injector mud::Type* DECL mud_Injector__type() { return &mud::type<mud::Injector>(); } void DECL mud_Injector__destroy(mud::Injector* self) { delete self; } // Method mud::Type* DECL mud_Method__type() { return &mud::type<mud::Method>(); } void DECL mud_Method__destroy(mud::Method* self) { delete self; } mud::System* DECL mud_system_0() { return &mud::system(); } // TypeClass mud::TypeClass DECL mud_TypeClass_None() { return mud::TypeClass::None; } mud::TypeClass DECL mud_TypeClass_Object() { return mud::TypeClass::Object; } mud::TypeClass DECL mud_TypeClass_Struct() { return mud::TypeClass::Struct; } mud::TypeClass DECL mud_TypeClass_Sequence() { return mud::TypeClass::Sequence; } mud::TypeClass DECL mud_TypeClass_BaseType() { return mud::TypeClass::BaseType; } mud::TypeClass DECL mud_TypeClass_Enum() { return mud::TypeClass::Enum; } }
25.023529
99
0.696599
[ "object", "vector" ]
46791ee7b00f3ec994be6ae76f9dd8c22c7b45f1
3,905
cpp
C++
lib/net/src/nrun/net_04.cpp
lcityd/paragon
47a43872a5656a8c431c774d353ed214f9d0ed1d
[ "MIT" ]
1
2019-03-11T14:46:04.000Z
2019-03-11T14:46:04.000Z
lib/net/src/nrun/net_04.cpp
lcityd/paragon
47a43872a5656a8c431c774d353ed214f9d0ed1d
[ "MIT" ]
null
null
null
lib/net/src/nrun/net_04.cpp
lcityd/paragon
47a43872a5656a8c431c774d353ed214f9d0ed1d
[ "MIT" ]
null
null
null
// ================================================== // Example code: how to model cosmological parameters // Data from Addison et al. 2013 // ================================================== #include "Data1D.h" #include "Modelling_Cosmology.h" #include "net_03.cpp" // these two variables contain the name of the CosmoBolognaLib // directory and the name of the current directory (useful when // launching the code on remote systems) string cosmobl::par::DirCosmo = DIRCOSMO, cosmobl::par::DirLoc = DIRL; int main () { try { // --------------------------------------------------------------------------- // ---------------- using one of the built-in cosmological models ------------ // --------------------------------------------------------------------------- cosmobl::cosmology::Cosmology cosmology {cosmobl::cosmology::_Planck15_, "LCDM", false}; // ---------------------------------------------- // ---------------- Read the dataset ------------ // ---------------------------------------------- string data_file = cosmobl::par::DirCosmo+"/External/Data/BAO/BAO_Addison2013.dat"; string covariance_file = cosmobl::par::DirCosmo+"/External/Data/BAO/BAO_Addison2013_covariance.dat"; auto data = make_shared<cosmobl::data::Data1D>(cosmobl::data::Data1D(data_file, 1)); data->set_covariance(covariance_file, 2, 1); // ------------------------------------------------ // ---------------- Read the data type ------------ // ------------------------------------------------ vector<string> data_type; ifstream fin(data_file.c_str()); string line; // skip header getline(fin,line); while(getline(fin, line)) { double A; string dt; stringstream ss(line); ss >> A >> A >> A >> dt; data_type.push_back(dt); } fin.clear(); fin.close(); // ------------------------------------------------------------------------------------ // ---------------- modelling cosmological parameters from BAO information ------------ // ------------------------------------------------------------------------------------ cosmobl::modelling::cosmology::Modelling_Cosmology modelCosmo(data, data_type); // --------------------------------------------------------------------- // ---------------- define cosmological parameters to model ------------ // --------------------------------------------------------------------- modelCosmo.set_fiducial_cosmology(cosmology); vector<cosmobl::cosmology::CosmoPar> Cpar = {cosmobl::cosmology::CosmoPar::_Omega_matter_LCDM_, cosmobl::cosmology::CosmoPar::_H0_, cosmobl::cosmology::CosmoPar::_rs_}; cosmobl::statistics::Prior OmegaM_prior(cosmobl::glob::DistributionType::_UniformDistribution_, 0.1, 0.5); cosmobl::statistics::Prior H0_prior(cosmobl::glob::DistributionType::_UniformDistribution_, 50, 100); cosmobl::statistics::Prior rs_prior(cosmobl::glob::DistributionType::_GaussianDistribution_, {cosmology.rs_CAMB(), 10}, 130, 180); modelCosmo.set_cosmological_parameters(Cpar, {OmegaM_prior, H0_prior, rs_prior}); // ---------------------------------------------------------------------- // ------------- run chains and write output chain and model ------------ // ---------------------------------------------------------------------- const int chain_size = 1000; const int nwalkers = 10; const int seed = 4232; vector<double> starting_parameters = {cosmology.Omega_matter(), cosmology.H0(), 150.}; double radius = 1.e-3; modelCosmo.set_likelihood(cosmobl::statistics::LikelihoodType::_GaussianLikelihood_Covariance_); modelCosmo.run_MCMC(chain_size, nwalkers, seed, starting_parameters, radius); modelCosmo.show_results(500, 10, 3213); net_03:: main(); } catch(cosmobl::glob::Exception &exc) { std::cerr << exc.what() << std::endl; exit(1); } return 0; }
52.77027
172
0.503713
[ "vector", "model" ]
4686855fc12e43d25ce11b6adbcfdbf9725ea54e
10,886
cc
C++
tfx_bsl/cc/arrow/table_util.cc
opeoluwabanwo/tfx-bsl
ad8abaec6ebb9195bc91d26df9d76e7de4e2bcca
[ "Apache-2.0" ]
null
null
null
tfx_bsl/cc/arrow/table_util.cc
opeoluwabanwo/tfx-bsl
ad8abaec6ebb9195bc91d26df9d76e7de4e2bcca
[ "Apache-2.0" ]
null
null
null
tfx_bsl/cc/arrow/table_util.cc
opeoluwabanwo/tfx-bsl
ad8abaec6ebb9195bc91d26df9d76e7de4e2bcca
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC // // 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. #include "tfx_bsl/cc/arrow/table_util.h" #include <cstddef> #include <memory> #include "absl/container/flat_hash_map.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "arrow/api.h" #include "arrow/array/concatenate.h" #include "arrow/visitor_inline.h" #include "tfx_bsl/cc/arrow/array_util.h" #include "tfx_bsl/cc/util/status.h" #include "tfx_bsl/cc/util/status_util.h" namespace tfx_bsl { namespace { using ::arrow::Array; using ::arrow::ArrayVector; using ::arrow::ChunkedArray; using ::arrow::Concatenate; using ::arrow::Field; using ::arrow::RecordBatch; using ::arrow::Schema; using ::arrow::Table; using ::arrow::Type; // Returns an empty table that has the same schema as `table`. Status GetEmptyTableLike(const Table& table, std::shared_ptr<Table>* result) { std::vector<std::shared_ptr<Array>> empty_arrays; for (const auto& f : table.schema()->fields()) { empty_arrays.emplace_back(); TFX_BSL_RETURN_IF_ERROR(FromArrowStatus( arrow::MakeArrayOfNull(f->type(), /*length=*/0, &empty_arrays.back()))); } *result = Table::Make(table.schema(), empty_arrays, 0); return Status::OK(); } // Represents a field (i.e. column name and type) in the merged table. class FieldRep { public: FieldRep(std::shared_ptr<Field> field, const int64_t leading_nulls) : field_(std::move(field)) { if (leading_nulls > 0) { arrays_or_nulls_.push_back(leading_nulls); } } // Appends `column` to the column of the field in merged table. Status AppendColumn(const ChunkedArray& column) { const auto& this_type = field_->type(); const auto& other_type = column.type(); if (other_type->id() == Type::NA) { AppendNulls(column.length()); return Status::OK(); } if (this_type->id() == Type::NA) { field_ = arrow::field(field_->name(), other_type); } else if (!this_type->Equals(other_type)) { return errors::InvalidArgument( absl::StrCat("Trying to append a column of different type. ", "Column name: ", field_->name(), " , Current type: ", this_type->ToString(), " , New type: ", other_type->ToString())); } arrays_or_nulls_.insert(arrays_or_nulls_.end(), column.chunks().begin(), column.chunks().end()); return Status::OK(); } // Appends `num_nulls` nulls to the column of the field in the merged table. void AppendNulls(const int64_t num_nulls) { if (arrays_or_nulls_.empty() || absl::holds_alternative<std::shared_ptr<Array>>( arrays_or_nulls_.back())) { arrays_or_nulls_.push_back(num_nulls); } else { absl::get<int64_t>(arrays_or_nulls_.back()) += num_nulls; } } const std::shared_ptr<Field>& field() const { return field_; } // Makes a merged array out of columns and nulls appended that can form // the column of the field in the merged table. Status ToMergedArray(std::shared_ptr<Array>* merged_array) const { if (field_->type()->id() == Type::NA) { arrow::NullBuilder null_builder; if (!arrays_or_nulls_.empty()) { TFX_BSL_RETURN_IF_ERROR(FromArrowStatus(null_builder.AppendNulls( absl::get<int64_t>(arrays_or_nulls_.back())))); } TFX_BSL_RETURN_IF_ERROR( FromArrowStatus(null_builder.Finish(merged_array))); } else { std::vector<std::shared_ptr<Array>> arrays_to_merge; for (const auto& array_or_num_nulls : arrays_or_nulls_) { std::shared_ptr<Array> array; if (absl::holds_alternative<int64_t>(array_or_num_nulls)) { TFX_BSL_RETURN_IF_ERROR(FromArrowStatus(arrow::MakeArrayOfNull( field_->type(), absl::get<int64_t>(array_or_num_nulls), &array))); } else { array = absl::get<std::shared_ptr<Array>>(array_or_num_nulls); } arrays_to_merge.push_back(std::move(array)); } TFX_BSL_RETURN_IF_ERROR(FromArrowStatus(Concatenate( arrays_to_merge, arrow::default_memory_pool(), merged_array))); } return Status::OK(); } std::shared_ptr<Field> field_; std::vector<absl::variant<std::shared_ptr<Array>, int64_t>> arrays_or_nulls_; }; template <typename RowIndicesT> Status SliceTableByRowIndicesInternal( const std::shared_ptr<Table>& table, const absl::Span<const RowIndicesT> row_indices_span, std::shared_ptr<Table>* result) { if (row_indices_span.empty()) { return GetEmptyTableLike(*table, result); } if (row_indices_span.back() >= table->num_rows()) { return errors::InvalidArgument("Row indices out of range."); } std::vector<std::shared_ptr<Table>> table_slices; // The following loop essentially turns consecutive indices into // ranges, and slice `table` by those ranges. for (int64_t begin = 0, end = 1; end <= row_indices_span.size(); ++end) { while (end < row_indices_span.size() && row_indices_span[end] == row_indices_span[end - 1] + 1) { ++end; } // Verify that the row indices are sorted. if (end < row_indices_span.size() && row_indices_span[begin] >= row_indices_span[end]) { return errors::InvalidArgument("Row indices are not sorted."); } table_slices.push_back(table->Slice(row_indices_span[begin], end - begin)); begin = end; } // Make sure to never return a table with non-zero offset (that is a slice // of another table). This is needed because Array.flatten() is buggy and // does not handle offsets correctly. // TODO(zhuo): Remove once https://github.com/apache/arrow/pull/6006 is // available. if (table_slices.size() == 1) { table_slices.emplace_back(); TFX_BSL_RETURN_IF_ERROR(GetEmptyTableLike(*table, &table_slices.back())); } std::shared_ptr<Table> concatenated; TFX_BSL_RETURN_IF_ERROR( FromArrowStatus(arrow::ConcatenateTables(table_slices, &concatenated))); return FromArrowStatus( concatenated->CombineChunks(arrow::default_memory_pool(), result)); } } // namespace // TODO(zhuo): This can be replaced by Table::ConcatenateTables with // promote_null_type = true in Arrow post 0.15. There is also a Python API. Status MergeTables(const std::vector<std::shared_ptr<Table>>& tables, std::shared_ptr<Table>* result) { absl::flat_hash_map<std::string, int> field_index_by_field_name; std::vector<FieldRep> field_rep_by_field_index; int64_t total_num_rows = 0; for (const auto& t : tables) { std::vector<bool> field_seen_by_field_index(field_rep_by_field_index.size(), false); for (int i = 0; i < t->schema()->num_fields(); ++i) { const auto& f = t->schema()->field(i); auto iter = field_index_by_field_name.find(f->name()); if (iter == field_index_by_field_name.end()) { std::tie(iter, std::ignore) = field_index_by_field_name.insert( std::make_pair(f->name(), field_rep_by_field_index.size())); field_rep_by_field_index.emplace_back(f, total_num_rows); field_seen_by_field_index.push_back(true); } field_seen_by_field_index[iter->second] = true; FieldRep& field_rep = field_rep_by_field_index[iter->second]; TFX_BSL_RETURN_IF_ERROR(field_rep.AppendColumn(*t->column(i))); } for (int i = 0; i < field_seen_by_field_index.size(); ++i) { if (!field_seen_by_field_index[i]) { field_rep_by_field_index[i].AppendNulls(t->num_rows()); } } total_num_rows += t->num_rows(); } std::vector<std::shared_ptr<Field>> fields; ArrayVector merged_arrays; for (const FieldRep& field_rep : field_rep_by_field_index) { fields.push_back(field_rep.field()); std::shared_ptr<Array> merged_array; TFX_BSL_RETURN_IF_ERROR(field_rep.ToMergedArray(&merged_array)); merged_arrays.push_back(std::move(merged_array)); } *result = Table::Make(std::make_shared<Schema>(std::move(fields)), merged_arrays, /*num_rows=*/total_num_rows); return Status::OK(); } Status SliceTableByRowIndices(const std::shared_ptr<Table>& table, const std::shared_ptr<Array>& row_indices, std::shared_ptr<Table>* result) { if (row_indices->type()->id() == arrow::Type::INT32) { const arrow::Int32Array* row_indices_array = static_cast<const arrow::Int32Array*>(row_indices.get()); absl::Span<const int32_t> row_indices_span( row_indices_array->raw_values(), row_indices_array->length()); return SliceTableByRowIndicesInternal(table, row_indices_span, result); } else if (row_indices->type()->id() == arrow::Type::INT64) { const arrow::Int64Array* row_indices_array = static_cast<const arrow::Int64Array*>(row_indices.get()); absl::Span<const int64_t> row_indices_span(row_indices_array->raw_values(), row_indices_array->length()); return SliceTableByRowIndicesInternal(table, row_indices_span, result); } else { return errors::InvalidArgument( "Expected row_indices to be an Int32Array or an Int64Array"); } } Status TotalByteSize(const Table& table, const bool ignore_unsupported, size_t* result) { *result = 0; for (int i = 0; i < table.num_columns(); ++i) { auto chunked_array = table.column(i); for (int j = 0; j < chunked_array->num_chunks(); ++j) { size_t array_size; auto status = GetByteSize(*chunked_array->chunk(j), &array_size); if (ignore_unsupported && status.code() == error::UNIMPLEMENTED) { continue; } TFX_BSL_RETURN_IF_ERROR(status); *result += array_size; } } return Status::OK(); } Status TotalByteSize(const RecordBatch& record_batch, const bool ignore_unsupported, size_t* result) { *result = 0; for (int i = 0; i < record_batch.num_columns(); ++i) { size_t array_size; auto status = GetByteSize(*record_batch.column(i), &array_size); if (ignore_unsupported && status.code() == error::UNIMPLEMENTED) { continue; } TFX_BSL_RETURN_IF_ERROR(status); *result += array_size; } return Status::OK(); } } // namespace tfx_bsl
38.062937
80
0.666452
[ "vector" ]
4694e28e04d8c3c33bd3d48d13652b7dca467c9b
19,469
hpp
C++
src/end2end_legs_collision_check.hpp
thibnoel/solo-collisions
87bf492266578b7bfd04a6657675b1477d27b314
[ "BSD-2-Clause" ]
null
null
null
src/end2end_legs_collision_check.hpp
thibnoel/solo-collisions
87bf492266578b7bfd04a6657675b1477d27b314
[ "BSD-2-Clause" ]
null
null
null
src/end2end_legs_collision_check.hpp
thibnoel/solo-collisions
87bf492266578b7bfd04a6657675b1477d27b314
[ "BSD-2-Clause" ]
1
2022-03-04T07:49:28.000Z
2022-03-04T07:49:28.000Z
#include <iostream> //#include <hpp/fcl/collision_object.h> //#include <hpp/fcl/shape/geometric_shapes.h> #include "relative-placement-codegen.hpp" #include "segment-segment-distance-codegen.hpp" #include "pinocchio/algorithm/joint-configuration.hpp" #include "pinocchio/algorithm/geometry.hpp" //#include "pinocchio/fcl.hpp" using namespace pinocchio; // Function to generate // Wrapper for pinocchio::forwardKinematics for frames f1, f2 + segmentDistance template<typename Scalar> Scalar legsCapsulesDistanceCheck(pinocchio::ModelTpl<Scalar> model, pinocchio::DataTpl<Scalar> data, Eigen::Matrix<Scalar, Eigen::Dynamic, 1>& config, int frameInd1, int frameInd2, Scalar capsLength1, Scalar capsRadius1, Scalar capsLength2, Scalar capsRadius2, pinocchio::SE3Tpl<Scalar> f1Mcaps1, pinocchio::SE3Tpl<Scalar> f2Mcaps2) { // Define capsule directing vector Eigen::Matrix<Scalar, 3, 1> capsDirVec1; capsDirVec1[0] = 0; capsDirVec1[1] = 0; capsDirVec1[2] = -1*capsLength1; Eigen::Matrix<Scalar, 3, 1> capsDirVec2; capsDirVec2[0] = 0; capsDirVec2[1] = 0; capsDirVec2[2] = -1*capsLength2; // Get relative placement between f1, f2 computeFK(model, data, config); pinocchio::SE3Tpl<Scalar> f1Mf2 = getRelativePlacement<Scalar>(data, std::make_pair(frameInd1, frameInd2)); // Initialize capsule positions Eigen::Matrix<Scalar, 3, 1> caps1P0; Eigen::Matrix<Scalar, 3, 1> caps1P1; Eigen::Matrix<Scalar, 3, 1> caps1P1bis; Eigen::Matrix<Scalar, 3, 1> caps2P0; Eigen::Matrix<Scalar, 3, 1> caps2P1; // Compute capsule ends positions caps1P0[0] = 0; caps1P0[1] = 0; caps1P0[2] = 0; // Rewrite needed maybe? (order matters here) caps1P1 << caps1P0 + capsDirVec1; caps1P1bis << caps1P0 + capsDirVec2; caps2P0 << f1Mf2.act(f2Mcaps2.act(caps1P0)); caps2P1 << f1Mf2.act(f2Mcaps2.act(caps1P1bis)); caps1P0 << f1Mcaps1.act(caps1P0); caps1P1 << f1Mcaps1.act(caps1P1); std::cout << capsRadius1 << std::endl; // Compute min. distance between capsules segments minus capsules radii return CppAD::sqrt(segmentSegmentSqrDistance_scalar<Scalar>(caps1P0[0], caps1P0[1], caps1P0[2], caps1P1[0], caps1P1[1], caps1P1[2], caps2P0[0], caps2P0[1], caps2P0[2], caps2P1[0], caps2P1[1], caps2P1[2])) - (capsRadius1 + capsRadius2); } template<typename Scalar> Scalar legsCapsulesDistanceCheckNoFK(pinocchio::DataTpl<Scalar> data, int frameInd1, int frameInd2, Scalar capsLength1, Scalar capsRadius1, Scalar capsLength2, Scalar capsRadius2, pinocchio::SE3Tpl<Scalar> f1Mcaps1, pinocchio::SE3Tpl<Scalar> f2Mcaps2) { // Define capsule directing vector Eigen::Matrix<Scalar, 3, 1> capsDirVec1; capsDirVec1[0] = 0; capsDirVec1[1] = 0; capsDirVec1[2] = -1*capsLength1; Eigen::Matrix<Scalar, 3, 1> capsDirVec2; capsDirVec2[0] = 0; capsDirVec2[1] = 0; capsDirVec2[2] = -1*capsLength2; // Get relative placement between f1, f2 //computeFK(model, data, config); pinocchio::SE3Tpl<Scalar> f1Mf2 = getRelativePlacement<Scalar>(data, std::make_pair(frameInd1, frameInd2)); // Initialize capsule positions Eigen::Matrix<Scalar, 3, 1> caps1P0; Eigen::Matrix<Scalar, 3, 1> caps1P1; Eigen::Matrix<Scalar, 3, 1> caps1P1bis; Eigen::Matrix<Scalar, 3, 1> caps2P0; Eigen::Matrix<Scalar, 3, 1> caps2P1; // Compute capsule ends positions caps1P0[0] = 0; caps1P0[1] = 0; caps1P0[2] = 0; // Rewrite needed maybe? (order matters here) caps1P1 << caps1P0 + capsDirVec1; caps1P1bis << caps1P0 + capsDirVec2; caps2P0 << f1Mf2.act(f2Mcaps2.act(caps1P0)); caps2P1 << f1Mf2.act(f2Mcaps2.act(caps1P1bis)); caps1P0 << f1Mcaps1.act(caps1P0); caps1P1 << f1Mcaps1.act(caps1P1); std::cout << capsRadius1 << std::endl; // Compute min. distance between capsules segments minus capsules radii return CppAD::sqrt(segmentSegmentSqrDistance_scalar<Scalar>(caps1P0[0], caps1P0[1], caps1P0[2], caps1P1[0], caps1P1[1], caps1P1[2], caps2P0[0], caps2P0[1], caps2P0[2], caps2P1[0], caps2P1[1], caps2P1[2])) - (capsRadius1 + capsRadius2); } template<typename Scalar> Eigen::Matrix<Scalar, 4, 1> legToLegDistanceCheck(pinocchio::ModelTpl<Scalar> model, pinocchio::DataTpl<Scalar> rdata, std::string leg1, std::string leg2, Scalar upperCapsLength, Scalar upperCapsRadius, Scalar lowerCapsLength, Scalar lowerCapsRadius, pinocchio::SE3Tpl<Scalar> f1Mcaps1, pinocchio::SE3Tpl<Scalar> f2Mcaps2 ) { const int frame1Up = (int)model.getFrameId(leg1 + "_UPPER_LEG"); const int frame1Low = (int)model.getFrameId(leg1 + "_LOWER_LEG"); const int frame2Up = (int)model.getFrameId(leg2 + "_UPPER_LEG"); const int frame2Low = (int)model.getFrameId(leg2 + "_LOWER_LEG"); Scalar d1u2u = legsCapsulesDistanceCheckNoFK<Scalar>(rdata, frame1Up, frame2Up, upperCapsLength, upperCapsRadius, upperCapsLength, upperCapsRadius, f1Mcaps1, f2Mcaps2); Scalar d1u2l = legsCapsulesDistanceCheckNoFK<Scalar>(rdata, frame1Up, frame2Low, upperCapsLength, upperCapsRadius, lowerCapsLength, lowerCapsRadius, f1Mcaps1, f2Mcaps2); Scalar d1l2u = legsCapsulesDistanceCheckNoFK<Scalar>(rdata, frame1Low, frame2Up, lowerCapsLength, lowerCapsRadius, upperCapsLength, upperCapsRadius, f1Mcaps1, f2Mcaps2); Scalar d1l2l = legsCapsulesDistanceCheckNoFK<Scalar>(rdata, frame1Low, frame2Low, lowerCapsLength, lowerCapsRadius, lowerCapsLength, lowerCapsRadius, f1Mcaps1, f2Mcaps2); Eigen::Matrix<Scalar, 4, 1> distVec; distVec << d1u2u, d1u2l, d1l2u, d1l2l; return distVec; } // MOVED TO autocollision-code-generation.hpp /* std::pair<int,int> getFramesPair(std::string frameName1, std::string frameName2, pinocchio::Model model) { return std::make_pair((int)model.getFrameId(frameName1),(int)model.getFrameId(frameName2)); } std::pair<int,int>* getLegToLegPairs(std::string leg1, std::string leg2, pinocchio::Model model) { static std::pair<int,int> pairs[4] = {getFramesPair(leg1 + "_UPPER_LEG", leg2 + "_UPPER_LEG", model), getFramesPair(leg1 + "_UPPER_LEG", leg2 + "_LOWER_LEG", model), getFramesPair(leg1 + "_LOWER_LEG", leg2 + "_UPPER_LEG", model), getFramesPair(leg1 + "_LOWER_LEG", leg2 + "_LOWER_LEG", model)}; return pairs; } */ // Returns the distances between all leg segments as a 8x8 matrix (symetric with null diagonal -> 24 coeffs determin the matrix) // Matrix Shape : // FLU FLL FRU FRL HLU HLL HRU HRL // FLU x x dFlFr[0] dFlFr[2] dFlHl[0] ... ... // // FLL x x dFlFr[1] dFlFr[3] ... // // FRU x x ... // // FRL x x // // HLU // // HLL // // HRU // // HRL template<typename Scalar> Eigen::Matrix<Scalar, 64, 1> allLegsDistanceCheck(pinocchio::ModelTpl<Scalar> model, pinocchio::DataTpl<Scalar> rdata, Eigen::Matrix<Scalar, Eigen::Dynamic, 1>& config, Scalar upperCapsLength, Scalar upperCapsRadius, Scalar lowerCapsLength, Scalar lowerCapsRadius, pinocchio::SE3Tpl<Scalar> f1Mcaps1, pinocchio::SE3Tpl<Scalar> f2Mcaps2, int npairs) { std::string legs[4] = {"FL","FR","HL","HR"}; Eigen::Matrix<Scalar, 8, 8> distMatrix; Eigen::Matrix<Scalar, 2, 2> distSubMatrices[6]; Eigen::Matrix<Scalar,2,2> zero22 = Eigen::Matrix<Scalar,2,2>::Zero(2,2); computeFK(model, rdata, config); // TO DO : adjust f1Mcaps1, f2Mcaps2 (upper and lower caps poses in leg segments frames) to account for legs symetries // TO DO : check the placements with FCL int counter = 0; for(int i=0; i<4; i++) { for(int j=i+1; j<4; j++) { Eigen::Matrix<Scalar, 2, 2> legToLegMatrix; if(counter < npairs) { std::string leg1 = legs[i]; std::string leg2 = legs[j]; Eigen::Matrix<Scalar, 4, 1> legToLegResult = legToLegDistanceCheck<Scalar>(model, rdata, leg1, leg2, upperCapsLength, upperCapsRadius, lowerCapsLength, lowerCapsRadius, f1Mcaps1, f2Mcaps2); legToLegMatrix = Eigen::Map<const Eigen::Matrix<Scalar, 2, 2> >(legToLegResult.data()); } else { legToLegMatrix = zero22; } int ind; if(i == 0){ ind = i+j-1; } else {ind = i+j;} distSubMatrices[ind] = legToLegMatrix; counter += 1; } } distMatrix << zero22, distSubMatrices[0], distSubMatrices[1], distSubMatrices[2], distSubMatrices[0].transpose(), zero22, distSubMatrices[3], distSubMatrices[4], distSubMatrices[1].transpose(), distSubMatrices[3].transpose(), zero22, distSubMatrices[5], distSubMatrices[2].transpose(), distSubMatrices[4].transpose(), distSubMatrices[5].transpose(), zero22; return Eigen::Map<const Eigen::Matrix<Scalar, 64, 1> >(distMatrix.data()); } // Helper function : returns the jMf SE3 placement given a frame f, j being its parent joint pinocchio::SE3 jointToFrameRelativePlacement(pinocchio::Model model, pinocchio::Data data, int frameInd) { //forwardKinematics(model, data, config); //updateFramePlacements(model, data); SE3 oMf = data.oMf[frameInd]; SE3 oMj = data.oMi[model.frames[frameInd].parent]; return oMj.inverse() * oMf; } // Get the result of the FCL evaluation to test against double getPairFCLResult(pinocchio::Model& model, pinocchio::GeometryModel& gmodel, pinocchio::Data& data, Eigen::Matrix<double, Eigen::Dynamic, 1>& config, std::string frameName1, std::string frameName2, double capsLength1, double capsRadius1, double capsLength2, double capsRadius2, pinocchio::SE3 f1Mcaps1, pinocchio::SE3 f2Mcaps2) { typedef boost::shared_ptr< fcl::CollisionGeometry > CollisionGeometryPtr; // Get frames indices from the model pinocchio::FrameIndex frameInd1 = model.getFrameId(frameName1); pinocchio::FrameIndex frameInd2 = model.getFrameId(frameName2); // Offset f1Mcaps1 to an end of the capsule // TODO : Do the same for caps2 (f2Mcaps as arg) // Translations Eigen::Matrix<double, 3, 1> capsPosOffset1; capsPosOffset1[0] = 0; capsPosOffset1[1] = 0; capsPosOffset1[2] = -0.5*capsLength1; Eigen::Matrix<double, 3, 1> capsPosOffset2; capsPosOffset2[0] = 0; capsPosOffset2[1] = 0; capsPosOffset2[2] = -0.5*capsLength2; // Rotation Eigen::Quaternion<double> capsRotOffset; capsRotOffset.setIdentity(); // SE3 object pinocchio::SE3 capsFrame1(capsRotOffset, capsPosOffset1); capsFrame1 = f1Mcaps1.act(capsFrame1); pinocchio::SE3 capsFrame2(capsRotOffset, capsPosOffset2); capsFrame2 = f2Mcaps2.act(capsFrame2); pinocchio::SE3 j1Mframe1 = jointToFrameRelativePlacement(model, data, (int)frameInd1); pinocchio::SE3 j2Mframe2 = jointToFrameRelativePlacement(model, data, (int)frameInd2); // Initialize fcl geometries const CollisionGeometryPtr caps_geom1 (new hpp::fcl::Capsule(capsRadius1, capsLength1)); const CollisionGeometryPtr caps_geom2 (new hpp::fcl::Capsule(capsRadius2, capsLength2)); // Initialize geometry objects // Capsule 1 std::string caps1_name = std::string("caps_") + frameName1; pinocchio::GeometryObject caps1_gobj(caps1_name, frameInd1, model.frames[frameInd1].parent, caps_geom1, j1Mframe1.act(capsFrame1)); // Capsule 2 std::string caps2_name = std::string("caps_") + frameName2; pinocchio::GeometryObject caps2_gobj(caps2_name, frameInd2, model.frames[frameInd2].parent, caps_geom2, j2Mframe2.act(capsFrame2)); // Add capsules to the model and make them a collision pair pinocchio::GeomIndex caps1 = gmodel.addGeometryObject(caps1_gobj, model); pinocchio::GeomIndex caps2 = gmodel.addGeometryObject(caps2_gobj, model); gmodel.addCollisionPair(pinocchio::CollisionPair(caps1,caps2)); // Compute and return the distance result pinocchio::GeometryData gdata(gmodel); pinocchio::computeDistances(model,data,gmodel,gdata,config); std::vector< fcl::DistanceResult > collisions_dist = gdata.distanceResults; return collisions_dist[gmodel.findCollisionPair(pinocchio::CollisionPair(caps1,caps2))].min_distance; } // Get the result of the FCL evaluation to test against /* Eigen::Matrix<double, 8, 8> getAllLegsFCLResult(pinocchio::Model& model, pinocchio::GeometryModel& gmodel, pinocchio::Data& data, Eigen::Matrix<double, Eigen::Dynamic, 1>& config, double upperCapsLength, double upperCapsRadius, double lowerCapsLength, double lowerC apsRadius, pinocchio::SE3 f1Mcaps1, pinocchio::SE3 f2Mcaps2) { } */ // Generates the model for the function f(q, f1, f2) = dist. between legs f1,f2 ADFun tapeADFunEnd2End(pinocchio::Model model, int frameInd1, int frameInd2, ADScalar capsLength1, ADScalar capsRadius1, ADScalar capsLength2, ADScalar capsRadius2, pinocchio::SE3Tpl<ADScalar> f1Mcaps1, pinocchio::SE3Tpl<ADScalar> f2Mcaps2 ) { // Cast the model to ADScalar type and regenerate the model data ModelTpl<ADScalar> cast_rmodel = model.cast<ADScalar>(); DataTpl<ADScalar> cast_rdata(cast_rmodel); // Initnialize AD input and output Eigen::Matrix<ADScalar, Eigen::Dynamic, 1> ad_X; Eigen::Matrix<ADScalar, Eigen::Dynamic, 1> ad_Y; ad_X.resize(cast_rmodel.nq); ad_Y.resize(1); CppAD::Independent(ad_X); // Initialize AD function ADFun ad_fun; pinocchio::forwardKinematics(cast_rmodel, cast_rdata, ad_X); pinocchio::updateFramePlacements(cast_rmodel, cast_rdata); ADScalar a = legsCapsulesDistanceCheck<ADScalar>(cast_rmodel, cast_rdata, ad_X, frameInd1, frameInd2, capsLength1, capsRadius1, capsLength2, capsRadius2, f1Mcaps1, f2Mcaps2); ad_Y[0] = a; ad_fun.Dependent(ad_X, ad_Y); return ad_fun; } // Generates the model for the function f(q, l1, l2) = dist.vec. between legs 1,2 // Result is given as a vector of distances between the pairs, in the following order : // [(frame1Up, frame2Up) // (frame1Up, frame2Low) // (frame2Up, frame1Low) // (frame1Low, frame2Low)] ADFun tapeADFunFullLeg(pinocchio::Model model, std::string leg1, std::string leg2, ADScalar upperCapsLength, ADScalar upperCapsRadius, ADScalar lowerCapsLength, ADScalar lowerCapsRadius, pinocchio::SE3Tpl<ADScalar> f1Mcaps1, pinocchio::SE3Tpl<ADScalar> f2Mcaps2 ) { // Cast the model to ADScalar type and regenerate the model data ModelTpl<ADScalar> cast_rmodel = model.cast<ADScalar>(); DataTpl<ADScalar> cast_rdata(cast_rmodel); // Initnialize AD input and output Eigen::Matrix<ADScalar, Eigen::Dynamic, 1> ad_X; Eigen::Matrix<ADScalar, Eigen::Dynamic, 1> ad_Y; ad_X.resize(cast_rmodel.nq); ad_Y.resize(4); CppAD::Independent(ad_X); // Initialize AD function ADFun ad_fun; pinocchio::forwardKinematics(cast_rmodel, cast_rdata, ad_X); pinocchio::updateFramePlacements(cast_rmodel, cast_rdata); ad_Y = legToLegDistanceCheck<ADScalar>(cast_rmodel, cast_rdata, leg1, leg2, upperCapsLength, upperCapsRadius, lowerCapsLength, lowerCapsRadius, f1Mcaps1, f2Mcaps2); ad_fun.Dependent(ad_X, ad_Y); return ad_fun; } ADFun tapeADFunAllLegs(pinocchio::Model model, ADScalar upperCapsLength, ADScalar upperCapsRadius, ADScalar lowerCapsLength, ADScalar lowerCapsRadius, pinocchio::SE3Tpl<ADScalar> f1Mcaps1, pinocchio::SE3Tpl<ADScalar> f2Mcaps2, int npairs ) { // Cast the model to ADScalar type and regenerate the model data ModelTpl<ADScalar> cast_rmodel = model.cast<ADScalar>(); DataTpl<ADScalar> cast_rdata(cast_rmodel); // Initnialize AD input and output Eigen::Matrix<ADScalar, Eigen::Dynamic, 1> ad_X; Eigen::Matrix<ADScalar, Eigen::Dynamic, 1> ad_Y; ad_X.resize(cast_rmodel.nq); ad_Y.resize(64); CppAD::Independent(ad_X); // Initialize AD function ADFun ad_fun; pinocchio::forwardKinematics(cast_rmodel, cast_rdata, ad_X); pinocchio::updateFramePlacements(cast_rmodel, cast_rdata); ad_Y = allLegsDistanceCheck<ADScalar>(cast_rmodel, cast_rdata, ad_X, upperCapsLength, upperCapsRadius, lowerCapsLength, lowerCapsRadius, f1Mcaps1, f2Mcaps2, npairs); ad_fun.Dependent(ad_X, ad_Y); return ad_fun; }
41.868817
239
0.588525
[ "geometry", "object", "shape", "vector", "model" ]
469d18748714707e17d6ff06492f15e84ab570cc
1,797
cpp
C++
Engine/src/math/Vector4f.cpp
DaanSander/Polygon-Engine
cdbf42b070c75f37d1e52caa788546f83156d80d
[ "MIT" ]
null
null
null
Engine/src/math/Vector4f.cpp
DaanSander/Polygon-Engine
cdbf42b070c75f37d1e52caa788546f83156d80d
[ "MIT" ]
null
null
null
Engine/src/math/Vector4f.cpp
DaanSander/Polygon-Engine
cdbf42b070c75f37d1e52caa788546f83156d80d
[ "MIT" ]
null
null
null
#include "Vector4f.h" namespace engine { namespace math { Vector4f::Vector4f(float x, float y, float z, float w) { this->x = x; this->y = y; this->z = z; this->w = w; } float Vector4f::dot(Vector4f other) const { float xm = (this->x * other.x) + (this->x * other.y) + (this->x * other.z) + (this->x * other.w); float ym = (this->y * other.x) + (this->y * other.y) + (this->y * other.z) + (this->y * other.w); float zm = (this->z * other.x) + (this->z * other.y) + (this->z * other.z) + (this->z * other.w); float wm = (this->w * other.x) + (this->w * other.y) + (this->w * other.z) + (this->w * other.w); return xm + ym + zm + wm; } Vector4f Vector4f::multiply(float scalar) const { Vector4f out; out.x = this->x * scalar; out.y = this->y * scalar; out.z = this->z * scalar; out.w = this->w * scalar; return out; } Vector4f Vector4f::reverse() const { Vector4f out; out.x = -this->x; out.y = -this->y; out.z = -this->z; out.w = -this->w; return out; } Vector4f Vector4f::substract(Vector4f other) const { return add(reverse()); } Vector4f Vector4f::add(Vector4f other) const { Vector4f out; out.x = this->x + other.x; out.y = this->y + other.y; out.z = this->z + other.z; out.w = this->w + other.w; return out; } Vector4f Vector4f::operator-() const { return this->reverse(); } Vector4f operator-(const Vector4f& vector) { return vector.reverse(); } Vector4f operator+(const Vector4f& a, const Vector4f& b) { return a.add(b); } Vector4f operator-(const Vector4f& a, const Vector4f& b) { return a.substract(b); } float operator* (const Vector4f& a, const Vector4f& other) { return a.dot(other); } Vector4f operator* (const Vector4f& vector, float scalar) { return vector.multiply(scalar); } }}
24.283784
99
0.605454
[ "vector" ]
469d2e9405cb60b0bcaea0f3214bcf0d6f65a0c7
4,897
cpp
C++
Engine/Source/Developer/RealtimeProfiler/Private/SRealtimeProfilerTimeline.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Developer/RealtimeProfiler/Private/SRealtimeProfilerTimeline.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Developer/RealtimeProfiler/Private/SRealtimeProfilerTimeline.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "SlateBasics.h" #include "TaskGraphInterfaces.h" #include "VisualizerEvents.h" #include "SRealtimeProfilerTimeline.h" #include "STimeline.h" #include "SRealtimeProfilerVisualizer.h" #include "SRealtimeProfilerLineGraph.h" #include "RealtimeProfiler.h" void SRealtimeProfilerTimeline::Construct( const FArguments& InArgs ) { ZoomSliderValue = 0.0f; ScrollbarOffset = 0.0f; Visualizer = InArgs._Visualizer; ViewMode = EVisualizerViewMode::Hierarchical; this->ChildSlot [ SNew( SVerticalBox ) +SVerticalBox::Slot() .Padding( 2 ) .FillHeight( 1 ) .VAlign( VAlign_Fill ) [ SNew(SHorizontalBox) +SHorizontalBox::Slot().AutoWidth() .Padding( 2 ) .FillWidth( 1 ) .HAlign( HAlign_Fill ) [ SAssignNew( LineGraph, SRealtimeProfilerLineGraph ) .OnGeometryChanged( this, &SRealtimeProfilerTimeline::OnLineGraphGeometryChanged ) .Visualizer(InArgs._Visualizer) ] ] +SVerticalBox::Slot().AutoHeight() .Padding( 2 ) .VAlign( VAlign_Fill ) [ SAssignNew( Timeline, STimeline ) .MinValue(0.0f) .MaxValue(200.0f) ] +SVerticalBox::Slot().AutoHeight() .Padding( 2 ) .VAlign( VAlign_Fill ) [ SAssignNew( ScrollBar, SScrollBar ) .Orientation( Orient_Horizontal ) .OnUserScrolled( this, &SRealtimeProfilerTimeline::ScrollBar_OnUserScrolled ) ] +SVerticalBox::Slot().AutoHeight() .Padding( 2 ) .VAlign( VAlign_Fill ) [ SNew( SHorizontalBox ) +SHorizontalBox::Slot() .Padding( 2 ) .FillWidth( 1 ) .HAlign( HAlign_Fill ) [ SAssignNew( ZoomLabel, STextBlock ).Text( this, &SRealtimeProfilerTimeline::GetZoomLabel ) ] +SHorizontalBox::Slot() .Padding( 2 ) .FillWidth( 5 ) .HAlign( HAlign_Fill ) [ SNew( SSlider ) .Value( this, &SRealtimeProfilerTimeline::GetZoomValue ) .OnValueChanged( this, &SRealtimeProfilerTimeline::OnSetZoomValue ) ] ] ]; ScrollBar->SetState(0.0f, 1.0f); } void SRealtimeProfilerTimeline::AppendData(TSharedPtr< FVisualizerEvent > ProfileData, FRealtimeProfilerFPSChartFrame * InFPSChartFrame) { LineGraph->AppendData(ProfileData,InFPSChartFrame); } bool SRealtimeProfilerTimeline::IsProfiling() { return LineGraph->bIsProfiling; } void SRealtimeProfilerTimeline::ScrollBar_OnUserScrolled( float InScrollOffsetFraction ) { if( ZoomSliderValue > 0.0f ) { const float MaxOffset = GetMaxScrollOffsetFraction(); const float MaxGraphOffset = GetMaxGraphOffset(); InScrollOffsetFraction = FMath::Clamp( InScrollOffsetFraction, 0.0f, MaxOffset ); float GraphOffset = -( InScrollOffsetFraction / MaxOffset ) * MaxGraphOffset; ScrollBar->SetState( InScrollOffsetFraction, 1.0f / GetZoom() ); LineGraph->SetOffset(GraphOffset); Timeline->SetOffset( GraphOffset ); ScrollbarOffset = GraphOffset; } } FText SRealtimeProfilerTimeline::GetZoomLabel() const { static const FNumberFormattingOptions ZoomFormatOptions = FNumberFormattingOptions() .SetMinimumFractionalDigits(2) .SetMaximumFractionalDigits(2); return FText::Format( NSLOCTEXT("TaskGraph", "ZoomLabelFmt", "Zoom: {0}x"), FText::AsNumber(GetZoom(), &ZoomFormatOptions) ); } float SRealtimeProfilerTimeline::GetZoomValue() const { return ZoomSliderValue; } void SRealtimeProfilerTimeline::OnSetZoomValue( float NewValue ) { const float PrevZoom = GetZoom(); const float PrevVisibleRange = 1.0f / PrevZoom; ZoomSliderValue = NewValue; const float Zoom = GetZoom(); float GraphOffset = 0.0f; float ScrollOffsetFraction = 0.0f; const float MaxOffset = GetMaxScrollOffsetFraction(); const float MaxGraphOffset = GetMaxGraphOffset(); const float PrevGraphOffset = -LineGraph->GetOffset(); GraphOffset = FMath::Clamp( -LineGraph->GetOffset(), 0.0f, MaxGraphOffset ); const float VisibleRange = 1.0f / GetZoom(); const float PrevGraphCenterValue = PrevGraphOffset / PrevZoom + PrevVisibleRange * 0.5f; const float NewGraphCenterValue = GraphOffset / Zoom + VisibleRange * 0.5f; GraphOffset += ( PrevGraphCenterValue - NewGraphCenterValue ) * Zoom; GraphOffset = FMath::Clamp( GraphOffset, 0.0f, MaxGraphOffset ); ScrollOffsetFraction = FMath::Clamp( MaxOffset * GraphOffset / MaxGraphOffset, 0.0f, MaxOffset ); ScrollBar->SetState( ScrollOffsetFraction, 1.0f / Zoom ); LineGraph->SetZoom( Zoom ); LineGraph->SetOffset( -GraphOffset ); Timeline->SetZoom( Zoom ); Timeline->SetOffset( -GraphOffset ); ScrollbarOffset = -GraphOffset; } void SRealtimeProfilerTimeline::OnLineGraphGeometryChanged( FGeometry Geometry ) { Timeline->SetDrawingGeometry( Geometry ); } void SRealtimeProfilerTimeline::AdjustTimeline( TSharedPtr< FVisualizerEvent > InEvent ) { check( InEvent.IsValid() ); const double TotalTimeMs = InEvent->DurationMs / InEvent->Duration; const double StartMs = InEvent->Start * TotalTimeMs; Timeline->SetMinMaxValues( StartMs, StartMs + InEvent->DurationMs ); }
29.5
136
0.745967
[ "geometry" ]
469f041e4d2bf2bf4733f3487a16da6d5ff49e2e
4,750
cpp
C++
source/radeon_gpu_analyzer_gui/rg_csv_file_parser.cpp
clayne/RGA
7ed370e00b635c5b558d4af4eb050e2a38f77e53
[ "MIT" ]
97
2020-03-12T01:47:49.000Z
2022-03-16T02:29:04.000Z
source/radeon_gpu_analyzer_gui/rg_csv_file_parser.cpp
clayne/RGA
7ed370e00b635c5b558d4af4eb050e2a38f77e53
[ "MIT" ]
34
2020-03-10T16:38:48.000Z
2022-03-19T04:05:04.000Z
source/radeon_gpu_analyzer_gui/rg_csv_file_parser.cpp
clayne/RGA
7ed370e00b635c5b558d4af4eb050e2a38f77e53
[ "MIT" ]
14
2020-03-13T00:50:23.000Z
2022-01-31T09:06:54.000Z
// C++. #include <cassert> #include <memory> #include <sstream> // Qt. #include <QFile> #include <QTextStream> // Local. #include "radeon_gpu_analyzer_gui/rg_csv_file_parser.h" #include "radeon_gpu_analyzer_gui/rg_string_constants.h" bool RgCsvFileParser::Parse(std::string& error_string) { bool is_parsing_failed = false; QFile csv_file(csv_file_path_.c_str()); QTextStream file_stream(&csv_file); // Attempt to open the CSV file and parse each line. bool is_file_opened = csv_file.open(QFile::ReadOnly | QFile::Text); assert(is_file_opened); if (is_file_opened) { // Read the first line and move on, as it's just column labels. QString csv_line = file_stream.readLine(); int line_index = 2; // Parse each new line in the CSV file. do { // Read the next line in the file. csv_line = file_stream.readLine(); if (!csv_line.isEmpty()) { std::vector<std::string> line_tokens; ParseLine(csv_line.toStdString(), line_tokens); bool line_parsed_successfully = false; if (!line_tokens.empty()) { line_parsed_successfully = ProcessLineTokens(line_tokens); assert(line_parsed_successfully); } // Was the line processed correctly? if (!line_parsed_successfully) { // Build an error message indicating that parsing the file failed. std::stringstream error_stream; error_stream << kStrErrCsvParsingFailedA; error_stream << csv_file_path_.c_str(); error_stream << kStrErrCsvParsingFailedB; error_stream << line_index; // Return the error string. error_string = error_stream.str(); is_parsing_failed = true; } } // Increment the line index currently being parsed. line_index++; } while (!file_stream.atEnd()); } else { // Failed to load the CSV file correctly. std::stringstream error_stream; error_stream << kStrErrCsvParsingFailedA; error_stream << csv_file_path_.c_str(); // Return the error string. error_string = error_stream.str(); is_parsing_failed = true; } return !is_parsing_failed; } void RgCsvFileParser::ParseLine(const std::string& csv_line, std::vector<std::string>& line_tokens) { std::stringstream line_stream; line_stream.str(csv_line); std::string substr; // Step through the entire line of text, and split into tokens based on comma position. while (std::getline(line_stream, substr, ',')) { // Are there any quotation marks within the token? If so, parsing is handled differently. size_t num_quotes_in_token = std::count(substr.begin(), substr.end(), '\"'); switch (num_quotes_in_token) { case 0: { // If there are no quotes, just add the token to the line tokens list. line_tokens.push_back(substr); } break; case 1: { // Found a start quote. Keep reading new tokens to find the matching end quote. std::stringstream token_stream; do { // Add the token to the quoted column string. token_stream << substr << ','; std::getline(line_stream, substr, ','); } while (!(substr.find('"') != substr.npos)); // Add the final portion of the token to the stream. token_stream << substr; // Remove the quotation marks from the final token string. std::string quoted_token = token_stream.str(); quoted_token.erase(std::remove(quoted_token.begin(), quoted_token.end(), '\"'), quoted_token.end()); // Add the token to the line tokens list. line_tokens.push_back(quoted_token); } break; case 2: { // There's a single token surrounded with 2 quotes. Just remove the quotes and add the token to the lines. substr.erase(std::remove(substr.begin(), substr.end(), '\"'), substr.end()); line_tokens.push_back(substr); } break; default: // If this happens, the format of the ISA line likely wasn't handled correctly. assert(false); break; } } }
34.671533
122
0.559368
[ "vector" ]
46a21c263ce2e78b9f296b9a06eff033f625384a
2,761
cpp
C++
2nd_100/problem147.cpp
takekoputa/project-euler
6f434be429bd26f5d0f84f5ab0f5fa2bd677c790
[ "MIT" ]
null
null
null
2nd_100/problem147.cpp
takekoputa/project-euler
6f434be429bd26f5d0f84f5ab0f5fa2bd677c790
[ "MIT" ]
null
null
null
2nd_100/problem147.cpp
takekoputa/project-euler
6f434be429bd26f5d0f84f5ab0f5fa2bd677c790
[ "MIT" ]
1
2021-11-02T12:08:46.000Z
2021-11-02T12:08:46.000Z
// Question: https://projecteuler.net/problem=147 #include<iostream> #include<vector> using namespace std; typedef int64_t i64; #define endl "\n" const i64 N = 47; const i64 M = 43; void draw_diagonal(i64 i_row, i64 i_col, i64 length, vector<vector<bool>>& grid) { for (i64 i = 0; i < length; i++) grid[i_row-i][i_col+i] = true; } void draw_grid(const vector<vector<bool>>& grid) { auto n = grid.size(); auto m = grid[0].size(); for (i64 i = 0; i < n; i++) { for (i64 j = 0; j < m; j++) if (grid[i][j]) cout << "*"; else cout << "-"; cout << endl; } } void draw_diagonals(vector<vector<bool>>& grid, i64 n, i64 m) { i64 row = n; i64 col = 0; draw_diagonal(row, col, n-1, grid); row = row + 1; for (i64 i = 0; i < m-1; i++) { draw_diagonal(row, col, n, grid); draw_diagonal(row, col+1, n-1, grid); row = row + 1; col = col + 1; } } i64 check_rectangle(i64 row1, i64 col1, i64 row2, i64 col2, const vector<vector<bool>>& grid) { for (i64 row = row1; row <= row2; row++) for (i64 col = col1; col <= col2; col++) if (!grid[row][col]) return 0; return 1; } i64 count_rectangles(i64 d_row, i64 d_col, const vector<vector<bool>>& grid) { i64 ans = 0; i64 n = grid.size(); i64 m = grid[0].size(); for (i64 row = 0; row <= n-d_row; row++) for (i64 col = 0; col <= m-d_col; col++) ans = ans + check_rectangle(row, col, row+d_row-1, col+d_col-1, grid); if (d_row != d_col) ans = ans * 2; return ans; } int main() { i64 ans = 0; for (i64 m = 1; m <= M; m++) for (i64 n = m; n <= N; n++) { vector<vector<bool>> grid = vector<vector<bool>>(2*n); for (i64 i = 0; i < 2*n; i++) grid[i] = vector<bool>(2*n, false); i64 delta = n*(n+1)*m*(m+1)/4; draw_diagonals(grid, n, m); for (i64 d_row = 1; d_row <= 2*n; d_row++) { i64 prev_delta = delta; for (i64 d_col = d_row; d_col <= 2*n; d_col++) { i64 new_rectangles = count_rectangles(d_row, d_col, grid); if (new_rectangles == 0) break; delta = delta + new_rectangles; } if (delta == prev_delta) break; } cout << n << " " << m << " " << delta << endl; if (n != m && n <= M && m <= N) delta = delta * 2; ans = ans + delta; } cout << ans << endl; return 0; }
23.598291
93
0.456719
[ "vector" ]
46a46ae09b6c428728a54f98c793416154e794fe
11,258
cpp
C++
CSGOSimple/features/skins/kit_parser.cpp
YMY1666527646/CustomHooks-csgo
c79cb831dbcab044969abf556b5bfe6fab5b187c
[ "MIT" ]
7
2022-02-08T18:19:07.000Z
2022-03-25T22:17:55.000Z
CSGOSimple/features/skins/kit_parser.cpp
Kajus14/CustomHooks-csgo
aebc092ff4c5930ec7672501ba5b450dc0cbe5ba
[ "MIT" ]
null
null
null
CSGOSimple/features/skins/kit_parser.cpp
Kajus14/CustomHooks-csgo
aebc092ff4c5930ec7672501ba5b450dc0cbe5ba
[ "MIT" ]
5
2022-02-04T09:29:11.000Z
2022-03-21T15:09:13.000Z
#include <algorithm> #include "kit_parser.h" #include "../../helpers/utils.hpp" #include <iostream> #include <sstream> #include <algorithm> #include <vector> #include <string> #include "parser.h" #include <set> #include <map> #include "../../options.hpp" #include <array> struct skin_info { int seed = -1; int paintkit; int rarity = 0; std::string tag_name; std::string cdn_name; }; bool skins_parsed = false; std::vector<paint_kit> k_skins; std::vector<paint_kit> k_gloves; std::vector<paint_kit> k_stickers; class CCStrike15ItemSchema; class CCStrike15ItemSystem; template <typename Key, typename Value> struct Node_t { int previous_id; //0x0000 int next_id; //0x0004 void* _unknown_ptr; //0x0008 int _unknown; //0x000C Key key; //0x0010 Value value; //0x0014 }; template <typename Key, typename Value> struct Head_t { Node_t<Key, Value>* memory; //0x0000 int allocation_count; //0x0004 int grow_size; //0x0008 int start_element; //0x000C int next_available; //0x0010 int _unknown; //0x0014 int last_element; //0x0018 }; //Size=0x001C // could use CUtlString but this is just easier and CUtlString isn't needed anywhere else struct String_t { char* buffer; //0x0000 int capacity; //0x0004 int grow_size; //0x0008 int length; //0x000C }; //Size=0x0010 struct CPaintKit { int id; //0x0000 String_t name; //0x0004 String_t description; //0x0014 String_t item_name; //0x0024 String_t material_name; //0x0034 String_t image_inventory; //0x0044 char pad_0x0054[0x8C]; //0x0054 }; //Size=0x00E0 struct CStickerKit { int id; int item_rarity; String_t name; String_t description; String_t item_name; String_t material_name; String_t image_inventory; int tournament_event_id; int tournament_team_id; int tournament_player_id; bool is_custom_sticker_material; float rotate_end; float rotate_start; float scale_min; float scale_max; float wear_min; float wear_max; String_t image_inventory2; String_t image_inventory_large; std::uint32_t pad0[4]; }; int GetWeaponRarity(std::string rarity) { if (rarity == "default") return 0; else if (rarity == "common") return 1; else if (rarity == "uncommon") return 2; else if (rarity == "rare") return 3; else if (rarity == "mythical") return 4; else if (rarity == "legendary") return 5; else if (rarity == "ancient") return 6; else if (rarity == "immortal") return 7; else if (rarity == "unusual") return 99; return 0; } auto get_export(const char* module_name, const char* export_name) -> void* { HMODULE mod; while (!((mod = GetModuleHandleA(module_name)))) Sleep(100); return reinterpret_cast<void*>(GetProcAddress(mod, export_name)); } auto initialize_kits() -> void { /*std::ifstream items{ "csgo/scripts/items/items_game_cdn.txt" }; const std::string gameItems{ std::istreambuf_iterator<char>{ items }, std::istreambuf_iterator<char>{ } }; items.close(); const auto V_UCS2ToUTF8 = static_cast<int(*)(const wchar_t* ucs2, char* utf8, int len)>(get_export("vstdlib.dll", "V_UCS2ToUTF8")); const auto sig_address = Utils::PatternScan(GetModuleHandle(L"client.dll"), "E8 ? ? ? ? FF 76 0C 8D 48 04 E8"); const auto item_system_offset = *reinterpret_cast<std::int32_t*>(sig_address + 1); const auto item_system_fn = reinterpret_cast<CCStrike15ItemSystem* (*)()>(sig_address + 5 + item_system_offset); const auto item_schema = reinterpret_cast<CCStrike15ItemSchema*>(std::uintptr_t(item_system_fn()) + sizeof(void*)); // Dump paint kits { // Skip the instructions between, skip the opcode, read rel32 address const auto get_paint_kit_definition_offset = *reinterpret_cast<std::int32_t*>(sig_address + 11 + 1); // Add the offset to the end of the instruction const auto get_paint_kit_definition_fn = reinterpret_cast<CPaintKit*(__thiscall*)(CCStrike15ItemSchema*, int)>(sig_address + 11 + 5 + get_paint_kit_definition_offset); // The last offset is start_element, we need that // push ebp // mov ebp, esp // sub esp, 0Ch // mov eax, [ecx+298h] // Skip instructions, skip opcode, read offset const auto start_element_offset = *reinterpret_cast<std::intptr_t*>(std::uintptr_t(get_paint_kit_definition_fn) + 8 + 2); // Calculate head base from start_element's offset const auto head_offset = start_element_offset - 12; const auto map_head = reinterpret_cast<Head_t<int, CPaintKit*>*>(std::uintptr_t(item_schema) + head_offset); for (auto i = 0; i <= map_head->last_element; ++i) { const auto paint_kit = map_head->memory[i].value; if (paint_kit->id == 9001) continue; const auto wide_name = g_Localize->Find(paint_kit->item_name.buffer + 1); const int itemNameLength = WideCharToMultiByte(CP_UTF8, 0, wide_name, -1, nullptr, 0, nullptr, nullptr); if (std::string name(itemNameLength, 0); WideCharToMultiByte(CP_UTF8, 0, wide_name, -1, &name[0], itemNameLength, nullptr, nullptr)) { std::string old_name = paint_kit->name.buffer; if (paint_kit->id > 10000) { std::string weap; std::string_view gloveName{ paint_kit->name.buffer }; weap += '(' + std::string{ gloveName.substr(0, gloveName.find('_')) } +')'; k_gloves.push_back({ paint_kit->id, name, old_name }); } } } //std::sort(k_skins.begin(), k_skins.end()); std::sort(k_gloves.begin(), k_gloves.end()); }*/ std::unordered_map<std::string, std::set<std::string>> weaponSkins; std::unordered_map<std::string, skin_info> skinMap; std::unordered_map<std::string, std::string> skinNames; valve_parser::document doc; auto r = doc.load(R"(.\csgo\scripts\items\items_game.txt)", valve_parser::encoding::utf8); if (!r) return; valve_parser::document english; r = english.load(R"(.\csgo\resource\csgo_english.txt)", valve_parser::encoding::utf16_le); if (!r) return; auto weapon_skin_combo = doc.breadth_first_search("weapon_icons"); if (!weapon_skin_combo || !weapon_skin_combo->to_object()) return; auto paint_kits_rarity = doc.breadth_first_search_multiple("paint_kits_rarity"); if (paint_kits_rarity.empty()) return; auto skin_data_vec = doc.breadth_first_search_multiple("paint_kits"); if (skin_data_vec.empty()) return; auto paint_kit_names = english.breadth_first_search("Tokens"); if (!paint_kit_names || !paint_kit_names->to_object()) return; std::array weaponNames = { std::string("deagle"), std::string("elite"), std::string("fiveseven"), std::string("glock"), std::string("ak47"), std::string("aug"), std::string("awp"), std::string("famas"), std::string("g3sg1"), std::string("galilar"), std::string("m249"), std::string("m4a1_silencer"), std::string("m4a1"), std::string("mac10"), std::string("p90"), std::string("ump45"), std::string("xm1014"), std::string("bizon"), std::string("mag7"), std::string("negev"), std::string("sawedoff"), std::string("tec9"), std::string("hkp2000"), std::string("mp5sd"), std::string("mp7"), std::string("mp9"), std::string("nova"), std::string("p250"), std::string("scar20"), std::string("sg556"), std::string("ssg08"), std::string("usp_silencer"), std::string("cz75a"), std::string("revolver"), std::string("knife_m9_bayonet"), std::string("bayonet"), std::string("knife_flip"), std::string("knife_gut"), std::string("knife_css"), std::string("knife_cord"), std::string("knife_canis"), std::string("knife_karambit"), std::string("knife_tactical"), std::string("knife_outdoor"), std::string("knife_skeleton"), std::string("knife_falchion"), std::string("knife_survival_bowie"), std::string("knife_butterfly"), std::string("knife_push"), std::string("knife_ursus"), std::string("knife_gypsy_jackknife"), std::string("knife_stiletto"), std::string("knife_widowmaker"), std::string("studded_bloodhound_gloves"), std::string("sporty_gloves"), std::string("slick_gloves"), std::string("leather_handwraps"), std::string("motorcycle_gloves"), std::string("specialist_gloves"), std::string("studded_hydra_gloves") }; for (const auto& child : weapon_skin_combo->children) { if (child->to_object()) { for (const auto& weapon : weaponNames) { auto skin_name = child->to_object()->get_key_by_name("icon_path")->to_key_value()->value.to_string(); const auto pos = skin_name.find(weapon); if (pos != std::string::npos) { const auto pos2 = skin_name.find_last_of('_'); weaponSkins[weapon].insert( skin_name.substr(pos + weapon.length() + 1, pos2 - pos - weapon.length() - 1) ); break; } } } } for (const auto& skin_data : skin_data_vec) { if (skin_data->to_object()) { for (const auto& skin : skin_data->children) { if (skin->to_object()) { skin_info si; si.paintkit = skin->to_object()->name.to_int(); if (si.paintkit == 0) continue; auto skin_name = skin->to_object()->get_key_by_name("name")->to_key_value()->value.to_string(); si.cdn_name = skin_name; auto tag_node = skin->to_object()->get_key_by_name("description_tag"); if (tag_node) { auto tag = tag_node->to_key_value()->value.to_string(); tag = tag.substr(1, std::string::npos); std::transform(tag.begin(), tag.end(), tag.begin(), towlower); si.tag_name = tag; } auto key_val = skin->to_object()->get_key_by_name("seed"); if (key_val != nullptr) si.seed = key_val->to_key_value()->value.to_int(); skinMap[skin_name] = si; } } } } for (const auto& child : paint_kit_names->children) { if (child->to_key_value()) { auto key = child->to_key_value()->key.to_string(); std::transform(key.begin(), key.end(), key.begin(), towlower); if (key.find("paintkit") != std::string::npos && key.find("tag") != std::string::npos) { skinNames[key] = child->to_key_value()->value.to_string(); } } } for (const auto& rarity : paint_kits_rarity) { if (rarity->to_object()) { for (const auto& child : rarity->children) { if (child->to_key_value()) { std::string paint_kit_name = child->to_key_value()->key.to_string(); std::string paint_kit_rarity = child->to_key_value()->value.to_string(); auto skinInfo = &skinMap[paint_kit_name]; skinInfo->rarity = GetWeaponRarity(paint_kit_rarity); } } } } for (auto weapon : weaponNames) { for (auto skin : weaponSkins[weapon]) { if (skinMap[skin].paintkit < 10000) { paint_kit info; //= &k_skins[skinMap[skin].paintkit]; info.id = skinMap[skin].paintkit; info.weaponName.push_back(weapon); info.name_short = skin; info.name = skin == "cu_m4a4_ancestral" ? "Dragon King" : skinNames[skinMap[skin].tag_name]; info.rarity = skinMap[skin].rarity; if (!skinNames[skinMap[skin].tag_name].empty()) k_skins.push_back(info); } else { paint_kit info; //= //&k_skins[skinMap[skin].paintkit]; info.id = skinMap[skin].paintkit; info.weaponName.push_back(weapon); info.name_short = skin; info.name = skinNames[skinMap[skin].tag_name]; info.rarity = skinMap[skin].rarity; k_gloves.push_back(info); } std::sort(k_gloves.begin(), k_gloves.end()); std::sort(k_skins.begin(), k_skins.end()); } } skins_parsed = true; }
27.797531
169
0.68005
[ "vector", "transform" ]
46a78d338f19837e9ebb42b4a696ba0aa6c6748c
11,507
cpp
C++
samples/crush/src/PlayerSystem.cpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
41
2017-08-29T12:14:36.000Z
2022-02-04T23:49:48.000Z
samples/crush/src/PlayerSystem.cpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
11
2017-09-02T15:32:45.000Z
2021-12-27T13:34:56.000Z
samples/crush/src/PlayerSystem.cpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
5
2020-01-25T17:51:45.000Z
2022-03-01T05:20:30.000Z
/*----------------------------------------------------------------------- Matt Marchant 2021 http://trederia.blogspot.com crogine application - Zlib license. This software is provided 'as-is', without any express or implied warranty.In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions : 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. -----------------------------------------------------------------------*/ #include "PlayerSystem.hpp" #include "CommonConsts.hpp" #include "ServerPacketData.hpp" #include "Messages.hpp" #include "GameConsts.hpp" #include "Collision.hpp" #include "DebugDraw.hpp" #include "AvatarScaleSystem.hpp" #include <crogine/ecs/Scene.hpp> #include <crogine/ecs/components/Transform.hpp> #include <crogine/ecs/components/DynamicTreeComponent.hpp> #include <crogine/ecs/systems/DynamicTreeSystem.hpp> #include <crogine/util/Network.hpp> #include <crogine/util/Maths.hpp> #include <crogine/util/Easings.hpp> PlayerSystem::PlayerSystem(cro::MessageBus& mb) : cro::System (mb, typeid(PlayerSystem)) { requireComponent<Player>(); requireComponent<cro::Transform>(); m_playerStates[Player::State::Falling] = std::make_unique<PlayerStateFalling>(); m_playerStates[Player::State::Walking] = std::make_unique<PlayerStateWalking>(); m_playerStates[Player::State::Teleport] = std::make_unique<PlayerStateTeleport>(); m_playerStates[Player::State::Dead] = std::make_unique<PlayerStateDead>(); m_playerStates[Player::State::Reset] = std::make_unique<PlayerStateReset>(); m_playerStates[Player::State::Spectate] = std::make_unique<PlayerStateSpectate>(); } //public void PlayerSystem::handleMessage(const cro::Message& msg) { } void PlayerSystem::process(float) { auto& entities = getEntities(); for (auto entity : entities) { processInput(entity); } } void PlayerSystem::reconcile(cro::Entity entity, const PlayerUpdate& update) { if (entity.isValid()) { auto& tx = entity.getComponent<cro::Transform>(); auto& player = entity.getComponent<Player>(); //apply position/rotation from server tx.setPosition(cro::Util::Net::decompressVec3(update.position)); tx.setRotation(cro::Util::Net::decompressQuat(update.rotation)); update.unpack(player); //rewind player's last input to timestamp and //re-process all succeeding events auto lastIndex = player.lastUpdatedInput; while (player.inputStack[lastIndex].timeStamp > update.timestamp) { lastIndex = (lastIndex + (Player::HistorySize - 1)) % Player::HistorySize; if (player.inputStack[lastIndex].timeStamp == player.inputStack[player.lastUpdatedInput].timeStamp) { //we've looped all the way around so the requested timestamp must //be too far in the past... have to skip this update //setting the resync flag temporarily ignores input //so that the client remains in place until the next update comes //in to guarantee input/position etc match player.waitResync = true; cro::Logger::log("Requested timestamp too far in the past... potential desync!", cro::Logger::Type::Warning); return; } } player.lastUpdatedInput = lastIndex; const auto& lastInput = player.inputStack[player.lastUpdatedInput]; if (lastInput.buttonFlags == 0) { player.waitResync = false; } processInput(entity); } } //private void PlayerSystem::processInput(cro::Entity entity) { auto& player = entity.getComponent<Player>(); player.collisionLayer; //update all the inputs until 1 before next //free input. Remember to take into account //the wrap around of the indices //auto lastIdx = (player.nextFreeInput + (Player::HistorySize - 2)) % Player::HistorySize; //player.previousInputFlags = player.inputStack[lastIdx].buttonFlags; //adjust for correct value auto lastIdx = (player.nextFreeInput + (Player::HistorySize - 1)) % Player::HistorySize; while (player.lastUpdatedInput != lastIdx) { auto lastState = player.state; m_playerStates[player.state]->processMovement(entity, player.inputStack[player.lastUpdatedInput], *getScene()); processCollision(entity, player.state); if (lastState != player.state) { //raise a message to say something happened auto* msg = postMessage<PlayerEvent>(MessageID::PlayerMessage); msg->player = entity; switch (player.state) { default: break; case Player::State::Teleport: msg->type = PlayerEvent::Teleported; break; case Player::State::Walking: msg->type = PlayerEvent::Landed; break; case Player::State::Falling: if (player.velocity.y > 0) { msg->type = PlayerEvent::Jumped; } else if (lastState == Player::State::Reset) { msg->type = PlayerEvent::Spawned; } break; case Player::State::Reset: msg->type = PlayerEvent::Reset; break; case Player::State::Spectate: msg->type = PlayerEvent::Retired; break; case Player::State::Dead: msg->type = PlayerEvent::Died; break; } } player.lastUpdatedInput = (player.lastUpdatedInput + 1) % Player::HistorySize; } //update the avatar (which in turn is sent to client actors) auto& avatar = player.avatar.getComponent<PlayerAvatar>(); auto targetRotation = cro::Util::Const::PI; targetRotation *= 1 - ((player.direction + 1) / 2); targetRotation += cro::Util::Const::PI * player.collisionLayer; avatar.rotation += cro::Util::Maths::shortestRotation(avatar.rotation, targetRotation) * 20.f * ConstVal::FixedGameUpdate; player.avatar.getComponent<cro::Transform>().setRotation(cro::Transform::Y_AXIS, avatar.rotation); if (avatar.holoEnt.isValid()) { avatar.holoEnt.getComponent<AvatarScale>().target = player.carrying ? 1.f : 0.f; } if (avatar.crateEnt.isValid()) { auto offset = CrateCarryOffset; offset.x *= player.direction; offset.x *= Util::direction(player.collisionLayer); avatar.crateEnt.getComponent<cro::Transform>().setPosition(entity.getComponent<cro::Transform>().getPosition() + offset); } //recharge the punt if this is server side if (!player.local) { player.puntLevelLinear = std::min(Player::PuntCoolDown, player.puntLevelLinear + ConstVal::FixedGameUpdate); player.puntLevel = cro::Util::Easing::easeInQuint(player.puntLevelLinear / Player::PuntCoolDown) * Player::PuntCoolDown; } //do some basic bounds checking in case we escape the map if (entity.getComponent<cro::Transform>().getPosition().y < -1) { player.state = Player::State::Dead; auto* msg = postMessage<PlayerEvent>(MessageID::PlayerMessage); msg->player = entity; msg->type = PlayerEvent::Died; } } void PlayerSystem::processCollision(cro::Entity entity, std::uint32_t playerState) { //do broadphase pass then send results to specific state for processing auto& player = entity.getComponent<Player>(); player.collisionFlags = 0; auto position = entity.getComponent<cro::Transform>().getPosition(); auto bb = PlayerBounds; bb += position; auto& collisionComponent = entity.getComponent<CollisionComponent>(); //adjust crate rect for direction auto crateOffset = CrateCarryOffset; crateOffset.x *= player.direction * Util::direction(player.collisionLayer); auto crateArea = CrateArea; crateArea.left += crateOffset.x; crateArea.bottom += crateOffset.y; collisionComponent.rects[2].bounds = crateArea; auto bounds2D = collisionComponent.sumRect; bounds2D.left += position.x; bounds2D.bottom += position.y; std::vector<cro::Entity> collisions; //broadphase auto entities = getScene()->getSystem<cro::DynamicTreeSystem>()->query(bb, player.collisionLayer + 1); for (auto e : entities) { //make sure we skip our own ent if (e != entity) { auto otherPos = e.getComponent<cro::Transform>().getPosition(); auto otherBounds = e.getComponent<CollisionComponent>().sumRect; otherBounds.left += otherPos.x; otherBounds.bottom += otherPos.y; if (otherBounds.intersects(bounds2D)) { collisions.push_back(e); } } } #ifdef CRO_DEBUG_ if (entity.hasComponent<DebugInfo>()) { auto& db = entity.getComponent<DebugInfo>(); db.nearbyEnts = static_cast<std::int32_t>(entities.size()); db.collidingEnts = static_cast<std::int32_t>(collisions.size()); db.bounds = bb; } #endif m_playerStates[playerState]->processCollision(entity, collisions); //if the collision changed the player state, update the collision //again using the new result if (player.state != playerState) { player.collisionFlags = 0; m_playerStates[player.state]->processCollision(entity, collisions); } } std::uint8_t PlayerUpdate::getPlayerID() const { return (bitfield & 0x03); } //packs/unpacks player data in the the update struct void PlayerUpdate::pack(const Player& player) { velocity = cro::Util::Net::compressVec3(player.velocity); timestamp = player.inputStack[player.lastUpdatedInput].timeStamp; prevInputFlags = player.previousInputFlags; collisionFlags = player.collisionFlags; puntLevel = static_cast<std::uint8_t>(255.f * (player.puntLevel / Player::PuntCoolDown)); state = player.state; bitfield = player.id; bitfield |= ((player.collisionLayer & 0x01) << 2); if (player.direction == Player::Direction::Right) { bitfield |= DirectionBit; } if (player.carrying) { bitfield |= CarryBit; } } void PlayerUpdate::unpack(Player& player) const { player.velocity = cro::Util::Net::decompressVec3(velocity); //set the state player.previousInputFlags = prevInputFlags; player.collisionFlags = collisionFlags; player.puntLevel = (static_cast<float>(puntLevel) / 255.f) * Player::PuntCoolDown; player.state = state; player.collisionLayer = (bitfield & LayerBit) >> 2; player.direction = (bitfield & DirectionBit) ? Player::Right : Player::Left; player.carrying = (bitfield & CarryBit) != 0; }
34.452096
129
0.646215
[ "vector", "transform" ]
9e4e10a2d6942db0f9aa27661900102f11660396
2,042
cpp
C++
out/production/leetcode/io/github/zhengyhn/leetcode/combination_sum_ii/combination-sum-ii.cpp
zhengyhn/leetcode
2e5e618dd7c964c8e983b187c6b1762cbe1764de
[ "MIT" ]
null
null
null
out/production/leetcode/io/github/zhengyhn/leetcode/combination_sum_ii/combination-sum-ii.cpp
zhengyhn/leetcode
2e5e618dd7c964c8e983b187c6b1762cbe1764de
[ "MIT" ]
null
null
null
out/production/leetcode/io/github/zhengyhn/leetcode/combination_sum_ii/combination-sum-ii.cpp
zhengyhn/leetcode
2e5e618dd7c964c8e983b187c6b1762cbe1764de
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <set> using namespace std; class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<int> stack; vector<vector<int>> ret; if (candidates.size() == 0) { return ret; } std::sort(candidates.begin(), candidates.end()); stack.push_back(-1); int sum = 0; int back = stack.back(); while (!stack.empty()) { for (int i = back + 1; i < candidates.size(); ++i) { sum += candidates[i]; stack.push_back(i); // std::cout << "value:" << candidates[i] << " " << sum << std::endl; if (sum == target) { vector<int> temp(stack.size() - 1); for (int j = 1; j < stack.size(); ++j) { temp[j - 1] = candidates[stack[j]]; } int k = 0; for (; k < ret.size(); ++k) { if (temp == ret[k]) { break; } } if (k == ret.size()) { ret.push_back(temp); } break; } else if (sum > target) { sum -= candidates[i]; stack.pop_back(); break; } } if (stack.size() > 0) { back = stack.back(); if (back >= 0) { sum -= candidates[back]; // std::cout << back << " " << candidates[back] << std::endl; } stack.pop_back(); } } return ret; } }; int main() { Solution sln; vector<vector<int>> ret; vector<int> candidates; candidates = {2,5,1,1,2,3,3,3,1,2,2}; ret = sln.combinationSum2(candidates, 5); // candidates = {2,5,2,1,2}; // ret = sln.combinationSum2(candidates, 5); // candidates = {10,1,2,7,6,1,5}; // ret = sln.combinationSum2(candidates, 8); for (vector<int> row: ret) { for (int col: row) { std::cout << col << " "; } std::cout << std::endl; } return 0; }
25.525
79
0.459354
[ "vector" ]
9e4e21c07551298a25999a9b61c8b22a284e331f
7,208
cpp
C++
scene-window-system/WmiAccess.cpp
dpw901e17/Direct3D12-Application
c4d3cb992c7fea3f577e645f7879cd1a0fd21776
[ "MIT" ]
null
null
null
scene-window-system/WmiAccess.cpp
dpw901e17/Direct3D12-Application
c4d3cb992c7fea3f577e645f7879cd1a0fd21776
[ "MIT" ]
null
null
null
scene-window-system/WmiAccess.cpp
dpw901e17/Direct3D12-Application
c4d3cb992c7fea3f577e645f7879cd1a0fd21776
[ "MIT" ]
null
null
null
#include "WmiAccess.h" void WMIAccessor::Connect(const bstr_t & wmiNamespace) { HRESULT hres; // Step 1: -------------------------------------------------- // Initialize COM. ------------------------------------------ hres = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hres)) { std::string msg = "Failed to initialize COM library. Error code = " + hres; throw std::runtime_error(msg); CoUninitialize(); } // Step 3: --------------------------------------------------- // Obtain the initial locator to WMI ------------------------- hres = CoCreateInstance( CLSID_WbemLocator, // CLSID associated with data and code used to create the object. 0, // pointer to the aggregate object IUnknown interface (can be NULL) CLSCTX_INPROC_SERVER, // makes sure this process runs in our c++ context IID_IWbemLocator, // Interface of output parameter (LPVOID *)&pLoc); // OUTPUT: Pointer to pointer to data if (FAILED(hres)) { std::string msg = "Failed to create IWbemLocator object. Err code = " + hres; throw std::runtime_error(msg); CoUninitialize(); } // Step 4: ----------------------------------------------------- // Connect to WMI through the IWbemLocator::ConnectServer method // Connect to the root\cimv2 namespace with // the current user and obtain pointer pSvc // to make IWbemServices calls. hres = pLoc->ConnectServer( _bstr_t("ROOT\\" + wmiNamespace), // Object path of WMI namespace NULL, // User name. NULL = current user NULL, // User password. NULL = current 0, // Locale. NULL indicates current NULL, // Security flags. 0, // Authority (for example, Kerberos) 0, // Context object &pSvc // pointer to IWbemServices proxy ); if (FAILED(hres)) { std::string msg = "Could not connect. Error code = " + hres; throw std::runtime_error(msg); pLoc->Release(); CoUninitialize(); } } WMIAccessor::~WMIAccessor() { if (pSvc) { pSvc->Release(); } if (pLoc) { pLoc->Release(); } CoUninitialize(); } std::wstring WMIAccessor::Query(const bstr_t & wmiClass, const bstr_t wmiProperties[], int arrayCount) { // Step 6: -------------------------------------------------- // Use the IWbemServices pointer to make requests of WMI ---- // For example, get the name of the operating system HRESULT hres; IEnumWbemClassObject* pEnumerator = NULL; bstr_t query = "SELECT "; bool isFirstRun = true; for (auto i = 0; i < arrayCount; ++i) { if (!isFirstRun) { query += ", "; } else { isFirstRun = false; } query += wmiProperties[i]; } query += " FROM " + wmiClass; hres = pSvc->ExecQuery( bstr_t("WQL"), bstr_t(query), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator); if (FAILED(hres)) { std::string msg = "Query for operating system name failed. Error code = " + hres; throw std::runtime_error(msg); pSvc->Release(); pLoc->Release(); CoUninitialize(); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- IWbemClassObject *pclsObj = NULL; std::wstring result; ULONG uReturn = 0; while (pEnumerator) { HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) { break; } // Get the value of the Identifier property _variant_t vtProp; isFirstRun = true; for (auto i = 0; i < arrayCount; ++i) { auto p = wmiProperties[i]; hr = pclsObj->Get(p, 0, &vtProp, 0, //<--- CIM_EMPTY 0); //force type to be BSTR (if actual value is a number n, then this call makes it "n") vtProp.ChangeType(VT_BSTR); //append WMIA_OUTPUT_SEPERATOR only if we had previous data in result if (!isFirstRun) { result += WMIA_OUTPUT_SEPARATOR; } isFirstRun = false; result += vtProp.bstrVal; isFirstRun = false; VariantClear(&vtProp); } pclsObj->Release(); result += L"\n"; } pEnumerator->Release(); return result; } std::vector<WMIDataItem> WMIAccessor::QueryItem(const bstr_t & wmiClass, const bstr_t wmiProperties[], const int arrayCount) { std::vector<WMIDataItem> result; // Step 6: -------------------------------------------------- // Use the IWbemServices pointer to make requests of WMI ---- // For example, get the name of the operating system HRESULT hres; IEnumWbemClassObject* pEnumerator = NULL; bstr_t query = "SELECT "; bool isFirstRun = true; for (auto i = 0; i < arrayCount; ++i) { if (!isFirstRun) { query += ", "; } else { isFirstRun = false; } query += wmiProperties[i]; } query += " FROM " + wmiClass; hres = pSvc->ExecQuery( bstr_t("WQL"), bstr_t(query), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator); if (FAILED(hres)) { std::string msg = "Query for operating system name failed. Error code = " + hres; throw std::runtime_error(msg); pSvc->Release(); pLoc->Release(); CoUninitialize(); } // Step 7: ------------------------------------------------- // Get the data from the query in step 6 ------------------- IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; while (pEnumerator) { HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) { break; } std::vector<std::string> propertyData; // Get the value of the Identifier property _variant_t vtProp; for (auto i = 0; i < arrayCount; ++i) { auto p = wmiProperties[i]; hr = pclsObj->Get(p, 0, &vtProp, 0, //<--- CIM_EMPTY 0); //force type to be BSTR (if actual value is a number n, then this call makes it "n") vtProp.ChangeType(VT_BSTR); std::string propertyDataVal = _bstr_t(vtProp.bstrVal); propertyData.push_back(propertyDataVal); VariantClear(&vtProp); } pclsObj->Release(); WMIDataItem item; Arrange_OHM_Data(propertyData.data(), &item); result.push_back(item); } pEnumerator->Release(); return result; } //Determines how the cells (items) in the database look (name = attribute/collumn in db, value = entry in cell) void Arrange_OHM_Data(const std::string* dataArr, WMIDataItem* item) { /* dataArr[0] is Identifyer (when called in this main). dataArr[1] is Value dataArr[2] is SensorType Since Identifyer has the general structure "/[component]/[compId]/[sensorType]/[sensorId]", then this can be split into db collumns (parts) like: [component] | [compId] | [sensorId] */ //split Identifyer up as described above: std::vector<std::string> parts; std::string part = ""; for (char c : dataArr[0]) { if (c == '/') { if (part != "") { parts.push_back(part); part = ""; } } else { part += c; } } //add the last identifyed part: parts.push_back(part); item->ComponentType = parts[0]; //some identifiers (/ram/data/[id]) only have 3 parts to them (missing the ComponentID) if (parts.size() % 4 == 0) { item->ComponentID = parts[1]; } else { item->ComponentID = "N/A"; } item->SensorID = parts[parts.size() - 1]; item->Value = dataArr[1]; item->SensorType = dataArr[2]; }
23.632787
124
0.602802
[ "object", "vector" ]
9e61613e251216fae942ebba32659540dbaa0fcf
892
hpp
C++
src/general.hpp
RobertZ2011/qatux
150ec5df6f719a71e603a1aea79a3b3bfbf0667e
[ "BSD-3-Clause" ]
null
null
null
src/general.hpp
RobertZ2011/qatux
150ec5df6f719a71e603a1aea79a3b3bfbf0667e
[ "BSD-3-Clause" ]
null
null
null
src/general.hpp
RobertZ2011/qatux
150ec5df6f719a71e603a1aea79a3b3bfbf0667e
[ "BSD-3-Clause" ]
null
null
null
#ifndef QATUX_GENERAL #define QATUX_GENERAL #include <Eigen/Sparse> #include <Eigen/Dense> #include <Eigen/KroneckerProduct> #include <bitset> #include <cmath> #include <random> #include <assert.h> namespace Qatux { template<typename T = float> using Complex = std::complex<T>; template<typename T = float> using Vector = Eigen::Matrix<Complex<T>, Eigen::Dynamic, 1>; template<typename T = float> using Matrix = Eigen::SparseMatrix<Complex<T>>; int pow2(int exp); void printBin(int N, int BITS); //return |0> template<typename T = float> Vector<T> zero(void); //return |1> template<typename T = float> Vector<T> one(void); template<typename T = float> Matrix<T> identityGate(int NQUBITS); //returns |N> for a space of size NQUBITS template<typename T = float> Vector<T> basis(int N, int NQUBITS); } #endif
21.238095
64
0.663677
[ "vector" ]
9e62dce4140bdd49663ea698e695c261cabc6208
1,067
cpp
C++
leetcode/problems/medium/75-sort-colors.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/medium/75-sort-colors.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/medium/75-sort-colors.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Sort Colors https://leetcode.com/problems/sort-colors/ Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function. Example 1: Input: nums = [2,0,2,1,1,0] Output: [0,0,1,1,2,2] Example 2: Input: nums = [2,0,1] Output: [0,1,2] Example 3: Input: nums = [0] Output: [0] Example 4: Input: nums = [1] Output: [1] Constraints: n == nums.length 1 <= n <= 300 nums[i] is 0, 1, or 2. Follow up: Could you come up with a one-pass algorithm using only constant extra space? */ class Solution { public: void sortColors(vector<int>& nums) { int l = 0, r = nums.size() - 1, i = 0; while(i <= r) { if(nums[i] == 0) swap(nums[l++], nums[i++]); else if(nums[i] == 2) swap(nums[i], nums[r--]); else i++; } } };
21.77551
181
0.618557
[ "vector" ]
9e6552ad79fedb53d8d15a0091f43cca3d6e20ee
16,823
cpp
C++
src/ModularServer/Response.cpp
peterpolidoro/arduino_remote_device
cb6ec7b9c059aba4bec4ea747b36986ca7aa20f8
[ "BSD-3-Clause" ]
1
2017-05-02T10:38:03.000Z
2017-05-02T10:38:03.000Z
src/ModularServer/Response.cpp
peterpolidoro/arduino_remote_device
cb6ec7b9c059aba4bec4ea747b36986ca7aa20f8
[ "BSD-3-Clause" ]
null
null
null
src/ModularServer/Response.cpp
peterpolidoro/arduino_remote_device
cb6ec7b9c059aba4bec4ea747b36986ca7aa20f8
[ "BSD-3-Clause" ]
1
2015-07-13T18:11:03.000Z
2015-07-13T18:11:03.000Z
// ---------------------------------------------------------------------------- // Response.cpp // // // Authors: // Peter Polidoro peter@polidoro.io // ---------------------------------------------------------------------------- #include "Response.h" namespace modular_server { // public void Response::writeResultKey() { // Prevent multiple results in one response if (!result_key_in_response_ && !error_) { result_key_in_response_ = true; json_stream_ptr_->writeKey(constants::result_constant_string); } } void Response::write(Vector<constants::SubsetMemberType> & value, JsonStream::JsonTypes type) { if (error_) { return; } switch (type) { case JsonStream::LONG_TYPE: { Array<long,constants::SUBSET_ELEMENT_COUNT_MAX> subset_elements_array; for (size_t i=0; i<value.size(); ++i) { subset_elements_array.push_back(value[i].l); } json_stream_ptr_->write(subset_elements_array); break; } case JsonStream::DOUBLE_TYPE: { break; } case JsonStream::BOOL_TYPE: { break; } case JsonStream::NULL_TYPE: { break; } case JsonStream::STRING_TYPE: { Array<const ConstantString *,constants::SUBSET_ELEMENT_COUNT_MAX> subset_elements_array; for (size_t i=0; i<value.size(); ++i) { subset_elements_array.push_back(value[i].cs_ptr); } json_stream_ptr_->write(subset_elements_array); break; } case JsonStream::OBJECT_TYPE: { break; } case JsonStream::ARRAY_TYPE: { break; } case JsonStream::ANY_TYPE: { break; } } } void Response::writeNull() { if (error_) { return; } json_stream_ptr_->writeNull(); } void Response::beginObject() { if (error_) { return; } json_stream_ptr_->beginObject(); } void Response::endObject() { if (error_) { return; } json_stream_ptr_->endObject(); } void Response::beginArray() { if (error_) { return; } json_stream_ptr_->beginArray(); } void Response::endArray() { if (error_) { return; } json_stream_ptr_->endArray(); } long Response::pipeFrom(Stream & stream) { if (error_) { return 0; } JsonStream json_stream(stream); return pipeFrom(json_stream); } long Response::pipeFrom(JsonStream & json_stream) { if (error_) { return 0; } if (&(json_stream.getStream()) == &(json_stream_ptr_->getStream())) { return -1; } bool found_eol = false; char c; long chars_piped = 0; long read_tries = 0; while (!found_eol && (read_tries < constants::response_pipe_read_max)) { if (json_stream.available()) { read_tries = 0; c = json_stream.readChar(); if (c >= 0) { if (c != JsonStream::EOL) { json_stream_ptr_->writeChar(c); chars_piped++; } else { found_eol = true; } } } else { ++read_tries; } } if (found_eol) { return chars_piped; } else { return -1; } } bool Response::error() { return error_; } // private Response::Response() { json_stream_ptr_ = NULL; reset(); } void Response::reset() { error_ = false; result_key_in_response_ = false; } void Response::setJsonStream(JsonStream & json_stream) { json_stream_ptr_ = &json_stream; } void Response::begin() { reset(); beginObject(); } void Response::end() { if (!error_ && !result_key_in_response_) { writeNull(constants::result_constant_string); } error_ = false; endObject(); json_stream_ptr_->writeNewline(); } void Response::setCompactPrint() { json_stream_ptr_->setCompactPrint(); } void Response::setPrettyPrint() { json_stream_ptr_->setPrettyPrint(); } void Response::returnRequestParseError(const char * const request) { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::parse_error_message); write(constants::data_constant_string,request); write(constants::code_constant_string,constants::parse_error_code); endObject(); error_ = true; } } void Response::returnParameterCountError(size_t parameter_count, size_t parameter_count_needed) { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::invalid_params_error_message); char incorrect_parameter_number_str[constants::incorrect_parameter_number_error_data.length()+1]; incorrect_parameter_number_str[0] = '\0'; constants::incorrect_parameter_number_error_data.copy(incorrect_parameter_number_str); char error_str[constants::STRING_LENGTH_ERROR]; error_str[0] = '\0'; strcat(error_str,incorrect_parameter_number_str); char parameter_count_str[constants::STRING_LENGTH_PARAMETER_COUNT]; parameter_count_str[0] = '\0'; dtostrf(parameter_count,0,0,parameter_count_str); strcat(error_str,parameter_count_str); char given_str[constants::given_constant_string.length()+1]; given_str[0] = '\0'; constants::given_constant_string.copy(given_str); strcat(error_str,given_str); dtostrf(parameter_count_needed,0,0,parameter_count_str); strcat(error_str,parameter_count_str); char needed_str[constants::needed_constant_string.length()+1]; needed_str[0] = '\0'; constants::needed_constant_string.copy(needed_str); strcat(error_str,needed_str); write(constants::data_constant_string,error_str); write(constants::code_constant_string,constants::invalid_params_error_code); endObject(); error_ = true; } } void Response::returnMethodNotFoundError() { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::method_not_found_error_message); write(constants::code_constant_string,constants::method_not_found_error_code); endObject(); error_ = true; } } void Response::returnParameterNotFoundError() { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::invalid_params_error_message); write(constants::data_constant_string,constants::parameter_not_found_error_data); write(constants::code_constant_string,constants::invalid_params_error_code); endObject(); error_ = true; } } void Response::returnParameterIncorrectTypeError(const ConstantString & parameter_name) { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::invalid_params_error_message); char parameter_name_str[parameter_name.length()+1]; parameter_name_str[0] = '\0'; parameter_name.copy(parameter_name_str); char parameter_incorrect_type_error_str[constants::parameter_incorrect_type_error_data.length()+1]; parameter_incorrect_type_error_str[0] = '\0'; constants::parameter_incorrect_type_error_data.copy(parameter_incorrect_type_error_str); char error_str[constants::STRING_LENGTH_ERROR]; error_str[0] = '\0'; strcat(error_str,parameter_name_str); strcat(error_str,parameter_incorrect_type_error_str); write(constants::data_constant_string,error_str); write(constants::code_constant_string,constants::invalid_params_error_code); endObject(); error_ = true; } } void Response::returnParameterArrayLengthError(const ConstantString & parameter_name, const char * const min_str, const char * const max_str) { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::invalid_params_error_message); char error_str[constants::STRING_LENGTH_ERROR]; error_str[0] = '\0'; constants::array_parameter_length_error_error_data.copy(error_str); char value_not_in_range_str[constants::value_not_in_range_error_data.length() + 1]; constants::value_not_in_range_error_data.copy(value_not_in_range_str); strcat(error_str,value_not_in_range_str); strcat(error_str,min_str); char less_than_equal_str[constants::less_than_equal_constant_string.length()+1]; less_than_equal_str[0] = '\0'; constants::less_than_equal_constant_string.copy(less_than_equal_str); strcat(error_str,less_than_equal_str); char parameter_name_str[parameter_name.length()+1]; parameter_name_str[0] = '\0'; parameter_name.copy(parameter_name_str); strcat(error_str,parameter_name_str); char array_length_str[constants::array_length_spaces_constant_string.length()+1]; array_length_str[0] = '\0'; constants::array_length_spaces_constant_string.copy(array_length_str); strcat(error_str,array_length_str); strcat(error_str,less_than_equal_str); strcat(error_str,max_str); write(constants::data_constant_string,error_str); write(constants::code_constant_string,constants::invalid_params_error_code); endObject(); error_ = true; } } void Response::returnParameterInvalidError(const ConstantString & error) { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::invalid_params_error_message); write(constants::data_constant_string,error); write(constants::code_constant_string,constants::invalid_params_error_code); endObject(); error_ = true; } } void Response::returnParameterNotInSubsetError(const char * const subset_str, const JsonStream::JsonTypes & parameter_type) { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::invalid_params_error_message); char error_str[constants::STRING_LENGTH_ERROR]; error_str[0] = '\0'; if (parameter_type != JsonStream::ARRAY_TYPE) { constants::parameter_error_error_data.copy(error_str); } else { constants::array_parameter_error_error_data.copy(error_str); } char value_not_in_subset_str[constants::value_not_in_subset_error_data.length() + 1]; value_not_in_subset_str[0] = '\0'; constants::value_not_in_subset_error_data.copy(value_not_in_subset_str); strcat(error_str,value_not_in_subset_str); size_t length_left = constants::STRING_LENGTH_ERROR - strlen(error_str) - 1; strncat(error_str,subset_str,length_left); write(constants::data_constant_string,error_str); write(constants::code_constant_string,constants::invalid_params_error_code); endObject(); error_ = true; } } void Response::returnParameterNotInRangeError(const ConstantString & parameter_name, const JsonStream::JsonTypes & parameter_type, const char * const min_str, const char * const max_str) { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::invalid_params_error_message); char error_str[constants::STRING_LENGTH_ERROR]; error_str[0] = '\0'; if (parameter_type != JsonStream::ARRAY_TYPE) { constants::parameter_error_error_data.copy(error_str); } else { constants::array_parameter_error_error_data.copy(error_str); } char value_not_in_range_str[constants::value_not_in_range_error_data.length() + 1]; value_not_in_range_str[0] = '\0'; constants::value_not_in_range_error_data.copy(value_not_in_range_str); strcat(error_str,value_not_in_range_str); strcat(error_str,min_str); char less_than_equal_str[constants::less_than_equal_constant_string.length()+1]; less_than_equal_str[0] = '\0'; constants::less_than_equal_constant_string.copy(less_than_equal_str); strcat(error_str,less_than_equal_str); char parameter_name_str[parameter_name.length()+1]; parameter_name_str[0] = '\0'; parameter_name.copy(parameter_name_str); strcat(error_str,parameter_name_str); if (parameter_type == JsonStream::ARRAY_TYPE) { char element_str[constants::element_constant_string.length()+1]; element_str[0] = '\0'; constants::element_constant_string.copy(element_str); strcat(error_str,element_str); } strcat(error_str,less_than_equal_str); strcat(error_str,max_str); write(constants::data_constant_string,error_str); write(constants::code_constant_string,constants::invalid_params_error_code); endObject(); error_ = true; } } void Response::returnPropertyFunctionNotFoundError() { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::property_function_not_found_error_data); write(constants::code_constant_string,constants::invalid_params_error_code); endObject(); error_ = true; } } void Response::returnPropertyParameterCountError(size_t parameter_count, size_t parameter_count_needed) { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::invalid_params_error_message); char incorrect_parameter_number_str[constants::incorrect_parameter_number_error_data.length()+1]; incorrect_parameter_number_str[0] = '\0'; constants::incorrect_property_parameter_number_error_data.copy(incorrect_parameter_number_str); char error_str[constants::STRING_LENGTH_ERROR]; error_str[0] = '\0'; strcat(error_str,incorrect_parameter_number_str); char parameter_count_str[constants::STRING_LENGTH_PARAMETER_COUNT]; parameter_count_str[0] = '\0'; dtostrf(parameter_count,0,0,parameter_count_str); strcat(error_str,parameter_count_str); char given_str[constants::given_constant_string.length()+1]; given_str[0] = '\0'; constants::given_constant_string.copy(given_str); strcat(error_str,given_str); dtostrf(parameter_count_needed,0,0,parameter_count_str); strcat(error_str,parameter_count_str); char needed_str[constants::needed_constant_string.length()+1]; needed_str[0] = '\0'; constants::needed_constant_string.copy(needed_str); strcat(error_str,needed_str); write(constants::data_constant_string,error_str); write(constants::code_constant_string,constants::invalid_params_error_code); endObject(); error_ = true; } } void Response::returnCallbackFunctionNotFoundError() { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::callback_function_not_found_error_data); write(constants::code_constant_string,constants::invalid_params_error_code); endObject(); error_ = true; } } void Response::returnCallbackParameterCountError(size_t parameter_count, size_t parameter_count_needed) { // Prevent multiple errors in one response if (!error_) { writeKey(constants::error_constant_string); beginObject(); write(constants::message_constant_string,constants::invalid_params_error_message); char incorrect_parameter_number_str[constants::incorrect_parameter_number_error_data.length()+1]; incorrect_parameter_number_str[0] = '\0'; constants::incorrect_callback_parameter_number_error_data.copy(incorrect_parameter_number_str); char error_str[constants::STRING_LENGTH_ERROR]; error_str[0] = '\0'; strcat(error_str,incorrect_parameter_number_str); char parameter_count_str[constants::STRING_LENGTH_PARAMETER_COUNT]; parameter_count_str[0] = '\0'; dtostrf(parameter_count,0,0,parameter_count_str); strcat(error_str,parameter_count_str); char given_str[constants::given_constant_string.length()+1]; given_str[0] = '\0'; constants::given_constant_string.copy(given_str); strcat(error_str,given_str); dtostrf(parameter_count_needed,0,0,parameter_count_str); strcat(error_str,parameter_count_str); char needed_str[constants::needed_constant_string.length()+1]; needed_str[0] = '\0'; constants::needed_constant_string.copy(needed_str); strcat(error_str,needed_str); write(constants::data_constant_string,error_str); write(constants::code_constant_string,constants::invalid_params_error_code); endObject(); error_ = true; } } }
29.105536
103
0.723652
[ "vector" ]
9e7698842f9801ffbf0bbaf844b4a3cf06f92cb2
15,813
cpp
C++
demo.cpp
ahhz/resumable_dijkstra
1fa57b7de5dd9ce9a23f146b709f7cb76cdf01d1
[ "BSL-1.0" ]
1
2015-11-18T15:55:43.000Z
2015-11-18T15:55:43.000Z
demo.cpp
ahhz/resumable_dijkstra
1fa57b7de5dd9ce9a23f146b709f7cb76cdf01d1
[ "BSL-1.0" ]
null
null
null
demo.cpp
ahhz/resumable_dijkstra
1fa57b7de5dd9ce9a23f146b709f7cb76cdf01d1
[ "BSL-1.0" ]
null
null
null
// //======================================================================= // Copyright 2012-2104 // Author: Alex Hagen-Zanker // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= // // Demonstrates different ways of using the resumable dijkstra classes // //======================================================================= // #include <blink/graph/resumable_dijkstra.hpp> #include <blink/graph/dijkstra_object.hpp> #include <blink/graph/dijkstra_functions.hpp> #include <blink/graph/dijkstra_state.hpp> #include <blink/graph/dijkstra_heap_wrapper.hpp> #include <blink/graph/dijkstra_visitor/distance_visitor.hpp> #include <blink/graph/dijkstra_visitor/joined_visitor.hpp> #include <blink/graph/dijkstra_visitor/logging_visitor.hpp> #include <blink/graph/dijkstra_visitor/target_visitor.hpp> #include <blink/graph/dijkstra_visitor/nearest_source_visitor.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/iteration_macros.hpp> #include <boost/graph/properties.hpp> #include <boost/heap/d_ary_heap.hpp> #include <boost/ref.hpp> #include <iostream> #include <vector> template<typename Graph, typename DistanceMap, typename ColorMap> void report_progress(const Graph& g, DistanceMap d, ColorMap c) { std::cout <<"Vertex" <<'\t' << "Color" <<'\t' << "Distance" << std::endl; BGL_FORALL_VERTICES_T(v, g, Graph) { std::cout << v <<'\t' << get(c,v) <<'\t' << get(d,v) << std::endl; } std::cout << std::endl; } template<typename Graph, typename DistanceMap, typename ColorMap, typename NearestMap> void report_progress(const Graph& g, DistanceMap d, ColorMap c, NearestMap n) { std::cout <<"Vertex" <<'\t' << "Color" <<'\t' << "Distance" << std::endl; BGL_FORALL_VERTICES_T(v, g, Graph) { std::cout << v <<'\t' << get(c,v) <<'\t' << get(d,v) <<'\t' << get(n,v) << std::endl; } std::cout << std::endl; } typedef boost::property<boost::edge_weight_t, double> edge_prop; typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, edge_prop> graph_type; typedef boost::graph_traits<graph_type>::vertex_descriptor vertex_descriptor; typedef boost::property_map<graph_type, boost::vertex_index_t>::type vertex_index_map_type; typedef boost::shared_array_property_map<vertex_descriptor, vertex_index_map_type> predecessor_map_type; typedef boost::shared_array_property_map<double, vertex_index_map_type> distance_map_type; typedef boost::two_bit_color_map<vertex_index_map_type> color_map_type; graph_type make_a_simple_graph(size_t n) { graph_type g(n); for(size_t i = 0; i < n; ++i) { const vertex_descriptor a = i; const vertex_descriptor b = (i + 1) % n; const double w = 1.0; boost::add_edge(a, b, w, g); boost::add_edge(b, a, w, g); } return g; } void test_target_visitor(int n) { std::cout << "Test Target Visitor" << std::endl; typedef blink::target_helper_indirect<graph_type, boost::no_named_parameters>::visitor_type visitor_type; typedef blink::resumable_dijkstra_helper<graph_type, boost::no_named_parameters>::type dijkstra_type; graph_type g = make_a_simple_graph(n); dijkstra_type dijkstra = blink::make_resumable_dijkstra(g); visitor_type vis = blink::make_target_visitor(dijkstra.get_dijkstra_state()); vis.add_target(3); vis.add_target(6); dijkstra.init_from_source(4, vis); dijkstra_type::param<boost::vertex_distance_t>::type& distance_map = dijkstra.get(boost::vertex_distance_t() ); dijkstra_type::param<boost::vertex_color_t>::type& color_map = dijkstra.get(boost::vertex_color_t() ); dijkstra.expand(vis, vis); // vis doubles as interruptor std::cout << "Must reach targets 3 and 6" << std::endl; report_progress(g, distance_map, color_map); vis.add_target(5); dijkstra.expand(vis, vis); // vis doubles as interruptor std::cout << "Must reach target 5 too" << std::endl; report_progress(g, distance_map, color_map); vis.add_target(8); dijkstra.expand(vis, vis); // vis doubles as interruptor std::cout << "Must reach target 8 too" << std::endl; report_progress(g, distance_map, color_map); dijkstra.expand(); std::cout << "Must reach all targets" << std::endl; report_progress(g, distance_map, color_map); } void test_target_visitor_auto(int n) { std::cout << "Test Target Visitor" << std::endl; auto g = make_a_simple_graph(n); auto dijkstra = blink::make_resumable_dijkstra(g); auto vis = blink::make_target_visitor(dijkstra.get_dijkstra_state()); vis.add_target(3); vis.add_target(6); dijkstra.init_from_source(4, vis); dijkstra.expand(vis,vis ); // vis doubles as interruptor auto distance_map = dijkstra.get(boost::vertex_distance_t()); auto color_map = dijkstra.get(boost::vertex_color_t()); report_progress(g, distance_map, color_map); vis.add_target(5); dijkstra.expand(vis, vis); // vis doubles as interruptor report_progress(g, distance_map, color_map); vis.add_target(8); dijkstra.expand(vis, vis); // vis doubles as interruptor report_progress(g, distance_map, color_map); dijkstra.expand(); report_progress(g, distance_map, color_map); } void test_target_visitor_convenience(int n) { std::cout << "Test Target Visitor - Convenience" << std::endl; graph_type g = make_a_simple_graph(n); distance_map_type distance(n, get(boost::vertex_index_t(), g) ); color_map_type color(n, get(boost::vertex_index_t(), g) ); std::vector<int> targets; targets.push_back(5); targets.push_back(6); vertex_descriptor orig = 4; blink::dijkstra_shortest_path_targets(g, orig, targets, distance_map(distance).color_map(color) ); report_progress(g, distance, color); } void test_nearest_visitor(int n) { std::cout << "Test Nearest Visitor" << std::endl; typedef blink::nearest_source_helper_indirect<graph_type, boost::no_named_parameters>::visitor_type visitor_type; typedef blink::resumable_dijkstra_helper<graph_type, boost::no_named_parameters>::type dijkstra_type; graph_type g = make_a_simple_graph(n); dijkstra_type dijkstra = blink::make_resumable_dijkstra(g); visitor_type vis = blink::make_nearest_source_visitor(dijkstra.get_dijkstra_state()); std::vector<vertex_descriptor> sources; sources.push_back(4); sources.push_back(7); sources.push_back(11); dijkstra.init_from_sources(sources, vis); dijkstra.expand(blink::default_interruptor(), vis); dijkstra_type::param<boost::vertex_distance_t>::type distance_map = dijkstra.get(boost::vertex_distance_t() ); dijkstra_type::param<boost::vertex_color_t>::type color_map = dijkstra.get(boost::vertex_color_t() ); report_progress(g, distance_map, color_map, vis.m_nearest_source_map); } void test_nearest_visitor_convenience(int n) { std::cout << "Test Nearest Visitor - Convenience Function" << std::endl; graph_type g = make_a_simple_graph(n); typedef blink::dijkstra_state_helper<graph_type, boost::no_named_parameters>::type state_type; typedef blink::nearest_source_helper<state_type>::visitor_type visitor_type; typedef blink::nearest_source_helper<state_type>::map_type map_type; std::vector<vertex_descriptor> sources; sources.push_back(4); sources.push_back(7); sources.push_back(11); std::pair<state_type, visitor_type> result = blink::dijkstra_shortest_path_nearest_source(g, sources); state_type::param<boost::vertex_distance_t>::type distance_map = result.first.get<boost::vertex_distance_t>(); state_type::param<boost::vertex_color_t>::type color_map = result.first.get<boost::vertex_color_t>(); report_progress(g, distance_map, color_map, result.second.m_nearest_source_map); } void test_distance_visitor(int n) { typedef blink::resumable_dijkstra_helper<graph_type, boost::no_named_parameters>::type dijkstra_type; typedef blink::distance_visitor_helper_indirect<graph_type, boost::no_named_parameters> helper; typedef helper::type visitor_type; std::cout << "Test Distance Visitor" << std::endl; graph_type g = make_a_simple_graph(n); double first_target_distance = 2.0; double second_target_distance = 4.0; dijkstra_type dijkstra = blink::make_resumable_dijkstra(g); visitor_type visitor = helper::make(dijkstra.get_dijkstra_state(), first_target_distance); vertex_descriptor orig = 4; dijkstra.init_from_source(orig, visitor); dijkstra.expand(visitor, visitor); // vis doubles as interrupetor dijkstra_type::param<boost::vertex_distance_t>::type distance_map = dijkstra.get(boost::vertex_distance_t() ); dijkstra_type::param<boost::vertex_color_t>::type color_map = dijkstra.get(boost::vertex_color_t() ); std::cout << "must reach distance 2" << std::endl; report_progress(g, distance_map, color_map); visitor_type second_visitor = helper::make(dijkstra.get_dijkstra_state(), second_target_distance); dijkstra.expand(second_visitor, second_visitor); // now secondvis is the interruptor std::cout << "must reach distance 4" << std::endl; report_progress(g, distance_map, color_map); } void test_classic_boost(int n) { std::cout << "Test Classic Boost(note the faulty colormap)" << std::endl; graph_type g = make_a_simple_graph(n); distance_map_type distance(n, get(boost::vertex_index, g)); color_map_type color(n, get(boost::vertex_index, g) ); vertex_descriptor orig = 4; boost::dijkstra_shortest_paths(g, orig, distance_map(distance).color_map(color)); report_progress(g, distance, color); } void test_classic_blink(int n) { std::cout << "Test Classic Blink" << std::endl; graph_type g = make_a_simple_graph(n); typedef blink::dijkstra_state_helper<graph_type, boost::no_named_parameters>::type state_type; vertex_descriptor orig = 4; state_type state = blink::dijkstra_shortest_path_plain(g, orig); report_progress(g, state.get<boost::vertex_distance_t>(), state.get<boost::vertex_color_t>()); } void test_distance_visitor_convenience(int n) { std::cout << "Test Distance Visitor - Convenience" << std::endl; graph_type g = make_a_simple_graph(n); distance_map_type distance(n, get(boost::vertex_index, g)); color_map_type color(n, get(boost::vertex_index, g) ); double target_distance = 4; vertex_descriptor orig = 4; blink::dijkstra_shortest_path_distance(g, orig, target_distance, distance_map(distance).color_map(color)); std::cout << "must reach distance 4" << std::endl; report_progress(g, distance, color ); } void test_dijkstra_object(int n) { std::cout << "Test Dijkstra Object" << std::endl; graph_type g = make_a_simple_graph(n); typedef std::vector<vertex_descriptor> source_range_type; typedef blink::only_finish_vertex_type control_map_type; typedef boost::no_named_parameters parameters_type; typedef blink::dijkstra_object_helper< graph_type, source_range_type, control_map_type, parameters_type>::type dijkstra_object_type; double target_distance = 4; vertex_descriptor orig = 4; source_range_type sources(1,orig); dijkstra_object_type dijkstra = blink::make_dijkstra_object(g, sources, blink::only_finish_vertex_type()); dijkstra_object_type::param<boost::vertex_distance_t>::type distance_map = dijkstra.get(boost::vertex_distance_t() ); dijkstra_object_type::param<boost::vertex_color_t >::type color_map = dijkstra.get(boost::vertex_color_t() ); while(dijkstra()) { const double distance = get(distance_map, dijkstra.get_u()); if(distance >= target_distance) { break; } } std::cout << "must reach distance " << target_distance << std::endl; report_progress(g, distance_map, color_map ); } void test_dijkstra_object2(int n) { std::cout << "Test Dijkstra Object - yielding at all visitor positions" << std::endl; std::cout << "Every action should be logged twice once by the object and once by the object user" << std::endl; typedef blink::logging_visitor<std::ostream> visitor_type; typedef boost::bgl_named_params<visitor_type, boost::graph_visitor_t> parameters_type; typedef std::vector<vertex_descriptor> source_range_type; typedef blink::dijkstra_visitor_control_point_vector control_map_type; typedef blink::dijkstra_object_helper< graph_type, source_range_type, control_map_type, parameters_type>::type dijkstra_object_type; graph_type g = make_a_simple_graph(n); visitor_type vis(std::cout); vertex_descriptor orig = 4; source_range_type sources(1,orig); dijkstra_object_type dijkstra = blink::make_dijkstra_object(g, sources, control_map_type(), boost::visitor(vis) ); while(dijkstra()) { switch(dijkstra.get_control_point()) { case blink::cp_initialize_vertex: vis.initialize_vertex(dijkstra.get_v(), g); break; case blink::cp_examine_vertex: vis.examine_vertex(dijkstra.get_u(), g); break; case blink::cp_examine_edge: vis.examine_edge(dijkstra.get_e(), g); break; case blink::cp_discover_vertex: vis.discover_vertex(dijkstra.get_v(), g); break; case blink::cp_edge_relaxed: vis.edge_relaxed(dijkstra.get_e(), g); break; case blink::cp_edge_not_relaxed: vis.edge_not_relaxed(dijkstra.get_e(), g); break; case blink::cp_finish_vertex: vis.finish_vertex(dijkstra.get_u(), g); break; default : std::cout << "other control_point" << std::endl; } } } void test_with_boost_heap(int n) { typedef boost::indirect_cmp<distance_map_type, std::greater<double> > indirect_compare; typedef boost::heap::d_ary_heap < vertex_descriptor , boost::heap::compare<indirect_compare> , boost::heap::mutable_<true> , boost::heap::arity<4> , boost::heap::store_parent_pointer<false> , boost::heap::constant_time_size<false> > heap_type; typedef blink::dijkstra_heap_wrapper<heap_type, graph_type, vertex_index_map_type> wrapped_heap_type; typedef boost::bgl_named_params<boost::reference_wrapper<wrapped_heap_type>, boost::max_priority_queue_t, boost::bgl_named_params<distance_map_type, boost::vertex_distance_t> > parameters_type; typedef blink::dijkstra_state_helper<graph_type, parameters_type>::type state_type; graph_type g = make_a_simple_graph(n); vertex_index_map_type index = get(boost::vertex_index, g); distance_map_type distance(n, index); vertex_descriptor orig = 4; wrapped_heap_type heap(g, index, distance); state_type state = blink::dijkstra_shortest_path_plain(g, orig, boost::max_priority_queue(heap).distance_map(distance)); report_progress(g, state.get<boost::vertex_distance_t>(), state.get<boost::vertex_color_t>()); } void test_dijkstra_object3(int n) { std::cout << "Test Dijkstra Object - Simplest Demo" << std::endl; graph_type g = make_a_simple_graph(n); vertex_descriptor orig = 4; std::vector<vertex_descriptor> sources(1, orig); auto dijkstra = blink::make_dijkstra_object(g, sources); while (dijkstra()) { auto v = dijkstra.get_vertex(); auto distance_map = dijkstra.get<boost::vertex_distance_t>(); if (get(distance_map, v) >= 2) break; } report_progress(g, dijkstra.get<boost::vertex_distance_t>(), dijkstra.get<boost::vertex_color_t>()); } int main() { int n = 12; test_target_visitor(n); test_target_visitor_convenience(n); test_distance_visitor(n); test_distance_visitor_convenience(n); test_classic_boost(n); test_classic_blink(n); test_nearest_visitor(n); test_nearest_visitor_convenience(n); test_dijkstra_object(n); test_dijkstra_object2(n); test_dijkstra_object3(n); test_with_boost_heap(n); return 0; }
33.933476
120
0.725669
[ "object", "vector" ]
9e807ed1aa9a4eabc4f3b2230ae60aaa3bdcbb71
1,155
cc
C++
src/Foundational/data_source/tiwds_stdin.cc
michaelweiss092/LillyMol
a2b7d1d8a07ef338c754a0a2e3b2624aac694cc9
[ "Apache-2.0" ]
53
2018-06-01T13:16:15.000Z
2022-02-23T21:04:28.000Z
src/Foundational/data_source/tiwds_stdin.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
19
2018-08-14T13:43:18.000Z
2021-09-24T12:53:11.000Z
src/Foundational/data_source/tiwds_stdin.cc
IanAWatson/LillyMol-4.0-Bazel
f38f23a919c622c31280222f8a90e6ab7d871b93
[ "Apache-2.0" ]
19
2018-10-23T19:41:01.000Z
2022-02-17T08:14:00.000Z
/* Tests the iwstring_data_source object reading from stdin */ #include <stdlib.h> #include "cmdline.h" #include "iwstring_data_source.h" using std::cerr; using std::cout; using std::endl; const char * prog_name = NULL; static int verbose = 0; static void usage (int rc) { cerr << __FILE__ << " compiled " << __DATE__ << " " << __TIME__ << endl; cerr << "$Id$\n"; cerr << "Echo stdin input to stdout\n"; cerr << " -v verbose output\n"; exit (rc); } static int tiwds_stdin (int argc, char ** argv) { Command_Line cl (argc, argv, "v"); if (cl.unrecognised_options_encountered ()) { cerr << "Unrecognised options encountered\n"; usage (1); } verbose = cl.option_count ('v'); if (cl.number_elements ()) cerr << "Command line arguments ignored\n"; iwstring_data_source input ("-"); const_IWSubstring buffer; while (input.next_record (buffer)) { cout << buffer << endl; } if (verbose) cerr << "Read " << input.lines_read () << " lines from stdin\n"; return 0; } int main (int argc, char ** argv) { prog_name = argv[0]; int rc = tiwds_stdin (argc, argv); return rc; }
16.985294
74
0.623377
[ "object" ]
9e8966743963ce267020799a70208b9841e1d612
24,211
hpp
C++
libNCUI/transfer/Transfer.hpp
realmark1r8h/tomoyadeng
aceab8fe403070bc12f9d49fdb7add0feb20424d
[ "BSD-2-Clause" ]
24
2018-11-20T14:45:57.000Z
2021-12-30T13:38:42.000Z
libNCUI/transfer/Transfer.hpp
realmark1r8h/tomoyadeng
aceab8fe403070bc12f9d49fdb7add0feb20424d
[ "BSD-2-Clause" ]
null
null
null
libNCUI/transfer/Transfer.hpp
realmark1r8h/tomoyadeng
aceab8fe403070bc12f9d49fdb7add0feb20424d
[ "BSD-2-Clause" ]
11
2018-11-29T00:09:14.000Z
2021-11-23T08:13:17.000Z
// Created by amoylel on 06/12/2017. // Copyright (c) 2017 amoylel All rights reserved. #ifndef AMO_TRANSFER_HPP__ #define AMO_TRANSFER_HPP__ #include <string> #include <map> #include <amo/json.hpp> #include <amo/stdint.hpp> #include <amo/logger.hpp> #include "ipc/Any.hpp" #include "ipc/IPCMessage.hpp" #include "transfer/FunctionWrapper.hpp" #include "transfer/TransferEventInfo.hpp" #ifndef AMO_CLASS_TRANSFER_DECLARE #define AMO_CLASS_TRANSFER_DECLARE(LIB_API)\ extern "C"{\ LIB_API bool registerTransfer(std::shared_ptr<amo::TransferRegister> info);\ LIB_API void unregisterTransfer();\ LIB_API void removeTransferByName(const std::string& strClass);\ LIB_API void removeTransferByID(const int64_t& nID);\ } #endif #ifndef AMO_CLASS_REGISTER_BEGIN #define AMO_CLASS_REGISTER_BEGIN()\ using namespace amo;\ ClassTransfer::getTransferMap() = info->transferMap;\ int nBrowserID = info->nBrowserID;\ auto fn = info->fnCallback;\ amo::log::register_logger(info->pLogger); \ #endif #ifndef AMO_CLASS_REGISTER #define AMO_CLASS_REGISTER(ClassName) \ {\ auto pTransfer = ClassTransfer::getUniqueTransfer<ClassName>(); \ pTransfer->setModuleName(info->moduleName);\ if (fn) {\ fn(nBrowserID, pTransfer);\ }\ \ }\ #endif #ifndef AMO_CLASS_REGISTER_END #define AMO_CLASS_REGISTER_END()\ return true; #endif #ifndef AMO_UNREGISTER_TRANSFER #define AMO_UNREGISTER_TRANSFER(LIB_API)\ LIB_API void unregisterTransfer(){\ using namespace amo;\ ClassTransfer::getTransferMap().reset();\ return;\ }\ #endif #ifndef AMO_REMOVE_TRANSFER_BY_NAME #define AMO_REMOVE_TRANSFER_BY_NAME(LIB_API)\ LIB_API void removeTransferByName(const std::string& strClassName){\ amo::ClassTransfer::removeTransferByName(strClassName);\ return;\ }\ #endif #ifndef AMO_REMOVE_TRANSFER_BY_ID #define AMO_REMOVE_TRANSFER_BY_ID(LIB_API)\ LIB_API void removeTransferByID(const int64_t& nID){\ amo::ClassTransfer::removeTransfer(nID);\ return;\ }\ #endif #ifndef AMO_REGISTER_TRANSFER_BEGIN #define AMO_REGISTER_TRANSFER_BEGIN(LIB_API)\ AMO_UNREGISTER_TRANSFER(LIB_API)\ AMO_REMOVE_TRANSFER_BY_NAME(LIB_API)\ AMO_REMOVE_TRANSFER_BY_ID(LIB_API)\ LIB_API bool registerTransfer(std::shared_ptr<amo::TransferRegister> info) {\ AMO_CLASS_REGISTER_BEGIN()\ #endif #ifndef AMO_REGISTER_TRANSFER_END #define AMO_REGISTER_TRANSFER_END()\ AMO_CLASS_REGISTER_END()\ }\ #endif // JS函数注册宏 开始 #define AMO_CEF_MESSAGE_TRANSFER_BEGIN(ClassName, BaseClassName)\ virtual void registerFunction(){\ typedef ClassName ClassType;\ typedef BaseClassName BaseClassType;\ // JS函数注册 同名函数 #define AMO_CEF_MESSAGE_TRANSFER_FUNC(Func, nExecType)\ registerTransfer(#Func,\ std::bind(&ClassType::Func, \ this, \ std::placeholders::_1), \ nExecType); #define AMO_CEF_MESSAGE_TRANSFER_ATTR(Func)\ registerAttribute(#Func, Func); #define AMO_CEF_MESSAGE_TRANSFER_ATTR2(Func, VALUE)\ registerAttribute(#Func, VALUE); // JS函数注册宏 结束 #define AMO_CEF_MESSAGE_TRANSFER_END()\ BaseClassType::registerFunction();\ } namespace amo { /*! * @class Transfer * * @brief JS调用C++时消息遍历基类. * 所有的JS对C++的调用都由此类派生 */ class Transfer : public log_object, public std::enable_shared_from_this<Transfer> { public: /*! * @typedef std::function<bool(const std::string&, * IPCMessage::SmartType, amo::IPCResult&)> BerforeResultFunc * * @brief 回传执行结果前的回调函数 */ typedef std::function<bool(const std::string&, IPCMessage::SmartType, amo::IPCResult&)> BerforeResultFunc; public: /*! * @fn template<typename T> std::shared_ptr<T> Transfer::getDerivedClass() * * @brief 获取当前对象的智能指针. * * @tparam T 派生类类型. * * @return 派生类的智能指针. */ template<typename T> std::shared_ptr<T> getDerivedClass() { return std::dynamic_pointer_cast<T>(shared_from_this()); } public: /*! * @fn Transfer::Transfer() * * @brief Default constructor 主要用作类实例的创建类 * (通过这个Transfer创建类对象). */ Transfer() { transferName("Transfer"); m_oFuncMgr.name(transferName()); setWorkOnRenderer(false); //m_bWorkOnRenderer = false; setObjectID(amo::uid::generate_uid()); m_oFuncMgr.setObjectID(getObjectID()); setFuncRegistered(false); setTransferObject(true); m_bReleased = false; } /*! * @fn Transfer::Transfer(const std::string& strName) * * @brief Constructor. * * @param strName Transfer 名称. */ Transfer(const std::string& strName) { transferName(strName); m_oFuncMgr.name(strName); m_bWorkOnRenderer = false; setObjectID(amo::uid::generate_uid()); m_oFuncMgr.setObjectID(getObjectID()); setFuncRegistered(false); setTransferObject(true); m_bReleased = false; } ~Transfer() { /* $cdevel("release transfer:transferName = \"{0}\", objectName = \"{1}\", objectID = {2}", transferName(), getObjectName(), getObjectID());*/ } virtual Any onRelase(IPCMessage::SmartType msg) { return Undefined(); } /** * @fn virtual std::string Transfer::getClass() const * * @brief 获取类名. * * @return The class. */ virtual std::string getClass() const { return "Transfer"; } /** * @fn virtual Transfer* Transfer::getInterface(const std::string& name) * * @brief 通过类开获取接口. * * @param name The name. * * @return null if it fails, else the interface. */ virtual Transfer* getInterface(const std::string& name) { if (name == Transfer::getClass()) { return this; } return NULL; } /*! * @fn void Transfer::setObjectID(int64_t nID) * * @brief 设置Transfer ID. * * @param nID Transfer ID. */ void setObjectID(int64_t nID) { m_nObjectID = nID; } /*! * @fn int64_t Transfer::getObjectID() const * * @brief 获取Transfer ID. * * @return 返回Transfer ID. */ int64_t getObjectID() const { return m_nObjectID; } /** * @fn std::string Transfer::getObjectName() const * * @brief 获取当前Transfer的名称. * * @return The object name. */ std::string getObjectName() const { return m_strObjectName; } /** * @fn void Transfer::setObjectName(std::string val) * * @brief 设置当前Transfer的名称. * * @param val The value. */ void setObjectName(std::string val) { m_strObjectName = val; m_oFuncMgr.setObjectName(getObjectName()); } /** * @fn bool Transfer::isTransferOjbect() const * * @brief 判断当前Transfer是否为对象. * * @return true if class ojbect, false if not. */ bool isTransferOjbect() const { return m_bTransferObject; } /** * @fn void Transfer::setClassObject(bool val) * * @brief 设置当前Trasnfer是否为对象. * * @param val true to value. */ void setTransferObject(bool val) { m_bTransferObject = val; } /*! * @fn void Transfer::setWorkOnRenderer(bool bWorkOnRenderer = true) * * @brief 设置当前Transfer是否工作在渲染进程(渲染线程)上. * * @param bWorkOnRenderer (Optional) true to work on renderer. */ void setWorkOnRenderer(bool bWorkOnRenderer = true) { m_bWorkOnRenderer = bWorkOnRenderer; } /*! * @fn bool Transfer::isWorkOnRenderer() const * * @brief 判断当前Transfer是否工作在渲染进程(渲染线程)上. * * @return true if work on renderer, false if not. */ bool isWorkOnRenderer() const { return m_bWorkOnRenderer; } /*! * @fn const std::string& Transfer::transferName() const * * @brief 获取Transfer 名称 类和类的实例对象名称相同.. * * @return 返回Transfer 名称. */ const std::string& transferName() const { return m_strName; } /*! * @fn void Transfer::transferName(const std::string& strName) * * @brief 设置Transfer 名称 类和类的实例对象名称相同. * * @param strName The Transfer name. */ void transferName(const std::string& strName) { m_strName = strName; } /*! * @fn virtual TransferType Transfer::transferType() * * @brief Transfer 类型 包括类/对象. * * @return 返回 TransferType. */ virtual TransferType transferType() { return TransferUnknown; } /** * @fn TransferMultiType Transfer::multiType(const std::string& funcName) * * @brief 判断当前函数是否支持多线程执行. * * @param funcName Name of the function. * * @return A TransferMultiType. */ TransferMultiType multiType(const std::string& funcName) { return getFuncMgr().multiType(funcName); } /*! * @fn TransferFuncType Transfer::functionType(const std::string& funcName) * * @brief 获取函数类型普通/静态/构造. * * @param funcName 函数名. * * @return 函数类型 TransferFuncType. */ TransferFuncType functionType(const std::string& funcName) { return getFuncMgr().functionType(funcName); } /*! * @fn TransferExecType Transfer::execType(const std::string& funcName) * * @brief 获取函数的调用方式 普通/同步/异步. * * @param funcName 函数名. * * @return 函数调用方式 TransferExecType. */ TransferExecType execType(const std::string& funcName) { return getFuncMgr().execType(funcName); } /*! * @fn virtual void Transfer::registerFunction() * * @brief 注册JS函数 设置注册状态为true. */ virtual void registerFunction() { setFuncRegistered(true); } /*! * @fn virtual bool Transfer::registerTransfer(const std::string& name, * FunctionWrapper::TransferFunc fn, int nType = 0) * * @brief Registers the transfer. * * @param name JS函数名. * @param fn JS函数所对应的C++函数. * @param nType 函数类型及执行方式. * * @return true if it succeeds, false if it fails. */ virtual bool registerTransfer(const std::string& name, FunctionWrapper::TransferFunc fn, int nType = 0) { return getFuncMgr().toMap().insert( std::make_pair(name, FunctionWrapper(name, fn, nType))).second; } /*! * @fn void Transfer::addModule(const std::string& strName) * * @brief 添加需要调用的JS模块,模块存在于渲染进程中, * 做为当前Transfer的子模块调用. * * @param strName The name. */ void addModule(const std::string& strName) { getFuncMgr().addModule(strName); } void addDepends(const std::string& strName) { getFuncMgr().addDepends(strName); } void registerAttribute(const std::string& strName, Any val) { getFuncMgr().addAttribute(strName, val); } /*! * @fn void Transfer::setBeforeResultCallback(BerforeResultFunc fn) * * @brief 设置JS调用C++的结果回调处理函数. * * @param fn 回调函数. */ void setBeforeResultCallback(BerforeResultFunc fn) { m_fnResultCallback = fn; } /*! * @fn BerforeResultFunc Transfer::getBeforeResultCallback() * * @brief 获取调用结果回调处理函数,如果回调函数有效,将优先处理结果. * * @return 回调处理函数. */ BerforeResultFunc getBeforeResultCallback() { return m_fnResultCallback; } /*! * @fn amo::FunctionWrapperMgr& Transfer::getFuncMgr() * * @brief 获取可以用JS访问的函数列表. * * @return 函数列表. */ amo::FunctionWrapperMgr& getFuncMgr() { return m_oFuncMgr; } virtual Any onDefaultMessageTransfer(IPCMessage::SmartType msg) { if (m_fnDefaultMsgFunc) { return m_fnDefaultMsgFunc(msg); } return Nothing(); } /*! * @fn virtual Any Transfer::onMessageTransfer(IPCMessage::SmartType message) * * @brief 执行JS函数对应的C++函数. * * @param 进程消息. * * @return Any. */ virtual Any onMessageTransfer(IPCMessage::SmartType msg) { // 函数调用方式 std::string strExecName = msg->getMessageName(); std::shared_ptr<AnyArgsList> args = msg->getArgumentList(); int nBrowserID = args->getInt(IPCArgsPosInfo::BrowserID); int nFrameID = args->getInt(IPCArgsPosInfo::FrameID); // 对应的C++函数名, 没有汉字 std::string strFuncName = args->getString(IPCArgsPosInfo::FuncName); // 查找当前Transfer是否存在所给函数 auto iter = getFuncMgr().toMap().find(strFuncName); amo::IPCResult result; result.setID(args->getInt(IPCArgsPosInfo::MessageID)); //JS普通调用C++, 这种执行方式不向调用者返回结果 if (strExecName == MSG_NATIVE_EXECUTE) { Any ret; if (iter == getFuncMgr().toMap().end()) { ret = onDefaultMessageTransfer(msg); if (ret.is<Nothing>()) { return Nothing(); } } else { // 调用所注册的C++函数 ret = iter->second(msg); } result.setResult(ret); // 向调用者返回结果前先处理该结果 if (m_fnResultCallback && m_fnResultCallback(MSG_NATIVE_EXECUTE, msg, result)) { //如果当前结果已被处理,那么不返回当前结果 return Nothing(); } return ret; } //JS同步调用C++,此消息需要通过管道向页面返回结果 else if (strExecName == MSG_NATIVE_SYNC_EXECUTE) { // if (iter != getFuncMgr().toMap().end()) { Any ret = iter->second(msg); result.setResult(ret); if (m_fnResultCallback && m_fnResultCallback(MSG_NATIVE_SYNC_EXECUTE, msg, result)) { //如果当前结果已被处理,那么不返回当前结果 return Nothing(); } return ret; } else { Any ret = onDefaultMessageTransfer(msg); // 没有找到相关函数,但是还是需要返回一个值给调用者,以免死锁 if (ret.is<Nothing>()) { ret = Undefined(); } result.setResult(ret); if (m_fnResultCallback && m_fnResultCallback(MSG_NATIVE_SYNC_EXECUTE, msg, result)) { return Nothing(); } return ret; } } //JS异步调用C++,此消息需要通过JS向页面返回结果 else if (strExecName == MSG_NATIVE_ASYNC_EXECUTE) { if (iter != getFuncMgr().toMap().end()) { Any ret = iter->second(msg); result.setResult(ret); if (m_fnResultCallback && m_fnResultCallback(MSG_NATIVE_ASYNC_EXECUTE, msg, result)) { return Nothing(); } return ret; } else { Any ret = onDefaultMessageTransfer(msg); // 没有找到相关函数,但是还是需要返回一个值给调用者,以免死锁 if (ret.is<Nothing>()) { ret = Undefined(); } result.setResult(ret); if (m_fnResultCallback && m_fnResultCallback(MSG_NATIVE_ASYNC_EXECUTE, msg, result)) { return Nothing(); } return ret; } } return Nothing(); } /*! * @fn bool Transfer::isFuncRegistered() const * * @brief 查询Transfer注册状态. * * @return true/false 已注册/未注册. */ bool isFuncRegistered() const { return m_bIsRegistered; } /*! * @fn void Transfer::setFuncRegistered(bool val) * * @brief 设置Transfer注册状态. * * @param true/false 注册/未注册. */ void setFuncRegistered(bool val) { m_bIsRegistered = val; } /** * @fn std::function<void(IPCMessage::SmartType) > getDefaultTriggerEventFunc() const * * @brief 获取事件触发函数. * * @return The trigger event function. */ std::function<void(IPCMessage::SmartType) > getDefaultTriggerEventFunc() const { return m_fnDefaultTriggerEventFunc; } /** * @fn virtual void Transfer::setDefaultTriggerEventFunc( std::function<void(IPCMessage::SmartType) > val) * * @brief 设置Transfer中需要触发事件时的回调函数, 一般用于外部Transfer的事件触发. * * @param val The value. */ virtual void setDefaultTriggerEventFunc( std::function<void(IPCMessage::SmartType) > val) { m_fnDefaultTriggerEventFunc = val; } /** * @fn std::function<void(IPCMessage::SmartType) > getTriggerEventFunc() const * * @brief 获取事件触发函数. * * @return The trigger event function. */ std::function<void(IPCMessage::SmartType) > getTriggerEventFunc() const { return m_fnTriggerEventFunc; } /** * @fn void Transfer::setTriggerEventFunc(std::function<void(IPCMessage::SmartType) > val) * * @brief 设置Transfer中需要触发事件时的回调函数, * 一般用于外部Transfer的事件触发. * * @param val The value. */ virtual void setTriggerEventFunc(std::function<void(IPCMessage::SmartType) > val) { m_fnTriggerEventFunc = val; } Any triggerEvent(const TransferEventInfo& info) { IPCMessage::SmartType ipcMessage(new IPCMessage()); ipcMessage->setMessageName(MSG_NATIVE_EXECUTE); std::shared_ptr<AnyArgsList>& ipcArgs = ipcMessage->getArgumentList(); ipcArgs->setValue(IPCArgsPosInfo::TransferName, "ipcRenderer"); ipcArgs->setValue(IPCArgsPosInfo::TransferID, 0); ipcArgs->setValue(IPCArgsPosInfo::EventObjectID, getObjectID()); ipcArgs->setValue(IPCArgsPosInfo::BrowserID, info.browser); ipcArgs->setValue(IPCArgsPosInfo::FrameID, info.frame); if (info.toAll) { ipcArgs->setValue(IPCArgsPosInfo::FuncName, "emitEventAllFrame"); } else { ipcArgs->setValue(IPCArgsPosInfo::FuncName, "triggerEvent"); } if (info.name == "transfer.release") { ipcArgs->setValue(IPCArgsPosInfo::FuncName, "releaseAllTransfer"); } ipcArgs->setValue(0, info.name); ipcArgs->setValue(1, info.toJson()); //ipcArgs->setValue(1, info.toJson()); ipcArgs->setValue(IPCArgsPosInfo::ArgsLength, 2); if (getTriggerEventFunc()) { getTriggerEventFunc()(ipcMessage); } else if (getDefaultTriggerEventFunc()) { getDefaultTriggerEventFunc()(ipcMessage); } return Undefined(); } std::function < Any(IPCMessage::SmartType) > getDefaultMsgFunc() const { return m_fnDefaultMsgFunc; } void setDefaultMsgFunc(std::function < Any(IPCMessage::SmartType) > val) { m_fnDefaultMsgFunc = val; } std::string getModuleName() const { return m_strModuleName; } void setModuleName(const std::string& val) { m_strModuleName = val; } protected: /*! @brief JS调用C++回调处理函数集合. */ std::map < std::string, FunctionWrapper > m_mpJsFunction; /*! @brief Transfer名称. */ std::string m_strName; /*! @brief 结果返回前的回调函数,如果该函数返回true那么将不会再向调用都返回执行结果. */ BerforeResultFunc m_fnResultCallback; /*! @brief JS调用C++回调处理函数集合. */ FunctionWrapperMgr m_oFuncMgr; /*! @brief 是否运行在Renderer线程上. */ bool m_bWorkOnRenderer; /*! @brief 当前Transfer ID. */ int64_t m_nObjectID; /** @brief 当前Transfer 名称. */ std::string m_strObjectName; /*! @brief 判断当前类是否已经注册. */ bool m_bIsRegistered; /** @brief 判断当前transfer是类还是对象. */ bool m_bTransferObject; /** @brief Transfer中产生的默认事件触发函数,m_fnTriggerEventFunc无效时会尝试使用该函数. */ std::function<void(IPCMessage::SmartType)> m_fnDefaultTriggerEventFunc; /** @brief Transfer中产生的事件触发函数. */ std::function<void(IPCMessage::SmartType)> m_fnTriggerEventFunc; /** @brief 默认消息处理函数,如果没有找到消息处理函数将触发该函数. */ std::function<Any(IPCMessage::SmartType)> m_fnDefaultMsgFunc; /** @brief 是否已经被释放掉,(在页面上释放掉). */ std::atomic_bool m_bReleased; /** @brief 所属模块名称. */ std::string m_strModuleName; amo::u8json userData; }; } #endif // AMO_TRANSFER_HPP__
29.743243
114
0.50126
[ "object" ]
9e97eb7ebc1a361b8a74ff78c9435bc2457eb1a7
16,089
cc
C++
TopQuarkAnalysis/TopHitFit/src/Top_Fit.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
TopQuarkAnalysis/TopHitFit/src/Top_Fit.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
TopQuarkAnalysis/TopHitFit/src/Top_Fit.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
// // // File: src/Top_Fit.cc // Purpose: Handle jet permutations. // Created: Jul, 2000, sss, based on run 1 mass analysis code. // // XXX handle merging jets. // XXX btagging for ttH. // // CMSSW File : src/Top_Fit.cc // Original Author : Scott Stuart Snyder <snyder@bnl.gov> for D0 // Imported to CMSSW by Haryo Sumowidagdo <Suharyo.Sumowidagdo@cern.ch> // /** @file Top_Fit.cc @brief Handle and fit jet permutations of an event. This is the primary interface between user's Lepjets_Event and HitFit kinematic fitting algorithm. See the documentation for the header file Top_Fit.h for details. @author Scott Stuart Snyder <snyder@bnl.gov> @par Creation date: Jul 2000. @par Modification History: Apr 2009: Haryo Sumowidagdo <Suharyo.Sumowidagdo@cern.ch>: Imported to CMSSW.<br> Nov 2009: Haryo Sumowidagdo <Suharyo.Sumowidagdo@cern.ch>: Added doxygen tags for automatic generation of documentation. @par Terms of Usage: With consent for the original author (Scott Snyder). */ #include "TopQuarkAnalysis/TopHitFit/interface/Top_Fit.h" #include "TopQuarkAnalysis/TopHitFit/interface/Lepjets_Event.h" #include "TopQuarkAnalysis/TopHitFit/interface/Top_Decaykin.h" #include "TopQuarkAnalysis/TopHitFit/interface/Defaults.h" #include "TopQuarkAnalysis/TopHitFit/interface/Fit_Results.h" #include "TopQuarkAnalysis/TopHitFit/interface/fourvec.h" #include <iostream> #include <algorithm> #include <cmath> #include <cassert> using std::cout; using std::endl; using std::abs; using std::next_permutation; using std::stable_sort; using std::vector; using std::ostream; namespace hitfit { //************************************************************************* // Argument handling. // Top_Fit_Args::Top_Fit_Args (const Defaults& defs) // // Purpose: Constructor. // // Inputs: // defs - The Defaults instance from which to initialize. // : _print_event_flag (defs.get_bool ("print_event_flag")), _do_higgs_flag (defs.get_bool ("do_higgs_flag")), _jet_mass_cut (defs.get_float ("jet_mass_cut")), _mwhad_min_cut (defs.get_float ("mwhad_min_cut")), _mwhad_max_cut (defs.get_float ("mwhad_max_cut")), _mtdiff_max_cut (defs.get_float ("mtdiff_max_cut")), _nkeep (defs.get_int ("nkeep")), _solve_nu_tmass (defs.get_bool ("solve_nu_tmass")), _args (defs) { } bool Top_Fit_Args::print_event_flag () const // // Purpose: Return the print_event_flag parameter. // See the header for documentation. // { return _print_event_flag; } bool Top_Fit_Args::do_higgs_flag () const // // Purpose: Return the do_higgs_flag parameter. // See the header for documentation. // { return _do_higgs_flag; } double Top_Fit_Args::jet_mass_cut () const // // Purpose: Return the jet_mass_cut parameter. // See the header for documentation. // { return _jet_mass_cut; } double Top_Fit_Args::mwhad_min_cut () const // // Purpose: Return the mwhad_min_cut parameter. // See the header for documentation. // { return _mwhad_min_cut; } double Top_Fit_Args::mwhad_max_cut () const // // Purpose: Return the mwhad_max_cut parameter. // See the header for documentation. // { return _mwhad_max_cut; } double Top_Fit_Args::mtdiff_max_cut () const // // Purpose: Return the mtdiff_max_cut parameter. // See the header for documentation. // { return _mtdiff_max_cut; } int Top_Fit_Args::nkeep () const // // Purpose: Return the nkeep parameter. // See the header for documentation. // { return _nkeep; } bool Top_Fit_Args::solve_nu_tmass () const // // Purpose: Return the solve_nu_tmass parameter // See the header for documentation. // { return _solve_nu_tmass; } const Constrained_Top_Args& Top_Fit_Args::constrainer_args () const // // Purpose: Return the contained subobject parameters. // { return _args; } //************************************************************************* // Helper functions. // namespace { /** @brief Helper function: apply mass cuts to see if this event should be rejected before fitting. @param ev The event to test. @param args The parameter settings. @param mwhad The hadronic \f$ W- \f$ boson mass. @param umthad The mass of the hadronic top quark before fit. @param umtlep The mass of the leptonic top quark before fit. */ bool test_for_bad_masses (const Lepjets_Event& ev, const Top_Fit_Args& args, double mwhad, double umthad, double umtlep) // // Purpose: Apply mass cuts to see if this event should be rejected // without fitting. // // Inputs: // ev - The event to test. // args - Parameter setting. // mwhad - The hadronic W mass. // umthad - The hadronic top mass. // umtlep - The leptonic top mass. // // Returns: // True if the event should be rejected. // { // Reject the event if any jet's mass is too large. if (ev.sum (lepb_label).m() > args.jet_mass_cut() || ev.sum (hadb_label).m() > args.jet_mass_cut() || ev.sum (hadw1_label).m() > args.jet_mass_cut() || ev.sum (hadw2_label).m() > args.jet_mass_cut()) { return true; } // Reject if if the hadronic W mass is outside the window. if (mwhad < args.mwhad_min_cut()) { return true; } // Reject if if the hadronic W mass is outside the window. if (mwhad > args.mwhad_max_cut()) { return true; } // And if the two top masses are too far apart. if (abs (umthad - umtlep) > args.mtdiff_max_cut()) { return true; } // It's ok. return false; } /** @brief Helper function: classify a jet permutation, to decide on what result lists it should be put. @param jet_types The vector representing a particular jet permutation, which is a vector of jet types. @param ev The original event being fit. */ vector<int> classify_jetperm (const vector<int>& jet_types, const Lepjets_Event& ev) // // Purpose: Classify a jet permutation, to decide on what result // lists it should be put. // // Inputs: // jet_types - Vector of jet types. // ev - The original event being fit. // // Returns: // A list_flags vector, appropriate to pass to Fit_Results::push. // { // Start by assuming it's on all the lists. // We'll clear the flags if we see that it actually doesn't // belong. vector<int> out (n_lists); out[all_list] = 1; out[noperm_list] = 1; out[semicorrect_list] = 1; out[limited_isr_list] = 1; out[topfour_list] = 1; out[btag_list] = 1; out[htag_list] = 1; // Loop over jets. assert (jet_types.size() == ev.njets()); for (vector<int>::size_type i=0; i < jet_types.size(); i++) { { int t1 = jet_types[i]; // Current type of this jet. int t2 = ev.jet(i).type(); // `Correct' type of this jet. // Consider hadw1_label and hadw2_label the same. if (t1 == hadw2_label) t1 = hadw1_label; if (t2 == hadw2_label) t2 = hadw1_label; // If they're not the same, the permutation isn't correct. if (t1 != t2) out[noperm_list] = 0; // Test for a semicorrect permutation. // Here, all hadronic-side jets are considered equivalent. if (t1 == hadw1_label) t1 = hadb_label; if (t2 == hadw1_label) t2 = hadb_label; if (t1 != t2) out[semicorrect_list] = 0; } if (jet_types[i] == isr_label && i <= 2) out[limited_isr_list] = 0; if ((jet_types[i] == isr_label && i <= 3) || (jet_types[i] != isr_label && i >= 4)) out[topfour_list] = 0; if ((ev.jet(i).svx_tag() || ev.jet(i).slt_tag()) && ! (jet_types[i] == hadb_label || jet_types[i] == lepb_label)) out[btag_list] = 0; if ((ev.jet(i).svx_tag() || ev.jet(i).slt_tag()) && ! (jet_types[i] == hadb_label || jet_types[i] == lepb_label || jet_types[i] == higgs_label)) out[htag_list] = 0; } return out; } /** @brief Helper function: update/overwrite the jet types in an event. @param jet_types The vector representing a particular jet permutation, which is a vector of jet types. @param ev Input: The event to update, output: the updated event. */ void set_jet_types (const vector<int>& jet_types, Lepjets_Event& ev) // // Purpose: Update EV with a new set of jet types. // // Inputs: // jet_types - Vector of new jet types. // ev - The event to update. // // Outputs: // ev - The updated event. // { assert (ev.njets() == jet_types.size()); bool saw_hadw1 = false; for (vector<int>::size_type i=0; i < ev.njets(); i++) { int t = jet_types[i]; if (t == hadw1_label) { if (saw_hadw1) t = hadw2_label; saw_hadw1 = true; } ev.jet (i).type() = t; } } } // unnamed namespace //************************************************************************* Top_Fit::Top_Fit (const Top_Fit_Args& args, double lepw_mass, double hadw_mass, double top_mass) // // Purpose: Constructor. // // Inputs: // args - The parameter settings for this instance. // lepw_mass - The mass to which the leptonic W should be constrained, // or 0 to skip this constraint. // hadw_mass - The mass to which the hadronic W should be constrained, // or 0 to skip this constraint. // top_mass - The mass to which the top quarks should be constrained, // or 0 to skip this constraint. // : _args (args), _constrainer (args.constrainer_args(), lepw_mass, hadw_mass, top_mass), _lepw_mass(lepw_mass), _hadw_mass (hadw_mass) { } double Top_Fit::fit_one_perm (Lepjets_Event& ev, bool& nuz, double& umwhad, double& utmass, double& mt, double& sigmt, Column_Vector& pullx, Column_Vector& pully) // // Purpose: Fit a single jet permutation. // // Inputs: // ev - The event to fit. // The object labels must have already been assigned. // nuz - Boolean flag to indicate which neutrino solution to be // used. // false = use smaller neutrino z solution // true = use larger neutrino z solution // // Outputs: // ev- The event after the fit. // umwhad - Hadronic W mass before fitting. // utmass - Top mass before fitting, averaged from both sides. // mt - Top mass after fitting. // sigmt - Top mass uncertainty after fitting. // pullx - Vector of pull quantities for well-measured variables. // pully - Vector of pull quantities for poorly-measured variables. // // Returns: // The fit chisq, or < 0 if the fit didn't converge. // // Adaptation note by Haryo Sumowidagdo: // This function is rewritten in order to make its purpose reflects // the function's name. The function nows only fit one jet permutation // with one neutrino solution only. // // { mt = 0; sigmt = 0; // Find the neutrino solutions by requiring either: // 1) that the leptonic top have the same mass as the hadronic top. // 2) that the mass of the lepton and neutrino is equal to the W mass umwhad = Top_Decaykin::hadw (ev) . m(); double umthad = Top_Decaykin::hadt (ev) . m(); double nuz1, nuz2; if (_args.solve_nu_tmass()) { Top_Decaykin::solve_nu_tmass (ev, umthad, nuz1, nuz2); } else { Top_Decaykin::solve_nu (ev, _lepw_mass, nuz1, nuz2); } // Set up to use the selected neutrino solution if (!nuz) { ev.met().setZ(nuz1); } else { ev.met().setZ(nuz2); } // Note: We have set the neutrino Pz, but we haven't set the neutrino energy. // Remember that originally the neutrino energy was equal to // sqrt(nu_px*nu_px + nu_py*nu_py). Calculating the invariant mass squared // for the neutrino will give negative mass squared. // Therefore we need to adjust (increase) the neutrino energy in order to // make its mass remain zero. adjust_e_for_mass(ev.met(),0); // Find the unfit top mass as the average of the two sides. double umtlep = Top_Decaykin::lept (ev) . m(); utmass = (umthad + umtlep) / 2; // Trace, if requested. if (_args.print_event_flag()) { cout << "Top_Fit::fit_one_perm() : Before fit:\n"; Top_Decaykin::dump_ev (cout, ev); } // Maybe reject this event. if (_hadw_mass > 0 && test_for_bad_masses (ev, _args, umwhad, umthad, umtlep)) { cout << "Top_Fit: bad mass comb.\n"; return -999; } // Do the fit. double chisq = _constrainer.constrain (ev, mt, sigmt, pullx, pully); // Trace, if requested. if (_args.print_event_flag()) { cout << "Top_Fit::fit_one_perm() : After fit:\n"; cout << "chisq: " << chisq << " mt: " << mt << " "; Top_Decaykin::dump_ev (cout, ev); } // Done! return chisq; } Fit_Results Top_Fit::fit (const Lepjets_Event& ev) // // Purpose: Fit all jet permutations for EV. // // Inputs: // ev - The event to fit. // // Returns: // The results of the fit. // { // Make a new Fit_Results object. Fit_Results res (_args.nkeep(), n_lists); // Set up the vector of jet types. vector<int> jet_types (ev.njets(), isr_label); assert (ev.njets() >= 4); jet_types[0] = lepb_label; jet_types[1] = hadb_label; jet_types[2] = hadw1_label; jet_types[3] = hadw1_label; if (_args.do_higgs_flag() && ev.njets() >= 6) { jet_types[4] = higgs_label; jet_types[5] = higgs_label; } // Must be in sorted order. stable_sort (jet_types.begin(), jet_types.end()); do { // Loop over the two possible neutrino solution for (int nusol = 0 ; nusol != 2 ; nusol++) { // Set up the neutrino solution to be used bool nuz = bool(nusol); // Copy the event. Lepjets_Event fev = ev; // Install the new jet types. set_jet_types (jet_types, fev); // Figure out on what lists this permutation should go. vector<int> list_flags = classify_jetperm (jet_types, ev); // Set up the output variables for fit results. double umwhad, utmass, mt, sigmt; Column_Vector pullx; Column_Vector pully; double chisq; // Tracing. cout << "Top_Fit::fit(): Before fit: ("; for (vector<int>::size_type i=0; i < jet_types.size(); i++) { if (i) cout << " "; cout << jet_types[i]; } cout << " nuz = " << nuz ; cout << ") " << std::endl; // Do the fit. chisq = fit_one_perm (fev, nuz, umwhad, utmass, mt, sigmt, pullx, pully); // Print the result, if requested. if (_args.print_event_flag()) { cout << "Top_Fit::fit(): After fit:\n"; char buf[256]; sprintf (buf, "chisq: %8.3f mt: %6.2f pm %5.2f %c\n", chisq, mt, sigmt, (list_flags[noperm_list] ? '*' : ' ')); cout << buf; } // Add it to the results. res.push (chisq, fev, pullx, pully, umwhad, utmass, mt, sigmt, list_flags); } // end of for loop over the two neutrino solution // Step to the next permutation. } while (next_permutation (jet_types.begin(), jet_types.end())); return res; } /** @brief Output stream operator, print the content of this Top_Fit object to an output stream. @param s The output stream to which to write. @param fitter The instance of Top_Fit to be printed. */ std::ostream& operator<< (std::ostream& s, const Top_Fit& fitter) // // Purpose: Print the object to S. // // Inputs: // s - The stream to which to write. // fitter - The object to write. // // Returns: // The stream S. // { return s << fitter._constrainer; } const Top_Fit_Args& Top_Fit::args() const { return _args; } } // namespace hitfit
26.203583
79
0.615638
[ "object", "vector" ]
9ea351dd32f859e0ac5297201d5603d0bef4f22c
5,630
cc
C++
curv/export_mesh.cc
lf94/curv
f7c54d0ba92cb719255db84309848f6cb6e72935
[ "Apache-2.0" ]
921
2019-01-13T18:47:47.000Z
2022-03-28T03:36:18.000Z
curv/export_mesh.cc
lf94/curv
f7c54d0ba92cb719255db84309848f6cb6e72935
[ "Apache-2.0" ]
93
2019-01-11T15:35:01.000Z
2022-01-14T17:42:05.000Z
curv/export_mesh.cc
lf94/curv
f7c54d0ba92cb719255db84309848f6cb6e72935
[ "Apache-2.0" ]
59
2019-01-20T09:37:59.000Z
2022-02-17T15:12:10.000Z
// Copyright 2016-2021 Doug Moen // Licensed under the Apache License, version 2.0 // See accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0 #include <iostream> #include <climits> #include <cmath> #include <cstdlib> #include <chrono> #include <thread> #include <glm/geometric.hpp> #include "export.h" #include "mesher.h" #include <libcurv/io/compiled_shape.h> #include <libcurv/io/mesh.h> #include <libcurv/shape.h> #include <libcurv/exception.h> #include <libcurv/context.h> #include <libcurv/die.h> using namespace curv::io; void export_mesh(Mesh_Format, curv::Value value, curv::Program&, const Export_Params& params, std::ostream& out); void export_stl(curv::Value value, curv::Program& prog, const Export_Params& params, Output_File& ofile) { ofile.open(); export_mesh(Mesh_Format::stl, value, prog, params, ofile.ostream()); } void export_obj(curv::Value value, curv::Program& prog, const Export_Params& params, Output_File& ofile) { ofile.open(); export_mesh(Mesh_Format::obj, value, prog, params, ofile.ostream()); } void export_x3d(curv::Value value, curv::Program& prog, const Export_Params& params, Output_File& ofile) { ofile.open(); export_mesh(Mesh_Format::x3d, value, prog, params, ofile.ostream()); } void export_gltf(curv::Value value, curv::Program& prog, const Export_Params& params, Output_File& ofile) { ofile.open(); export_mesh(Mesh_Format::gltf, value, prog, params, ofile.ostream()); } void describe_mesh_opts(std::ostream& out) { out << "-O mgen=#smooth|#sharp : Mesh generator algorithm (default #smooth).\n" "-O jit : Fast evaluation using JIT compiler (uses C++ compiler).\n" "-O vsize=<voxel size>\n" "-O vcount=<approximate voxel count>\n" "-O eps=<small number> : epsilon to compute normal by partial differences\n" "-O adaptive=<0...1> : Deprecated. Use meshlab to simplify mesh.\n" ; } void describe_colour_mesh_opts(std::ostream& out) { describe_mesh_opts(out); out << "-O colouring=#face|#vertex (default #face)\n" ; } void export_mesh(Mesh_Format format, curv::Value value, curv::Program& prog, const Export_Params& params, std::ostream& out) { curv::Shape_Program shape(prog); curv::At_Program cx(prog); if (!shape.recognize(value, nullptr) || !shape.is_3d_) throw curv::Exception(cx, "mesh export: not a 3D shape"); Mesh_Export opts; for (auto& i : params.map_) { Param p{params, i}; if (p.name_ == "mgen") { auto val = p.to_symbol(); if (val == "smooth") opts.mgen_ = Mesh_Gen::smooth; else if (val == "sharp") opts.mgen_ = Mesh_Gen::sharp; else if (val == "iso") opts.mgen_ = Mesh_Gen::iso; else if (val == "hybrid") opts.mgen_ = Mesh_Gen::hybrid; else if (val == "tmc") opts.mgen_ = Mesh_Gen::tmc; else throw curv::Exception(p, "'mgen' must be #smooth|#sharp|#iso|#hybrid|#tmc"); } else if (p.name_ == "jit") { opts.jit_ = p.to_bool(); } else if (p.name_ == "vsize") { opts.vsize_ = p.to_double(); if (opts.vsize_ <= 0.0) { throw curv::Exception(p, "'vsize' must be positive"); } } else if (p.name_ == "vcount") { opts.vcount_ = p.to_int(1, INT_MAX); } else if (p.name_ == "eps") { opts.eps_ = p.to_double(); } else if (p.name_ == "adaptive") { opts.adaptive_ = p.to_double(1.0); if (opts.adaptive_ < 0.0 || opts.adaptive_ > 1.0) { throw curv::Exception(p, "'adaptive' must be in range 0...1"); } } else if (format == Mesh_Format::x3d && p.name_ == "colouring") { auto val = p.to_symbol(); if (val == "face") opts.colouring_ = Mesh_Export::face_colour; else if (val == "vertex") opts.colouring_ = Mesh_Export::vertex_colour; else { throw curv::Exception(p, "'colouring' must be #face or #vertex"); } } else p.unknown_parameter(); } std::unique_ptr<curv::io::Compiled_Shape> cshape = nullptr; if (opts.jit_) { auto cstart_time = std::chrono::steady_clock::now(); cshape = std::make_unique<curv::io::Compiled_Shape>(shape); auto cend_time = std::chrono::steady_clock::now(); std::chrono::duration<double> compile_time = cend_time - cstart_time; std::cerr << "Compiled shape in " << compile_time.count() << "s\n"; std::cerr.flush(); } else { std::cerr << "You are in SLOW MODE. Use '-O jit' to speed up rendering.\n"; } const curv::Shape* pshape; if (cshape) pshape = &*cshape; else pshape = &shape; bool multithreaded = (cshape != nullptr); #if LEAN_BUILD tmc_mesher(*pshape, multithreaded, opts, cx, format, out); #else switch (opts.mgen_) { case Mesh_Gen::smooth: vdb_mesher(*pshape, multithreaded, opts, cx, format, out); break; case Mesh_Gen::sharp: case Mesh_Gen::iso: case Mesh_Gen::hybrid: libfive_mesher(*pshape, multithreaded, opts, cx, format, out); break; case Mesh_Gen::tmc: tmc_mesher(*pshape, multithreaded, opts, cx, format, out); break; default: throw curv::Exception(cx, "mesh export: unknown mesh generator"); } #endif }
31.629213
81
0.591119
[ "mesh", "shape", "3d" ]
9ea4f6106912066b7b437240da4783e2990f4383
186
hh
C++
include/readWav.hh
skrollilehti/spektrogrammi
f08168c5973af23d3635f40265c03930c61eaed2
[ "Unlicense" ]
2
2020-10-15T18:02:17.000Z
2020-11-30T19:52:49.000Z
include/readWav.hh
skrollilehti/spektrogrammi
f08168c5973af23d3635f40265c03930c61eaed2
[ "Unlicense" ]
null
null
null
include/readWav.hh
skrollilehti/spektrogrammi
f08168c5973af23d3635f40265c03930c61eaed2
[ "Unlicense" ]
null
null
null
#ifndef READWAV_HH #define READWAV_HH #include <vector> #include <string> #include <utility> std::pair<std::vector<short>, int> readUncompressedWavFile(std::string file_name); #endif
16.909091
82
0.763441
[ "vector" ]
9eb454d9688396acc6ae2340b59d2cdaa900d236
11,852
cc
C++
source/main.cc
kdavison/fortress
6c04bcd0eded658fadd40818057a37696b28f793
[ "MIT" ]
null
null
null
source/main.cc
kdavison/fortress
6c04bcd0eded658fadd40818057a37696b28f793
[ "MIT" ]
null
null
null
source/main.cc
kdavison/fortress
6c04bcd0eded658fadd40818057a37696b28f793
[ "MIT" ]
null
null
null
#define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> #include <vector> #include <string> #include <memory> #include <stdexcept> #include <algorithm> #include <cstring> #include <set> #include <iostream> class Application { public: virtual void run() = 0; }; const std::vector<const char*> validationLayers = #if NDEBUG { }; #else { "VK_LAYER_LUNARG_standard_validation" }; #endif const std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; bool checkValidationLayerSupport() { uint32_t layer_count = 0; vkEnumerateInstanceLayerProperties(&layer_count, nullptr); std::vector<VkLayerProperties> availableLayers(layer_count); vkEnumerateInstanceLayerProperties(&layer_count, availableLayers.data()); std::cout << "available validation layers: " << layer_count << "\n"; for(const char* layer_name : validationLayers) { std::cout << "checking validation layer: " << std::string(layer_name) << "\n"; auto found = std::find_if(std::begin(availableLayers), std::end(availableLayers), [layer_name](auto const& layer) { return (std::strcmp(layer_name, layer.layerName) == 0); }); } return true; } std::vector<const char*> getRequiredExtensions() { std::vector<const char*> extensions; uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); for(uint32_t index = 0; index < glfwExtensionCount; ++index) { extensions.push_back(glfwExtensions[index]); } if(!validationLayers.empty()) { extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); } return extensions; } VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugReportFlagsEXT msgFlags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char *pLayerPrefix, const char *pMsg, void *pUserData) { std::cerr << "validation layer: " << std::string(pMsg) << std::endl; return VK_FALSE; } VkResult CreateDebugReportCallbackEXT( VkInstance instance, const VkDebugReportCallbackCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugReportCallbackEXT* pCallback) { auto func = (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT"); if (func != nullptr) { return func(instance, pCreateInfo, pAllocator, pCallback); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } void DestroyDebugReportCallbackEXT(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks* pAllocator) { auto func = (PFN_vkDestroyDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"); if (func != nullptr) { func(instance, callback, pAllocator); } } class HelloTriangleApplication : public Application { public: void run() { init_window(512, 512); init_vulkan(); main_loop(); cleanup(); } private: void init_window(std::size_t width, std::size_t height) { glfwInit(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); _window = glfwCreateWindow(width, height, "Vulkan", nullptr, nullptr); } void init_vulkan() { if(!checkValidationLayerSupport()) { throw std::runtime_error("validation layer request, but not supported!"); } //create application info VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Hello Triangle!"; appInfo.applicationVersion = VK_MAKE_VERSION(0, 0, 0); appInfo.pEngineName = "No Engine"; appInfo.engineVersion = VK_MAKE_VERSION(0, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_0; //create constructor info VkInstanceCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; auto glfwExtensions = getRequiredExtensions(); createInfo.enabledExtensionCount = glfwExtensions.size(); createInfo.ppEnabledExtensionNames = glfwExtensions.data(); if(!validationLayers.empty()) { createInfo.enabledLayerCount = validationLayers.size(); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } //create instance! VkResult result = vkCreateInstance(&createInfo, nullptr, &_instance); if(result != VK_SUCCESS) { throw std::runtime_error("failed to create instance(" + std::to_string(result) + ")"); } uint32_t vulkanExtensionCount = 0; vkEnumerateInstanceExtensionProperties(nullptr, &vulkanExtensionCount, nullptr); std::vector<VkExtensionProperties> extensions(vulkanExtensionCount); vkEnumerateInstanceExtensionProperties(nullptr, &vulkanExtensionCount, extensions.data()); std::cout << "available extensions:\n"; for(const auto& extension : extensions) { std::cout << "\t" << extension.extensionName << "\n"; } //setup debug callback if(!validationLayers.empty()) { VkDebugReportCallbackCreateInfoEXT debugCallbackCreateInfo = {}; debugCallbackCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; debugCallbackCreateInfo.pNext = nullptr; debugCallbackCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; debugCallbackCreateInfo.pfnCallback = debugCallback; debugCallbackCreateInfo.pUserData = nullptr; if(CreateDebugReportCallbackEXT(_instance, &debugCallbackCreateInfo, nullptr, &_debugCallback) != VK_SUCCESS) { throw std::runtime_error("debug callback setup failed"); } } create_surface(); pick_physical_device(); create_logical_device(); } void create_surface() { if(glfwCreateWindowSurface(_instance, _window, nullptr, &_surface) != VK_SUCCESS) { throw std::runtime_error("failed to create window surface!"); } } void pick_physical_device() { _physicalDevice = VK_NULL_HANDLE; uint32_t device_count = 0; vkEnumeratePhysicalDevices(_instance, &device_count, nullptr); if(device_count == 0) { throw std::runtime_error("failed to find GPUs with vulkan support"); } std::vector<VkPhysicalDevice> devices(device_count); vkEnumeratePhysicalDevices(_instance, &device_count, devices.data()); for(const auto& device : devices) { if(isDeviceSuitable(device)) { _physicalDevice = device; break; } } if(_physicalDevice == VK_NULL_HANDLE) { throw std::runtime_error("failed to find suitable GPU!"); } } struct QueueFamilyIndices { int32_t graphicsFamily = -1; int32_t presentFamily = -1; bool isComplete() { return graphicsFamily >= 0 && presentFamily >= 0; } }; QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data()); int32_t index = 0; for(const auto& queueFamily : queueFamilies) { if(queueFamily.queueCount > 0 && queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = index; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(device, index, _surface, &presentSupport); if(queueFamily.queueCount > 0 && presentSupport) { indices.presentFamily = index; } if(indices.isComplete()) { break; } else { ++index; } } return indices; } bool isDeviceSuitable(VkPhysicalDevice device) { VkPhysicalDeviceProperties device_properties; VkPhysicalDeviceFeatures device_features; vkGetPhysicalDeviceProperties(device, &device_properties); vkGetPhysicalDeviceFeatures(device, &device_features); QueueFamilyIndices indices = findQueueFamilies(device); return indices.isComplete() && checkDeviceExtensionSupport(device); } bool checkDeviceExtensionSupport(VkPhysicalDevice physicalDevice) { uint32_t extension_count = 0; vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extension_count, nullptr); std::vector<VkExtensionProperties> availableExtensions(extension_count); vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extension_count, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for(const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } return requiredExtensions.empty(); } void create_logical_device() { QueueFamilyIndices indices = findQueueFamilies(_physicalDevice); std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<int32_t> uniqueQueueFamilies = {indices.graphicsFamily, indices.presentFamily}; for(int32_t queueFamily : uniqueQueueFamilies) { VkDeviceQueueCreateInfo queueCreateInfo = {}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = indices.graphicsFamily; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &QUEUE_PRIORITY; queueCreateInfos.push_back(queueCreateInfo); } VkPhysicalDeviceFeatures deviceFeatures = {}; VkDeviceCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); if(validationLayers.size()) { createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } if(vkCreateDevice(_physicalDevice, &createInfo, nullptr, &_device) != VK_SUCCESS) { throw std::runtime_error("failed to create logical device!"); } vkGetDeviceQueue(_device, indices.graphicsFamily, 0, &_graphicsQueue); } void main_loop() { while(!glfwWindowShouldClose(_window)) { glfwPollEvents(); } } void cleanup() { if(_instance) { if(_debugCallback) { DestroyDebugReportCallbackEXT(_instance, _debugCallback, nullptr); } if(_surface) { vkDestroySurfaceKHR(_instance, _surface, nullptr); } vkDestroyInstance(_instance, nullptr); } if(_device) { vkDestroyDevice(_device, nullptr); } if(_window) { glfwDestroyWindow(_window); } glfwTerminate(); } private: float QUEUE_PRIORITY = 1.0f; private: GLFWwindow * _window; VkInstance _instance; VkPhysicalDevice _physicalDevice; VkDevice _device; VkQueue _graphicsQueue; VkDebugReportCallbackEXT _debugCallback; VkSurfaceKHR _surface; VkQueue presentQueue; }; int main(int argc, char * argv[]) { std::unique_ptr<Application> app = std::make_unique<HelloTriangleApplication>(); try { app->run(); } catch(std::runtime_error &ex) { std::cerr << ex.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
31.437666
133
0.71625
[ "vector" ]
9eb6004d93bee8a6062e1065d815fb552e54fdfa
272
cpp
C++
Leetcode/0790. Domino and Tromino Tiling/0790.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0790. Domino and Tromino Tiling/0790.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0790. Domino and Tromino Tiling/0790.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: int numTilings(int N) { constexpr int kMod = 1e9 + 7; vector<long> dp(1001, 0); dp[1] = 1; dp[2] = 2; dp[3] = 5; for (int i = 4; i <= N; ++i) dp[i] = (2 * dp[i - 1] + dp[i - 3]) % kMod; return dp[N]; } };
16
49
0.444853
[ "vector" ]
9eb7e5df65312b1d055272d604f28e5f3b0568b9
2,373
cpp
C++
frameworks/runtime-src/Classes/LSTG/LWBuiltInFunction.cpp
Xiliusha/LuaSTG-x
27db15a1557baedd908f19be1ea9b2c80499129a
[ "MIT" ]
null
null
null
frameworks/runtime-src/Classes/LSTG/LWBuiltInFunction.cpp
Xiliusha/LuaSTG-x
27db15a1557baedd908f19be1ea9b2c80499129a
[ "MIT" ]
null
null
null
frameworks/runtime-src/Classes/LSTG/LWBuiltInFunction.cpp
Xiliusha/LuaSTG-x
27db15a1557baedd908f19be1ea9b2c80499129a
[ "MIT" ]
null
null
null
#include "LWBuiltInFunction.h" #include "AppFrame.h" #include "LWColor.h" #include "LWRandomizer.h" #include "LW_Audio.h" #include "LW_Frame.h" #include "LW_Graph.h" #include "LW_Input.h" #include "LW_Math.h" #include "LW_Object.h" #include "LW_Render.h" #include "LW_Text.h" using namespace std; using namespace lstg; using cocos2d::Color4B; void BuiltInFunctionWrapper::Register(lua_State* L) { vector<luaL_Reg> functions; auto lw_base = { LW_Audio(), LW_Frame(), LW_Graph(), LW_Input(), LW_Math(), LW_Object(), LW_Render(), LW_Text(), }; for(auto& lw : lw_base) functions.insert(functions.end(), lw.begin(), lw.end()); struct Misc { static int Snapshot(lua_State* L) noexcept { LAPP.snapShot(luaL_checkstring(L, 1)); return 0; } static int Execute(lua_State* L) noexcept { return 0; } }; struct Debug { static int ObjTable(lua_State* L) noexcept { return LPOOL.GetObjectTable(L); } }; struct Constructor { static int NewColor(lua_State* L) noexcept { Color4B c; if (lua_gettop(L) == 1) { // note: luaL_checkinteger return signed int const uint32_t val = luaL_checknumber(L, 1); c.a = val >> 24; c.r = val >> 16; c.g = val >> 8; c.b = val; } else { // a r g b c.set( int32_t(luaL_checkinteger(L, 2)), int32_t(luaL_checkinteger(L, 3)), int32_t(luaL_checkinteger(L, 4)), int32_t(luaL_checkinteger(L, 1)) ); } *ColorWrapper::CreateAndPush(L) = c; return 1; } static int NewRand(lua_State* L) noexcept { RandomizerWrapper::CreateAndPush(L); return 1; } }; struct Deprecated { static int UpdateObjList(lua_State* L) noexcept { return 0; } static int RegTTF(lua_State* L) noexcept { return 0; } static int UpdateSound(lua_State* L) noexcept { return 0; } }; vector<luaL_Reg> misc = { { "Snapshot", &Misc::Snapshot }, { "Execute", &Misc::Execute }, { "ObjTable", &Debug::ObjTable }, { "Color", &Constructor::NewColor }, { "Rand", &Constructor::NewRand }, { "UpdateObjList", &Deprecated::UpdateObjList }, { "RegTTF", &Deprecated::RegTTF }, { "UpdateSound", &Deprecated::UpdateSound }, }; functions.insert(functions.end(), misc.begin(), misc.end()); functions.push_back({ nullptr, nullptr }); luaL_register(L, "lstg", functions.data()); lua_pop(L, 1); }
19.137097
61
0.639275
[ "vector" ]