blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
6a9a2f0915276b04d663e5a3795d74fc4568447c
f052a43e591c1fb6b7984bc9ac1dae9ec2b9f139
/native/cocos/core/geometry/Obb.h
d0d8660dd5638ba5c2c0c65b2d3c5d21b4252589
[ "MIT" ]
permissive
BrokenTooth1989/engine
e430b258cdfb6ae6dcd10882aabaf0c714dd46f4
457f695e5c4c8b76f3e5970501c1d0224b0628d7
refs/heads/develop
2022-09-10T15:07:06.748314
2022-08-22T13:07:06
2022-08-22T13:07:06
194,266,719
1
0
null
2019-06-28T12:01:13
2019-06-28T12:01:13
null
UTF-8
C++
false
false
5,024
h
#pragma once #include "cocos/core/geometry/Enums.h" #include "cocos/math/Mat3.h" #include "cocos/math/Quaternion.h" #include "cocos/math/Vec3.h" namespace cc { namespace geometry { class OBB final : public ShapeBase { public: /** * @en * create a new obb * @zh * 创建一个新的 obb 实例。 * @param cx 形状的相对于原点的 X 坐标。 * @param cy 形状的相对于原点的 Y 坐标。 * @param cz 形状的相对于原点的 Z 坐标。 * @param hw - obb 宽度的一半。 * @param hh - obb 高度的一半。 * @param hl - obb 长度的一半。 * @param ox1 方向矩阵参数。 * @param ox2 方向矩阵参数。 * @param ox3 方向矩阵参数。 * @param oy1 方向矩阵参数。 * @param oy2 方向矩阵参数。 * @param oy3 方向矩阵参数。 * @param oz1 方向矩阵参数。 * @param oz2 方向矩阵参数。 * @param oz3 方向矩阵参数。 * @return 返回一个 obb。 */ static OBB *create( float cx, float cy, float cz, float hw, float hh, float hl, float ox1, float ox2, float ox3, float oy1, float oy2, float oy3, float oz1, float oz2, float oz3); /** * @en * clone a new obb * @zh * 克隆一个 obb。 * @param a 克隆的目标。 * @returns 克隆出的新对象。 */ static OBB *clone(const OBB &a); /** * @en * copy the values from one obb to another * @zh * 将从一个 obb 的值复制到另一个 obb。 * @param {OBB} out 接受操作的 obb。 * @param {OBB} a 被复制的 obb。 * @return {OBB} out 接受操作的 obb。 */ static OBB *copy(OBB *out, const OBB &a); /** * @en * create a new obb from two corner points * @zh * 用两个点创建一个新的 obb。 * @param out - 接受操作的 obb。 * @param minPos - obb 的最小点。 * @param maxPos - obb 的最大点。 * @returns {OBB} out 接受操作的 obb。 */ static OBB *fromPoints(OBB *out, const Vec3 &minPos, const Vec3 &maxPos); /** * @en * Set the components of a obb to the given values * @zh * 将给定 obb 的属性设置为给定的值。 * @param cx - obb 的原点的 X 坐标。 * @param cy - obb 的原点的 Y 坐标。 * @param cz - obb 的原点的 Z 坐标。 * @param hw - obb 宽度的一半。 * @param hh - obb 高度的一半。 * @param hl - obb 长度的一半。 * @param ox1 方向矩阵参数。 * @param ox2 方向矩阵参数。 * @param ox3 方向矩阵参数。 * @param oy1 方向矩阵参数。 * @param oy2 方向矩阵参数。 * @param oy3 方向矩阵参数。 * @param oz1 方向矩阵参数。 * @param oz2 方向矩阵参数。 * @param oz3 方向矩阵参数。 * @return {OBB} out */ static OBB *set(OBB *out, float cx, float cy, float cz, float hw, float hh, float hl, float ox1, float ox2, float ox3, float oy1, float oy2, float oy3, float oz1, float oz2, float oz3); /** * @zh * 本地坐标的中心点。 */ Vec3 center; /** * @zh * 长宽高的一半。 */ Vec3 halfExtents; /** * @zh * 方向矩阵。 */ Mat3 orientation; explicit OBB(float cx = 0, float cy = 0, float cz = 0, float hw = 1, float hh = 1, float hl = 1, float ox1 = 1, float ox2 = 0, float ox3 = 0, float oy1 = 0, float oy2 = 1, float oy3 = 0, float oz1 = 0, float oz2 = 0, float oz3 = 1); /** * @en * Get the bounding points of this shape * @zh * 获取 obb 的最小点和最大点。 * @param {Vec3} minPos 最小点。 * @param {Vec3} maxPos 最大点。 */ void getBoundary(Vec3 *minPos, Vec3 *maxPos) const; /** * Transform this shape * @zh * 将 out 根据这个 obb 的数据进行变换。 * @param m 变换的矩阵。 * @param pos 变换的位置部分。 * @param rot 变换的旋转部分。 * @param scale 变换的缩放部分。 * @param out 变换的目标。 */ void transform(const Mat4 &m, const Vec3 &pos, const Quaternion &rot, const Vec3 &scale, OBB *out) const; /** * @zh * 将 out 根据这个 obb 的数据进行变换。 * @param m 变换的矩阵。 * @param rot 变换的旋转部分。 * @param out 变换的目标。 */ void translateAndRotate(const Mat4 &m, const Quaternion &rot, OBB *out) const; /** * @zh * 将 out 根据这个 obb 的数据进行缩放。 * @param scale 缩放值。 * @param out 缩放的目标。 */ void setScale(const Vec3 &scale, OBB *out) const; }; } // namespace geometry } // namespace cc
dc8f2729174f4788e022a766684a436690879ddc
93ecc078956d4bd6c888c6e7710315ddc2504d74
/build/src_gen/GEN_CSV_WRITER_gen.cpp
cacaa8366c9ebf3a12713827edd4ae20f3d50516
[]
no_license
TuojianLYU/Forte_Dev_RevPi
bf0b4eee577c34ee9fb9dac9e8e89162e7a4148d
2b12cbebaebd574019b87ea3017f9b340168aefc
refs/heads/main
2023-07-09T16:30:48.393031
2021-08-19T07:52:49
2021-08-19T07:52:49
397,851,400
1
0
null
null
null
null
UTF-8
C++
false
false
1,178
cpp
/******************************************************************************* * Copyright (c) 2012 Profactor GmbH * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Michael Hofmann * - initial API and implementation and/or initial documentation *******************************************************************************/ //!!!autogenerated code - DO NOT EDIT!!! extern const CStringDictionary::TStringId g_nStringIdBOOL; extern const CStringDictionary::TStringId g_nStringIdCNF; extern const CStringDictionary::TStringId g_nStringIdFILE_NAME; extern const CStringDictionary::TStringId g_nStringIdINIT; extern const CStringDictionary::TStringId g_nStringIdINITO; extern const CStringDictionary::TStringId g_nStringIdQI; extern const CStringDictionary::TStringId g_nStringIdQO; extern const CStringDictionary::TStringId g_nStringIdREQ; extern const CStringDictionary::TStringId g_nStringIdSTATUS; extern const CStringDictionary::TStringId g_nStringIdSTRING;
a96fe6bdab52fcfa4230ba8127c81ae330548010
2694a23a6b19eb203cb5afacc2f17317cc0cad78
/sfmlHonors/Game.cpp
30ce3a11ee7109da9902bc69c84c228cbefa5d9c
[]
no_license
huntingforirish/AuthenticSpit
1f716a9f32f69ea8413a6250b8ff15ca49ddbd46
be42d9ed3f93302a8f840b22d0e58024f1f5c8c2
refs/heads/master
2020-03-28T23:36:25.717399
2018-09-18T14:20:52
2018-09-18T14:20:52
149,299,417
0
0
null
null
null
null
UTF-8
C++
false
false
3,847
cpp
#include "stdafx.h" #include "Game.h" //THIS CLASS IS OBSOLETE //NO LONGER USED //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Game::Game(Player p1, Player p2) { this->player1 = p1; this->player2 = p2; } Game::~Game() { } //sets the game up in preparation void Game::setup() { //creates and prints the initial deck this->newDeck.createDeck(); this->newDeck.toString(); //deals the deck's contents out to either player this->newDeck.deal(this->player1Deck, this->player2Deck); std::cout << "Player 1's deck contents post deal" << std::endl; this->player1Deck.toString(); std::cout << "Player 2's deck contents post deal" << std::endl; this->player2Deck.toString(); //deals each this->player1Deck.dealHand(&this->player1Hand.getHand1(), &this->player1Hand.getHand2(), &this->player1Hand.getHand3(), &this->player1Hand.getHand4(), &this->player1Hand.getHand5()); this->player2Deck.dealHand(&this->player2Hand.getHand1(), &this->player2Hand.getHand2(), &this->player2Hand.getHand3(), &this->player2Hand.getHand4(), &this->player2Hand.getHand5()); std::cout << "Player 1's deck size post dealing their hand" << std::endl; std::cout << this->player1Deck.size() << std::endl; std::cout << "Player 2's deck size post dealing their hand" << std::endl; std::cout << this->player2Deck.size() << std::endl; std::cout << "" << std::endl; this->player1Hand.getHand1().toString(); this->player1Hand.getHand2().toString(); this->player1Hand.getHand3().toString(); this->player1Hand.getHand4().toString(); this->player1Hand.getHand5().toString(); std::cout << "" << std::endl; this->player2Hand.getHand1().toString(); this->player2Hand.getHand2().toString(); this->player2Hand.getHand3().toString(); this->player2Hand.getHand4().toString(); this->player2Hand.getHand5().toString(); std::cout << "" << std::endl; } //begins the round by flipping over cards onto the game piles void Game::startRound() { this->player1Deck.play(this->gameDeck1); this->player2Deck.play(this->gameDeck2); gameDeck1.toString(); gameDeck2.toString(); std::cout << "" << std::endl; std::cout << player1Hand.getHand1().isPlayable(gameDeck1) << std::endl; std::cout << player1Hand.getHand1().isPlayable(gameDeck2) << std::endl; std::cout << player1Hand.getHand2().isPlayable(gameDeck1) << std::endl; std::cout << player1Hand.getHand2().isPlayable(gameDeck2) << std::endl; std::cout << player1Hand.getHand3().isPlayable(gameDeck1) << std::endl; std::cout << player1Hand.getHand3().isPlayable(gameDeck2) << std::endl; std::cout << player1Hand.getHand4().isPlayable(gameDeck1) << std::endl; std::cout << player1Hand.getHand4().isPlayable(gameDeck2) << std::endl; std::cout << player1Hand.getHand5().isPlayable(gameDeck1) << std::endl; std::cout << player1Hand.getHand5().isPlayable(gameDeck2) << std::endl; std::cout << "" << std::endl; std::cout << player2Hand.getHand1().isPlayable(gameDeck1) << std::endl; std::cout << player2Hand.getHand1().isPlayable(gameDeck2) << std::endl; std::cout << player2Hand.getHand2().isPlayable(gameDeck1) << std::endl; std::cout << player2Hand.getHand2().isPlayable(gameDeck2) << std::endl; std::cout << player2Hand.getHand3().isPlayable(gameDeck1) << std::endl; std::cout << player2Hand.getHand3().isPlayable(gameDeck2) << std::endl; std::cout << player2Hand.getHand4().isPlayable(gameDeck1) << std::endl; std::cout << player2Hand.getHand4().isPlayable(gameDeck2) << std::endl; std::cout << player2Hand.getHand5().isPlayable(gameDeck1) << std::endl; std::cout << player2Hand.getHand5().isPlayable(gameDeck2) << std::endl; this->playingStatus = true; } //clears all decks and resets game values void Game::wipe() { this->player1Deck.wipe(); this->player2Deck.wipe(); this->gameDeck1.wipe(); this->gameDeck2.wipe(); this->player1Hand.wipe(); this->player1Hand.wipe(); }
eaebe73d1fbe379a81218807babce293e984c4e7
7fb8348e0b4b2ba110cff377b704674495687fe4
/far/locale.cpp
987841ab65d6e3fb2be236a7078cfa0b13ea8e89
[ "BSD-3-Clause" ]
permissive
ziceptor/FarManager
b31df7ba91d389c7dbc8449a178f5e9722063d98
ae71819113b4ccdb619b60bdbeb2092f31299246
refs/heads/master
2021-05-09T11:28:56.660214
2018-01-25T22:15:17
2018-01-25T22:15:17
118,988,582
1
0
null
2018-01-26T01:23:01
2018-01-26T01:23:01
null
UTF-8
C++
false
false
3,286
cpp
/* locale.cpp */ /* Copyright © 2014 Far Group 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. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "headers.hpp" #pragma hdrstop #include "locale.hpp" #include "config.hpp" int locale::GetDateFormat() { int Result; // TODO: log if (!GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IDATE | LOCALE_RETURN_NUMBER, reinterpret_cast<wchar_t*>(&Result), sizeof(Result) / sizeof(wchar_t))) return 0; return Result; } wchar_t locale::GetDateSeparator() { wchar_t Info[100]; if (!GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SDATE, Info, static_cast<int>(std::size(Info)))) { // TODO: log return L'/'; } return *Info; } wchar_t locale::GetTimeSeparator() { wchar_t Info[100]; if (!GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STIME, Info, static_cast<int>(std::size(Info)))) { // TODO: log return L':'; } return *Info; } wchar_t locale::GetDecimalSeparator() { wchar_t Separator[4]; if (!GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, Separator, static_cast<int>(std::size(Separator)))) { // TODO: log *Separator = L'.'; } if (Global && Global->Opt && Global->Opt->FormatNumberSeparators.size() > 1) *Separator = Global->Opt->FormatNumberSeparators[1]; return *Separator; } wchar_t locale::GetThousandSeparator() { wchar_t Separator[4]; if (!GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, Separator, static_cast<int>(std::size(Separator)))) { // TODO: log *Separator = L','; } if (Global && Global->Opt && !Global->Opt->FormatNumberSeparators.empty()) *Separator = Global->Opt->FormatNumberSeparators[0]; return *Separator; } string locale::GetValue(LCID lcid, LCTYPE id) { return os::GetLocaleValue(lcid, id); } string locale::GetTimeFormat() { wchar_t TimeBuffer[MAX_PATH]; const size_t Size = ::GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, nullptr, nullptr, TimeBuffer, static_cast<int>(std::size(TimeBuffer))); if (!Size) { // TODO: log return {}; } return { TimeBuffer, Size - 1 }; }
85dd73f13101b579deac3d2f105b087c8a2cd2e9
fa0eb130ba70c58f01e6a0cb24e6b8116d575f08
/Drei/drei/camera/Camera.h
21d38884ff9731e52f9fcb5df26fc4f8e1d5994d
[]
no_license
gue-ni/Drei
422468c4fa66e3242b1d2f57f1b20fd766b3daec
13fad507bad648fd27e75d9b76353bcbeb97e485
refs/heads/master
2023-06-08T12:03:58.535143
2021-07-04T12:23:18
2021-07-04T12:23:18
382,815,773
0
0
null
null
null
null
UTF-8
C++
false
false
325
h
#pragma once #include "../core/Object3D.h" #include <glm/glm.hpp> namespace DREI { class Camera : public DREI::Object3D { public: float fov; float width; float height; float near; float far; glm::mat4 view; glm::mat4 projection; Camera(float width, float height, float fov, float near, float far); }; }
b3a8b88d345126679fd344cd5bd3425acf2b94d1
40b244391bffe9c935c21b269a47da5ae02ad4e8
/src/Window.h
7232b9c66c8cca18800be2561f416a0561e089ea
[]
no_license
SebastianDang/OpenGL
a15794edc73cb14bdab4a1317f00071c01b2b768
b0b564dac4b1c5cd39f930192959ffc0dc5174e4
refs/heads/master
2022-02-17T19:11:02.117509
2019-08-16T05:18:41
2019-08-16T05:18:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,298
h
#pragma once enum E_MOUSE { IDLE = 0, LEFT_HOLD = 1, RIGHT_HOLD = 2 }; class Window { private: // Perspective properties. static float FieldOfView; static float NearPlane; static float FarPlane; // Window size properties static int Width; static int Height; // Mouse properties static int Mouse_Status; static glm::vec3 LastPoint; static glm::vec3 CurrPoint; // Frame Time calculation static float LastFrameTime; static float DeltaFrameTime; public: // Matrix Coordinate Transformation properties static glm::mat4 P; static glm::mat4 V; // Window functions static GLFWwindow* create_window(int width, int height); static void Start(); static void Stop(); // Window callbacks static void resize_callback(GLFWwindow* window, int width, int height); static void idle_callback(); static void frame_time_callback(); static void display_callback(GLFWwindow*); // Keyboard and mouse callback functions static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); static void cursor_pos_callback(GLFWwindow* window, double xpos, double ypos); static void cursor_button_callback(GLFWwindow* window, int button, int action, int mods); static void cursor_scroll_callback(GLFWwindow* window, double xoffset, double yoffset); };
ff4a17f6f5fd53ca14c7af4f6d57de56b5401556
7f597f759afc110477cf4779a9d3f0b1e6e4c096
/DuggooEngine/src/utils/file_io.h
45a4c661eeab53ca32c2bb50b3b5f6b1855bb981
[]
no_license
Zn0w/DuggooEngine
52454fa08b10f5abd085e6b0774c85ef19a41c92
64fe037176f52d7c7f0ba872927271e00254b3ec
refs/heads/master
2020-04-03T03:38:24.670435
2019-10-23T06:33:13
2019-10-23T06:33:13
154,991,353
0
0
null
null
null
null
UTF-8
C++
false
false
136
h
#pragma once #include <stdio.h> #include <stdlib.h> #include <string> namespace dg { std::string readFile(const char* filepath); }
acba7608a87f976e07dc8040f2cf60403048993b
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/components/update_client/component.h
cc263f45af441347e5e74f67154ed8e043c997c9
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
16,213
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_UPDATE_CLIENT_COMPONENT_H_ #define COMPONENTS_UPDATE_CLIENT_COMPONENT_H_ #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "base/callback.h" #include "base/files/file_path.h" #include "base/gtest_prod_util.h" #include "base/memory/ref_counted.h" #include "base/optional.h" #include "base/sequence_checker.h" #include "base/time/time.h" #include "base/version.h" #include "components/update_client/crx_downloader.h" #include "components/update_client/protocol_parser.h" #include "components/update_client/update_client.h" #include "url/gurl.h" namespace base { class Value; } // namespace base namespace update_client { class ActionRunner; class Configurator; struct CrxUpdateItem; struct UpdateContext; // Describes a CRX component managed by the UpdateEngine. Each instance of // this class is associated with one instance of UpdateContext. class Component { public: using Events = UpdateClient::Observer::Events; using CallbackHandleComplete = base::OnceCallback<void()>; Component(const UpdateContext& update_context, const std::string& id); Component(const Component&) = delete; Component& operator=(const Component&) = delete; ~Component(); // Handles the current state of the component and makes it transition // to the next component state before |callback_handle_complete_| is invoked. void Handle(CallbackHandleComplete callback_handle_complete); CrxUpdateItem GetCrxUpdateItem() const; // Sets the uninstall state for this component. void Uninstall(const base::Version& cur_version, int reason); // Called by the UpdateEngine when an update check for this component is done. void SetUpdateCheckResult( const base::Optional<ProtocolParser::Result>& result, ErrorCategory error_category, int error); // Called by the UpdateEngine when a component enters a wait for throttling // purposes. void NotifyWait(); // Returns true if the component has reached a final state and no further // handling and state transitions are possible. bool IsHandled() const { return is_handled_; } // Returns true if an update is available for this component, meaning that // the update server has return a response containing an update. bool IsUpdateAvailable() const { return is_update_available_; } base::TimeDelta GetUpdateDuration() const; ComponentState state() const { return state_->state(); } std::string id() const { return id_; } const base::Optional<CrxComponent>& crx_component() const { return crx_component_; } void set_crx_component(const CrxComponent& crx_component) { crx_component_ = crx_component; } const base::Version& previous_version() const { return previous_version_; } void set_previous_version(const base::Version& previous_version) { previous_version_ = previous_version; } const base::Version& next_version() const { return next_version_; } std::string previous_fp() const { return previous_fp_; } void set_previous_fp(const std::string& previous_fp) { previous_fp_ = previous_fp; } std::string next_fp() const { return next_fp_; } void set_next_fp(const std::string& next_fp) { next_fp_ = next_fp; } bool is_foreground() const; const std::vector<GURL>& crx_diffurls() const { return crx_diffurls_; } bool diff_update_failed() const { return !!diff_error_code_; } ErrorCategory error_category() const { return error_category_; } int error_code() const { return error_code_; } int extra_code1() const { return extra_code1_; } ErrorCategory diff_error_category() const { return diff_error_category_; } int diff_error_code() const { return diff_error_code_; } int diff_extra_code1() const { return diff_extra_code1_; } std::string action_run() const { return action_run_; } scoped_refptr<Configurator> config() const; std::string session_id() const; const std::vector<base::Value>& events() const { return events_; } // Returns a clone of the component events. std::vector<base::Value> GetEvents() const; private: friend class MockPingManagerImpl; friend class UpdateCheckerTest; FRIEND_TEST_ALL_PREFIXES(PingManagerTest, SendPing); FRIEND_TEST_ALL_PREFIXES(PingManagerTest, RequiresEncryption); FRIEND_TEST_ALL_PREFIXES(UpdateCheckerTest, NoUpdateActionRun); FRIEND_TEST_ALL_PREFIXES(UpdateCheckerTest, UpdateCheckCupError); FRIEND_TEST_ALL_PREFIXES(UpdateCheckerTest, UpdateCheckError); FRIEND_TEST_ALL_PREFIXES(UpdateCheckerTest, UpdateCheckInvalidAp); FRIEND_TEST_ALL_PREFIXES(UpdateCheckerTest, UpdateCheckRequiresEncryptionError); FRIEND_TEST_ALL_PREFIXES(UpdateCheckerTest, UpdateCheckSuccess); FRIEND_TEST_ALL_PREFIXES(UpdateCheckerTest, UpdateCheckUpdateDisabled); // Describes an abstraction for implementing the behavior of a component and // the transition from one state to another. class State { public: using CallbackNextState = base::OnceCallback<void(std::unique_ptr<State> next_state)>; State(Component* component, ComponentState state); virtual ~State(); // Handles the current state and initiates a transition to a new state. // The transition to the new state is non-blocking and it is completed // by the outer component, after the current state is fully handled. void Handle(CallbackNextState callback); ComponentState state() const { return state_; } protected: // Initiates the transition to the new state. void TransitionState(std::unique_ptr<State> new_state); // Makes the current state a final state where no other state transition // can further occur. void EndState(); Component& component() { return component_; } const Component& component() const { return component_; } SEQUENCE_CHECKER(sequence_checker_); const ComponentState state_; private: virtual void DoHandle() = 0; Component& component_; CallbackNextState callback_next_state_; }; class StateNew : public State { public: explicit StateNew(Component* component); StateNew(const StateNew&) = delete; StateNew& operator=(const StateNew&) = delete; ~StateNew() override; private: // State overrides. void DoHandle() override; }; class StateChecking : public State { public: explicit StateChecking(Component* component); StateChecking(const StateChecking&) = delete; StateChecking& operator=(const StateChecking&) = delete; ~StateChecking() override; private: // State overrides. void DoHandle() override; void UpdateCheckComplete(); }; class StateUpdateError : public State { public: explicit StateUpdateError(Component* component); StateUpdateError(const StateUpdateError&) = delete; StateUpdateError& operator=(const StateUpdateError&) = delete; ~StateUpdateError() override; private: // State overrides. void DoHandle() override; }; class StateCanUpdate : public State { public: explicit StateCanUpdate(Component* component); StateCanUpdate(const StateCanUpdate&) = delete; StateCanUpdate& operator=(const StateCanUpdate&) = delete; ~StateCanUpdate() override; private: // State overrides. void DoHandle() override; bool CanTryDiffUpdate() const; }; class StateUpToDate : public State { public: explicit StateUpToDate(Component* component); StateUpToDate(const StateUpToDate&) = delete; StateUpToDate& operator=(const StateUpToDate&) = delete; ~StateUpToDate() override; private: // State overrides. void DoHandle() override; }; class StateDownloadingDiff : public State { public: explicit StateDownloadingDiff(Component* component); StateDownloadingDiff(const StateDownloadingDiff&) = delete; StateDownloadingDiff& operator=(const StateDownloadingDiff&) = delete; ~StateDownloadingDiff() override; private: // State overrides. void DoHandle() override; // Called when progress is being made downloading a CRX. Can be called // multiple times due to how the CRX downloader switches between // different downloaders and fallback urls. void DownloadProgress(int64_t downloaded_bytes, int64_t total_bytes); void DownloadComplete(const CrxDownloader::Result& download_result); // Downloads updates for one CRX id only. scoped_refptr<CrxDownloader> crx_downloader_; }; class StateDownloading : public State { public: explicit StateDownloading(Component* component); StateDownloading(const StateDownloading&) = delete; StateDownloading& operator=(const StateDownloading&) = delete; ~StateDownloading() override; private: // State overrides. void DoHandle() override; // Called when progress is being made downloading a CRX. Can be called // multiple times due to how the CRX downloader switches between // different downloaders and fallback urls. void DownloadProgress(int64_t downloaded_bytes, int64_t total_bytes); void DownloadComplete(const CrxDownloader::Result& download_result); // Downloads updates for one CRX id only. scoped_refptr<CrxDownloader> crx_downloader_; }; class StateUpdatingDiff : public State { public: explicit StateUpdatingDiff(Component* component); StateUpdatingDiff(const StateUpdatingDiff&) = delete; StateUpdatingDiff& operator=(const StateUpdatingDiff&) = delete; ~StateUpdatingDiff() override; private: // State overrides. void DoHandle() override; void InstallProgress(int install_progress); void InstallComplete(ErrorCategory error_category, int error_code, int extra_code1); }; class StateUpdating : public State { public: explicit StateUpdating(Component* component); StateUpdating(const StateUpdating&) = delete; StateUpdating& operator=(const StateUpdating&) = delete; ~StateUpdating() override; private: // State overrides. void DoHandle() override; void InstallProgress(int install_progress); void InstallComplete(ErrorCategory error_category, int error_code, int extra_code1); }; class StateUpdated : public State { public: explicit StateUpdated(Component* component); StateUpdated(const StateUpdated&) = delete; StateUpdated& operator=(const StateUpdated&) = delete; ~StateUpdated() override; private: // State overrides. void DoHandle() override; }; class StateUninstalled : public State { public: explicit StateUninstalled(Component* component); StateUninstalled(const StateUninstalled&) = delete; StateUninstalled& operator=(const StateUninstalled&) = delete; ~StateUninstalled() override; private: // State overrides. void DoHandle() override; }; class StateRun : public State { public: explicit StateRun(Component* component); StateRun(const StateRun&) = delete; StateRun& operator=(const StateRun&) = delete; ~StateRun() override; private: // State overrides. void DoHandle() override; void ActionRunComplete(bool succeeded, int error_code, int extra_code1); // Runs the action referred by the |action_run_| member of the Component // class. std::unique_ptr<ActionRunner> action_runner_; }; // Returns true is the update payload for this component can be downloaded // by a downloader which can do bandwidth throttling on the client side. bool CanDoBackgroundDownload() const; void AppendEvent(base::Value event); // Changes the component state and notifies the caller of the |Handle| // function that the handling of this component state is complete. void ChangeState(std::unique_ptr<State> next_state); // Notifies registered observers about changes in the state of the component. // If an UpdateClient::CrxStateChangeCallback is provided as an argument to // UpdateClient::Install or UpdateClient::Update function calls, then the // callback is invoked as well. void NotifyObservers(Events event) const; void SetParseResult(const ProtocolParser::Result& result); // These functions return a specific event. Each data member of the event is // represented as a key-value pair in a dictionary value. base::Value MakeEventUpdateComplete() const; base::Value MakeEventDownloadMetrics( const CrxDownloader::DownloadMetrics& download_metrics) const; base::Value MakeEventUninstalled() const; base::Value MakeEventActionRun(bool succeeded, int error_code, int extra_code1) const; std::unique_ptr<CrxInstaller::InstallParams> install_params() const; SEQUENCE_CHECKER(sequence_checker_); const std::string id_; base::Optional<CrxComponent> crx_component_; // The status of the updatecheck response. std::string status_; // Time when an update check for this CRX has happened. base::TimeTicks last_check_; // Time when the update of this CRX has begun. base::TimeTicks update_begin_; // A component can be made available for download from several urls. std::vector<GURL> crx_urls_; std::vector<GURL> crx_diffurls_; // The cryptographic hash values for the component payload. std::string hash_sha256_; std::string hashdiff_sha256_; // The from/to version and fingerprint values. base::Version previous_version_; base::Version next_version_; std::string previous_fp_; std::string next_fp_; // Contains the file name of the payload to run. This member is set by // the update response parser, when the update response includes a run action. std::string action_run_; // True if the update check response for this component includes an update. bool is_update_available_ = false; // The error reported by the update checker. int update_check_error_ = 0; base::FilePath crx_path_; // The byte counts below are valid for the current url being fetched. // |total_bytes| is equal to the size of the CRX file and |downloaded_bytes| // represents how much has been downloaded up to that point. A value of -1 // means that the byte count is unknown. int64_t downloaded_bytes_ = -1; int64_t total_bytes_ = -1; // Install progress, in the range of [0, 100]. A value of -1 means that the // progress is unknown. int install_progress_ = -1; // The error information for full and differential updates. // The |error_category| contains a hint about which module in the component // updater generated the error. The |error_code| constains the error and // the |extra_code1| usually contains a system error, but it can contain // any extended information that is relevant to either the category or the // error itself. ErrorCategory error_category_ = ErrorCategory::kNone; int error_code_ = 0; int extra_code1_ = 0; ErrorCategory diff_error_category_ = ErrorCategory::kNone; int diff_error_code_ = 0; int diff_extra_code1_ = 0; // Contains app-specific custom response attributes from the server, sent in // the last update check. std::map<std::string, std::string> custom_attrs_; // Contains the optional |run| and |arguments| values in the update response // manifest. This data is provided as an argument to the |Install| call. base::Optional<CrxInstaller::InstallParams> install_params_; // Contains the events which are therefore serialized in the requests. std::vector<base::Value> events_; CallbackHandleComplete callback_handle_complete_; std::unique_ptr<State> state_; const UpdateContext& update_context_; base::OnceClosure update_check_complete_; ComponentState previous_state_ = ComponentState::kLastStatus; // True if this component has reached a final state because all its states // have been handled. bool is_handled_ = false; }; using IdToComponentPtrMap = std::map<std::string, std::unique_ptr<Component>>; } // namespace update_client #endif // COMPONENTS_UPDATE_CLIENT_COMPONENT_H_
0d496e3ae2bf543973ac2cc4c52c676cb1187507
68cd659b44f57adf266dd37789bd1da31f61670d
/C/0926/자가 복제 문자열/자가 복제 문자열/소스.cpp
c74fb2e89f210748ca294b75ba2f1b4e4b3d271b
[]
no_license
01090841589/solved_problem
c0c6f5a46e4d48860dccb3b0288aa5b56868fbca
bbea2f31e5fe36cad100bc514eacd83545fb25b1
refs/heads/master
2023-07-02T23:55:51.631478
2021-08-04T13:57:00
2021-08-04T13:57:00
197,157,830
2
0
null
null
null
null
UHC
C++
false
false
514
cpp
#include <stdio.h> int T; long long K; int result; int main() { freopen("자가복제문자열.txt", "r", stdin); scanf("%d", &T); for (int tc = 0; tc < T; tc++) { scanf("%lld", &K); while (true) { if (K % 4 == 3) { result = 1; break; } if (K % 4 == 1) { result = 0; break; } if (K % 8 == 6) { result = 1; break; } if (K % 8 == 2) { result = 0; break; } if (K % 4 == 0) { K = K / 4; } } printf("#%d %d\n",tc+1, result); } return 0; }
b63e0c17cd262fda9249806fb8abfba3e10707d1
9214dcc856f50248f10cc6c73f75588888f2b108
/RoadStyle/main.cpp
b83a8b8f2b1fa5507cfb8720a387b022a7a8dbcf
[]
no_license
gnishida/RoadStyle
f50b08ea9894332fe589afa0320308ecb864733e
faeffc3e9ae436d687a9bcda6f13ccb4f01d109c
refs/heads/master
2016-09-05T12:02:36.246386
2013-12-16T03:25:12
2013-12-16T03:25:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
201
cpp
#include "RoadStyle.h" #include "Util.h" #include <QtGui/QApplication> #include <assert.h> int main(int argc, char *argv[]) { QApplication a(argc, argv); RoadStyle w; w.show(); return a.exec(); }
be70d8f837205812d6cae824ceb1bc08836b48ba
e3e012664e3b4c016b7ed240cd9b81af1289149e
/thirdparty/linux/ntl/src/WordVector.c
4cd71ca48f2ba191b382ff9c97e0cbe0b75d8a8a
[ "GPL-1.0-or-later", "Unlicense" ]
permissive
osu-crypto/MultipartyPSI
b48ce23163fed8eb458a05e3af6e4432963f08c7
44e965607b0d27416420d32cd09e6fcc34782c3a
refs/heads/implement
2023-07-20T10:16:55.866284
2021-05-12T22:01:12
2021-05-12T22:01:12
100,207,769
73
29
Unlicense
2023-07-11T04:42:04
2017-08-13T22:15:27
C++
UTF-8
C++
false
false
7,560
c
#include <NTL/WordVector.h> #include <NTL/new.h> #include <cstdio> NTL_START_IMPL void WordVector::DoSetLength(long n) { long m; if (n < 0) { LogicError("negative length in vector::SetLength"); } if (NTL_OVERFLOW(n, NTL_BITS_PER_LONG, 0)) ResourceError("length too big in vector::SetLength"); if (n == 0) { if (rep) rep[-1] = 0; return; } if (!rep) { m = ((n+NTL_WordVectorMinAlloc-1)/NTL_WordVectorMinAlloc) * NTL_WordVectorMinAlloc; if (NTL_OVERFLOW(m, NTL_BITS_PER_LONG, 0)) ResourceError("length too big in vector::SetLength"); _ntl_ulong *p = (_ntl_ulong *) NTL_MALLOC(m, sizeof(_ntl_ulong), 2*sizeof(_ntl_ulong)); if (!p) { MemoryError(); } rep = p+2; rep[-1] = n; rep[-2] = m << 1; return; } long max_length = (rep[-2] >> 1); if (n <= max_length) { rep[-1] = n; return; } long frozen = (rep[-2] & 1); if (frozen) LogicError("Cannot grow this WordVector"); m = max(n, long(NTL_WordVectorExpansionRatio*max_length)); m = ((m+NTL_WordVectorMinAlloc-1)/NTL_WordVectorMinAlloc)*NTL_WordVectorMinAlloc; _ntl_ulong *p = rep - 2; if (NTL_OVERFLOW(m, NTL_BITS_PER_LONG, 0)) ResourceError("length too big in vector::SetLength"); p = (_ntl_ulong *) NTL_REALLOC(p, m, sizeof(_ntl_ulong), 2*sizeof(_ntl_ulong)); if (!p) { MemoryError(); } rep = p+2; rep[-1] = n; rep[-2] = m << 1; } void WordVector::SetMaxLength(long n) { long OldLength = length(); DoSetLength(n); if (rep) rep[-1] = OldLength; } WordVector& WordVector::operator=(const WordVector& a) { long i, n; _ntl_ulong *p; const _ntl_ulong *ap; if (this == &a) return *this; n = a.length(); ap = a.elts(); SetLength(n); p = elts(); for (i = 0; i < n; i++) p[i] = ap[i]; return *this; } WordVector::~WordVector() { if (!rep) return; if (rep[-2] & 1) TerminalError("Cannot free this WordVector"); free(rep-2); } void WordVector::kill() { if (!rep) return; if (rep[-2] & 1) LogicError("Cannot free this WordVector"); free(rep-2); rep = 0; } void CopySwap(WordVector& x, WordVector& y) { NTL_TLS_LOCAL(WordVector, t); WordVectorWatcher watch_t(t); long sz_x = x.length(); long sz_y = y.length(); long sz = (sz_x > sz_y) ? sz_x : sz_y; x.SetMaxLength(sz); y.SetMaxLength(sz); // EXCEPTIONS: all of the above ensures that swap provides strong ES t = x; x = y; y = t; } void WordVector::swap(WordVector& y) { if ((this->rep && (this->rep[-2] & 1)) || (y.rep && (y.rep[-2] & 1))) { CopySwap(*this, y); return; } _ntl_swap(this->rep, y.rep); } void WordVector::append(_ntl_ulong a) { long l = this->length(); this->SetLength(l+1); (*this)[l] = a; } void WordVector::append(const WordVector& w) { long l = this->length(); long m = w.length(); long i; this->SetLength(l+m); for (i = 0; i < m; i++) (*this)[l+i] = w[i]; } istream & operator>>(istream& s, WordVector& a) { WordVector ibuf; long c; long n; if (!s) NTL_INPUT_ERROR(s, "bad vector input"); c = s.peek(); while (IsWhiteSpace(c)) { s.get(); c = s.peek(); } if (c != '[') { NTL_INPUT_ERROR(s, "bad vector input"); } n = 0; ibuf.SetLength(0); s.get(); c = s.peek(); while (IsWhiteSpace(c)) { s.get(); c = s.peek(); } while (c != ']' && c != EOF) { if (n % NTL_WordVectorInputBlock == 0) ibuf.SetMaxLength(n + NTL_WordVectorInputBlock); n++; ibuf.SetLength(n); if (!(s >> ibuf[n-1])) NTL_INPUT_ERROR(s, "bad vector input"); c = s.peek(); while (IsWhiteSpace(c)) { s.get(); c = s.peek(); } } if (c == EOF) NTL_INPUT_ERROR(s, "bad vector input"); s.get(); a = ibuf; return s; } ostream& operator<<(ostream& s, const WordVector& a) { long i, n; n = a.length(); s << '['; for (i = 0; i < n; i++) { s << a[i]; if (i < n-1) s << " "; } s << ']'; return s; } long operator==(const WordVector& a, const WordVector& b) { long n = a.length(); if (b.length() != n) return 0; const _ntl_ulong* ap = a.elts(); const _ntl_ulong* bp = b.elts(); long i; for (i = 0; i < n; i++) if (ap[i] != bp[i]) return 0; return 1; } long operator!=(const WordVector& a, const WordVector& b) { return !(a == b); } long InnerProduct(const WordVector& a, const WordVector& b) { long n = min(a.length(), b.length()); const _ntl_ulong *ap = a.elts(); const _ntl_ulong *bp = b.elts(); _ntl_ulong acc; long i; acc = 0; for (i = 0; i < n; i++) acc ^= ap[i] & bp[i]; #if (NTL_BITS_PER_LONG == 32) acc ^= acc >> 16; acc ^= acc >> 8; acc ^= acc >> 4; acc ^= acc >> 2; acc ^= acc >> 1; acc &= 1; #elif (NTL_BITS_PER_LONG == 64) acc ^= acc >> 32; acc ^= acc >> 16; acc ^= acc >> 8; acc ^= acc >> 4; acc ^= acc >> 2; acc ^= acc >> 1; acc &= 1; #else _ntl_ulong t = acc; while (t) { t = t >> 8; acc ^= t; } acc ^= acc >> 4; acc ^= acc >> 2; acc ^= acc >> 1; acc &= 1; #endif return long(acc); } void ShiftAdd(_ntl_ulong *cp, const _ntl_ulong* ap, long sa, long n) // c = c + (a << n) { if (sa == 0) return; long i; long wn = n/NTL_BITS_PER_LONG; long bn = n - wn*NTL_BITS_PER_LONG; if (bn == 0) { for (i = sa+wn-1; i >= wn; i--) cp[i] ^= ap[i-wn]; } else { _ntl_ulong t = ap[sa-1] >> (NTL_BITS_PER_LONG-bn); if (t) cp[sa+wn] ^= t; for (i = sa+wn-1; i >= wn+1; i--) cp[i] ^= (ap[i-wn] << bn) | (ap[i-wn-1] >> (NTL_BITS_PER_LONG-bn)); cp[wn] ^= ap[0] << bn; } } long WV_BlockConstructAlloc(WordVector& x, long d, long n) { long nwords, nbytes, AllocAmt, m, j; _ntl_ulong *p, *q; /* check n value */ if (n <= 0) LogicError("block construct: n must be positive"); /* check d value */ if (d <= 0) LogicError("block construct: d must be positive"); if (NTL_OVERFLOW(d, NTL_BITS_PER_LONG, 0) || NTL_OVERFLOW(d, sizeof(_ntl_ulong), 2*sizeof(_ntl_ulong))) ResourceError("block construct: d too large"); nwords = d + 2; nbytes = nwords*sizeof(_ntl_ulong); AllocAmt = (NTL_MAX_ALLOC_BLOCK - sizeof(_ntl_ulong)) / nbytes; if (AllocAmt == 0) AllocAmt = 1; if (AllocAmt < n) m = AllocAmt; else m = n; p = (_ntl_ulong *) NTL_MALLOC(m, nbytes, sizeof(_ntl_ulong)); if (!p) MemoryError(); *p = m; q = p+3; x.rep = q; for (j = 0; j < m; j++) { q[-2] = (d << 1) | 1; q[-1] = 0; q += nwords; } return m; } void WV_BlockConstructSet(WordVector& x, WordVector& y, long i) { long d, size; d = x.rep[-2] >> 1; size = d + 2; y.rep = x.rep + i*size; } long WV_BlockDestroy(WordVector& x) { long m; _ntl_ulong *p; p = x.rep - 3; m = (long) *p; free(p); return m; } long WV_storage(long d) { return (d + 2)*sizeof(_ntl_ulong) + sizeof(WordVector); } NTL_END_IMPL
3d1511fd6480fb1f3d9e165d074b90aef91290e6
e27d9e460c374473e692f58013ca692934347ef1
/drafts/quickSpectrogram_2/libraries/liblsl/external/lslboost/function/function_fwd.hpp
ecf542f49e0b33c97cb3047169c26f4de7877348
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
thoughtworksarts/Dual_Brains
84a0edf69d95299021daf4af9311aed5724a2e84
a7a6586b91a280950693b427d8269bd68bf8a7ab
refs/heads/master
2021-09-18T15:50:51.397078
2018-07-16T23:20:18
2018-07-16T23:20:18
119,759,649
3
0
null
2018-07-16T23:14:34
2018-02-01T00:09:16
HTML
UTF-8
C++
false
false
2,760
hpp
// Boost.Function library // Copyright (C) Douglas Gregor 2008 // // Use, modification and distribution is subject to the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.lslboost.org/LICENSE_1_0.txt) // // For more information, see http://www.lslboost.org #ifndef BOOST_FUNCTION_FWD_HPP #define BOOST_FUNCTION_FWD_HPP #include <lslboost/config.hpp> #if defined(__sgi) && defined(_COMPILER_VERSION) && _COMPILER_VERSION <= 730 && !defined(BOOST_STRICT_CONFIG) // Work around a compiler bug. // lslboost::python::objects::function has to be seen by the compiler before the // lslboost::function class template. namespace lslboost { namespace python { namespace objects { class function; }}} #endif #if defined (BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \ || defined(BOOST_BCB_PARTIAL_SPECIALIZATION_BUG) \ || !(defined(BOOST_STRICT_CONFIG) || !defined(__SUNPRO_CC) || __SUNPRO_CC > 0x540) # define BOOST_FUNCTION_NO_FUNCTION_TYPE_SYNTAX #endif namespace lslboost { class bad_function_call; #if !defined(BOOST_FUNCTION_NO_FUNCTION_TYPE_SYNTAX) // Preferred syntax template<typename Signature> class function; template<typename Signature> inline void swap(function<Signature>& f1, function<Signature>& f2) { f1.swap(f2); } #endif // have partial specialization // Portable syntax template<typename R> class function0; template<typename R, typename T1> class function1; template<typename R, typename T1, typename T2> class function2; template<typename R, typename T1, typename T2, typename T3> class function3; template<typename R, typename T1, typename T2, typename T3, typename T4> class function4; template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5> class function5; template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> class function6; template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> class function7; template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> class function8; template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> class function9; template<typename R, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> class function10; } #endif
de38770f62e78857243ad12d9c505f1f62dcab82
0ff28e62a0df150d58b4b782254e84c78238dc0e
/jump-game-ii.cpp
8b64ae4ba9d574531962ed2db8c8220c4749d254
[]
no_license
spacelan/leetcode
3066331117c2ce1c7345d75b5dfb5eab7ff039f1
c495d8bca0ae9d75b5e1f1b97136e47b0c9343db
refs/heads/master
2020-04-14T13:07:14.846634
2015-07-03T14:10:26
2015-07-03T14:10:26
31,496,845
2
1
null
null
null
null
UTF-8
C++
false
false
1,634
cpp
/** \link https://leetcode.com/problems/jump-game-ii/ * \comments 这是别人的答案,写得非常简洁,用的贪心算法。一开始看到这个题我就想着用动态规划,实现也非常简单,结果超时。确实,用动规的搜索范围也很大,最坏情况下O(n^2)。所以我又想了各种办法剪枝,也不行。没办法,去讨论看到了这个答案,贪心算法,时间O(n)。其思路是迭代当前节点与当前节点所能跳到的最远节点之间的所有节点,找出再跳一次能到达的最远节点,跳到该节点,更新状态,继续迭代。最后,这次我深刻地认识到,千万不要不相信Tag标签给的提示,,说是贪心,那么,,还真的是用贪心。。。 */ class Solution { public: int jump(int A[], int n) { int i = 0, j = 1, cnt = 0, mx; if (n == 1) return 0; while (i < n - 1 && i + A[i] < n - 1) { for (mx = j; j <= i + A[i]; j++) { mx = (mx + A[mx] <= j + A[j]) ? j : mx; } i = mx; cnt++; } return ++cnt; } }; /*还是贴上我自己的动规代码*/ class Solution { public: int jump(int A[], int n) { int jump_count[n]; int index = n - 1; int i; memset(jump_count,0,n*sizeof(int)); jump_count[0] = n - 1; while(index--){ if(A[index] == 0) continue; i = 0; while(index+A[index]<jump_count[i]) i++; if(jump_count[i] == 0) continue; jump_count[i+1] = index; } return i+1; } };
3263dbb34944ea77a71533839df67587ced210bd
df3562b194ad2728a9aeebbdfd6b5d3117b37456
/Src/Lib/STLRelated/STLLib/Includes/Always.h
53ec00dd189f6285ab13557cfd2970f990892ccb
[ "MIT" ]
permissive
ericyao2013/UAV-Drona
f96a749ea9cfadb946c3691e0d93ee77e9fd52a2
1877b3d658401b9d65d4b5cf52b96e7efa479d6a
refs/heads/master
2020-03-18T17:18:12.162654
2018-04-10T18:35:09
2018-04-10T18:35:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
312
h
#ifndef ALWAYS_H #define ALWAYS_H #include "STL.h" #include <sstream> using namespace std; class Always : public STL { private: STL *subFormula; double t_start, t_end; // interval times public: Always(STL* subFormula, double t_start, double t_end); string ToString(); }; #endif // ALWAYS_H
b8d297a874ead942505a9576a643df41dc0533fd
1757a77fcc570703a12e16fc94146f36e766424c
/include/fcl/math/vec_3f.h
840ba8de3a915781b78df126104c81ca486e7eb3
[]
no_license
panjia1983/fcl_with_pd
8ef66219c720229f514e22e1a997389fef2366cb
17ce8bbe95403b610475528a7028fb48791dc7a6
refs/heads/master
2021-01-01T06:54:44.379076
2014-05-15T19:01:12
2014-05-15T19:01:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,475
h
/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** \author Jia Pan */ #ifndef FCL_VEC_3F_H #define FCL_VEC_3F_H #include "fcl/config.h" #include "fcl/data_types.h" #include "fcl/math/math_details.h" #if FCL_HAVE_SSE # include "fcl/simd/math_simd_details.h" #endif #include <cmath> #include <iostream> #include <limits> namespace fcl { /// @brief Vector3 class wrapper. The core data is in the template parameter class. template <typename T> class Vec3fX { public: typedef typename T::meta_type U; /// @brief interval vector3 data T data; Vec3fX() {} Vec3fX(const Vec3fX& other) : data(other.data) {} /// @brief create Vector (x, y, z) Vec3fX(U x, U y, U z) : data(x, y, z) {} /// @brief create vector (x, x, x) Vec3fX(U x) : data(x) {} /// @brief create vector using the internal data type Vec3fX(const T& data_) : data(data_) {} inline U operator [] (size_t i) const { return data[i]; } inline U& operator [] (size_t i) { return data[i]; } inline Vec3fX operator + (const Vec3fX& other) const { return Vec3fX(data + other.data); } inline Vec3fX operator - (const Vec3fX& other) const { return Vec3fX(data - other.data); } inline Vec3fX operator * (const Vec3fX& other) const { return Vec3fX(data * other.data); } inline Vec3fX operator / (const Vec3fX& other) const { return Vec3fX(data / other.data); } inline Vec3fX& operator += (const Vec3fX& other) { data += other.data; return *this; } inline Vec3fX& operator -= (const Vec3fX& other) { data -= other.data; return *this; } inline Vec3fX& operator *= (const Vec3fX& other) { data *= other.data; return *this; } inline Vec3fX& operator /= (const Vec3fX& other) { data /= other.data; return *this; } inline Vec3fX operator + (U t) const { return Vec3fX(data + t); } inline Vec3fX operator - (U t) const { return Vec3fX(data - t); } inline Vec3fX operator * (U t) const { return Vec3fX(data * t); } inline Vec3fX operator / (U t) const { return Vec3fX(data / t); } inline Vec3fX& operator += (U t) { data += t; return *this; } inline Vec3fX& operator -= (U t) { data -= t; return *this; } inline Vec3fX& operator *= (U t) { data *= t; return *this; } inline Vec3fX& operator /= (U t) { data /= t; return *this; } inline Vec3fX operator - () const { return Vec3fX(-data); } inline Vec3fX cross(const Vec3fX& other) const { return Vec3fX(details::cross_prod(data, other.data)); } inline U dot(const Vec3fX& other) const { return details::dot_prod3(data, other.data); } inline Vec3fX& normalize() { U sqr_length = details::dot_prod3(data, data); if(sqr_length > 0) *this /= (U)sqrt(sqr_length); return *this; } inline Vec3fX& normalize(bool* signal) { U sqr_length = details::dot_prod3(data, data); if(sqr_length > 0) { *this /= (U)sqrt(sqr_length); *signal = true; } else *signal = false; return *this; } inline Vec3fX& abs() { data = abs(data); return *this; } inline U length() const { return sqrt(details::dot_prod3(data, data)); } inline U sqrLength() const { return details::dot_prod3(data, data); } inline void setValue(U x, U y, U z) { data.setValue(x, y, z); } inline void setValue(U x) { data.setValue(x); } inline bool equal(const Vec3fX& other, U epsilon = std::numeric_limits<U>::epsilon() * 100) const { return details::equal(data, other.data, epsilon); } inline Vec3fX<T>& negate() { data.negate(); return *this; } bool operator == (const Vec3fX& other) const { return equal(other, 0); } bool operator != (const Vec3fX& other) const { return !(*this == other); } inline Vec3fX<T>& ubound(const Vec3fX<T>& u) { data.ubound(u.data); return *this; } inline Vec3fX<T>& lbound(const Vec3fX<T>& l) { data.lbound(l.data); return *this; } bool isZero() const { return (data[0] == 0) && (data[1] == 0) && (data[2] == 0); } }; template<typename T> static inline Vec3fX<T> normalize(const Vec3fX<T>& v) { typename T::meta_type sqr_length = details::dot_prod3(v.data, v.data); if(sqr_length > 0) return v / (typename T::meta_type)sqrt(sqr_length); else return v; } template <typename T> static inline typename T::meta_type triple(const Vec3fX<T>& x, const Vec3fX<T>& y, const Vec3fX<T>& z) { return x.dot(y.cross(z)); } template <typename T> std::ostream& operator << (std::ostream& out, const Vec3fX<T>& x) { out << x[0] << " " << x[1] << " " << x[2]; return out; } template <typename T> static inline Vec3fX<T> min(const Vec3fX<T>& x, const Vec3fX<T>& y) { return Vec3fX<T>(details::min(x.data, y.data)); } template <typename T> static inline Vec3fX<T> max(const Vec3fX<T>& x, const Vec3fX<T>& y) { return Vec3fX<T>(details::max(x.data, y.data)); } template <typename T> static inline Vec3fX<T> abs(const Vec3fX<T>& x) { return Vec3fX<T>(details::abs(x.data)); } template <typename T> void generateCoordinateSystem(const Vec3fX<T>& w, Vec3fX<T>& u, Vec3fX<T>& v) { typedef typename T::meta_type U; U inv_length; if(std::abs(w[0]) >= std::abs(w[1])) { inv_length = (U)1.0 / sqrt(w[0] * w[0] + w[2] * w[2]); u[0] = -w[2] * inv_length; u[1] = (U)0; u[2] = w[0] * inv_length; v[0] = w[1] * u[2]; v[1] = w[2] * u[0] - w[0] * u[2]; v[2] = -w[1] * u[0]; } else { inv_length = (U)1.0 / sqrt(w[1] * w[1] + w[2] * w[2]); u[0] = (U)0; u[1] = w[2] * inv_length; u[2] = -w[1] * inv_length; v[0] = w[1] * u[2] - w[2] * u[1]; v[1] = -w[0] * u[2]; v[2] = w[0] * u[1]; } } #if FCL_HAVE_SSE typedef Vec3fX<details::sse_meta_f4> Vec3f; #else typedef Vec3fX<details::Vec3Data<FCL_REAL> > Vec3f; #endif static inline std::ostream& operator << (std::ostream& o, const Vec3f& v) { o << "(" << v[0] << " " << v[1] << " " << v[2] << ")"; return o; } } #endif
[ "jia@rll6.(none)" ]
jia@rll6.(none)
985d67b2ce07aa8291f214fbc030ef87827a4930
9f62aedc13da30a94caea232ce3f5511619d2de9
/OpenGL_Client/source/AgentBlack/SceneSkiingBonusStage.cpp
9481571363a8419274e89f4f4e2ede701f555b07
[]
no_license
OtterBub/2014-2-Virtual_Reality
c9e8cee01aeecc952bfc2865ab91a6d9fa96389c
957029f1087bfb3e42301dd536edb39f42280465
refs/heads/master
2021-01-01T18:17:26.660573
2015-03-27T03:16:50
2015-03-27T03:16:50
32,965,493
0
0
null
null
null
null
UTF-8
C++
false
false
14,792
cpp
#include "SceneSkiingBonusStage.h" #include <iterator> #include <fstream> SceneSkiingBonusStage::SceneSkiingBonusStage() { mSceneName = "Bonus Skiing"; for( unsigned int i = 0; i < UCHAR_MAX; ++i ) mKey[i] = false; mLeftButtonDown = false; mCurveUpdate = false; mStartSkier = false; mHeight = 300; mAngleY = -30; } SceneSkiingBonusStage::~SceneSkiingBonusStage() { } void SceneSkiingBonusStage::Enter() { Vector2 lClientSize = SCENEMGR_INST->GetClientSize(); SCENEMGR_INST->SetPerspectiveMode( false ); SKCONSOLE << "HELP"; SKCONSOLE << "a/d - Camera Y Angle "; SKCONSOLE << "w/s - Camera Z Move "; SKCONSOLE << "r/f - Camera Y Move "; SKCONSOLE << "Mouse Left - Set Points(MAX 8)"; SKCONSOLE << "Point Drag - Reset Points"; SKCONSOLE << "Add Collision Animation"; SKCONSOLE << "Add Last Line"; SKCONSOLE << "Add Camera Follow Skier"; SKCONSOLE << "Add Snow"; mSkier.SetPosition( Vector3( 0, mHeight, lClientSize.y / 2.f ) ); mSkier.SetVelocityAndIncrement( 0, 100 ); mSkier.SetAutoRotate( true ); mStartPos = mSkier.GetPosition(); mCubePos.resize( 1 ); mFirework.SetCreateMaxHeight( 600 ); mFirework.SetCreateRange( 0, lClientSize.x ); mFirework.SetDynamicColor( true ); mEyePos = Vector3( -100, 200, 0 ); mLookatPos = Vector3( lClientSize.x / 2.f, 0, lClientSize.y / 2.f ); // random Tree int lTreeCount = 3 + ( rand() % 3 ); for( int i = 0; lTreeCount > i; ++i ) { std::shared_ptr< ObjectOutLineCube > lObjTree = std::make_shared< ObjectOutLineCube >(); lObjTree->SetColor( Vector4( 1.f, 0.5f, 0.f, 1 ) ); lObjTree->SetSize( 20 ); lObjTree->SetScale( Vector3( 1, 5, 1 ) ); Vector3 lTreePos; lTreePos.x = 50 + rand() % ( (int)lClientSize.x - 50 ); lTreePos.y = ( 1 - ( lTreePos.x / lClientSize.x ) ) * mHeight; lTreePos.z = ( lClientSize.y / 3.f ) + ( rand() % (int)( lClientSize.y / 3.f ) ); lObjTree->SetPosition( lTreePos ); mTreeVec.push_back( lObjTree ); } mButton.SetButtonSize( 170 ); mButton.AddButton( "MainMenu", Vector2( 0, 10 ), 1 ); mButton.AddButton( ">>", Vector2( SCENEMGR_INST->GetClientSize().x - 150, 10 ), 2 ); mButton.AddButton( "Reset", Vector2( SCENEMGR_INST->GetClientSize().x - 150, 60 ), 3 ); mButton.AddButton( "Start", Vector2( SCENEMGR_INST->GetClientSize().x - 150, 110 ), 4 ); { std::ifstream lMapFile( "Map.txt", std::ios::in ); mCubeVec.clear(); mCubePos.clear(); mCubePos.resize( 1 ); mCubePos.reserve( 1 ); while( !lMapFile.eof() ) { char garbage; Vector3 lLoadPos; lMapFile >> lLoadPos.x >> lLoadPos.y >> lLoadPos.z; lMapFile.get( garbage ); if( ( lLoadPos.x == 0 ) && ( lLoadPos.y == 0 ) && ( lLoadPos.z == 0 ) ) { break; } std::shared_ptr< ObjectOutLineCube > lObj = std::make_shared<ObjectOutLineCube>(); lObj->SetPosition( lLoadPos ); lObj->SetSize( 10 ); mCubeVec.push_back( lObj ); Vector3 lObjPos = lObj->GetPosition(); mCubePos.push_back( lObjPos ); } lMapFile.close(); unsigned int cubeIndex = 0; if( mCubePos.size() <= mCubeVec.size() ) { mCubePos.clear(); mCubePos.reserve( mCubeVec.size() + 1 ); } mCubePos[cubeIndex] = mStartPos; for( auto it : mCubeVec ) { cubeIndex++; if( cubeIndex >= mCubePos.size() ) break; mCubePos[cubeIndex] = it->GetPosition(); } SetMultiCurve( mCubePos, 50, mLineVec ); if( mCubeVec.size() > 8 ) { Vector3 lLastPos = mCubePos[cubeIndex]; lLastPos.x = mClientWidth; lLastPos.y = 0; mLineVec.push_back( lLastPos ); } } } void SceneSkiingBonusStage::Exit() { } void SceneSkiingBonusStage::Draw() { glPushMatrix(); { /*if( SCENEMGR_INST->GetPerspectiveMode() ) { gluLookAt( mEyePos.x, mEyePos.y, mEyePos.z, 0, 0, 0, 0, 1, 0 ); glRotatef( mAngleY, 0, 1, 0 ); glTranslatef( -mLastPos.x, -mLastPos.y, -mLastPos.z ); } else { glRotatef( 90, 1, 0, 0 ); glTranslatef( 0, 0, -mClientHeight ); }*/ gluLookAt( mEyePos.x, mEyePos.y, mEyePos.z, 0, 0, 0, 0, 1, 0 ); glRotatef( mAngleY, 0, 1, 0 ); glTranslatef( -mLastPos.x, -mLastPos.y, -mLastPos.z ); // Draw Ground glPushMatrix(); { glBegin( GL_QUADS ); glColor4f( 0.5, 0, 0.5, 1 ); glVertex3fv( reinterpret_cast<GLfloat*>( &Vector3( 0, 0, 0 ) ) ); glColor4f( 0.5, 0, 1, 1 ); glVertex3fv( reinterpret_cast<GLfloat*>( &Vector3( mClientWidth, 0, 0 ) ) ); glColor4f( 1, 0, 0.5, 1 ); glVertex3fv( reinterpret_cast<GLfloat*>( &Vector3( mClientWidth, 0, mClientHeight ) ) ); glColor4f( 0.5, 1, 0.5, 1 ); glVertex3fv( reinterpret_cast<GLfloat*>( &Vector3( 0, 0, mClientHeight ) ) ); glEnd(); glBegin( GL_QUADS ); glColor4f( 1, 1, 1, 1 ); glVertex3fv( reinterpret_cast<GLfloat*>( &Vector3( 0, mHeight, 0 ) ) ); glVertex3fv( reinterpret_cast<GLfloat*>( &Vector3( 0, mHeight, mClientHeight ) ) ); glColor4f( 0.5f, 0.5f, 0.5f, 1 ); glVertex3fv( reinterpret_cast<GLfloat*>( &Vector3( mClientWidth, 0, mClientHeight ) ) ); glVertex3fv( reinterpret_cast<GLfloat*>( &Vector3( mClientWidth, 0, 0 ) ) ); glEnd(); } glPopMatrix(); for( auto it : mCubeVec ) it->Draw(); glPushMatrix(); { glTranslatef( 0, 40, 0 ); for( auto it : mTreeVec ) it->Draw(); } glPopMatrix(); mSkier.Draw(); glPushMatrix(); { glTranslatef( 0, 1, 0 ); glBegin( GL_LINE_STRIP ); glColor4f( 0, 0, 0, 1 ); for( auto it : mLineVec ) { glVertex3fv( reinterpret_cast<GLfloat*>( &it ) ); } glEnd(); } glPopMatrix(); mSnow.Draw(); mFirework.Draw(); mButton.Draw(); } glPopMatrix(); } void SceneSkiingBonusStage::Update( double dt ) { // Update CurveLine unsigned int cubeIndex = 0; if( mCubePos.size() <= mCubeVec.size() ) { mCubePos.clear(); mCubePos.reserve( mCubeVec.size() + 1 ); } mCubePos[cubeIndex] = mStartPos; for( auto it : mCubeVec ) { cubeIndex++; if( cubeIndex >= mCubePos.size() ) break; mCubePos[cubeIndex] = it->GetPosition(); } SetMultiCurve( mCubePos, 50, mLineVec ); if( mCubeVec.size() > 8 ) { Vector3 lLastPos = mCubePos[cubeIndex]; lLastPos.x = mClientWidth; lLastPos.y = 0; mLineVec.push_back( lLastPos ); } if( mStartSkier ) { mSkier.Update( dt ); mSnow.Update( dt ); mFirework.Update( dt ); if( !mSkier.GetCollisionTree() ) { mLastPos = mSkier.GetPosition(); for( auto it : mTreeVec ) { if( CollisionCheck3DBox( mSkier.GetMidPosition(), mSkier.GetSize(), it->GetPosition(), it->GetSize() ) ) { mSkier.SetCollisionTree( true ); Vector3 lSkierPos = mSkier.GetPosition(); Vector3 lDestFly; lDestFly.x = lSkierPos.x - ( rand() % 300 ); lDestFly.y = 900; lDestFly.z = lSkierPos.z + ( ( rand() % 300 ) - 150 ); std::list< Vector3 > lList; lList.push_back( lDestFly ); mSkier.SetDest( lList ); } } } } float lSpeed = 500; float lAngularSpeed = 50; if( mKey['a'] ) { mAngleY -= ( lAngularSpeed * dt ); } if( mKey['d'] ) { mAngleY += ( lAngularSpeed * dt ); } if( mKey['w'] ) { mEyePos.z -= ( lSpeed * dt ); } if( mKey['k'] ) { mStartSkier = true; mSkier.SetDest( std::list<Vector3>( mLineVec.begin(), mLineVec.end() ) ); SCENEMGR_INST->SetPerspectiveMode( true ); } if( mKey['y'] ) { ////mStartSkier = false; //mSkier.SetPosition( mStartPos ); //mSkier.SetCollisionTree( false ); //mLastPos = mSkier.GetPosition(); mStartSkier = false; mSkier.SetPosition( mStartPos ); mSkier.SetCollisionTree( false ); mLastPos = mSkier.GetPosition(); //mSnow.Clear(); //SCENEMGR_INST->SetPerspectiveMode( false ); } if( mKey['r'] ) { mEyePos.y += ( lSpeed * dt ); } if( mKey['f'] ) { mEyePos.y -= ( lSpeed * dt ); } } void SceneSkiingBonusStage::Reshape( int w, int h ) { mClientWidth = w; mClientHeight = h; mButton.Reshape( w, h ); mSnow.Reshape( w, h ); mFirework.SetCreateRange( 0, w ); mFirework.SetDrawZaxis( w ); } void SceneSkiingBonusStage::KeyBoard( unsigned char key, int x, int y ) { mKey[key] = true; } void SceneSkiingBonusStage::KeyBoardUp( unsigned char key, int x, int y ) { mKey[key] = false; } void SceneSkiingBonusStage::Mouse( int button, int state, int x, int y ) { Vector3 MousePos( x, ( 1 - ( x / (float)mClientWidth ) ) * mHeight, y ); switch( button ) { case GLUT_LEFT_BUTTON: switch( state ) { case GLUT_DOWN: { int lButtonId = mButton.CheckButtonId( x, y ); if( lButtonId ) { switch( lButtonId ) { case 1: SCENEMGR_INST->SceneChangeByName( "Main" ); break; case 2: break; case 3: { mStartSkier = false; mSkier.SetPosition( mStartPos ); mSkier.SetCollisionTree( false ); mSnow.Clear(); SCENEMGR_INST->SetPerspectiveMode( false ); } break; case 4: { mStartSkier = true; mSkier.SetDest( std::list<Vector3>( mLineVec.begin(), mLineVec.end() ) ); SCENEMGR_INST->SetPerspectiveMode( true ); } break; case 5: // Save { std::ofstream lMapFile( "Map.txt", std::ios::out ); int count = 0; for( auto it : mCubePos ) { count++; if( 1 == count ) { continue; } Vector3 lPos = it; lMapFile << std::to_string( lPos.x ) << ' ' << std::to_string( lPos.y ) << ' ' << std::to_string( lPos.z ) << std::endl; } lMapFile.close(); } break; case 6: // Load { std::ifstream lMapFile( "Map.txt", std::ios::in ); mCubeVec.clear(); mCubePos.clear(); mCubePos.resize( 1 ); mCubePos.reserve( 1 ); while( !lMapFile.eof() ) { char garbage; Vector3 lLoadPos; lMapFile >> lLoadPos.x >> lLoadPos.y >> lLoadPos.z; lMapFile.get( garbage ); if( ( lLoadPos.x == 0 ) && ( lLoadPos.y == 0 ) && ( lLoadPos.z == 0 ) ) { break; } std::shared_ptr< ObjectOutLineCube > lObj = std::make_shared<ObjectOutLineCube>(); lObj->SetPosition( lLoadPos ); lObj->SetSize( 10 ); mCubeVec.push_back( lObj ); Vector3 lObjPos = lObj->GetPosition(); mCubePos.push_back( lObjPos ); } lMapFile.close(); } break; } break; } } mLeftButtonDown = true; { mSelectCube = nullptr; for( auto it : mCubeVec ) { float lHalfSize = it->GetSize() / 2.f; Vector3 lObjPos = it->GetPosition(); Vector2 l2DBoxStart = Vector2( lObjPos.x - lHalfSize, lObjPos.z - lHalfSize ); Vector2 l2DBoxEnd = Vector2( lObjPos.x + lHalfSize, lObjPos.z + lHalfSize ); Vector2 lMousePos = Vector2( MousePos.x, MousePos.z ); if( CollisionCheck2DBox( l2DBoxStart, l2DBoxEnd, lMousePos, lMousePos ) ) mSelectCube = it; } if( mSelectCube != nullptr ) { SKCONSOLE << "2d Collision Check"; } else if( mCubeVec.size() <= 8 ) { std::shared_ptr< ObjectOutLineCube > lObj = std::make_shared<ObjectOutLineCube>(); lObj->SetPosition( MousePos ); lObj->SetSize( 10 ); mCubeVec.push_back( lObj ); Vector3 lObjPos = lObj->GetPosition(); mCubePos.push_back( lObjPos ); SKCONSOLE << std::to_string( lObjPos.x ) + ", " + std::to_string( lObjPos.y ) + ", " + std::to_string( lObjPos.z ); } } break; case GLUT_UP: mLeftButtonDown = false; break; } break; } } void SceneSkiingBonusStage::MouseMotion( int x, int y ) { Vector3 MousePos( x, ( 1 - ( x / (float)mClientWidth ) ) * mHeight, y ); if( mLeftButtonDown && ( mSelectCube != nullptr ) ) { mSelectCube->SetPosition( MousePos ); } } bool SceneSkiingBonusStage::Command( std::vector< std::string > commandTokens ) { if( ( commandTokens[0] == "start" ) && ( commandTokens.size() >= 1 ) ) { mStartSkier = true; mSkier.SetDest( std::list<Vector3>( mLineVec.begin(), mLineVec.end() ) ); SCENEMGR_INST->SetPerspectiveMode( true ); return true; } else if( ( commandTokens[0] == "reset" ) && ( commandTokens.size() >= 1 ) ) { mStartSkier = false; mSkier.SetPosition( mStartPos ); mSkier.SetCollisionTree( false ); mSnow.Clear(); SCENEMGR_INST->SetPerspectiveMode( false ); return true; } else if( ( commandTokens[0] == "eye" ) && ( commandTokens.size() >= 4 ) ) { mEyePos = Vector3( std::stof( commandTokens[1] ), std::stof( commandTokens[2] ), std::stof( commandTokens[3] ) ); return true; } else { return false; } } //Vector3 SceneSkiingBonusStage::GetBezierCurve( std::vector< Vector3 > points, float t ) //{ // Vector3 lResult; // // if( ( points.size() < 4 ) ) // { // SKCONSOLE << "GetBezierCurve() Size Fail " + std::to_string( points.size() ); // return lResult; // } // lResult = // ( std::powf( 1 - t, 3 ) * std::powf( t, 0 ) * ( points[0] ) ) + // ( 3 * std::powf( 1 - t, 2 ) * std::powf( t, 1 ) * ( points[1] ) ) + // ( 3 * std::powf( 1 - t, 1 ) * std::powf( t, 2 ) * ( points[2] ) ) + // ( std::powf( 1 - t, 0 ) * std::powf( t, 3 ) * ( points[3] ) ); // // return lResult; //} // //std::vector< Vector3 > SceneSkiingBonusStage::CreateCurve( std::vector< Vector3 > points, int separate ) //{ // std::vector< Vector3 > lResult; // // if( ( points.size() < 4 ) ) // { // SKCONSOLE << "CreateCurve() Size Fail " + std::to_string( points.size() ); // return lResult; // } // // for( float i = 0; ( i / separate ) <= 1; ++i ) // { // float lT = ( i / separate ); // lResult.push_back( GetBezierCurve( points, lT ) ); // } // // return lResult; //} // //bool SceneSkiingBonusStage::AddMultiCurve( std::vector< Vector3 > points, int separate, std::vector< Vector3 >& vecDest ) //{ // std::vector< Vector3 > lResult = CreateCurve( points, separate ); // // if( lResult.size() == 0 ) // { // SKCONSOLE << "AddMultiCurve() Get Result Fail " + std::to_string( points.size() ); // return false; // } // else // { // std::copy( lResult.begin(), lResult.end(), std::back_inserter( vecDest ) ); // // return true; // } //} // //bool SceneSkiingBonusStage::SetMultiCurve( std::vector< Vector3 > points, int separate, std::vector< Vector3 >& vecDest ) //{ // int lPointCount = points.size(); // // if( lPointCount >= 4 ) // { // std::vector< Vector3 >::iterator it = points.begin(); // vecDest.clear(); // while( lPointCount >= 4 ) // { // std::vector< Vector3 > lResult = CreateCurve( std::vector< Vector3 >( it, it + 4 ), separate ); // std::copy( lResult.begin(), lResult.end(), std::back_inserter( vecDest ) ); // lPointCount -= 3; // if( ( lPointCount ) >= 4 ) // { // it = it + 3; // } // } // } // // // return true; //}
b3a2695075b443a3fd4ea508e16ac45cd5cf1abf
fb66a5cc43d27f33c85320a6dba8b9a8ff4765a9
/gapputils/gapphost/interfaces/String_parameter.cpp
6309dc9e8f9ac15497c72d73d7ef145e254b638f
[]
no_license
e-thereal/gapputils
7a211c7d92fd2891703cb16bf94e6e05f0fb3b8a
a9eca31373c820c12f4f5f308c0e2005e4672fd0
refs/heads/master
2021-04-26T16:42:58.303603
2015-09-02T21:32:45
2015-09-02T21:32:45
38,838,767
2
0
null
null
null
null
UTF-8
C++
false
false
839
cpp
#include <gapputils/DefaultWorkflowElement.h> #include <gapputils/CollectionElement.h> #include <capputils/attributes/InputAttribute.h> #include <capputils/attributes/OutputAttribute.h> #include <gapputils/attributes/InterfaceAttribute.h> using namespace capputils::attributes; using namespace gapputils::attributes; namespace interfaces { namespace parameters { class String : public gapputils::workflow::DefaultWorkflowElement<String> { InitReflectableClass(String) typedef std::string property_t; Property(Description, std::string) Property(Value, property_t) public: String() { setLabel("String"); } }; BeginPropertyDefinitions(String, Interface()) ReflectableBase(gapputils::workflow::DefaultWorkflowElement<String>) WorkflowProperty(Description) WorkflowProperty(Value); EndPropertyDefinitions } }
d3972a4768ee77895a73953e54dc5d551979f368
1791461e6740f81c2dd6704ae6a899a6707ee6b1
/Codeforces/Gym101981G.cpp
2cf7dac4cc2cd1082114a71e3f28c3eeb384ceb0
[ "MIT" ]
permissive
HeRaNO/OI-ICPC-Codes
b12569caa94828c4bedda99d88303eb6344f5d6e
4f542bb921914abd4e2ee7e17d8d93c1c91495e4
refs/heads/master
2023-08-06T10:46:32.714133
2023-07-26T08:10:44
2023-07-26T08:10:44
163,658,110
22
6
null
null
null
null
UTF-8
C++
false
false
322
cpp
#include <bits/stdc++.h> using namespace std; const long long M=1e9+7; const long long inv24=41666667LL; int T; long long n,ans; int main() { scanf("%d",&T); while (T--) { scanf("%lld",&n); ans=n; (ans*=(n+1))%=M; (ans*=(n+2))%=M; (ans*=(n+3))%=M; (ans*=inv24)%=M; printf("%lld\n",ans); } return 0; }
d0c8e68d8d980b04863a62a01d5fd0350c70fd08
4dd444ad1403aae077b363da828e2ab658d3543d
/Hmwk/Assignment1/Savitch_7thEd_Chap1_ProgProj8/main.cpp
d9a0608de0d8a845e499b9772adfdf647a191cf7
[]
no_license
td2447437/DeJacoTatiana_CSC5_40717
bb23e5dc5670a72595e974845f1d900040533b37
0b34baf0e4154c97447cc3cbe9ab414f5de624e3
refs/heads/master
2020-12-24T14:54:01.380689
2015-02-12T08:22:04
2015-02-12T08:22:04
28,928,051
0
0
null
null
null
null
UTF-8
C++
false
false
1,625
cpp
/* * File: main.cpp * Author: Tati * Created on January 6, 2015, 6:43 PM * * Homework: * Write a program that allows the user to enter a number of quarters, dimes, * and nickels and then outputs the monetary value of the coins in cents. For * example, if the user enters 2 for the number of quarters, 3 for the number * of dimes, and 1 for the number of nickels, then the program should output * that the coins are worth 85 cents. */ #include <iostream> #include <cstdio> using namespace std; int main(int argc, char** argv) { // Declare local variables float quarts = 0.25f; // quarters float dimes = 0.10f; float nicks = 0.05f; // nickels int input; // user's input float sum; // the sum a certain coin float total; // the sum of all coins // Calculate the total sum of all quarters cout << "How many quarters are there? "; cin >> input; sum = input * quarts; total = sum; // Calculate the total sum of all dimes cout << "How many dimes are there? "; cin >> input; sum = input * dimes; total += sum; // Calculate the total sum of all nickels cout << "How many nickels are there? "; cin >> input; sum = input * nicks; total += sum; // Print the total value of all coins if (total < 1.00) { cout << "The monetary value of the coins is: "; printf("%.02f", total); cout << " cent(s)"; } else { cout << "The monetary value of the coins is: "; printf("%.02f", total); cout << " dollar(s)"; } return 0; }
6b07d853a78d93b130371ca8f9cf886e2df4610d
da3c59e9e54b5974648828ec76f0333728fa4f0c
/email/imum/Utils/Inc/ImumInMailboxUtilities.h
ad84e04ecf2eb414132b2d38104b4218a6adf909
[]
no_license
finding-out/oss.FCL.sf.app.messaging
552a95b08cbff735d7f347a1e6af69fc427f91e8
7ecf4269c53f5b2c6a47f3596e77e2bb75c1700c
refs/heads/master
2022-01-29T12:14:56.118254
2010-11-03T20:32:03
2010-11-03T20:32:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,366
h
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: ImumInMailboxUtilities.h * */ #ifndef M_IMUMINMAILBOXUTILITIES_H #define M_IMUMINMAILBOXUTILITIES_H #include <msvstd.h> // TMsvId //##ModelId=451CAF630197 class MImumInMailboxUtilities { public: /** */ enum TImumInMboxRequest { ERequestCurrent = 0, ERequestSending, ERequestReceiving }; /** */ enum TImumInMboxAlwaysOnlineState { /** Always Online is active */ EFlagTurnedOn = 0x01, /** Always Online is waiting for connecting */ EFlagWaitingToConnect = 0x02 }; /** */ typedef RArray<TMsvEntry> RMsvEntryArray; public: virtual TMsvId DefaultMailboxId( const TBool aForceGet = EFalse ) const = 0; virtual TBool IsMailMtm( const TUid& aMtm, const TBool& aAllowExtended = EFalse ) const = 0; virtual TBool IsMailbox( const TMsvId aMailboxId ) const = 0; virtual TBool IsMailbox( const TMsvEntry& aMailbox ) const = 0; virtual TMsvEntry GetMailboxEntryL( const TMsvId aMailboxId, const TImumInMboxRequest& aType = ERequestCurrent, const TBool aServiceCheck = EFalse ) const = 0; virtual const TUid& GetMailboxEntriesL( const TMsvId aMailboxId, RMsvEntryArray& aEntries, const TBool aResetArray = ETrue ) const = 0; virtual TBool IsInbox( const TMsvEntry& aFolderEntry ) const = 0; virtual TBool HasWlanConnectionL( const TMsvId aMailboxId ) const = 0; virtual TBool HasSubscribedFoldersL( const TMsvId aMailboxId ) const = 0; virtual void QueryAlwaysOnlineStateL( const TMsvId aMailboxId, TInt64& aAlwaysOnlineStatus ) const = 0; virtual void NextAlwaysOnlineIntervalL( const TMsvId aMailboxId, TInt64& aAlwaysOnlineStatus, TTimeIntervalSeconds& aSeconds ) const = 0; }; #endif /* M_IMUMINMAILBOXUTILITIES_H */
[ "none@none" ]
none@none
9201bee3f1fa08385ba243e55ed2dc3921a8d421
ec598fa8e931114a258d666c28f0700f7966588d
/include/Card.h
b7f14e850bf6be574587176892a2712c9e395b4f
[]
no_license
codarth/3720-ReviewAndCheat
a495e51f007fb0823b5d96e1c196bb780572d251
3880e42ec1659d9a342fcd9a953f5811257dfe44
refs/heads/master
2020-03-24T01:31:00.982101
2018-07-25T18:45:47
2018-07-25T18:45:47
142,339,895
0
0
null
null
null
null
UTF-8
C++
false
false
762
h
/****************************************************************************************************** Author: Zachary Nelson Date February 1st 2018 This is the Card class, which defines a Card as a value and a suit. ********************************************************************************** Contributor: Cody Crawford Date: March 9 2018 Re-factored and added the game "Cheat" *********************************************************************************/ #include<iostream> #include<vector> using namespace std; #ifndef Card_H #define Card_H class Card{ public: Card(char, string); virtual ~Card(); virtual char Value(); virtual string Suit(); virtual bool IsEqual(char); private: char val; string suit; }; #endif
05944e0003add05e7d7a6691d14657fcf43316c5
f104ee8dd58671d704d02d5a15e8ef24e3e22a8d
/Sandbox/src/Overlays/MenuLayer.h
30991dadc34d3300d61bfba991196690e30f1844
[ "MIT" ]
permissive
almic/Surface-Engine
3a7f35414c9be35c45fceb65b75c2f2594287238
be859f86f224042817b855199afd7e4f80596042
refs/heads/master
2020-04-09T03:07:03.882231
2019-06-14T17:14:47
2019-06-14T17:14:47
159,969,947
2
0
null
null
null
null
UTF-8
C++
false
false
5,743
h
#pragma once #include <Surface.h> #include <Surface/GUI/ImGuiOverlay.h> // Main Menu Bar #include "Gui/MainMenuBar.h" // Popups #include "Gui/ClosePopup.h" // Floating windows #include "Gui/GlmWindow.h" #include "Gui/UserSettingsWindow.h" // Main/ docked/ layout windows #include "Gui/ConsoleWindow.h" #include "Gui/HierarchyWindow.h" #include "Gui/LevelWindow.h" #include "Gui/ObjectPropertyWindow.h" using namespace Surface; class MenuLayer : public ImGuiOverlay { public: bool show_demo_window = false; char fix_layout = 1; // Always reset layout, because dear imgui doesn't quite save the settings properly yet // See notes in function declarations of Gui.h //bool save_layout = false; const char* dockspace_name = "MainDockSpace"; // Popups ClosePopup* closePopup; // Floating windows GlmWindow* glmWindow; UserSettingsWindow* userSettingsWindow; // Main windows ConsoleWindow* consoleWindow; HierarchyWindow* hierarchyWindow; LevelWindow* levelWindow; ObjectPropertyWindow* objectPropertyWindow; // Menu bar MainMenuBar* mainMenuBar; MenuLayer() : ImGuiOverlay("Menu") { } ~MenuLayer() { } void Initialize() override { MainMenuItems items; // Load popups first items.closePopup = closePopup = new ClosePopup(); // Load floating windows items.glmWindow = glmWindow = new GlmWindow(); items.userSettingsWindow = userSettingsWindow = new UserSettingsWindow(); items.showDemoWindow = &show_demo_window; // Load main windows items.consoleWindow = consoleWindow = new ConsoleWindow(); items.hierarchyWindow = hierarchyWindow = new HierarchyWindow(); items.levelWindow = levelWindow = new LevelWindow(); items.objectPropertyWindow = objectPropertyWindow = new ObjectPropertyWindow(); // Other stuff items.fixLayout = &fix_layout; // See notes in function declarations of Gui.h //items.saveLayout = &save_layout; // Load menu bar last, because it handles visibility for all other windows mainMenuBar = new MainMenuBar(items); LoadDefaultLayout(); } void ShowGui() override { // show menu bar first mainMenuBar->Show(); // create layout BeginDockSpace(); // See notes in function declarations of Gui.h /*if (save_layout) { builder.SaveLayoutFile(builder.SaveLayout(), "hippity hoppity"); save_layout = false; }*/ bool force = false; if (fix_layout == 1) { fix_layout = 2; } else if (fix_layout == 2) { fix_layout = 0; force = true; } else { fix_layout = 0; } // Build Layout static Builder builder = Builder(); // We always reset the layout at the start, because dear imgui doesn't quite save the settings properly yet if (builder.BeginLayout(ImGui::GetID(dockspace_name), force)) { ImVec2 view_size = GetCurrentWindow()->Size; // Default layout parameters float ratio_right = .17f; float ratio_left = (ratio_right * view_size.x) / ((1.f - ratio_right) * (view_size.x)); float ratio_level_view = (1.f - (ratio_right * 2)) * (view_size.x) * (9.f / 16.f) / (view_size.y); auto[right, left] = builder.SplitRight(ratio_right); builder.AddRight(objectPropertyWindow, objectPropertyWindow->flags | WindowFlags_DisableCloseForce, WindowType::ASIDE_RIGHT_2); auto[_, middle] = builder.SplitLeft(ratio_left, left); builder.SplitBottom(1.f - ratio_level_view, middle); builder.AddLeft(hierarchyWindow, hierarchyWindow->flags | WindowFlags_DisableCloseForce, WindowType::ASIDE_RIGHT); builder.AddTop(levelWindow, levelWindow->flags | WindowFlags_DisableTabForce, WindowType::MAIN); builder.AddBottom(consoleWindow, consoleWindow->flags | WindowFlags_DisableCloseForce, WindowType::MAIN_BOTTOM); builder.FinishLayout(); } EndDockSpace(); // show popups/ modals closePopup->Show(); // show floating windows glmWindow->Show(); userSettingsWindow->Show(); if (show_demo_window) ShowDemoWindow(&show_demo_window); // show main windows consoleWindow->Show(); hierarchyWindow->Show(); levelWindow->Show(); objectPropertyWindow->Show(); } void BeginDockSpace() { static bool mainLayout = true; static Gui::Window dockWindow; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, // because it would be confusing to have two docking targets within each others. ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar ; ImGuiViewport* viewport = ImGui::GetMainViewport(); float menubarheight = ImGui::FindWindowByName(mainMenuBar->name)->MenuBarHeight(); ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + menubarheight)); ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, viewport->Size.y - menubarheight)); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::SetNextWindowClass(&dockWindow.imGuiClass); ImGui::Begin(dockspace_name, &mainLayout, window_flags); ImGui::PopStyleVar(3); } void EndDockSpace() { ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_PassthruCentralNode | ImGuiDockNodeFlags_NoDockingInCentralNode ; ImGuiID dockspace_id = ImGui::GetID(dockspace_name); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); ImGui::End(); } void LoadDefaultLayout() { // TODO: load layout from file system, keep hardcode as backup } };
22d4a2e9108803fe54a6d5801b171b5ef1f046f5
dc25b23f8132469fd95cee14189672cebc06aa56
/vendor/mediatek/proprietary/hardware/mtkcam/legacy/platform/mt6795/core/featureio/pipe/aaa/state_mgr_n3d/aaa_state_af_n3d.cpp
53bee1bbbdb74a96d967bc887ae93ce130668d91
[]
no_license
nofearnohappy/alps_mm
b407d3ab2ea9fa0a36d09333a2af480b42cfe65c
9907611f8c2298fe4a45767df91276ec3118dd27
refs/heads/master
2020-04-23T08:46:58.421689
2019-03-28T21:19:33
2019-03-28T21:19:33
171,048,255
1
5
null
2020-03-08T03:49:37
2019-02-16T20:25:00
Java
UTF-8
C++
false
false
21,616
cpp
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. */ /* MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ /******************************************************************************************** * LEGAL DISCLAIMER * * (Header of MediaTek Software/Firmware Release or Documentation) * * BY OPENING OR USING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") RECEIVED * FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON AN "AS-IS" BASIS * ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR * A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY * WHATSOEVER WITH RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK * ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO * NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S SPECIFICATION * OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM. * * BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE LIABILITY WITH * RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE * FEES OR SERVICE CHARGE PAID BY BUYER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE WITH THE LAWS * OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF LAWS PRINCIPLES. ************************************************************************************************/ #define LOG_TAG "aaa_state_af_n3d" #ifndef ENABLE_MY_LOG #define ENABLE_MY_LOG (1) #endif #include <aaa_types.h> #include <aaa_error_code.h> #include <aaa_log.h> #include <core/featureio/pipe/aaa/aaa_hal.h> #include <core/featureio/pipe/aaa/state_mgr_n3d/aaa_state_n3d.h> #include <core/featureio/pipe/aaa/state_mgr/aaa_state_mgr.h> #include <core/featureio/pipe/aaa/aaa_scheduler.h> #include <ae_mgr_if.h> #include <flash_mgr.h> #include <af_mgr_if.h> #include <afo_buf_mgr.h> #include <awb_mgr_if.h> #include <aao_buf_mgr.h> #include <lsc_mgr2.h> #include <camera_custom_nvram.h> #include <mtkcam/hal/IHalSensor.h> #include <mtkcam/drv/isp_reg.h> #include <mtkcam/featureio/flicker_hal_base.h> #include "flash_param.h" #include "flash_tuning_custom.h" #include <aaa_common_custom.h> #include <mtkcam/featureio/ISync3A.h> using namespace NS3A; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // StateAFN3d //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ StateAFN3d:: StateAFN3d(MINT32 sensorDevId, StateMgr* pStateMgr) : StateAF(sensorDevId, pStateMgr) { MY_LOG("[%s] sensorDevId(%d)", __FUNCTION__, sensorDevId); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // eIntent_VsyncUpdate //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ MRESULT StateAFN3d:: sendIntent(intent2type<eIntent_VsyncUpdate>) { ::sem_wait(&m_pStateMgr->mSemAF); MRESULT err = S_3A_OK; MINT32 i4FrmCount; //update frame count m_pStateMgr->updateFrameCount(); i4FrmCount = m_pStateMgr->getFrameCount(); MY_LOG("[StateAF::sendIntent]<eIntent_VsyncUpdate> line=%d, frameCnt=%d, EAFState=%d" , __LINE__ , i4FrmCount , static_cast<int>(m_pStateMgr->getAFState())); //BufInfo_T rBufInfo; BufInfo_T & rBufInfo = *(BufInfo_T*)(m_pStateMgr->mpAAOBuf); if (ENABLE_3A_GENERAL & m_pHal3A->m_3ACtrlEnable) { if (ENABLE_AAOBUF & m_pHal3A->m_3ACtrlEnable) { // Dequeue AAO DMA buffer if (m_pScheduler->jobAssignAndTimerStart(E_Job_AAO)) IAAOBufMgr::getInstance().dequeueHwBuf(m_SensorDevId, rBufInfo); m_pScheduler->jobTimerEnd(E_Job_AAO); } } if (m_pStateMgr->getAFState() == eAFState_PreAF) err = sendAFIntent(intent2type<eIntent_VsyncUpdate>(), state2type<eAFState_PreAF>(), &rBufInfo); else if (m_pStateMgr->getAFState() == eAFState_AF) err = sendAFIntent(intent2type<eIntent_VsyncUpdate>(), state2type<eAFState_AF>(), &rBufInfo); if (m_pStateMgr->getAFState() == eAFState_PostAF) err = sendAFIntent(intent2type<eIntent_VsyncUpdate>(), state2type<eAFState_PostAF>(), &rBufInfo); if (ENABLE_3A_GENERAL & m_pHal3A->m_3ACtrlEnable) { if (ENABLE_AAOBUF & m_pHal3A->m_3ACtrlEnable) { // Enqueue AAO DMA buffer if (m_pScheduler->jobAssignAndTimerStart(E_Job_IspValidate)) IAAOBufMgr::getInstance().enqueueHwBuf(m_SensorDevId, rBufInfo); m_pScheduler->jobTimerEnd(E_Job_IspValidate); // Update AAO DMA address if (m_pScheduler->jobAssignAndTimerStart(E_Job_IspValidate, MFALSE)) IAAOBufMgr::getInstance().updateDMABaseAddr(m_SensorDevId); m_pScheduler->jobTimerEnd(E_Job_IspValidate); } } if (m_pStateMgr->getAFState() == eAFState_Num) //at the end of AF flow, transitState & CallbackNotify { m_pStateMgr->mAFStateCntSet.resetAll(); //reset all AFState cnt, flags if(m_pStateMgr->getStateStatus().eNextState!=eState_Invalid) { m_pStateMgr->transitState(eState_AF, m_pStateMgr->getStateStatus().eNextState); m_pStateMgr->setNextState(eState_Invalid); } else m_pStateMgr->transitState(eState_AF, m_pStateMgr->getStateStatus().ePrevState); #if 1 if (ISync3AMgr::getInstance()->isActive()&& ISync3AMgr::getSync3A()->isSyncEnable()) { MY_LOG("[%s] Sync 2A: Sensor(%d), AF End", __FUNCTION__, m_SensorDevId); ISync3AMgr::getInstance()->setAFState(0); } #endif IAfMgr::getInstance().SingleAF_CallbackNotify(m_SensorDevId); } ::sem_post(&m_pStateMgr->mSemAF); return err; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // eIntent_PrecaptureStart //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ MRESULT StateAFN3d:: sendIntent(intent2type<eIntent_PrecaptureStart>) { MY_LOG("[StateAF::sendIntent]<eIntent_PrecaptureStart>"); // State transition: eState_AF --> eState_Precapture //m_pStateMgr->transitState(eState_AF, eState_Precapture); m_pStateMgr->setNextState(eState_Precapture); return S_3A_OK; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // eAFState_PreAF //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ MRESULT StateAFN3d:: sendAFIntent(intent2type<eIntent_VsyncUpdate>, state2type<eAFState_PreAF>, MVOID* pBufInfo) { #define AFLAMP_PREPARE_FRAME 2 MRESULT err = S_3A_OK; // Update frame count m_pStateMgr->mAFStateCntSet.PreAFFrmCnt++; MY_LOG("[StateAF::sendAFIntent](eIntent_VsyncUpdate,eAFState_PreAF) PreAFFrmCnt=%d" , m_pStateMgr->mAFStateCntSet.PreAFFrmCnt); if (!( (ENABLE_3A_GENERAL & m_pHal3A->m_3ACtrlEnable) && (ENABLE_AE & m_pHal3A->m_3ACtrlEnable) && (ENABLE_AF & m_pHal3A->m_3ACtrlEnable) && (ENABLE_FLASH & m_pHal3A->m_3ACtrlEnable) )) {m_pStateMgr->proceedAFState(); return S_3A_OK;} if(!CUST_ONE_SHOT_AE_BEFORE_TAF()) { // change to next state directly MY_LOG("IsDoAEInPreAF is MFALSE, triggerAF, proceedAFState()"); IAfMgr::getInstance().triggerAF(m_SensorDevId); m_pStateMgr->proceedAFState(); return S_3A_OK; } MINT32 i4SyncFrmCount = ISync3A::getInstance()->getFrameCount(); // do AE/AWB before AF start BufInfo_T* pBuf = reinterpret_cast<BufInfo_T*>(pBufInfo); Param_T param; m_pHal3A->getParams(param); #if 0 if(m_pStateMgr->mAFStateCntSet.PreAFFrmCnt==1) m_pStateMgr->mAFStateCntSet.bLampAlreadyOnBeforeSingleAF = FlashMgr::getInstance().isAFLampOn(m_SensorDevId); if((m_pStateMgr->mAFStateCntSet.PreAFFrmCnt==1) && (m_pStateMgr->getStateStatus().ePrevState != eState_Recording) && (!m_pStateMgr->mAFStateCntSet.bLampAlreadyOnBeforeSingleAF)) { MY_LOG("Check and set AF Lamp On/Off"); //#if 0 /*FIXME*/ m_pStateMgr->mAFStateCntSet.PreAF_bNeedToTurnOnLamp = cust_isNeedAFLamp( FlashMgr::getInstance().getFlashMode(m_SensorDevId), FlashMgr::getInstance().getAfLampMode(m_SensorDevId), IAeMgr::getInstance().IsStrobeBVTrigger(m_SensorDevId)); MY_LOG("eAFState_PreAF-cust_isNeedAFLamp ononff:%d flashM:%d AfLampM:%d triger:%d", m_pStateMgr->mAFStateCntSet.PreAF_bNeedToTurnOnLamp, FlashMgr::getInstance().getFlashMode(m_SensorDevId), FlashMgr::getInstance().getAfLampMode(m_SensorDevId), IAeMgr::getInstance().IsStrobeBVTrigger(m_SensorDevId)); //#endif IAwbMgr::getInstance().setStrobeMode(m_SensorDevId, (m_pStateMgr->mAFStateCntSet.PreAF_bNeedToTurnOnLamp) ? AWB_STROBE_MODE_ON : AWB_STROBE_MODE_OFF); IAeMgr::getInstance().setStrobeMode(m_SensorDevId, (m_pStateMgr->mAFStateCntSet.PreAF_bNeedToTurnOnLamp) ? MTRUE : MFALSE); if(m_pStateMgr->mAFStateCntSet.PreAF_bNeedToTurnOnLamp==1) { MY_LOG("eAFState_PreAF-isAFLampOn=1"); IAeMgr::getInstance().doBackAEInfo(m_SensorDevId); FlashMgr::getInstance().setAFLampOnOff(m_SensorDevId, 1); } } #endif // if lamp is off, or lamp-on is ready if ((m_pStateMgr->mAFStateCntSet.PreAF_bNeedToTurnOnLamp == 0) || (m_pStateMgr->mAFStateCntSet.PreAFFrmCnt >= (1+AFLAMP_PREPARE_FRAME))) { MINT32 i4SyncOpt = 0; MINT32 i4ActiveAeItem = m_pScheduler->jobAssignAndTimerStart(E_Job_AeFlare); i4SyncOpt |= ((i4ActiveAeItem&E_AE_AE_CALC) ? ISync3A::E_SYNC3A_DO_AE : 0); // AE /*NeedUpdate*///CPTLog(Event_Pipe_3A_AE, CPTFlagStart); // Profiling Start. MBOOL isNeedUpdateI2C; IAeMgr::getInstance().doAFAEmonitor(m_SensorDevId, m_pStateMgr->getFrameCount() , reinterpret_cast<MVOID *>(pBuf->virtAddr) , i4ActiveAeItem, 1 , 1, isNeedUpdateI2C); if( MTRUE ) m_pHal3A->postToAESenThread(MFALSE); IAeMgr::getInstance().doAFAE(m_SensorDevId, i4SyncFrmCount , reinterpret_cast<MVOID *>(pBuf->virtAddr) , i4ActiveAeItem&(E_AE_AE_CALC|E_AE_FLARE), 1 , 1); m_pScheduler->jobTimerEnd(E_Job_AeFlare); // workaround for iVHDR MUINT32 u4AFSGG1Gain; IAeMgr::getInstance().getAESGG1Gain(m_SensorDevId, &u4AFSGG1Gain); IAfMgr::getInstance().setSGGPGN(m_SensorDevId, (MINT32) u4AFSGG1Gain); /*NeedUpdate*///CPTLog(Event_Pipe_3A_AE, CPTFlagEnd); // Profiling Start. if (m_pScheduler->jobAssignAndTimerStart(E_Job_Awb)) { i4SyncOpt |= ISync3A::E_SYNC3A_DO_AWB; IAwbMgr::getInstance().doAFAWB(m_SensorDevId, reinterpret_cast<MVOID *>(pBuf->virtAddr), MFALSE); } m_pScheduler->jobTimerEnd(E_Job_Awb); if (ISync3A::getInstance()->isSyncEnable()) { // 2A sync: independent AE/AWB MY_LOG("[%s] Sync 2A: Sensor(%d) =============", __FUNCTION__, m_SensorDevId); MINT32 i4Sync = ISync3AMgr::getSync3A()->sync(m_SensorDevId, i4SyncOpt); // apply MY_LOG("[%s] Sync 2A: Sensor(%d) Ready to validate (%d)", __FUNCTION__, m_SensorDevId, i4Sync); } IAeMgr::getInstance().doAFAE(m_SensorDevId, i4SyncFrmCount, reinterpret_cast<MVOID *>(pBuf->virtAddr), (i4ActiveAeItem&E_AE_AE_APPLY), (i4ActiveAeItem&(E_AE_AE_CALC|E_AE_FLARE))?0:1, 1); if( MTRUE ) m_pHal3A->postToAESenThread(MTRUE); if (IAeMgr::getInstance().IsAEStable(m_SensorDevId) == MTRUE) { #if 1 if (ISync3AMgr::getInstance()->isActive()&& ISync3AMgr::getSync3A()->isSyncEnable()) { MY_LOG("[%s] Sync 2A: Sensor(%d), AFAE End", __FUNCTION__, m_SensorDevId); ISync3AMgr::getInstance()->setAFState(2); } #endif IAfMgr::getInstance().triggerAF(m_SensorDevId); m_pStateMgr->proceedAFState(); MY_LOG("eAFState_PreAF, proceedAFState()"); m_pStateMgr->m_bPreStateIsFocused = MTRUE; m_pStateMgr->m_bIsFocuseFinish = MFALSE; } } return S_3A_OK; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // eAFState_AF //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ MRESULT StateAFN3d:: sendAFIntent(intent2type<eIntent_VsyncUpdate>, state2type<eAFState_AF>, MVOID* pBufInfo) { #define AFLAMP_OFF_PREPARE_FRAME 2//6 MY_LOG("[StateAF::sendAFIntent](eIntent_VsyncUpdate,eAFState_AF), AFFrmCnt=%d" , m_pStateMgr->mAFStateCntSet.AFFrmCnt); if (!( (ENABLE_3A_GENERAL & m_pHal3A->m_3ACtrlEnable) && (ENABLE_AE & m_pHal3A->m_3ACtrlEnable) && (ENABLE_AF & m_pHal3A->m_3ACtrlEnable) && (ENABLE_FLASH & m_pHal3A->m_3ACtrlEnable) )) {m_pStateMgr->proceedAFState(); return S_3A_OK;} MBOOL bIsFocusFinish; bIsFocusFinish = IAfMgr::getInstance().isFocusFinish(m_SensorDevId); MY_LOG("[%s] bIsFocusFinish = %d", __FUNCTION__, bIsFocusFinish); if (!(!m_pStateMgr->m_bPreStateIsFocused && bIsFocusFinish)) { if((FlashMgr::getInstance().isAFLampOn(m_SensorDevId)==1) && (FlashMgr::getInstance().getFlashMode(m_SensorDevId)!= LIB3A_FLASH_MODE_FORCE_TORCH) && (!m_pStateMgr->mAFStateCntSet.bLampAlreadyOnBeforeSingleAF)) m_pStateMgr->mAFStateCntSet.AF_bNeedToTurnOffLamp=1; else m_pStateMgr->mAFStateCntSet.AF_bNeedToTurnOffLamp=0; if (ISync3A::getInstance()->isSyncEnable()) { // 2A sync: independent AE/AWB MY_LOG("[%s] Sync 2A: Sensor(%d) =============", __FUNCTION__, m_SensorDevId); MINT32 i4Sync = ISync3AMgr::getSync3A()->sync(m_SensorDevId, ISync3A::E_SYNC3A_BYP_AE); // apply MY_LOG("[%s] Sync 2A: Sensor(%d) Ready to validate (%d)", __FUNCTION__, m_SensorDevId, i4Sync); } m_pStateMgr->m_bPreStateIsFocused = bIsFocusFinish; return S_3A_OK; } //now, isFocusFinish() == MTRUE m_pStateMgr->mAFStateCntSet.AFFrmCnt++; MY_LOG("isFocusFinish() == MTRUE, AFFrmCnt=%d, AF_bNeedToTurnOffLamp=%d" , m_pStateMgr->mAFStateCntSet.AFFrmCnt , m_pStateMgr->mAFStateCntSet.AF_bNeedToTurnOffLamp); if ((m_pStateMgr->mAFStateCntSet.AF_bNeedToTurnOffLamp == 0) || (m_pStateMgr->mAFStateCntSet.AFFrmCnt >= (1+AFLAMP_OFF_PREPARE_FRAME))) { if (ISync3A::getInstance()->isSyncEnable()) { // 2A sync: independent AE/AWB MY_LOG("[%s] Sync 2A: Sensor(%d) =============", __FUNCTION__, m_SensorDevId); MINT32 i4Sync = ISync3AMgr::getSync3A()->sync(m_SensorDevId, ISync3A::E_SYNC3A_BYP_AE); // apply MY_LOG("[%s] Sync 2A: Sensor(%d) Ready to validate (%d)", __FUNCTION__, m_SensorDevId, i4Sync); } m_pStateMgr->proceedAFState(); MY_LOG("eAFState_AF, proceedAFState()"); m_pStateMgr->m_bPreStateIsFocused = MTRUE; m_pStateMgr->m_bIsFocuseFinish = MTRUE; return S_3A_OK; } //now, AF_isAFLampOn == 1 AND AFFrmCnt < 1+AFLAMP_OFF_PREPARE_FRAME //which means we need to do/continue our AF Lamp-off flow BufInfo_T* pBuf = reinterpret_cast<BufInfo_T*>(pBufInfo); IAeMgr::getInstance().setRestore(m_SensorDevId, m_pStateMgr->mAFStateCntSet.AFFrmCnt/*-1*/); //-1 --> +0: is to advance by 1 frame //-1 is to align starting from 0 if (m_pStateMgr->mAFStateCntSet.AFFrmCnt == 1) IAeMgr::getInstance().doRestoreAEInfo(m_SensorDevId, MFALSE); if ((m_pStateMgr->mAFStateCntSet.AFFrmCnt == 1+1/*2*/) && //+2 --> +1: is to advance by 1 frame (FlashMgr::getInstance().getFlashMode(m_SensorDevId)!= LIB3A_FLASH_MODE_FORCE_TORCH) ) { #ifdef MTK_AF_SYNC_RESTORE_SUPPORT MY_LOG("af sync support"); usleep(33000); #else MY_LOG("af sync NOT support"); #endif FlashMgr::getInstance().setAFLampOnOff(m_SensorDevId, 0); IAwbMgr::getInstance().setStrobeMode(m_SensorDevId, AWB_STROBE_MODE_OFF); IAeMgr::getInstance().setStrobeMode(m_SensorDevId, MFALSE); } IAwbMgr::getInstance().doAFAWB(m_SensorDevId, reinterpret_cast<MVOID *>(pBuf->virtAddr)); return S_3A_OK; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // eAFState_PostAF //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ MRESULT StateAFN3d:: sendAFIntent(intent2type<eIntent_VsyncUpdate>, state2type<eAFState_PostAF>, MVOID* pBufInfo) { MRESULT err = S_3A_OK; MY_LOG("[StateAF::sendAFIntent](eIntent_VsyncUpdate,eAFState_PostAF)"); if (!( (ENABLE_3A_GENERAL & m_pHal3A->m_3ACtrlEnable) && (ENABLE_AE & m_pHal3A->m_3ACtrlEnable) )) {m_pStateMgr->proceedAFState(); return S_3A_OK;} if(CUST_ONE_SHOT_AE_BEFORE_TAF()) { m_pStateMgr->proceedAFState(); return S_3A_OK; } //now, IsDoAEInPreAF == MFALSE // do AE/AWB after AF done BufInfo_T* pBuf = reinterpret_cast<BufInfo_T*>(pBufInfo); MINT32 i4ActiveAeItem = m_pScheduler->jobAssignAndTimerStart(E_Job_AeFlare); MBOOL isNeedUpdateI2C; IAeMgr::getInstance().doAFAEmonitor(m_SensorDevId, m_pStateMgr->getFrameCount() , reinterpret_cast<MVOID *>(pBuf->virtAddr) , i4ActiveAeItem, 1 , 1, isNeedUpdateI2C); if( MTRUE ) m_pHal3A->postToAESenThread(MFALSE); // AE /*NeedUpdate*///CPTLog(Event_Pipe_3A_AE, CPTFlagStart); // Profiling Start. IAeMgr::getInstance().doAFAE(m_SensorDevId, m_pStateMgr->getFrameCount() , reinterpret_cast<MVOID *>(pBuf->virtAddr) , i4ActiveAeItem, 1 , 1); m_pScheduler->jobTimerEnd(E_Job_AeFlare); if (MTRUE) m_pHal3A->postToAESenThread(MTRUE); // workaround for iVHDR MUINT32 u4AFSGG1Gain; IAeMgr::getInstance().getAESGG1Gain(m_SensorDevId, &u4AFSGG1Gain); IAfMgr::getInstance().setSGGPGN(m_SensorDevId, (MINT32) u4AFSGG1Gain); /*NeedUpdate*///CPTLog(Event_Pipe_3A_AE, CPTFlagEnd); // Profiling Start. if (m_pScheduler->jobAssignAndTimerStart(E_Job_Awb)) IAwbMgr::getInstance().doAFAWB(m_SensorDevId, reinterpret_cast<MVOID *>(pBuf->virtAddr)); m_pScheduler->jobTimerEnd(E_Job_Awb); if(IAeMgr::getInstance().IsAEStable(m_SensorDevId) == MTRUE) { m_pStateMgr->proceedAFState(); MY_LOG("eAFState_PostAF, proceedAFState()"); return S_3A_OK; } return S_3A_OK; }
271add736a498738bd933a8f6003eb5d23074b7f
f0e2e649c56f69d806fd7ca1635952e5d32d5ff5
/csci111-prog7/csci111-matrices/csci111-matrices/matrices.cpp
911dd089c39906fa98b5cc9e430fac072ad95089
[]
no_license
jtcressy/csci111
3345d5ee9feda508f46c1e8842d964f667ed79b4
397bb33578eb62688e5c5ffc50fe45e5da8311a4
refs/heads/master
2021-01-13T16:48:38.092388
2017-06-20T21:26:07
2017-06-20T21:26:07
94,928,584
0
0
null
null
null
null
UTF-8
C++
false
false
3,960
cpp
//Joel Cressy /* Also, I'm trying some new stuff since it's extra credit. I'll experiment and go beyond some of the requirements of the assignment. */ #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <string> #include <sstream> using namespace std; //setup shortcut for defining 2-D vector (matrices) typedef vector<vector<int>> Matrix; void readem(Matrix&,Matrix&,ifstream&); void writeMatrix(Matrix&,ofstream&); Matrix add(Matrix&,Matrix&); Matrix subtract(Matrix&,Matrix&); Matrix scalarMulti(Matrix&,int); Matrix matrixMulti(Matrix&,Matrix&); void println(int, char, ofstream&); int main() { ifstream inf("matrices.dat"); ofstream outf("matrices.ot"); outf.setf(ios::fixed); outf.precision(2); Matrix A, B; readem(A, B, inf); //output matrices outf << "Matrix A:" << endl; writeMatrix(A, outf); outf << "Matrix B:" << endl; writeMatrix(B, outf); println(15, '=', outf); //add matrices outf << "Matrix A + B:" << endl; writeMatrix(add(A, B), outf); println(15, '=', outf); //subtract matrices outf << "Matrix A - B:" << endl; writeMatrix(subtract(A, B), outf); println(15, '=', outf); //scalar multiplication outf << "Matrix A * 5:" << endl; writeMatrix(scalarMulti(A, 5), outf); println(15, '=', outf); outf << "Matrix B * 5:" << endl; writeMatrix(scalarMulti(B, 5), outf); println(15, '=', outf); //matrix multiplication outf << "Matrix A * B:" << endl; writeMatrix(matrixMulti(A, B), outf); return 0; } void readem(Matrix &va, Matrix &vb, ifstream &inf) { while (!inf.eof()) { string str,line; stringstream ss; while (getline(inf, line) && line != "") { ss << line; vector<int> newRow; while (getline(ss, str,'\t')) { newRow.push_back(stoi(str)); } va.push_back(newRow); ss.clear(); line.clear(); str.clear(); } //input file separated matrices with empty lines, //to allow for dynamically sized matrices, //however only two matrices are allowed to be specified. while (getline(inf, line) && line != "") { ss << line; vector<int> newRow; while (getline(ss, str, '\t')) { newRow.push_back(stoi(str)); } vb.push_back(newRow); ss.clear(); line.clear(); str.clear(); } } } void writeMatrix(Matrix &a, ofstream &outf) { for (int i = 0; i < a.size(); i++) { for (int j = 0; j < a[i].size(); j++) outf << right << setw(4) << a[i][j]; outf << endl; } } Matrix add(Matrix &va, Matrix &vb) { Matrix out; if ((va.size() == vb.size()) && (va[0].size() == vb[0].size())) { int rows = va.size(); int columns = va[0].size(); for (int i = 0; i < rows; i++) { vector<int> newRow; for (int j = 0; j < columns; j++) newRow.push_back(va[i][j] + vb[i][j]); out.push_back(newRow); } } else out.push_back({ 0 }); return out; } Matrix subtract(Matrix &va, Matrix &vb) { Matrix out; if ((va.size() == vb.size()) && (va[0].size() == vb[0].size())) { int rows = va.size(); int columns = va[0].size(); for (int i = 0; i < rows; i++) { vector<int> newRow; for (int j = 0; j < columns; j++) newRow.push_back(va[i][j] - vb[i][j]); out.push_back(newRow); } } else out.push_back({ 0 }); return out; } Matrix scalarMulti(Matrix &a, int n) { Matrix out; for (int i = 0; i < a.size(); i++) { vector<int> newRow; for (int j = 0; j < a[i].size(); j++) newRow.push_back(a[i][j] * n); out.push_back(newRow); } return out; } Matrix matrixMulti(Matrix &va, Matrix &vb) { Matrix out; if (va[0].size() == vb.size()) { for (int x = 0; x < va[0].size(); x++) { vector<int> newRow; for (int y = 0; y < vb.size(); y++) { int n = 0; for (int z = 0; z < va[0].size(); z++) n += va[x][z] * vb[z][y]; newRow.push_back(n); } out.push_back(newRow); newRow.clear(); } } else out.push_back({ 0 }); return out; } void println(int n, char ch, ofstream &outf) { for (int i = 0; i < n; i++) outf << ch; outf << endl; }
de82dd4e9cb92ab7395fd1c837f8b8e521945c74
980ee5cac688b327bae129b8b4a428bd6e26bf87
/Devices/USBizi/Device.cpp
c1978f452addf061a219f6dab1f207eaa0bf558b
[ "Apache-2.0" ]
permissive
valoni/TinyCLR_Port
d86cc2c8aae0cad9afa6a407396b8d4bad0b654f
bdd29571561cda7aec4548478d93062fb4dd4bf2
refs/heads/master
2020-03-28T11:26:40.295204
2018-08-23T15:27:26
2018-08-23T15:27:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,926
cpp
// Copyright GHI Electronics, 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 // // 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 <TinyCLR.h> #include <Device.h> #include "../../Drivers/SPIDisplay/SPIDisplay.h" #include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices.h" #include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Interop.h" void LPC24_Startup_OnSoftResetDevice(const TinyCLR_Api_Provider* apiProvider, const TinyCLR_Interop_Provider* interopProvider) { apiProvider->Add(apiProvider, SPIDisplay_GetApi()); interopProvider->Add(interopProvider, &Interop_GHIElectronics_TinyCLR_Devices); } static int32_t lpc24_deviceId = 0; int32_t LPC24_Startup_GetDeviceId() { if (lpc24_deviceId == 0) { lpc24_deviceId = LPC24_Flash_GetPartId(); } return lpc24_deviceId; } const TinyCLR_Startup_UsbDebuggerConfiguration LPC24_Startup_UsbDebuggerConfiguration = { USB_DEBUGGER_VENDOR_ID, USB_DEBUGGER_PRODUCT_ID, CONCAT(L,DEVICE_MANUFACTURER), CONCAT(L,DEVICE_NAME), 0 }; void LPC24_Startup_GetDebuggerTransportProvider(const TinyCLR_Api_Info*& api, size_t& index, const void*& configuration) { #if defined(DEBUGGER_SELECTOR_PIN) TinyCLR_Gpio_PinValue value, valueUsbActive; auto provider = static_cast<const TinyCLR_Gpio_Provider*>(LPC24_Gpio_GetApi()->Implementation); auto gpioController = 0; //TODO Temporary set to 0 provider->AcquirePin(provider, gpioController, DEBUGGER_SELECTOR_PIN); provider->SetDriveMode(provider, gpioController, DEBUGGER_SELECTOR_PIN, DEBUGGER_SELECTOR_PULL); provider->Read(provider, gpioController, DEBUGGER_SELECTOR_PIN, value); provider->ReleasePin(provider, gpioController, DEBUGGER_SELECTOR_PIN); valueUsbActive = DEBUGGER_SELECTOR_USB_STATE; if (value == valueUsbActive) { api = LPC24_UsbClient_GetApi(); index = USB_DEBUGGER_INDEX; configuration = (const void*)&LPC24_Startup_UsbDebuggerConfiguration; } else { api = LPC24_Uart_GetApi(); index = UART_DEBUGGER_INDEX; } #elif defined(DEBUGGER_FORCE_API) && defined(DEBUGGER_FORCE_INDEX) api = DEBUGGER_FORCE_API; index = DEBUGGER_FORCE_INDEX; #else #error You must specify a debugger mode pin or specify the API explicitly. #endif } void LPC24_Startup_GetRunApp(bool& runApp) { #if defined(RUN_APP_PIN) TinyCLR_Gpio_PinValue value; auto provider = static_cast<const TinyCLR_Gpio_Provider*>(LPC24_Gpio_GetApi()->Implementation); auto gpioController = 0; //TODO Temporary set to 0 provider->AcquirePin(provider, gpioController, RUN_APP_PIN); provider->SetDriveMode(provider, gpioController, RUN_APP_PIN, RUN_APP_PULL); provider->Read(provider, gpioController, RUN_APP_PIN, value); provider->ReleasePin(provider, gpioController, RUN_APP_PIN); runApp = value == RUN_APP_STATE; #elif defined(RUN_APP_FORCE_STATE) runApp = RUN_APP_FORCE_STATE; #else runApp = true; #endif } // UsbClient void LPC24_UsbClient_PinConfiguration() { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) { OTGClkCtrl = 0x1F; while ((OTGClkSt & 0x1F) != 0x1F); LPC24_Gpio_ConfigurePin(PIN(0, 14), LPC24_Gpio_Direction::Input, LPC24_Gpio_PinFunction::PinFunction2, LPC24_Gpio_PinMode::Inactive); // connect pin LPC24_Gpio_ConfigurePin(PIN(0, 31), LPC24_Gpio_Direction::Input, LPC24_Gpio_PinFunction::PinFunction1, LPC24_Gpio_PinMode::Inactive); // D2+ pin. D2- has only USBD- function. no need to config OTGStCtrl |= 3; } else { // LPC2387 OTGClkCtrl = (1 << 1) + (1 << 4); while ((OTGClkSt & ((1 << 1) + (1 << 4))) != ((1 << 1) + (1 << 4))); // connect LPC24_Gpio_ConfigurePin(PIN(2, 9), LPC24_Gpio_Direction::Input, LPC24_Gpio_PinFunction::PinFunction1, LPC24_Gpio_PinMode::Inactive); // D+ LPC24_Gpio_ConfigurePin(PIN(0, 29), LPC24_Gpio_Direction::Input, LPC24_Gpio_PinFunction::PinFunction1, LPC24_Gpio_PinMode::Inactive); // D- LPC24_Gpio_ConfigurePin(PIN(0, 30), LPC24_Gpio_Direction::Input, LPC24_Gpio_PinFunction::PinFunction1, LPC24_Gpio_PinMode::Inactive); } } // Uart static const LPC24_Gpio_Pin g_lpc2387_uart_tx_pins[] = LPC2387_UART_TX_PINS; static const LPC24_Gpio_Pin g_lpc2387_uart_rx_pins[] = LPC2387_UART_RX_PINS; static const LPC24_Gpio_Pin g_lpc2387_uart_rts_pins[] = LPC2387_UART_RTS_PINS; static const LPC24_Gpio_Pin g_lpc2387_uart_cts_pins[] = LPC2387_UART_CTS_PINS; static const LPC24_Gpio_Pin g_lpc2388_uart_tx_pins[] = LPC2388_UART_TX_PINS; static const LPC24_Gpio_Pin g_lpc2388_uart_rx_pins[] = LPC2388_UART_RX_PINS; static const LPC24_Gpio_Pin g_lpc2388_uart_rts_pins[] = LPC2388_UART_RTS_PINS; static const LPC24_Gpio_Pin g_lpc2388_uart_cts_pins[] = LPC2388_UART_CTS_PINS; int32_t LPC24_Uart_GetTxPin(int32_t portNum) { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) return g_lpc2388_uart_tx_pins[portNum].number; else return g_lpc2387_uart_tx_pins[portNum].number; } int32_t LPC24_Uart_GetRxPin(int32_t portNum) { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) return g_lpc2388_uart_rx_pins[portNum].number; else return g_lpc2387_uart_rx_pins[portNum].number; } int32_t LPC24_Uart_GetRtsPin(int32_t portNum) { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) return g_lpc2388_uart_rts_pins[portNum].number; else return g_lpc2387_uart_rts_pins[portNum].number; } int32_t LPC24_Uart_GetCtsPin(int32_t portNum) { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) return g_lpc2388_uart_cts_pins[portNum].number; else return g_lpc2387_uart_cts_pins[portNum].number; } LPC24_Gpio_PinFunction LPC24_Uart_GetTxAlternateFunction(int32_t portNum) { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) return g_lpc2388_uart_tx_pins[portNum].pinFunction; else return g_lpc2387_uart_tx_pins[portNum].pinFunction; } LPC24_Gpio_PinFunction LPC24_Uart_GetRxAlternateFunction(int32_t portNum) { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) return g_lpc2388_uart_rx_pins[portNum].pinFunction; else return g_lpc2387_uart_rx_pins[portNum].pinFunction; } LPC24_Gpio_PinFunction LPC24_Uart_GetRtsAlternateFunction(int32_t portNum) { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) return g_lpc2388_uart_rts_pins[portNum].pinFunction; else return g_lpc2387_uart_rts_pins[portNum].pinFunction; } LPC24_Gpio_PinFunction LPC24_Uart_GetCtsAlternateFunction(int32_t portNum) { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) return g_lpc2388_uart_cts_pins[portNum].pinFunction; else return g_lpc2387_uart_cts_pins[portNum].pinFunction; } // ADC static const LPC24_Gpio_Pin g_lpc2388_adc_pins[] = LPC2388_ADC_PINS; static const LPC24_Gpio_Pin g_lpc2387_adc_pins[] = LPC2387_ADC_PINS; int32_t LPC24_Adc_GetChannelCount() { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) return SIZEOF_ARRAY(g_lpc2388_adc_pins); else return SIZEOF_ARRAY(g_lpc2387_adc_pins); } int32_t LPC24_Adc_GetPin(int32_t channel) { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) return g_lpc2388_adc_pins[channel].number; else return g_lpc2387_adc_pins[channel].number; } LPC24_Gpio_PinFunction LPC24_Adc_GetPinFunction(int32_t channel) { if (LPC24_Startup_GetDeviceId() != LPC2387_PARTID_1 && LPC24_Startup_GetDeviceId() != LPC2387_PARTID_2) return g_lpc2388_adc_pins[channel].pinFunction; else return g_lpc2387_adc_pins[channel].pinFunction; } //PWM const LPC24_Gpio_Pin g_lpc24_pwm_pins[MAX_PWM_PER_CONTROLLER] = LPC24_PWM_PINS; LPC24_Gpio_Pin LPC24_Pwm_GetPins(int32_t controller, int32_t channel) { return g_lpc24_pwm_pins[channel]; }
32f81464216eb1dc111ed314b52b9d8964e11145
f23fea7b41150cc5037ddf86cd7a83a4a225b68b
/SDK/BP_hair_col_black_03_Desc_classes.h
345b0aebdba0d52554d48ee7b4b0b2b2932c847d
[]
no_license
zH4x/SoT-SDK-2.2.0.1
36e1cf7f23ece6e6b45e5885f01ec7e9cd50625e
f2464e2e733637b9fa0075cde6adb5ed2be8cdbd
refs/heads/main
2023-06-06T04:21:06.057614
2021-06-27T22:12:34
2021-06-27T22:12:34
380,845,087
0
0
null
null
null
null
UTF-8
C++
false
false
765
h
#pragma once // Name: SoT, Version: 2.2.0b /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_hair_col_black_03_Desc.BP_hair_col_black_03_Desc_C // 0x0000 (FullSize[0x00E0] - InheritedSize[0x00E0]) class UBP_hair_col_black_03_Desc_C : public UClothingDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_hair_col_black_03_Desc.BP_hair_col_black_03_Desc_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
cc1227cafa67c51a562ce8e65cb0eb5b2acc5f8f
40696c2ad68772aeb72938d0d367df9080eed0b9
/cdn/GA.h
b681b26bc740eaa3d94f8ec53efb8c81246214b9
[]
no_license
hubery94/CDN_HUAWEI
4631a1457e9aec388570a4302b15b5dc432f123b
1f6e3d2484c475f0f49d18ac2acab6641c805e47
refs/heads/master
2021-01-01T18:39:25.118801
2017-07-26T07:51:06
2017-07-26T07:51:20
98,393,961
2
0
null
null
null
null
UTF-8
C++
false
false
1,377
h
/** * Copyright (C) 2017 All right reserved. * @ File: GA.h * @ VERSION: 1.0 * @ Author: HWJ([email protected]) * @ Brief: Genetic Algorithm; * Detail: * TODO * History: 2017/3/20 created by HWJ * * Note: */ #ifndef __GENETIC_H__ #define __GENETIC_H__ #pragma once #include "Location.h" #include "Population.h" class GA{ public: GA(int tournamentSize, double mutateRate); ~GA(void); Population evolvePopulation(Population* pop, int netSize, MCFF3* mc, Location bestLocation,int pop_scale_now,int iter); Population evolvePopulationEasy(Population* pop, int netSize, MCFF3* mc, Location bestLocation,int pop_scale_now,int iter); private: Location crossover(Location parent1, Location parent2, int netSize); Location crossoverEasy(Location parent1, Location parent2, int netSize); void mutateEasy(Location loc); void mutate(Location loc, int iter); Location tournamentSelection(Population* pop, int netSize, MCFF3* mc,int iter); Location tournamentSelectionEasy(Population* pop, int netSize, MCFF3* mc,int iter); Location bestLocation; double uniformRate; //uniformRate for crossover double mutationRate; // mutation rate int tournamentSize; //selection range, initial value is 5, static const bool elitism=true; // use elitism or not int iter; }; #endif //__GENETIC_H__
6f1ef2bb700469de98d9dfe5813a5adc51b17d4c
8fbac239c9ca8e0281ac2024d77a2d9ac14e65a3
/enemy.cpp
ddcad65817324a7a99293c49c772b184d59a2fd3
[]
no_license
FrancoisUgeux/SFML-clicker
81811986acd86a99bfbe0add06289e40776cdc55
b16dc3ab8c2aeab1ddd6757f1b8866f3ba80f772
refs/heads/master
2023-08-21T11:47:44.652123
2021-09-26T13:43:10
2021-09-26T13:43:10
410,562,977
0
0
null
null
null
null
UTF-8
C++
false
false
1,283
cpp
#include "enemy.h" #include <iostream> Enemy::Enemy(int e) { energy = e; } bool Enemy::performSetup() { if (!enemyTexture.loadFromFile("assets/enemy.png")) { std::cout << "Could not load enemy image" << std::endl; return false; } enemySprite.setTexture(enemyTexture); enemySprite.setPosition(sf::Vector2f(225,400)); enemySprite.scale(sf::Vector2f(2,2)); if (!attackSoundBuffer.loadFromFile("assets/damage.ogg")) { std::cout << "Could not load enemy audio" << std::endl; return false; } attackSound.setBuffer(attackSoundBuffer); return true; } void Enemy::draw(sf::RenderWindow * window) { window->draw(enemySprite); } bool Enemy::checkIfHit(sf::Vector2i mousePos) { float enemyMinX = enemySprite.getGlobalBounds().left; float enemyMaxX = enemySprite.getGlobalBounds().width + enemyMinX; float enemyMinY = enemySprite.getGlobalBounds().top; float enemyMaxY = enemySprite.getGlobalBounds().height + enemyMinY; float mouseX = mousePos.x; float mouseY = mousePos.y; return mouseX >= enemyMinX && mouseX <= enemyMaxX && mouseY >= enemyMinY && mouseY <= enemyMaxY; } bool Enemy::takeDamage(int damage) { energy -= damage; attackSound.play(); return energy <= 0; }
65dcda051a51aa49ec3bd34c7c48eda5c97eb990
2e5a59fedf90c75eb8e73baf270486ccb623274a
/ZemiNo3 ver1.6/ZemiNo3/SceneGame.h
422358957915f2ae81de79233055837b36da6365
[]
no_license
Honey-old-Fashion/Honer-old-Fashion
03d7355d3328d2a9bbd56ccebdb747f3fe890a44
7917b7b5067095b513ebbc3b6b6ed99db20a16c2
refs/heads/master
2021-01-24T07:46:05.968459
2017-09-05T10:59:43
2017-09-05T10:59:43
93,356,231
0
0
null
null
null
null
UTF-8
C++
false
false
362
h
#pragma once #include "SceneTask.h" #include "ISceneChanger.h" #include "StageManager.h" class SceneGame : public SceneTask { public: SceneGame(ISceneChanger* _changer); ~SceneGame(); virtual void mInit() override; virtual void mUpdate() override; virtual void mRender() override; virtual void mFinal() override; private: StageManager mgr; };
947ea8ffa8fa483706079d2502422ccfa75af9f7
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/cc/quads/draw_polygon.cc
59ecbef0edbacff11765138e2edf126695cfdfd6
[ "BSD-3-Clause" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
13,107
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/quads/draw_polygon.h" #include <stddef.h> #include <vector> #include "base/memory/ptr_util.h" #include "cc/output/bsp_compare_result.h" #include "cc/quads/draw_quad.h" namespace { // This threshold controls how "thick" a plane is. If a point's distance is // <= |split_threshold|, then it is considered on the plane for the purpose of // polygon splitting. static const float split_threshold = 0.05f; static const float normalized_threshold = 0.001f; void PointInterpolate(const gfx::Point3F& from, const gfx::Point3F& to, double delta, gfx::Point3F* out) { out->SetPoint(from.x() + (to.x() - from.x()) * delta, from.y() + (to.y() - from.y()) * delta, from.z() + (to.z() - from.z()) * delta); } } // namespace namespace cc { DrawPolygon::DrawPolygon() { } DrawPolygon::DrawPolygon(const DrawQuad* original, const std::vector<gfx::Point3F>& in_points, const gfx::Vector3dF& normal, int draw_order_index) : order_index_(draw_order_index), original_ref_(original), is_split_(true) { for (size_t i = 0; i < in_points.size(); i++) { points_.push_back(in_points[i]); } normal_ = normal; DCHECK_LE((ConstructNormal(), (normal_ - normal).Length()), normalized_threshold); } // This takes the original DrawQuad that this polygon should be based on, // a visible content rect to make the 4 corner points from, and a transformation // to move it and its normal into screen space. DrawPolygon::DrawPolygon(const DrawQuad* original_ref, const gfx::RectF& visible_layer_rect, const gfx::Transform& transform, int draw_order_index) : normal_(0.0f, 0.0f, 1.0f), order_index_(draw_order_index), original_ref_(original_ref), is_split_(false) { gfx::Point3F points[8]; int num_vertices_in_clipped_quad; gfx::QuadF send_quad(visible_layer_rect); // Doing this mapping here is very important, since we can't just transform // the points without clipping and not run into strange geometry issues when // crossing w = 0. At this point, in the constructor, we know that we're // working with a quad, so we can reuse the MathUtil::MapClippedQuad3d // function instead of writing a generic polygon version of it. MathUtil::MapClippedQuad3d( transform, send_quad, points, &num_vertices_in_clipped_quad); for (int i = 0; i < num_vertices_in_clipped_quad; i++) { points_.push_back(points[i]); } transform.TransformVector(&normal_); ConstructNormal(); } DrawPolygon::~DrawPolygon() { } std::unique_ptr<DrawPolygon> DrawPolygon::CreateCopy() { std::unique_ptr<DrawPolygon> new_polygon(new DrawPolygon()); new_polygon->order_index_ = order_index_; new_polygon->original_ref_ = original_ref_; new_polygon->points_.reserve(points_.size()); new_polygon->points_ = points_; new_polygon->normal_.set_x(normal_.x()); new_polygon->normal_.set_y(normal_.y()); new_polygon->normal_.set_z(normal_.z()); return new_polygon; } // // If this were to be more generally used and expected to be applicable // replacing this with Newell's algorithm (or an improvement thereof) // would be preferable, but usually this is coming in from a rectangle // that has been transformed to screen space and clipped. // Averaging a few near diagonal cross products is pretty good in that case. // void DrawPolygon::ConstructNormal() { gfx::Vector3dF new_normal(0.0f, 0.0f, 0.0f); int delta = points_.size() / 2; for (size_t i = 1; i + delta < points_.size(); i++) { new_normal += CrossProduct(points_[i] - points_[0], points_[i + delta] - points_[0]); } float normal_magnitude = new_normal.Length(); // Here we constrain the new normal to point in the same sense as the old one. // This allows us to handle winding-reversing transforms better. if (gfx::DotProduct(normal_, new_normal) < 0.0) { normal_magnitude *= -1.0; } if (normal_magnitude != 0 && normal_magnitude != 1) { new_normal.Scale(1.0f / normal_magnitude); } normal_ = new_normal; } #if defined(OS_WIN) // // Allows the unittest to invoke this for the more general constructor. // void DrawPolygon::RecomputeNormalForTesting() { ConstructNormal(); } #endif float DrawPolygon::SignedPointDistance(const gfx::Point3F& point) const { return gfx::DotProduct(point - points_[0], normal_); } // This function is separate from ApplyTransform because it is often unnecessary // to transform the normal with the rest of the polygon. // When drawing these polygons, it is necessary to move them back into layer // space before sending them to OpenGL, which requires using ApplyTransform, // but normal information is no longer needed after sorting. void DrawPolygon::ApplyTransformToNormal(const gfx::Transform& transform) { // Now we use the inverse transpose of |transform| to transform the normal. gfx::Transform inverse_transform; bool inverted = transform.GetInverse(&inverse_transform); DCHECK(inverted); if (!inverted) return; inverse_transform.Transpose(); gfx::Point3F new_normal(normal_.x(), normal_.y(), normal_.z()); inverse_transform.TransformPoint(&new_normal); // Make sure our normal is still normalized. normal_ = gfx::Vector3dF(new_normal.x(), new_normal.y(), new_normal.z()); float normal_magnitude = normal_.Length(); if (normal_magnitude != 0 && normal_magnitude != 1) { normal_.Scale(1.0f / normal_magnitude); } } void DrawPolygon::ApplyTransform(const gfx::Transform& transform) { for (size_t i = 0; i < points_.size(); i++) { transform.TransformPoint(&points_[i]); } } // TransformToScreenSpace assumes we're moving a layer from its layer space // into 3D screen space, which for sorting purposes requires the normal to // be transformed along with the vertices. void DrawPolygon::TransformToScreenSpace(const gfx::Transform& transform) { ApplyTransform(transform); transform.TransformVector(&normal_); ConstructNormal(); } // In the case of TransformToLayerSpace, we assume that we are giving the // inverse transformation back to the polygon to move it back into layer space // but we can ignore the costly process of applying the inverse to the normal // since we know the normal will just reset to its original state. void DrawPolygon::TransformToLayerSpace( const gfx::Transform& inverse_transform) { ApplyTransform(inverse_transform); normal_ = gfx::Vector3dF(0.0f, 0.0f, -1.0f); } // Split |polygon| based upon |this|, leaving the results in |front| and |back|. // If |polygon| is not split by |this|, then move it to either |front| or |back| // depending on its orientation relative to |this|. Sets |is_coplanar| to true // if |polygon| is actually coplanar with |this| (in which case whether it is // front facing or back facing is determined by the dot products of normals, and // document order). void DrawPolygon::SplitPolygon(std::unique_ptr<DrawPolygon> polygon, std::unique_ptr<DrawPolygon>* front, std::unique_ptr<DrawPolygon>* back, bool* is_coplanar) const { DCHECK_GE(normalized_threshold, std::abs(normal_.LengthSquared() - 1.0f)); const size_t num_points = polygon->points_.size(); const auto next = [num_points](size_t i) { return (i + 1) % num_points; }; const auto prev = [num_points](size_t i) { return (i + num_points - 1) % num_points; }; std::vector<float> vertex_distance; size_t pos_count = 0; size_t neg_count = 0; // Compute plane distances for each vertex of polygon. vertex_distance.resize(num_points); for (size_t i = 0; i < num_points; i++) { vertex_distance[i] = SignedPointDistance(polygon->points_[i]); if (vertex_distance[i] < -split_threshold) { ++neg_count; } else if (vertex_distance[i] > split_threshold) { ++pos_count; } else { vertex_distance[i] = 0.0; } } // Handle non-splitting cases. if (!pos_count && !neg_count) { double dot = gfx::DotProduct(normal_, polygon->normal_); if ((dot >= 0.0f && polygon->order_index_ >= order_index_) || (dot <= 0.0f && polygon->order_index_ <= order_index_)) { *back = std::move(polygon); } else { *front = std::move(polygon); } *is_coplanar = true; return; } *is_coplanar = false; if (!neg_count) { *front = std::move(polygon); return; } else if (!pos_count) { *back = std::move(polygon); return; } // Handle splitting case. size_t front_begin; size_t back_begin; size_t pre_front_begin; size_t pre_back_begin; // Find the first vertex that is part of the front split polygon. front_begin = std::find_if(vertex_distance.begin(), vertex_distance.end(), [](float val) { return val > 0.0; }) - vertex_distance.begin(); while (vertex_distance[pre_front_begin = prev(front_begin)] > 0.0) front_begin = pre_front_begin; // Find the first vertex that is part of the back split polygon. back_begin = std::find_if(vertex_distance.begin(), vertex_distance.end(), [](float val) { return val < 0.0; }) - vertex_distance.begin(); while (vertex_distance[pre_back_begin = prev(back_begin)] < 0.0) back_begin = pre_back_begin; DCHECK(vertex_distance[front_begin] > 0.0); DCHECK(vertex_distance[pre_front_begin] <= 0.0); DCHECK(vertex_distance[back_begin] < 0.0); DCHECK(vertex_distance[pre_back_begin] >= 0.0); gfx::Point3F pre_pos_intersection; gfx::Point3F pre_neg_intersection; // Compute the intersection points. N.B.: If the "pre" vertex is on // the thick plane, then the intersection will be at the same point, because // we set vertex_distance to 0 in this case. PointInterpolate( polygon->points_[pre_front_begin], polygon->points_[front_begin], -vertex_distance[pre_front_begin] / gfx::DotProduct(normal_, polygon->points_[front_begin] - polygon->points_[pre_front_begin]), &pre_pos_intersection); PointInterpolate( polygon->points_[pre_back_begin], polygon->points_[back_begin], -vertex_distance[pre_back_begin] / gfx::DotProduct(normal_, polygon->points_[back_begin] - polygon->points_[pre_back_begin]), &pre_neg_intersection); // Build the front and back polygons. std::vector<gfx::Point3F> out_points; out_points.push_back(pre_pos_intersection); do { out_points.push_back(polygon->points_[front_begin]); front_begin = next(front_begin); } while (vertex_distance[front_begin] > 0.0); out_points.push_back(pre_neg_intersection); *front = base::MakeUnique<DrawPolygon>(polygon->original_ref_, out_points, polygon->normal_, polygon->order_index_); out_points.clear(); out_points.push_back(pre_neg_intersection); do { out_points.push_back(polygon->points_[back_begin]); back_begin = next(back_begin); } while (vertex_distance[back_begin] < 0.0); out_points.push_back(pre_pos_intersection); *back = base::MakeUnique<DrawPolygon>(polygon->original_ref_, out_points, polygon->normal_, polygon->order_index_); DCHECK_GE((*front)->points().size(), 3u); DCHECK_GE((*back)->points().size(), 3u); } // This algorithm takes the first vertex in the polygon and uses that as a // pivot point to fan out and create quads from the rest of the vertices. // |offset| starts off as the second vertex, and then |op1| and |op2| indicate // offset+1 and offset+2 respectively. // After the first quad is created, the first vertex in the next quad is the // same as all the rest, the pivot point. The second vertex in the next quad is // the old |op2|, the last vertex added to the previous quad. This continues // until all points are exhausted. // The special case here is where there are only 3 points remaining, in which // case we use the same values for vertex 3 and 4 to make a degenerate quad // that represents a triangle. void DrawPolygon::ToQuads2D(std::vector<gfx::QuadF>* quads) const { if (points_.size() <= 2) return; gfx::PointF first(points_[0].x(), points_[0].y()); size_t offset = 1; while (offset < points_.size() - 1) { size_t op1 = offset + 1; size_t op2 = offset + 2; if (op2 >= points_.size()) { // It's going to be a degenerate triangle. op2 = op1; } quads->push_back( gfx::QuadF(first, gfx::PointF(points_[offset].x(), points_[offset].y()), gfx::PointF(points_[op1].x(), points_[op1].y()), gfx::PointF(points_[op2].x(), points_[op2].y()))); offset = op2; } } } // namespace cc
75487ae224023110c75729276bcb871a6d0f61b9
957696146d105bcd13790abcd237a60a1d8b36db
/Tae/ClientBoard.h
c2e3d5562540d477ea6d70e35e216eae81b842c7
[]
no_license
hyunjinYi/Bingo_Game
4f1a3afa1223eb1602d89ef1bfd29df32949ed5b
447e1b3f8b5fbca3c6700d092c143c81ee92be9a
refs/heads/master
2021-01-10T10:13:46.854795
2016-03-16T07:58:10
2016-03-16T07:58:10
54,010,710
1
0
null
null
null
null
UTF-8
C++
false
false
553
h
#pragma once #include"value.h" class CClientBoard { public: CClientBoard(int size, int number); ~CClientBoard(void); public: void shuffleNumber(); void printInfo(); void distributeNumber(); void setCurNumber(int number); bool checkRepetition(int number); bool checkBingo(); private: int** board; int** markBoard; int** positionNum; int* checkRow; int* checkCol; int* usedList; int* flag; int listIdx; int boardSize; int curBingo; int goalBingo; int bingoSize; int curNum; bool userState; };
24c2b925b456d75242dde211bd8d20090d70354b
bf6632634a16c91c7ee319ba9a4c95195ddf176d
/Tools/MapCreator/sources/SpriteBackground.cpp
1dc54c977f7fce9bf2575fd9d6db26c0b29c390f
[]
no_license
peauc/RType
b3c2d27b5c9204188ee98be0f868c9a49cd3efd8
8e04d99b82c36f77f600b9c41eff5c1781c058d6
refs/heads/master
2021-05-12T10:06:47.728866
2018-01-23T22:34:28
2018-01-23T22:34:28
117,344,079
0
0
null
null
null
null
UTF-8
C++
false
false
779
cpp
/* ** EPITECH PROJECT , 2020 ** MapCreator ** File description : ** No description */ #include "SpriteBackground.hpp" SpriteBackground::SpriteBackground(AItem *parent) : ASpriteBackground(parent) { this->associateEvents(); } void SpriteBackground::displayOnWindow(sf::RenderWindow &window) { window.draw(this->icon); } void SpriteBackground::associateEvents() { } void SpriteBackground::receiveEvent(const sf::Event &event) { } void SpriteBackground::refresh() { ASpriteBackground::refresh(); } void SpriteBackground::setTexture(sf::Texture &texture) { this->fillParent(); this->texture = texture; this->icon.setTexture(this->texture, true); this->icon.setPosition(this->getX(), this->getY()); ASpriteBackground::refresh(); } void SpriteBackground::init() { }
b5da5147f7edf61c3d4ac38aab32f1ea6dadc62a
6514d2069aaf14ae2c5d4b63a9667bc419b831f5
/score.h
b64c6a0a71d89fc654895caaa60b44c4dfe24507
[]
no_license
eecheng87/Qt-shootGame
933ccaff685bc91c20626a165f3e028ba89c6b03
9afdee6aaebf43e0eda8972956c38906afa8ba1a
refs/heads/master
2020-03-22T01:41:01.486843
2018-07-01T11:18:50
2018-07-01T11:18:50
139,322,551
0
0
null
null
null
null
UTF-8
C++
false
false
626
h
#ifndef SCORE_H #define SCORE_H #include <QLabel> #include <QLineEdit> #include<QGraphicsScene> #include<QGraphicsPixmapItem> #include <QGraphicsTextItem> #include <QFont> class MainWindow; class score:public QGraphicsTextItem { Q_OBJECT public: score(); score(MainWindow*); static void add_score(); static void add_ten_score(); static int get_score(); static int jet_num; QLabel *score_t; bool thanos_live; public slots: void update_score(); void distance_score(); signals: void call_thanos(); private: static int SCORE; MainWindow *tmp_window; }; #endif // SCORE_H
6df18c8fa67812233a7e8773b9b024be46738e59
e3aaf8087265cf28ccf41c5e494df12e3b4d9f77
/selectionSort.cpp
986dd77cc4fbe5c9f00b1cc8c8453efdc3ccd25d
[]
no_license
Scott-Canning/algorithms
20c4d0ccd6afb8e0512e550366910ed5a92b402f
a43ec1a7774850a0da8da59839ce24aaa2149149
refs/heads/main
2023-03-20T12:00:17.418887
2021-03-08T04:14:48
2021-03-08T04:14:48
325,856,678
0
0
null
null
null
null
UTF-8
C++
false
false
1,603
cpp
#include <iostream> #include <vector> using namespace std; template <class T> void selectionSort(vector<T>& v, int size); template <class T> int findMinInd(vector<T> v, int low, int high); template <class T> void printVector(vector<T> v); int main(){ srand(time(0)); vector<double> testV; // create random vector to test mergeSort double random; double randomTens = 0; double randomDigs = 0.00; rand(); for (int i = 0; i < 8; ++i) { randomTens = (rand() % 19 + 1); randomDigs = (double)(rand() % 99 + 1) / 100; random = randomTens + randomDigs; testV.push_back(random); } cout<<"Original vector: "<<endl; printVector(testV); selectionSort(testV, testV.size()-1); cout<<"Selection sorted vector: "<<endl; printVector(testV); return 0; } template <class T> void selectionSort(vector<T>& v, int size){ int midInd; for(int i = 0; i < size; i++){ midInd = findMinInd(v, i, size); swap(v[i], v[midInd]); } } template <class T> int findMinInd(vector<T> v, int low, int high){ int minInd; T min; min = v[low]; minInd = low; for (int i = low + 1; i <= high; i++) { if(v[i] < min){ min = v[i]; minInd = i; } } return minInd; } template <class T> void printVector(vector<T> v){ cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); for (int i = 0; i < v.size(); i++) { if(i < v.size() - 1) { cout << v[i] <<", "; } else cout<< v[i]<<endl; } }
3a07c95716189cfca7bd9edbba563527ed6f8f29
d558707243eeec902a2e26600acf0370451f0638
/060rewrite_literal_string.cc
9eeeefaab09b177395c0a893f48bbbebd8c2db51
[]
no_license
hu19891110/mu
7d9d5d563bd0509741ea4f517ec34caca8fe08dc
a9a2f7db59c1efdeaf0a4db41778c35f97054d61
refs/heads/master
2021-01-17T22:54:20.932765
2016-07-11T04:47:24
2016-07-11T04:47:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,022
cc
//: allow using literal strings anywhere that will accept immutable strings :(scenario passing_literals_to_recipes) def main [ 1:number/raw <- foo [abc] ] def foo x:address:array:character -> n:number [ local-scope load-ingredients n <- length *x ] +mem: storing 3 in location 1 :(before "End Instruction Inserting/Deleting Transforms") initialize_transform_rewrite_literal_string_to_text(); Transform.push_back(rewrite_literal_string_to_text); :(before "End Globals") set<string> recipes_taking_literal_strings; :(code) void initialize_transform_rewrite_literal_string_to_text() { recipes_taking_literal_strings.insert("$print"); recipes_taking_literal_strings.insert("$system"); recipes_taking_literal_strings.insert("trace"); recipes_taking_literal_strings.insert("stash"); recipes_taking_literal_strings.insert("assert"); recipes_taking_literal_strings.insert("new"); recipes_taking_literal_strings.insert("run"); recipes_taking_literal_strings.insert("assume-console"); recipes_taking_literal_strings.insert("memory-should-contain"); recipes_taking_literal_strings.insert("trace-should-contain"); recipes_taking_literal_strings.insert("trace-should-not-contain"); recipes_taking_literal_strings.insert("check-trace-count-for-label"); recipes_taking_literal_strings.insert("screen-should-contain"); recipes_taking_literal_strings.insert("screen-should-contain-in-color"); } void rewrite_literal_string_to_text(recipe_ordinal r) { recipe& caller = get(Recipe, r); trace(9991, "transform") << "--- rewrite literal strings in recipe " << caller.name << end(); if (contains_numeric_locations(caller)) return; vector<instruction> new_instructions; for (int i = 0; i < SIZE(caller.steps); ++i) { instruction& inst = caller.steps.at(i); if (recipes_taking_literal_strings.find(inst.name) == recipes_taking_literal_strings.end()) { for (int j = 0; j < SIZE(inst.ingredients); ++j) { if (!is_literal_string(inst.ingredients.at(j))) continue; instruction def; ostringstream ingredient_name; ingredient_name << inst.name << '_' << i << '_' << j << ":address:array:character"; def.name = "new"; def.ingredients.push_back(inst.ingredients.at(j)); def.products.push_back(reagent(ingredient_name.str())); new_instructions.push_back(def); inst.ingredients.at(j).clear(); // reclaim old memory inst.ingredients.at(j) = reagent(ingredient_name.str()); } } new_instructions.push_back(inst); } caller.steps.swap(new_instructions); } bool contains_numeric_locations(const recipe& caller) { for (int i = 0; i < SIZE(caller.steps); ++i) { const instruction& inst = caller.steps.at(i); for (int in = 0; in < SIZE(inst.ingredients); ++in) if (is_numeric_location(inst.ingredients.at(in))) return true; for (int out = 0; out < SIZE(inst.products); ++out) if (is_numeric_location(inst.products.at(out))) return true; } return false; }
5798e826d597c5df57600080efb88b7f842cac41
5bcd9425cc94182986ae02a1564e8eb06c224eb8
/SystemC_zadacic/common.hpp
5ba13ab63735ec2b4ead7dc4922ea2d9c7bd2cc6
[]
no_license
boris-98/edsr_systemc
2e8a640058bde7b98f79a62f9520c568ebbf860a
9b0693ac79a51986c2c9928dd146391080e7fd85
refs/heads/main
2023-05-29T02:28:15.139470
2021-05-26T21:22:05
2021-05-26T21:22:05
370,503,883
0
0
null
null
null
null
UTF-8
C++
false
false
298
hpp
#ifndef COMMON_HPP_INCLUDED #define COMMON_HPP_INCLUDED #define CACHE_SIZE 16 #define DATA_HEIGHT 10 #define DATA_WIDTH 12 #define DATA_DEPTH 4 #define Y_LIMIT1 11 #define Y_LIMIT2 495 #define W_kn 4 #define W_kh 3 #define W_kw 3 #define W_kd 4 typedef float type; #endif // COMMON_HPP_INCLUDED
dc9d928223dcfdfb58697a803edd97baae03bca3
90047daeb462598a924d76ddf4288e832e86417c
/components/prefs/overlay_user_pref_store.cc
ddc47c8f351d58320c3dc836c3208271a38b510e
[ "BSD-3-Clause" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
6,899
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/prefs/overlay_user_pref_store.h" #include <memory> #include <utility> #include "base/memory/ptr_util.h" #include "base/values.h" OverlayUserPrefStore::OverlayUserPrefStore( PersistentPrefStore* underlay) : underlay_(underlay) { underlay_->AddObserver(this); } bool OverlayUserPrefStore::IsSetInOverlay(const std::string& key) const { return overlay_.GetValue(key, NULL); } void OverlayUserPrefStore::AddObserver(PrefStore::Observer* observer) { observers_.AddObserver(observer); } void OverlayUserPrefStore::RemoveObserver(PrefStore::Observer* observer) { observers_.RemoveObserver(observer); } bool OverlayUserPrefStore::HasObservers() const { return observers_.might_have_observers(); } bool OverlayUserPrefStore::IsInitializationComplete() const { return underlay_->IsInitializationComplete(); } bool OverlayUserPrefStore::GetValue(const std::string& key, const base::Value** result) const { // If the |key| shall NOT be stored in the overlay store, there must not // be an entry. DCHECK(ShallBeStoredInOverlay(key) || !overlay_.GetValue(key, NULL)); if (overlay_.GetValue(key, result)) return true; return underlay_->GetValue(GetUnderlayKey(key), result); } std::unique_ptr<base::DictionaryValue> OverlayUserPrefStore::GetValues() const { auto values = underlay_->GetValues(); auto overlay_values = overlay_.AsDictionaryValue(); for (const auto& overlay_mapping : overlay_to_underlay_names_map_) { const std::string& overlay_key = overlay_mapping.first; const std::string& underlay_key = overlay_mapping.second; std::unique_ptr<base::Value> out_value; if (overlay_key != underlay_key) { values->Remove(underlay_key, &out_value); } overlay_values->Remove(overlay_key, &out_value); if (out_value) { values->Set(overlay_key, std::move(out_value)); } } return values; } bool OverlayUserPrefStore::GetMutableValue(const std::string& key, base::Value** result) { if (!ShallBeStoredInOverlay(key)) return underlay_->GetMutableValue(GetUnderlayKey(key), result); if (overlay_.GetValue(key, result)) return true; // Try to create copy of underlay if the overlay does not contain a value. base::Value* underlay_value = NULL; if (!underlay_->GetMutableValue(GetUnderlayKey(key), &underlay_value)) return false; *result = underlay_value->DeepCopy(); overlay_.SetValue(key, base::WrapUnique(*result)); return true; } void OverlayUserPrefStore::SetValue(const std::string& key, std::unique_ptr<base::Value> value, uint32_t flags) { if (!ShallBeStoredInOverlay(key)) { underlay_->SetValue(GetUnderlayKey(key), std::move(value), flags); return; } if (overlay_.SetValue(key, std::move(value))) ReportValueChanged(key, flags); } void OverlayUserPrefStore::SetValueSilently(const std::string& key, std::unique_ptr<base::Value> value, uint32_t flags) { if (!ShallBeStoredInOverlay(key)) { underlay_->SetValueSilently(GetUnderlayKey(key), std::move(value), flags); return; } overlay_.SetValue(key, std::move(value)); } void OverlayUserPrefStore::RemoveValue(const std::string& key, uint32_t flags) { if (!ShallBeStoredInOverlay(key)) { underlay_->RemoveValue(GetUnderlayKey(key), flags); return; } if (overlay_.RemoveValue(key)) ReportValueChanged(key, flags); } bool OverlayUserPrefStore::ReadOnly() const { return false; } PersistentPrefStore::PrefReadError OverlayUserPrefStore::GetReadError() const { return PersistentPrefStore::PREF_READ_ERROR_NONE; } PersistentPrefStore::PrefReadError OverlayUserPrefStore::ReadPrefs() { // We do not read intentionally. OnInitializationCompleted(true); return PersistentPrefStore::PREF_READ_ERROR_NONE; } void OverlayUserPrefStore::ReadPrefsAsync( ReadErrorDelegate* error_delegate_raw) { std::unique_ptr<ReadErrorDelegate> error_delegate(error_delegate_raw); // We do not read intentionally. OnInitializationCompleted(true); } void OverlayUserPrefStore::CommitPendingWrite() { underlay_->CommitPendingWrite(); // We do not write our content intentionally. } void OverlayUserPrefStore::SchedulePendingLossyWrites() { underlay_->SchedulePendingLossyWrites(); } void OverlayUserPrefStore::ReportValueChanged(const std::string& key, uint32_t flags) { for (PrefStore::Observer& observer : observers_) observer.OnPrefValueChanged(key); } void OverlayUserPrefStore::OnPrefValueChanged(const std::string& key) { if (!overlay_.GetValue(GetOverlayKey(key), NULL)) ReportValueChanged(GetOverlayKey(key), DEFAULT_PREF_WRITE_FLAGS); } void OverlayUserPrefStore::OnInitializationCompleted(bool succeeded) { for (PrefStore::Observer& observer : observers_) observer.OnInitializationCompleted(succeeded); } void OverlayUserPrefStore::RegisterOverlayPref(const std::string& key) { RegisterOverlayPref(key, key); } void OverlayUserPrefStore::RegisterOverlayPref( const std::string& overlay_key, const std::string& underlay_key) { DCHECK(!overlay_key.empty()) << "Overlay key is empty"; DCHECK(overlay_to_underlay_names_map_.find(overlay_key) == overlay_to_underlay_names_map_.end()) << "Overlay key already registered"; DCHECK(!underlay_key.empty()) << "Underlay key is empty"; DCHECK(underlay_to_overlay_names_map_.find(underlay_key) == underlay_to_overlay_names_map_.end()) << "Underlay key already registered"; overlay_to_underlay_names_map_[overlay_key] = underlay_key; underlay_to_overlay_names_map_[underlay_key] = overlay_key; } void OverlayUserPrefStore::ClearMutableValues() { overlay_.Clear(); } OverlayUserPrefStore::~OverlayUserPrefStore() { underlay_->RemoveObserver(this); } const std::string& OverlayUserPrefStore::GetOverlayKey( const std::string& underlay_key) const { NamesMap::const_iterator i = underlay_to_overlay_names_map_.find(underlay_key); return i != underlay_to_overlay_names_map_.end() ? i->second : underlay_key; } const std::string& OverlayUserPrefStore::GetUnderlayKey( const std::string& overlay_key) const { NamesMap::const_iterator i = overlay_to_underlay_names_map_.find(overlay_key); return i != overlay_to_underlay_names_map_.end() ? i->second : overlay_key; } bool OverlayUserPrefStore::ShallBeStoredInOverlay( const std::string& key) const { return overlay_to_underlay_names_map_.find(key) != overlay_to_underlay_names_map_.end(); }
1557a9bec4f39d45366cc08ea9c550f63786fac7
1739bba59ee114e0c3254e19ddd8b0c99b636e27
/src/main.cpp
c1fefbf15973bd7614e04e42ff5646f0b86e3be1
[]
no_license
alexdafoe/CodeTimer
8245987da96db460623e32368b52a8fa78fa22cf
74b9622c6cd2bcb71e2b75494e694d2a5c20fad8
refs/heads/master
2021-06-27T02:32:00.638967
2019-08-11T09:57:22
2019-08-11T09:57:22
190,724,256
0
0
null
2020-11-23T21:34:16
2019-06-07T10:13:47
C++
UTF-8
C++
false
false
1,467
cpp
#include "include/log.h" #include "include/controller.h" #include "include/trayiconwidget.h" #include "include/symbolssettings.h" #include "include/timer.h" #include "include/timerdata.h" #include "include/database/databasecontroller.h" #include "include/database/databasemodel.h" #include "include/database/database.h" #include <QApplication> #include <QQmlApplicationEngine> #include <QtQml> int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setWindowIcon(QIcon(":/images/main_icon.ico")); Controller controller; controller.init(); SymbolsSettings *settings = controller.getSymbolsSettings(); Log* log = controller.getLog(); Timer *timer = controller.getTimer(); DataBase* dataBase = controller.getDataBaseController()->getDataBase(); DataBaseModel * dataModel = controller.getDataBaseController()->getDataModel(); TrayIconWidget *sysTray = controller.getSysTrayWidget(); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("protocolLog", log); engine.rootContext()->setContextProperty("timer", timer); engine.rootContext()->setContextProperty("symbolsSettings", settings); engine.rootContext()->setContextProperty("dataBase", dataBase); engine.rootContext()->setContextProperty("databaseModel", dataModel); engine.rootContext()->setContextProperty("sysTray", sysTray); engine.load(QUrl(QStringLiteral("qrc:/qml/Main.qml"))); return app.exec(); }
215674195f526ab2308d41c56077c65c3b3dd679
0f05c7c6011360f1ef347d8e91b798a42a111bb5
/SimpleLines/MyForm.cpp
d39cace9a7d71ff44918042969cfd8c852b17feb
[]
no_license
mannaward/SimpleLines
76d567fe90de338ba352b0695c19dcf713c201f5
fdfeb719737d74b0c18c0a1206496c3f5dfdbc80
refs/heads/master
2021-01-10T22:28:36.426752
2014-05-20T17:01:57
2014-05-20T17:01:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
280
cpp
#include "MyForm.h" using namespace System; using namespace System::Windows::Forms; [STAThread] void Main(array<String^>^ args) { Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); SimpleLines::MyForm form; Application::Run(%form); }
6269fbbbd1c0c686b772d28d6a3f00f405d68a36
4930e3d42790a674bebe62762e6f4ce1c34f8cca
/gpucast_math/test/testnurbsvolume.cpp
76ede6fc4e65fe985f26bab1a29668c65e7378f3
[ "MIT", "BSD-3-Clause" ]
permissive
scholli/gpucast
b776c042641501c031b27bf5334eef4a32d81734
165ae5d29a9483189af2c5ceace3dd111c446444
refs/heads/master
2020-04-05T18:57:44.398649
2018-03-12T09:14:18
2018-03-12T09:14:18
15,339,846
4
1
null
null
null
null
UTF-8
C++
false
false
2,493
cpp
/******************************************************************************** * * Copyright (C) 2010 Bauhaus University Weimar * ********************************************************************************* * * module : test/testnurbsvolume.cpp * project : tml * description: * ********************************************************************************/ #include <unittest++/UnitTest++.h> #include <iostream> #include <set> #include <cstdlib> #include <cstdio> #include <ctime> #include <gpucast/math/parametric/nurbsvolume.hpp> using namespace gpucast::math; SUITE (nurbsvolume_class) { float random (float min, float max) { float rel_value = float(rand())/RAND_MAX; return min + rel_value * fabs(max - min); } nurbsvolume<point3d> create_volume() { nurbsvolume<point3d> nv; std::multiset<float> knots_u, knots_v, knots_w; std::size_t order_u = 4; std::size_t order_v = 5; std::size_t order_w = 3; nv.degree_u (order_u - 1); nv.degree_v (order_v - 1); nv.degree_w (order_w - 1); for (unsigned int u = 0; u != order_u; ++u) { knots_u.insert(0.f); knots_u.insert(1.f); knots_u.insert(random(0.1f, 0.9f)); knots_u.insert(random(0.1f, 0.9f)); } for (unsigned int v = 0; v != order_v; ++v) { knots_v.insert(0.0f); knots_v.insert(1.0f); knots_v.insert(random(0.1f, 0.9f)); knots_v.insert(random(0.1f, 0.9f)); knots_v.insert(random(0.1f, 0.9f)); } for (unsigned int w = 0; w != order_w; ++w) { knots_w.insert(0.0f); knots_w.insert(1.0f); knots_w.insert(random(0.1f, 0.9f)); } nv.knotvector_u(knots_u.begin(), knots_u.end()); nv.knotvector_v(knots_v.begin(), knots_v.end()); nv.knotvector_w(knots_w.begin(), knots_w.end()); nv.resize(knots_u.size() - order_u, knots_v.size() - order_v, knots_w.size() - order_w); for (unsigned int w = 0; w != knots_w.size() - order_w; ++w) { for (unsigned int v = 0; v != knots_v.size() - order_v; ++v) { for (unsigned int u = 0; u != knots_u.size() - order_u; ++u) { point3d p(u + random(-0.5f, 0.5f), v + random(-0.5f, 0.5f), w + random(-0.5f, 0.5f)); nv.set_point(u,v,w,p); } } } return nv; } TEST(default_ctor) { create_volume(); } }
e14df5b19d497a3e0c17de2702b0bf0194f3c598
327cb9c6448805d69eb1de0c46a9dd5d83ec932b
/Code/led_game_encoders_class/led_game_encoders_class.ino
2e83670e7bcc2cadc030eee8110448a6d107d834
[ "MIT" ]
permissive
Jaknil/LED_games
79667fd34186b297d6234a2d2cd102f06ea44272
d55dce86a7d4207342a8984b21e3724c30f30af4
refs/heads/master
2023-01-11T18:24:02.502409
2023-01-06T06:48:26
2023-01-06T06:48:26
277,350,577
0
0
null
null
null
null
UTF-8
C++
false
false
2,775
ino
/* Test program for the encoders for the LED games project Reads and logs the status of the encoders and prints them to the serial line after a set interval My first attempt at using classes for Arduino Documentation at https://github.com/Jaknil/LED_games/blob/master/README.md */ class Encoder { private: int state = 0; public: int leftPin = 0; int rightPin = 0; void begin(); int count = 0; //Incerement method, returns count int inc(){ // Read pins, correct inverted logic bool ENread[2]; //Saves time in the loop? ENread[0] = !digitalRead(leftPin) ; //Store state of left pin, positive logic ENread[1] = !digitalRead(rightPin) ; //Store state of right pin, positive logic //Track state and increment / decrement conter for the direction the signal moved, there are 4 states per step //they form a two bit gray code that is used to track the current position times 4. switch (state) { case 0: //both low, likely start if(ENread[0] && !ENread[1]){ state = 1; //L high count--;//CCW } if(!ENread[0] && ENread[1]){ state = 3;//R high count++;//CW } break; case 1: //L high if(ENread[0] && ENread[1]){ state = 2;//both high count--;//CCW } if(!ENread[0] && !ENread[1]){ state = 0;//both low, back to start count++;//CW } break; case 2: //both high if(!ENread[0] && ENread[1]){ state = 3;//R high count--; //CCW } if(ENread[0] && !ENread[1]){ state = 1;//L high count++; //CW } break; case 3: //R high if(!ENread[0] && !ENread[1]){ state = 0;//both low, back to start count--; //CCW } if(ENread[0] && ENread[1]){ state = 2;//both high count++; //CW } break; } } }; //end encoder class void Encoder::begin(){ // initialize the encoder pins as inputs: pinMode(leftPin, INPUT); pinMode(rightPin, INPUT); } //Timer unsigned long timer = 0; int holdTime = 100; //in millis //Create our encoders Encoder ENC1; Encoder ENC2; void setup() { //Setup our encoders ENC1.leftPin = 3; ENC1.rightPin = 6; ENC2.leftPin = 2; ENC2.rightPin = 5; ENC1.begin(); ENC2.begin(); // initialize serial communication at 9600 bits per second: Serial.begin(9600); } void loop() { //increment the encoders, as fast as possible ENC1.inc(); ENC2.inc(); //if enough time since read, send line if (millis() > (timer + holdTime)){ Serial.print("ENC1: "); Serial.print(ENC1.count/4); Serial.print(" ENC2: "); Serial.println(ENC2.count/4); //send line timer = millis(); // reset clock } }
d368ebe6a1f30eb6b4a51dc3f7273f939cc25fd1
f3c8d78b4f8af9a5a0d047fbae32a5c2fca0edab
/Qt/my_old_programm/Games/_Game/qt-sprite-animation-example/animationpool.h
7217af514b858244c200a960802ae8ddd3ddfa01
[]
no_license
RinatB2017/mega_GIT
7ddaa3ff258afee1a89503e42b6719fb57a3cc32
f322e460a1a5029385843646ead7d6874479861e
refs/heads/master
2023-09-02T03:44:33.869767
2023-08-21T08:20:14
2023-08-21T08:20:14
97,226,298
5
2
null
2022-12-09T10:31:43
2017-07-14T11:17:39
C++
UTF-8
C++
false
false
1,356
h
#ifndef ANIMATIONPOOL_H #define ANIMATIONPOOL_H #include <QMap> #include <QPixmap> #include "singleton.h" template <typename AnimationEnum> class AnimationPool { public: struct LoadException : public std::exception { virtual const char* what() const noexcept { return "Animation not loaded\n"; } }; void load(AnimationEnum id, QString filename, int nFrames, int height, int width) { QPixmap frames(filename); for (int nFrame = 0; nFrame < nFrames; ++nFrame) m_animations[id].push_back(cropFrame(frames, nFrames, height, width, nFrame)); } QVector<QPixmap*>& get(AnimationEnum id) throw(LoadException) { if (false == m_animations.contains(id)) throw LoadException(); return m_animations[id]; } private: QPixmap* cropFrame(const QPixmap frames, const int nFrames, const int height, const int width, const int nFrame) { const int frameWidth = frames.width() / nFrames, frameHeight = frames.height(); return new QPixmap( frames.copy(nFrame*frameWidth, 0, frameWidth, frameHeight) .scaled(width, height, Qt::IgnoreAspectRatio, Qt::FastTransformation) ); } QMap<AnimationEnum, QVector<QPixmap*> > m_animations; friend class Singleton<AnimationPool<AnimationEnum> >; }; #endif // ANIMATIONPOOL_H
55402200ea7949b5cbc253b17a2a352f1747dfad
1f66821be09fbb1b7fc60774d4487bcad3ee191a
/src/FilaEncadeadaDeInteiros.h
578b29c72c5134dc8daf5e9be52a7a73515adf41
[]
no_license
leosimoes/UERJ-Estruturas-de-dados-I
f8302a92ab65d50e9d3fc291d9ce5f89e6103b80
f795a25df4163a74745c08286836274bc59a5416
refs/heads/master
2022-11-30T01:55:35.290019
2020-08-07T16:29:43
2020-08-07T16:29:43
285,864,463
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,318
h
#ifndef FILAENCADEADADEINTEIROS_H_INCLUDED #define FILAENCADEADADEINTEIROS_H_INCLUDED #include <iostream> #include <iomanip> #include "NoDeInteiro.h" #include "Extremidade.h" using namespace std; class FilaEncadeadaDeInteiros { private: NoDeInteiro * inicioPtr; Extremidade extremidade; public: FilaEncadeadaDeInteiros(); FilaEncadeadaDeInteiros(Extremidade extremidade); void enqueue(NoDeInteiro *); void dequeue(); int consultar(); bool vazia(); void imprimeLista(); virtual ~FilaEncadeadaDeInteiros(); }; FilaEncadeadaDeInteiros::FilaEncadeadaDeInteiros() { } FilaEncadeadaDeInteiros::FilaEncadeadaDeInteiros(Extremidade extremidade) { this->inicioPtr = NULL; this->extremidade = extremidade; } void FilaEncadeadaDeInteiros::enqueue(NoDeInteiro * novoNo) { if (this->vazia()) { this->inicioPtr = novoNo; } else if (this->extremidade == esquerda) { //Se a extremidade for esquerda inserir no inicio novoNo->setProximo(this->inicioPtr); inicioPtr = novoNo; } else if (this->extremidade == direita) { //Cria um no auxiliar NoDeInteiro * noAuxPtr; //O no auxiliar aponta para o ultimo elemento da lista for (noAuxPtr = this->inicioPtr; noAuxPtr->getProximo() != NULL; noAuxPtr = noAuxPtr->getProximo()) ; //remove o ultimo elemento delete noAuxPtr; } } void FilaEncadeadaDeInteiros::dequeue() { if (this->vazia()) { cout << "Fila Vazia - não houve remocao" << endl; } else { if (this->extremidade == direita) { //Se a extremidade for direita excluir no inicio //Cria um no auxiliar NoDeInteiro * noAuxPtr; //O no auxiliar aponta para o segundo elemento da lista noAuxPtr = this->inicioPtr->getProximo(); //remove o primeiro elemento delete inicioPtr; //o inicio passa a comecar do "segundo" elemento this->inicioPtr = noAuxPtr; } else if (this->extremidade == esquerda) { //Cria um no auxiliar NoDeInteiro * noAuxPtr; //O no auxiliar aponta para o ultimo elemento da lista for (noAuxPtr = this->inicioPtr; noAuxPtr->getProximo()->getProximo() != NULL; noAuxPtr = noAuxPtr->getProximo()) ; //remove o ultimo elemento delete noAuxPtr->getProximo(); noAuxPtr->setProximo(NULL); } } } int FilaEncadeadaDeInteiros::consultar() { if (this->vazia()) { cout << "Fila Vazia - não ha elemento para ser consultado" << endl; return 0; } else { if (this->extremidade == direita) { return this->inicioPtr->getNumero(); } else if (this->extremidade == esquerda) { //Se a extremidade for esquerda retorna o final //Cria um no auxiliar NoDeInteiro * noAuxPtr; for (noAuxPtr = this->inicioPtr; noAuxPtr->getProximo() != NULL; noAuxPtr = noAuxPtr->getProximo()) ; return noAuxPtr->getNumero(); } } } bool FilaEncadeadaDeInteiros::vazia() { if (this->inicioPtr == NULL) { return true; } else { return false; } } void FilaEncadeadaDeInteiros::imprimeLista() { if (this->vazia()) { cout << "Fila Encadeada Vazia" << endl; } else { NoDeInteiro * noAuxPtr; cout << "Fila Encadeada: " << endl; for (noAuxPtr = this->inicioPtr; noAuxPtr != NULL; noAuxPtr = noAuxPtr->getProximo()) { cout << noAuxPtr->getNumero() << setw(5); } cout << endl; } } FilaEncadeadaDeInteiros::~FilaEncadeadaDeInteiros() { } #endif // FILAENCADEADADEINTEIROS_H_INCLUDED
849db33b75c2b442b8ce4eb8dca03a51744068cc
c4f925d09767fb5e33669c3d79847aeab603f0aa
/Src/Classes/Buttons.cpp
c863bae7b4b70926988851ffe1e559816b129796
[]
no_license
rvbc1/Carolo_2020
d6e32332e966eb73408b290ac69dd7119c396227
bc866d0348ad3de650cb0dc91d7451603eab0a6e
refs/heads/master
2020-11-26T00:25:51.951430
2019-12-18T19:59:02
2019-12-18T19:59:02
228,904,910
0
1
null
null
null
null
UTF-8
C++
false
false
1,363
cpp
/* * Buttons.cpp * * Created on: 29.01.2019 * Author: Igor */ #include "Buttons.h" #include "stm32f7xx_hal.h" Buttons buttons; uint8_t start_parking_USB = 0; uint8_t start_obstacle_USB = 0; uint8_t start_parking_sent = 0; uint8_t start_obstacle_sent = 0; void Buttons::Init(){ start1_state_of_pressing = false; start2_state_of_pressing = false; screen1_state_of_pressing = false; screen2_state_of_pressing = false; screen3_state_of_pressing = false; any_button_was_pressed = false; } void Buttons::process(){ //if(!start_parking_sent){ if(HAL_GPIO_ReadPin(START_BUTTON_1_GPIO_Port, START_BUTTON_1_Pin) == GPIO_PIN_RESET){ osDelay(40); if(HAL_GPIO_ReadPin(START_BUTTON_1_GPIO_Port, START_BUTTON_1_Pin) == GPIO_PIN_RESET){ start_parking_USB = 1; left_indicator = !left_indicator; } } // } // else{ // start_parking_USB = 0; // } //if(!start_obstacle_sent){ if(HAL_GPIO_ReadPin(START_BUTTON_2_GPIO_Port, START_BUTTON_2_Pin) == GPIO_PIN_RESET){ osDelay(40); if(HAL_GPIO_ReadPin(START_BUTTON_2_GPIO_Port, START_BUTTON_2_Pin) == GPIO_PIN_RESET){ start_obstacle_USB = 1; right_indicator = !right_indicator; } } // }else{ // start_obstacle_USB = 0; // } osDelay(5); } Buttons::Buttons() { // TODO Auto-generated constructor stub } Buttons::~Buttons() { // TODO Auto-generated destructor stub }
1a69860c4e186286ea0206f5a1f426dcee9c3f01
1de25b8d7f8adce4edae438178c1de2a8227d92c
/src/World.cpp
22a0e5fdb3a595d64f9ff7ea7f5aa3c331ff8695
[ "MIT" ]
permissive
TurkeyMcMac/intergrid
d72fc1a9621dd83d027eba4dedda21b7247f3ae0
31ba0b3a1f7a96d3e3c2d6b9aa79662811917870
refs/heads/master
2020-12-08T09:09:50.726480
2020-03-07T13:25:21
2020-03-07T13:25:21
232,942,716
0
0
null
null
null
null
UTF-8
C++
false
false
10,374
cpp
#include "World.hpp" using namespace intergrid; World::World(size_t width, size_t height) : temperature(width, height) , plants(width, height) , water(width, height) , clouds(width, height) , herbivores_food(width, height) , herbivores_moved(width, height) { } size_t World::get_width() { return temperature.get_width(); } size_t World::get_height() { return temperature.get_height(); } static float random_float() { return (float)rand() / RAND_MAX; } void World::randomize(Config& conf) { for (size_t x = 0; x < get_width(); ++x) { for (size_t y = 0; y < get_height(); ++y) { plants.at(x, y) = random_float() * conf.plants_initial_max; temperature.at(x, y) = random_float() * conf.temperature_initial_max; water.at(x, y) = random_float() * conf.water_initial_max; clouds.at(x, y) = random_float() * conf.clouds_initial_max; if (conf.herbivores_initial_chance > 0.) { herbivores_food.at(x, y) = rand() / (int)(RAND_MAX * conf.herbivores_initial_chance) == 0 ? conf.herbivores_initial_food : 0.; } } } } static float flow(float a, float b, float portion) { return (b - a) * portion; } static void disperse(Grid<float>& grid, float portion) { // This flow is not completely symmetrical, but it's good enough. for (size_t x = 0; x < grid.get_width(); ++x) { for (size_t y = 0; y < grid.get_height(); ++y) { float& here = grid.at(x, y); float& right = grid.at_small_trans(x, y, 1, 0); float& below = grid.at_small_trans(x, y, 0, 1); float flow_right = flow(here, right, portion); float flow_below = flow(here, below, portion); here += flow_right; right -= flow_right; here += flow_below; below -= flow_below; } } } static void breed_plants(Grid<float>& plants, Grid<float>& temperature, Grid<float>& water, Grid<float>& clouds, Config& conf) { for (size_t x = 0; x < plants.get_width(); ++x) { for (size_t y = 0; y < plants.get_height(); ++y) { float& here = plants.at(x, y); float mul = 1.; if (water.at(x, y) < here) { mul *= conf.plants_water_lack_mul; } if (temperature.at(x, y) > here) { mul *= conf.plants_temperature_excess_mul; } else { mul *= conf.plants_temperature_lack_mul; } if (plants.at_small_trans(x, y, 1, 0) > here && plants.at_small_trans(x, y, 0, 1) > here && plants.at_small_trans(x, y, -1, 0) > here && plants.at_small_trans(x, y, 0, -1) > here) { mul *= conf.plants_overpopulation_mul; } mul -= clouds.at(x, y) * conf.plants_overcast_mul; here *= mul; } } } static void vaporize(Grid<float>& temperature, Grid<float>& plants, Grid<float>& water, Grid<float>& clouds, Config& conf) { for (size_t x = 0; x < temperature.get_width(); ++x) { for (size_t y = 0; y < temperature.get_height(); ++y) { float vapor = temperature.at(x, y) * conf.water_evaporation_temperature_mul + plants.at(x, y) * conf.water_evaporation_plants_mul; if (water.at(x, y) < vapor) { vapor = water.at(x, y); } water.at(x, y) -= vapor; clouds.at(x, y) += vapor; } } } static void precipitate(Grid<float>& clouds, Grid<float>& water, Config& conf) { for (size_t x = 0; x < clouds.get_width(); ++x) { for (size_t y = 0; y < clouds.get_height(); ++y) { if (clouds.at(x, y) > conf.clouds_max_humidity) { clouds.at(x, y) -= conf.clouds_humidity_decrement; water.at(x, y) += conf.clouds_humidity_decrement; } } } } static void cool_down(Grid<float>& temperature, Config& conf) { for (size_t x = 0; x < temperature.get_width(); ++x) { for (size_t y = 0; y < temperature.get_height(); ++y) { temperature.at(x, y) *= conf.temperature_loss_mul; } } } static void produce_body_heat( Grid<float>& plants, Grid<float>& temperature, Config& conf) { for (size_t x = 0; x < plants.get_width(); ++x) { for (size_t y = 0; y < plants.get_height(); ++y) { temperature.at(x, y) += plants.at(x, y) * conf.plants_body_heat_mul; } } } static void eat_plants( Grid<float>& herbivores_food, Grid<float>& plants, Config& conf) { for (size_t x = 0; x < herbivores_food.get_width(); ++x) { for (size_t y = 0; y < herbivores_food.get_height(); ++y) { if (herbivores_food.at(x, y) > 0.) { herbivores_food.at(x, y) += plants.at(x, y) * conf.herbivores_plant_food_mul - conf.herbivores_food_decrement; plants.at(x, y) = 0.; } } } } static void move_herbivores(Grid<float>& herbivores_food, Grid<bool>& herbivores_moved, Grid<float>& plants, Config& conf) { for (size_t x = 0; x < herbivores_food.get_width(); ++x) { for (size_t y = 0; y < herbivores_food.get_height(); ++y) { float& here = herbivores_food.at(x, y); if (here > 0. && !herbivores_moved.at(x, y)) { int around[4][2] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; int idx = -1; float max = 0.; for (int i = 0; i < 4; ++i) { size_t there_x = x; size_t there_y = y; herbivores_food.small_trans( there_x, there_y, around[i][0], around[i][1]); if (herbivores_food.at(there_x, there_y) <= 0. && plants.at(there_x, there_y) > max) { idx = i; max = plants.at(there_x, there_y); } } if (idx >= 0) { size_t tx = x; size_t ty = y; herbivores_food.small_trans( tx, ty, around[idx][0], around[idx][1]); float& to = herbivores_food.at(tx, ty); if (here < conf.herbivores_baby_threshold) { to = here; here = 0.; } else { here *= conf.herbivores_birth_food_mul; to = here; herbivores_moved.at(x, y) = true; } herbivores_moved.at(tx, ty) = true; } } } } } void World::simulate(Config& conf) { disperse(temperature, conf.temperature_dispersal); disperse(plants, conf.plants_dispersal); disperse(water, conf.water_dispersal); disperse(clouds, conf.clouds_dispersal); breed_plants(plants, temperature, water, clouds, conf); vaporize(temperature, plants, water, clouds, conf); precipitate(clouds, water, conf); cool_down(temperature, conf); produce_body_heat(plants, temperature, conf); eat_plants(herbivores_food, plants, conf); herbivores_moved.fill(false); move_herbivores(herbivores_food, herbivores_moved, plants, conf); } static unsigned char amount2color(float amount) { amount *= 10.; if (amount < 0.) { return 0; } else if (amount > 255.) { return 255; } else { return amount; } } void World::draw(SDL_Renderer* renderer) { SDL_Rect viewport; SDL_RenderGetViewport(renderer, &viewport); int tile_width = viewport.w / get_width(); int tile_height = viewport.h / get_height(); for (size_t x = 0; x < get_width(); ++x) { for (size_t y = 0; y < get_height(); ++y) { SDL_Rect tile; tile.x = (int)x * tile_width; tile.y = (int)y * tile_height; tile.w = tile_width; tile.h = tile_height; SDL_SetRenderDrawColor(renderer, amount2color(temperature.at(x, y) * 2.), amount2color(plants.at(x, y) * 3.), amount2color(water.at(x, y) * 2.), 255); SDL_RenderFillRect(renderer, &tile); if (herbivores_food.at(x, y) > 0.) { tile.x += 1; tile.y += 1; tile.w -= 2; tile.h -= 2; SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderFillRect(renderer, &tile); } } } } double World::count_total_temperature() { double total = 0.; for (size_t x = 0; x < temperature.get_width(); ++x) { for (size_t y = 0; y < temperature.get_height(); ++y) { total += temperature.at(x, y); } } return total; } double World::count_total_plants() { double total = 0.; for (size_t x = 0; x < plants.get_width(); ++x) { for (size_t y = 0; y < plants.get_height(); ++y) { total += plants.at(x, y); } } return total; } double World::count_total_water() { double total = 0.; for (size_t x = 0; x < water.get_width(); ++x) { for (size_t y = 0; y < water.get_height(); ++y) { total += water.at(x, y); } } return total; } double World::count_total_clouds() { double total = 0.; for (size_t x = 0; x < clouds.get_width(); ++x) { for (size_t y = 0; y < clouds.get_height(); ++y) { total += clouds.at(x, y); } } return total; } long World::count_total_herbivores() { long total = 0; for (size_t x = 0; x < herbivores_food.get_width(); ++x) { for (size_t y = 0; y < herbivores_food.get_height(); ++y) { total += herbivores_food.at(x, y) > 0.; } } return total; } double World::count_total_herbivore_food() { double total = 0.; for (size_t x = 0; x < herbivores_food.get_width(); ++x) { for (size_t y = 0; y < herbivores_food.get_height(); ++y) { total += herbivores_food.at(x, y); } } return total; }
d373ea040af654d21c136cac00c19afda0866590
0641d87fac176bab11c613e64050330246569e5c
/tags/release-3-0-d03/source/i18n/gregocal.cpp
97c4fe3bb38744d817061c8d5fb55ebc67033873
[ "ICU" ]
permissive
svn2github/libicu_full
ecf883cedfe024efa5aeda4c8527f227a9dbf100
f1246dcb7fec5a23ebd6d36ff3515ff0395aeb29
refs/heads/master
2021-01-01T17:00:58.555108
2015-01-27T16:59:40
2015-01-27T16:59:40
9,308,333
0
2
null
null
null
null
UTF-8
C++
false
false
48,974
cpp
/* ******************************************************************************* * Copyright (C) 1997-2004, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* * * File GREGOCAL.CPP * * Modification History: * * Date Name Description * 02/05/97 clhuang Creation. * 03/28/97 aliu Made highly questionable fix to computeFields to * handle DST correctly. * 04/22/97 aliu Cleaned up code drastically. Added monthLength(). * Finished unimplemented parts of computeTime() for * week-based date determination. Removed quetionable * fix and wrote correct fix for computeFields() and * daylight time handling. Rewrote inDaylightTime() * and computeFields() to handle sensitive Daylight to * Standard time transitions correctly. * 05/08/97 aliu Added code review changes. Fixed isLeapYear() to * not cutover. * 08/12/97 aliu Added equivalentTo. Misc other fixes. Updated * add() from Java source. * 07/28/98 stephen Sync up with JDK 1.2 * 09/14/98 stephen Changed type of kOneDay, kOneWeek to double. * Fixed bug in roll() * 10/15/99 aliu Fixed j31, incorrect WEEK_OF_YEAR computation. * 10/15/99 aliu Fixed j32, cannot set date to Feb 29 2000 AD. * {JDK bug 4210209 4209272} * 11/15/99 weiv Added YEAR_WOY and DOW_LOCAL computation * to timeToFields method, updated kMinValues, kMaxValues & kLeastMaxValues * 12/09/99 aliu Fixed j81, calculation errors and roll bugs * in year of cutover. * 01/24/2000 aliu Revised computeJulianDay for YEAR YEAR_WOY WOY. ******************************************************************************** */ #include "unicode/utypes.h" #include <float.h> #if !UCONFIG_NO_FORMATTING #include "unicode/gregocal.h" #include "gregoimp.h" #include "mutex.h" #include "uassert.h" // ***************************************************************************** // class GregorianCalendar // ***************************************************************************** /** * Note that the Julian date used here is not a true Julian date, since * it is measured from midnight, not noon. This value is the Julian * day number of January 1, 1970 (Gregorian calendar) at noon UTC. [LIU] */ static const int32_t kNumDays[] = {0,31,59,90,120,151,181,212,243,273,304,334}; // 0-based, for day-in-year static const int32_t kLeapNumDays[] = {0,31,60,91,121,152,182,213,244,274,305,335}; // 0-based, for day-in-year static const int32_t kMonthLength[] = {31,28,31,30,31,30,31,31,30,31,30,31}; // 0-based static const int32_t kLeapMonthLength[] = {31,29,31,30,31,30,31,31,30,31,30,31}; // 0-based // setTimeInMillis() limits the Julian day range to +/-7F000000. // This would seem to limit the year range to: // ms=+183882168921600000 jd=7f000000 December 20, 5828963 AD // ms=-184303902528000000 jd=81000000 September 20, 5838270 BC // HOWEVER, CalendarRegressionTest/Test4167060 shows that the actual // range limit on the year field is smaller (~ +/-140000). [alan 3.0] static const int32_t kGregorianCalendarLimits[UCAL_FIELD_COUNT][4] = { // Minimum Greatest Least Maximum // Minimum Maximum { 0, 0, 1, 1 }, // ERA { 1, 1, 140742, 144683 }, // YEAR { 0, 0, 11, 11 }, // MONTH { 1, 1, 52, 53 }, // WEEK_OF_YEAR { 0, 0, 4, 6 }, // WEEK_OF_MONTH { 1, 1, 28, 31 }, // DAY_OF_MONTH { 1, 1, 365, 366 }, // DAY_OF_YEAR {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1},// DAY_OF_WEEK { -1, -1, 4, 6 }, // DAY_OF_WEEK_IN_MONTH {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1},// AM_PM {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1},// HOUR {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1},// HOUR_OF_DAY {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1},// MINUTE {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1},// SECOND {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1},// MILLISECOND {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1},// ZONE_OFFSET {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1},// DST_OFFSET { -140742, -140742, 140742, 144683 }, // YEAR_WOY {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1},// DOW_LOCAL { -140742, -140742, 140742, 144683 }, // EXTENDED_YEAR {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1},// JULIAN_DAY {/*N/A*/-1,/*N/A*/-1,/*N/A*/-1,/*N/A*/-1} // MILLISECONDS_IN_DAY }; /* * <pre> * Greatest Least * Field name Minimum Minimum Maximum Maximum * ---------- ------- ------- ------- ------- * ERA 0 0 1 1 * YEAR 1 1 140742 144683 * MONTH 0 0 11 11 * WEEK_OF_YEAR 1 1 52 53 * WEEK_OF_MONTH 0 0 4 6 * DAY_OF_MONTH 1 1 28 31 * DAY_OF_YEAR 1 1 365 366 * DAY_OF_WEEK 1 1 7 7 * DAY_OF_WEEK_IN_MONTH -1 -1 4 6 * AM_PM 0 0 1 1 * HOUR 0 0 11 11 * HOUR_OF_DAY 0 0 23 23 * MINUTE 0 0 59 59 * SECOND 0 0 59 59 * MILLISECOND 0 0 999 999 * ZONE_OFFSET -12* -12* 12* 12* * DST_OFFSET 0 0 1* 1* * YEAR_WOY 1 1 140742 144683 * DOW_LOCAL 1 1 7 7 * </pre> * (*) In units of one-hour */ #if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL) #include <stdio.h> #endif U_NAMESPACE_BEGIN UOBJECT_DEFINE_RTTI_IMPLEMENTATION(GregorianCalendar) // 00:00:00 UTC, October 15, 1582, expressed in ms from the epoch. // Note that only Italy and other Catholic countries actually // observed this cutover. Most other countries followed in // the next few centuries, some as late as 1928. [LIU] // in Java, -12219292800000L //const UDate GregorianCalendar::kPapalCutover = -12219292800000L; static const uint32_t kCutoverJulianDay = 2299161; static const UDate kPapalCutover = (2299161.0 - kEpochStartAsJulianDay) * U_MILLIS_PER_DAY; static const UDate kPapalCutoverJulian = (2299161.0 - kEpochStartAsJulianDay); // ------------------------------------- GregorianCalendar::GregorianCalendar(UErrorCode& status) : Calendar(TimeZone::createDefault(), Locale::getDefault(), status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(TimeZone* zone, UErrorCode& status) : Calendar(zone, Locale::getDefault(), status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(const TimeZone& zone, UErrorCode& status) : Calendar(zone, Locale::getDefault(), status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(const Locale& aLocale, UErrorCode& status) : Calendar(TimeZone::createDefault(), aLocale, status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(TimeZone* zone, const Locale& aLocale, UErrorCode& status) : Calendar(zone, aLocale, status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& status) : Calendar(zone, aLocale, status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { setTimeInMillis(getNow(), status); } // ------------------------------------- GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date, UErrorCode& status) : Calendar(TimeZone::createDefault(), Locale::getDefault(), status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { set(UCAL_ERA, AD); set(UCAL_YEAR, year); set(UCAL_MONTH, month); set(UCAL_DATE, date); } // ------------------------------------- GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, UErrorCode& status) : Calendar(TimeZone::createDefault(), Locale::getDefault(), status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { set(UCAL_ERA, AD); set(UCAL_YEAR, year); set(UCAL_MONTH, month); set(UCAL_DATE, date); set(UCAL_HOUR_OF_DAY, hour); set(UCAL_MINUTE, minute); } // ------------------------------------- GregorianCalendar::GregorianCalendar(int32_t year, int32_t month, int32_t date, int32_t hour, int32_t minute, int32_t second, UErrorCode& status) : Calendar(TimeZone::createDefault(), Locale::getDefault(), status), fGregorianCutover(kPapalCutover), fCutoverJulianDay(kCutoverJulianDay), fNormalizedGregorianCutover(fGregorianCutover), fGregorianCutoverYear(1582), fIsGregorian(TRUE), fInvertGregorian(FALSE) { set(UCAL_ERA, AD); set(UCAL_YEAR, year); set(UCAL_MONTH, month); set(UCAL_DATE, date); set(UCAL_HOUR_OF_DAY, hour); set(UCAL_MINUTE, minute); set(UCAL_SECOND, second); } // ------------------------------------- GregorianCalendar::~GregorianCalendar() { } // ------------------------------------- GregorianCalendar::GregorianCalendar(const GregorianCalendar &source) : Calendar(source), fGregorianCutover(source.fGregorianCutover), fCutoverJulianDay(source.fCutoverJulianDay), fNormalizedGregorianCutover(source.fNormalizedGregorianCutover), fGregorianCutoverYear(source.fGregorianCutoverYear), fIsGregorian(source.fIsGregorian), fInvertGregorian(source.fInvertGregorian) { } // ------------------------------------- Calendar* GregorianCalendar::clone() const { return new GregorianCalendar(*this); } // ------------------------------------- GregorianCalendar & GregorianCalendar::operator=(const GregorianCalendar &right) { if (this != &right) { Calendar::operator=(right); fGregorianCutover = right.fGregorianCutover; fNormalizedGregorianCutover = right.fNormalizedGregorianCutover; fGregorianCutoverYear = right.fGregorianCutoverYear; fCutoverJulianDay = right.fCutoverJulianDay; } return *this; } // ------------------------------------- UBool GregorianCalendar::isEquivalentTo(const Calendar& other) const { // Calendar override. return Calendar::isEquivalentTo(other) && fGregorianCutover == ((GregorianCalendar*)&other)->fGregorianCutover; } // ------------------------------------- void GregorianCalendar::setGregorianChange(UDate date, UErrorCode& status) { if (U_FAILURE(status)) return; fGregorianCutover = date; // Precompute two internal variables which we use to do the actual // cutover computations. These are the normalized cutover, which is the // midnight at or before the cutover, and the cutover year. The // normalized cutover is in pure date milliseconds; it contains no time // of day or timezone component, and it used to compare against other // pure date values. int32_t cutoverDay = (int32_t)Math::floorDivide(fGregorianCutover, (double)kOneDay); fNormalizedGregorianCutover = cutoverDay * kOneDay; // Handle the rare case of numeric overflow. If the user specifies a // change of UDate(Long.MIN_VALUE), in order to get a pure Gregorian // calendar, then the epoch day is -106751991168, which when multiplied // by ONE_DAY gives 9223372036794351616 -- the negative value is too // large for 64 bits, and overflows into a positive value. We correct // this by using the next day, which for all intents is semantically // equivalent. if (cutoverDay < 0 && fNormalizedGregorianCutover > 0) { fNormalizedGregorianCutover = (cutoverDay + 1) * kOneDay; } // Normalize the year so BC values are represented as 0 and negative // values. GregorianCalendar *cal = new GregorianCalendar(getTimeZone(), status); /* test for NULL */ if (cal == 0) { status = U_MEMORY_ALLOCATION_ERROR; return; } if(U_FAILURE(status)) return; cal->setTime(date, status); fGregorianCutoverYear = cal->get(UCAL_YEAR, status); if (cal->get(UCAL_ERA, status) == BC) fGregorianCutoverYear = 1 - fGregorianCutoverYear; fCutoverJulianDay = cutoverDay; delete cal; } void GregorianCalendar::handleComputeFields(int32_t julianDay, UErrorCode& status) { int32_t eyear, month, dayOfMonth, dayOfYear; if(U_FAILURE(status)) { return; } #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: jd%d- (greg's %d)- [cut=%d]\n", __FILE__, __LINE__, julianDay, getGregorianDayOfYear(), fCutoverJulianDay); #endif if (julianDay >= fCutoverJulianDay) { month = getGregorianMonth(); dayOfMonth = getGregorianDayOfMonth(); dayOfYear = getGregorianDayOfYear(); eyear = getGregorianYear(); } else { // The Julian epoch day (not the same as Julian Day) // is zero on Saturday December 30, 0 (Gregorian). int32_t julianEpochDay = julianDay - (kJan1_1JulianDay - 2); eyear = (int32_t) Math::floorDivide(4*julianEpochDay + 1464, 1461); // Compute the Julian calendar day number for January 1, eyear int32_t january1 = 365*(eyear-1) + Math::floorDivide(eyear-1, (int32_t)4); dayOfYear = (julianEpochDay - january1); // 0-based // Julian leap years occurred historically every 4 years starting // with 8 AD. Before 8 AD the spacing is irregular; every 3 years // from 45 BC to 9 BC, and then none until 8 AD. However, we don't // implement this historical detail; instead, we implement the // computatinally cleaner proleptic calendar, which assumes // consistent 4-year cycles throughout time. UBool isLeap = ((eyear&0x3) == 0); // equiv. to (eyear%4 == 0) // Common Julian/Gregorian calculation int32_t correction = 0; int32_t march1 = isLeap ? 60 : 59; // zero-based DOY for March 1 if (dayOfYear >= march1) { correction = isLeap ? 1 : 2; } month = (12 * (dayOfYear + correction) + 6) / 367; // zero-based month dayOfMonth = dayOfYear - (isLeap?kLeapNumDays[month]:kNumDays[month]) + 1; // one-based DOM ++dayOfYear; #if defined (U_DEBUG_CAL) // fprintf(stderr, "%d - %d[%d] + 1\n", dayOfYear, isLeap?kLeapNumDays[month]:kNumDays[month], month ); // fprintf(stderr, "%s:%d: greg's HCF %d -> %d/%d/%d not %d/%d/%d\n", // __FILE__, __LINE__,julianDay, // eyear,month,dayOfMonth, // getGregorianYear(), getGregorianMonth(), getGregorianDayOfMonth() ); fprintf(stderr, "%s:%d: doy %d (greg's %d)- [cut=%d]\n", __FILE__, __LINE__, dayOfYear, getGregorianDayOfYear(), fCutoverJulianDay); #endif } // [j81] if we are after the cutover in its year, shift the day of the year if((eyear == fGregorianCutoverYear) && (julianDay >= fCutoverJulianDay)) { //from handleComputeMonthStart int32_t gregShift = Grego::gregorianShift(eyear); #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: gregorian shift %d ::: doy%d => %d [cut=%d]\n", __FILE__, __LINE__,gregShift, dayOfYear, dayOfYear+gregShift, fCutoverJulianDay); #endif dayOfYear += gregShift; } internalSet(UCAL_MONTH, month); internalSet(UCAL_DAY_OF_MONTH, dayOfMonth); internalSet(UCAL_DAY_OF_YEAR, dayOfYear); internalSet(UCAL_EXTENDED_YEAR, eyear); int32_t era = AD; if (eyear < 1) { era = BC; eyear = 1 - eyear; } internalSet(UCAL_ERA, era); internalSet(UCAL_YEAR, eyear); } // ------------------------------------- UDate GregorianCalendar::getGregorianChange() const { return fGregorianCutover; } // ------------------------------------- UBool GregorianCalendar::isLeapYear(int32_t year) const { // MSVC complains bitterly if we try to use Grego::isLeapYear here // NOTE: year&0x3 == year%4 return (year >= fGregorianCutoverYear ? (((year&0x3) == 0) && ((year%100 != 0) || (year%400 == 0))) : // Gregorian ((year&0x3) == 0)); // Julian } // ------------------------------------- int32_t GregorianCalendar::handleComputeJulianDay(UCalendarDateFields bestField) { fInvertGregorian = FALSE; int32_t jd = Calendar::handleComputeJulianDay(bestField); if((bestField == UCAL_WEEK_OF_YEAR) && // if we are doing WOY calculations, we are counting relative to Jan 1 *julian* (internalGet(UCAL_EXTENDED_YEAR)==fGregorianCutoverYear) && jd >= fCutoverJulianDay) { fInvertGregorian = TRUE; // So that the Julian Jan 1 will be used in handleComputeMonthStart return Calendar::handleComputeJulianDay(bestField); } // The following check handles portions of the cutover year BEFORE the // cutover itself happens. //if ((fIsGregorian==TRUE) != (jd >= fCutoverJulianDay)) { /* cutoverJulianDay)) { */ if ((fIsGregorian==TRUE) != (jd >= fCutoverJulianDay)) { /* cutoverJulianDay)) { */ #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: jd [invert] %d\n", __FILE__, __LINE__, jd); #endif fInvertGregorian = TRUE; jd = Calendar::handleComputeJulianDay(bestField); #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: fIsGregorian %s, fInvertGregorian %s - ", __FILE__, __LINE__,fIsGregorian?"T":"F", fInvertGregorian?"T":"F"); fprintf(stderr, " jd NOW %d\n", jd); #endif } else { #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: jd [==] %d - %sfIsGregorian %sfInvertGregorian, %d\n", __FILE__, __LINE__, jd, fIsGregorian?"T":"F", fInvertGregorian?"T":"F", bestField); #endif } if(fIsGregorian && (internalGet(UCAL_EXTENDED_YEAR) == fGregorianCutoverYear)) { int32_t gregShift = Grego::gregorianShift(internalGet(UCAL_EXTENDED_YEAR)); if (bestField == UCAL_DAY_OF_YEAR) { #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: [DOY%d] gregorian shift of JD %d += %d\n", __FILE__, __LINE__, fFields[bestField],jd, gregShift); #endif jd -= gregShift; } else if ( bestField == UCAL_WEEK_OF_MONTH ) { int32_t weekShift = 14; #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: [WOY/WOM] gregorian week shift of %d += %d\n", __FILE__, __LINE__, jd, weekShift); #endif jd += weekShift; // shift by weeks for week based fields. } } return jd; } int32_t GregorianCalendar::handleComputeMonthStart(int32_t eyear, int32_t month, UBool /* useMonth */) const { GregorianCalendar *nonConstThis = (GregorianCalendar*)this; // cast away const // If the month is out of range, adjust it into range, and // modify the extended year value accordingly. if (month < 0 || month > 11) { eyear += Math::floorDivide(month, 12, month); } UBool isLeap = eyear%4 == 0; int32_t y = eyear-1; int32_t julianDay = 365*y + Math::floorDivide(y, 4) + (kJan1_1JulianDay - 3); nonConstThis->fIsGregorian = (eyear >= fGregorianCutoverYear); #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: (hcms%d/%d) fIsGregorian %s, fInvertGregorian %s\n", __FILE__, __LINE__, eyear,month, fIsGregorian?"T":"F", fInvertGregorian?"T":"F"); #endif if (fInvertGregorian) { nonConstThis->fIsGregorian = !fIsGregorian; } if (fIsGregorian) { isLeap = isLeap && ((eyear%100 != 0) || (eyear%400 == 0)); // Add 2 because Gregorian calendar starts 2 days after // Julian calendar int32_t gregShift = Grego::gregorianShift(eyear); #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: (hcms%d/%d) gregorian shift of %d += %d\n", __FILE__, __LINE__, eyear, month, julianDay, gregShift); #endif julianDay += gregShift; } // At this point julianDay indicates the day BEFORE the first // day of January 1, <eyear> of either the Julian or Gregorian // calendar. if (month != 0) { julianDay += isLeap?kLeapNumDays[month]:kNumDays[month]; } return julianDay; } int32_t GregorianCalendar::handleGetMonthLength(int32_t extendedYear, int32_t month) const { return isLeapYear(extendedYear) ? kLeapMonthLength[month] : kMonthLength[month]; } int32_t GregorianCalendar::handleGetYearLength(int32_t eyear) const { return isLeapYear(eyear) ? 366 : 365; } int32_t GregorianCalendar::monthLength(int32_t month) const { int32_t year = internalGet(UCAL_EXTENDED_YEAR); return handleGetMonthLength(year, month); } // ------------------------------------- int32_t GregorianCalendar::monthLength(int32_t month, int32_t year) const { return isLeapYear(year) ? kLeapMonthLength[month] : kMonthLength[month]; } // ------------------------------------- int32_t GregorianCalendar::yearLength(int32_t year) const { return isLeapYear(year) ? 366 : 365; } // ------------------------------------- int32_t GregorianCalendar::yearLength() const { return isLeapYear(internalGet(UCAL_YEAR)) ? 366 : 365; } // ------------------------------------- /** * After adjustments such as add(MONTH), add(YEAR), we don't want the * month to jump around. E.g., we don't want Jan 31 + 1 month to go to Mar * 3, we want it to go to Feb 28. Adjustments which might run into this * problem call this method to retain the proper month. */ void GregorianCalendar::pinDayOfMonth() { int32_t monthLen = monthLength(internalGet(UCAL_MONTH)); int32_t dom = internalGet(UCAL_DATE); if(dom > monthLen) set(UCAL_DATE, monthLen); } // ------------------------------------- UBool GregorianCalendar::validateFields() const { for (int32_t field = 0; field < UCAL_FIELD_COUNT; field++) { // Ignore DATE and DAY_OF_YEAR which are handled below if (field != UCAL_DATE && field != UCAL_DAY_OF_YEAR && isSet((UCalendarDateFields)field) && ! boundsCheck(internalGet((UCalendarDateFields)field), (UCalendarDateFields)field)) return FALSE; } // Values differ in Least-Maximum and Maximum should be handled // specially. if (isSet(UCAL_DATE)) { int32_t date = internalGet(UCAL_DATE); if (date < getMinimum(UCAL_DATE) || date > monthLength(internalGet(UCAL_MONTH))) { return FALSE; } } if (isSet(UCAL_DAY_OF_YEAR)) { int32_t days = internalGet(UCAL_DAY_OF_YEAR); if (days < 1 || days > yearLength()) { return FALSE; } } // Handle DAY_OF_WEEK_IN_MONTH, which must not have the value zero. // We've checked against minimum and maximum above already. if (isSet(UCAL_DAY_OF_WEEK_IN_MONTH) && 0 == internalGet(UCAL_DAY_OF_WEEK_IN_MONTH)) { return FALSE; } return TRUE; } // ------------------------------------- UBool GregorianCalendar::boundsCheck(int32_t value, UCalendarDateFields field) const { return value >= getMinimum(field) && value <= getMaximum(field); } // ------------------------------------- UDate GregorianCalendar::getEpochDay(UErrorCode& status) { complete(status); // Divide by 1000 (convert to seconds) in order to prevent overflow when // dealing with UDate(Long.MIN_VALUE) and UDate(Long.MAX_VALUE). double wallSec = internalGetTime()/1000 + (internalGet(UCAL_ZONE_OFFSET) + internalGet(UCAL_DST_OFFSET))/1000; return Math::floorDivide(wallSec, kOneDay/1000.0); } // ------------------------------------- // ------------------------------------- /** * Compute the julian day number of the day BEFORE the first day of * January 1, year 1 of the given calendar. If julianDay == 0, it * specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian * or Gregorian). */ double GregorianCalendar::computeJulianDayOfYear(UBool isGregorian, int32_t year, UBool& isLeap) { isLeap = year%4 == 0; int32_t y = year - 1; double julianDay = 365.0*y + Math::floorDivide(y, 4) + (kJan1_1JulianDay - 3); if (isGregorian) { isLeap = isLeap && ((year%100 != 0) || (year%400 == 0)); // Add 2 because Gregorian calendar starts 2 days after Julian calendar julianDay += Grego::gregorianShift(year); } return julianDay; } // /** // * Compute the day of week, relative to the first day of week, from // * 0..6, of the current DOW_LOCAL or DAY_OF_WEEK fields. This is // * equivalent to get(DOW_LOCAL) - 1. // */ // int32_t GregorianCalendar::computeRelativeDOW() const { // int32_t relDow = 0; // if (fStamp[UCAL_DOW_LOCAL] > fStamp[UCAL_DAY_OF_WEEK]) { // relDow = internalGet(UCAL_DOW_LOCAL) - 1; // 1-based // } else if (fStamp[UCAL_DAY_OF_WEEK] != kUnset) { // relDow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek(); // if (relDow < 0) relDow += 7; // } // return relDow; // } // /** // * Compute the day of week, relative to the first day of week, // * from 0..6 of the given julian day. // */ // int32_t GregorianCalendar::computeRelativeDOW(double julianDay) const { // int32_t relDow = julianDayToDayOfWeek(julianDay) - getFirstDayOfWeek(); // if (relDow < 0) { // relDow += 7; // } // return relDow; // } // /** // * Compute the DOY using the WEEK_OF_YEAR field and the julian day // * of the day BEFORE January 1 of a year (a return value from // * computeJulianDayOfYear). // */ // int32_t GregorianCalendar::computeDOYfromWOY(double julianDayOfYear) const { // // Compute DOY from day of week plus week of year // // Find the day of the week for the first of this year. This // // is zero-based, with 0 being the locale-specific first day of // // the week. Add 1 to get first day of year. // int32_t fdy = computeRelativeDOW(julianDayOfYear + 1); // return // // Compute doy of first (relative) DOW of WOY 1 // (((7 - fdy) < getMinimalDaysInFirstWeek()) // ? (8 - fdy) : (1 - fdy)) // // Adjust for the week number. // + (7 * (internalGet(UCAL_WEEK_OF_YEAR) - 1)) // // Adjust for the DOW // + computeRelativeDOW(); // } // ------------------------------------- double GregorianCalendar::millisToJulianDay(UDate millis) { return (double)kEpochStartAsJulianDay + Math::floorDivide(millis, (double)kOneDay); } // ------------------------------------- UDate GregorianCalendar::julianDayToMillis(double julian) { return (UDate) ((julian - kEpochStartAsJulianDay) * (double) kOneDay); } // ------------------------------------- int32_t GregorianCalendar::aggregateStamp(int32_t stamp_a, int32_t stamp_b) { return (((stamp_a != kUnset && stamp_b != kUnset) ? uprv_max(stamp_a, stamp_b) : (int32_t)kUnset)); } // ------------------------------------- /** * Roll a field by a signed amount. * Note: This will be made public later. [LIU] */ void GregorianCalendar::roll(EDateFields field, int32_t amount, UErrorCode& status) { roll((UCalendarDateFields) field, amount, status); } void GregorianCalendar::roll(UCalendarDateFields field, int32_t amount, UErrorCode& status) { if((amount == 0) || U_FAILURE(status)) { return; } // J81 processing. (gregorian cutover) UBool inCutoverMonth = FALSE; int32_t cMonthLen=0; // 'c' for cutover; in days int32_t cDayOfMonth=0; // no discontinuity: [0, cMonthLen) double cMonthStart=0.0; // in ms // Common code - see if we're in the cutover month of the cutover year if(get(UCAL_EXTENDED_YEAR, status) == fGregorianCutoverYear) { switch (field) { case UCAL_DAY_OF_MONTH: case UCAL_WEEK_OF_MONTH: { int32_t max = monthLength(internalGet(UCAL_MONTH)); UDate t = internalGetTime(); // We subtract 1 from the DAY_OF_MONTH to make it zero-based, and an // additional 10 if we are after the cutover. Thus the monthStart // value will be correct iff we actually are in the cutover month. cDayOfMonth = internalGet(UCAL_DAY_OF_MONTH) - ((t >= fGregorianCutover) ? 10 : 0); cMonthStart = t - ((cDayOfMonth - 1) * kOneDay); // A month containing the cutover is 10 days shorter. if ((cMonthStart < fGregorianCutover) && (cMonthStart + (cMonthLen=(max-10))*kOneDay >= fGregorianCutover)) { inCutoverMonth = TRUE; } } default: ; } } switch (field) { case UCAL_WEEK_OF_YEAR: { // Unlike WEEK_OF_MONTH, WEEK_OF_YEAR never shifts the day of the // week. Also, rolling the week of the year can have seemingly // strange effects simply because the year of the week of year // may be different from the calendar year. For example, the // date Dec 28, 1997 is the first day of week 1 of 1998 (if // weeks start on Sunday and the minimal days in first week is // <= 3). int32_t woy = get(UCAL_WEEK_OF_YEAR, status); // Get the ISO year, which matches the week of year. This // may be one year before or after the calendar year. int32_t isoYear = get(UCAL_YEAR_WOY, status); int32_t isoDoy = internalGet(UCAL_DAY_OF_YEAR); if (internalGet(UCAL_MONTH) == UCAL_JANUARY) { if (woy >= 52) { isoDoy += handleGetYearLength(isoYear); } } else { if (woy == 1) { isoDoy -= handleGetYearLength(isoYear - 1); } } woy += amount; // Do fast checks to avoid unnecessary computation: if (woy < 1 || woy > 52) { // Determine the last week of the ISO year. // We do this using the standard formula we use // everywhere in this file. If we can see that the // days at the end of the year are going to fall into // week 1 of the next year, we drop the last week by // subtracting 7 from the last day of the year. int32_t lastDoy = handleGetYearLength(isoYear); int32_t lastRelDow = (lastDoy - isoDoy + internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek()) % 7; if (lastRelDow < 0) lastRelDow += 7; if ((6 - lastRelDow) >= getMinimalDaysInFirstWeek()) lastDoy -= 7; int32_t lastWoy = weekNumber(lastDoy, lastRelDow + 1); woy = ((woy + lastWoy - 1) % lastWoy) + 1; } set(UCAL_WEEK_OF_YEAR, woy); set(UCAL_YEAR_WOY,isoYear); return; } case UCAL_DAY_OF_MONTH: if( !inCutoverMonth ) { Calendar::roll(field, amount, status); return; } else { // [j81] 1582 special case for DOM // The default computation works except when the current month // contains the Gregorian cutover. We handle this special case // here. [j81 - aliu] double monthLen = cMonthLen * kOneDay; double msIntoMonth = uprv_fmod(internalGetTime() - cMonthStart + amount * kOneDay, monthLen); if (msIntoMonth < 0) { msIntoMonth += monthLen; } #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: roll DOM %d -> %.0lf ms \n", __FILE__, __LINE__,amount, cMonthLen, cMonthStart+msIntoMonth); #endif setTimeInMillis(cMonthStart + msIntoMonth, status); return; } case UCAL_WEEK_OF_MONTH: if( !inCutoverMonth ) { Calendar::roll(field, amount, status); return; } else { #if defined (U_DEBUG_CAL) fprintf(stderr, "%s:%d: roll WOM %d ??????????????????? \n", __FILE__, __LINE__,amount); #endif // NOTE: following copied from the old // GregorianCalendar::roll( WEEK_OF_MONTH ) code // This is tricky, because during the roll we may have to shift // to a different day of the week. For example: // s m t w r f s // 1 2 3 4 5 // 6 7 8 9 10 11 12 // When rolling from the 6th or 7th back one week, we go to the // 1st (assuming that the first partial week counts). The same // thing happens at the end of the month. // The other tricky thing is that we have to figure out whether // the first partial week actually counts or not, based on the // minimal first days in the week. And we have to use the // correct first day of the week to delineate the week // boundaries. // Here's our algorithm. First, we find the real boundaries of // the month. Then we discard the first partial week if it // doesn't count in this locale. Then we fill in the ends with // phantom days, so that the first partial week and the last // partial week are full weeks. We then have a nice square // block of weeks. We do the usual rolling within this block, // as is done elsewhere in this method. If we wind up on one of // the phantom days that we added, we recognize this and pin to // the first or the last day of the month. Easy, eh? // Another wrinkle: To fix jitterbug 81, we have to make all this // work in the oddball month containing the Gregorian cutover. // This month is 10 days shorter than usual, and also contains // a discontinuity in the days; e.g., the default cutover month // is Oct 1582, and goes from day of month 4 to day of month 15. // Normalize the DAY_OF_WEEK so that 0 is the first day of the week // in this locale. We have dow in 0..6. int32_t dow = internalGet(UCAL_DAY_OF_WEEK) - getFirstDayOfWeek(); if (dow < 0) dow += 7; // Find the day of month, compensating for cutover discontinuity. int32_t dom = cDayOfMonth; // Find the day of the week (normalized for locale) for the first // of the month. int32_t fdm = (dow - dom + 1) % 7; if (fdm < 0) fdm += 7; // Get the first day of the first full week of the month, // including phantom days, if any. Figure out if the first week // counts or not; if it counts, then fill in phantom days. If // not, advance to the first real full week (skip the partial week). int32_t start; if ((7 - fdm) < getMinimalDaysInFirstWeek()) start = 8 - fdm; // Skip the first partial week else start = 1 - fdm; // This may be zero or negative // Get the day of the week (normalized for locale) for the last // day of the month. int32_t monthLen = cMonthLen; int32_t ldm = (monthLen - dom + dow) % 7; // We know monthLen >= DAY_OF_MONTH so we skip the += 7 step here. // Get the limit day for the blocked-off rectangular month; that // is, the day which is one past the last day of the month, // after the month has already been filled in with phantom days // to fill out the last week. This day has a normalized DOW of 0. int32_t limit = monthLen + 7 - ldm; // Now roll between start and (limit - 1). int32_t gap = limit - start; int32_t newDom = (dom + amount*7 - start) % gap; if (newDom < 0) newDom += gap; newDom += start; // Finally, pin to the real start and end of the month. if (newDom < 1) newDom = 1; if (newDom > monthLen) newDom = monthLen; // Set the DAY_OF_MONTH. We rely on the fact that this field // takes precedence over everything else (since all other fields // are also set at this point). If this fact changes (if the // disambiguation algorithm changes) then we will have to unset // the appropriate fields here so that DAY_OF_MONTH is attended // to. // If we are in the cutover month, manipulate ms directly. Don't do // this in general because it doesn't work across DST boundaries // (details, details). This takes care of the discontinuity. setTimeInMillis(cMonthStart + (newDom-1)*kOneDay, status); return; } default: Calendar::roll(field, amount, status); return; } } // ------------------------------------- /** * Return the minimum value that this field could have, given the current date. * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). * @param field the time field. * @return the minimum value that this field could have, given the current date. * @deprecated ICU 2.6. Use getActualMinimum(UCalendarDateFields field) instead. */ int32_t GregorianCalendar::getActualMinimum(EDateFields field) const { return getMinimum((UCalendarDateFields)field); } int32_t GregorianCalendar::getActualMinimum(EDateFields field, UErrorCode& /* status */) const { return getMinimum((UCalendarDateFields)field); } /** * Return the minimum value that this field could have, given the current date. * For the Gregorian calendar, this is the same as getMinimum() and getGreatestMinimum(). * @param field the time field. * @return the minimum value that this field could have, given the current date. * @draft ICU 2.6. */ int32_t GregorianCalendar::getActualMinimum(UCalendarDateFields field, UErrorCode& /* status */) const { return getMinimum(field); } // ------------------------------------ /** * Old year limits were least max 292269054, max 292278994. */ /** * @stable ICU 2.0 */ int32_t GregorianCalendar::handleGetLimit(UCalendarDateFields field, ELimitType limitType) const { return kGregorianCalendarLimits[field][limitType]; } /** * Return the maximum value that this field could have, given the current date. * For example, with the date "Feb 3, 1997" and the DAY_OF_MONTH field, the actual * maximum would be 28; for "Feb 3, 1996" it s 29. Similarly for a Hebrew calendar, * for some years the actual maximum for MONTH is 12, and for others 13. * @stable ICU 2.0 */ int32_t GregorianCalendar::getActualMaximum(UCalendarDateFields field, UErrorCode& status) const { /* It is a known limitation that the code here (and in getActualMinimum) * won't behave properly at the extreme limits of GregorianCalendar's * representable range (except for the code that handles the YEAR * field). That's because the ends of the representable range are at * odd spots in the year. For calendars with the default Gregorian * cutover, these limits are Sun Dec 02 16:47:04 GMT 292269055 BC to Sun * Aug 17 07:12:55 GMT 292278994 AD, somewhat different for non-GMT * zones. As a result, if the calendar is set to Aug 1 292278994 AD, * the actual maximum of DAY_OF_MONTH is 17, not 30. If the date is Mar * 31 in that year, the actual maximum month might be Jul, whereas is * the date is Mar 15, the actual maximum might be Aug -- depending on * the precise semantics that are desired. Similar considerations * affect all fields. Nonetheless, this effect is sufficiently arcane * that we permit it, rather than complicating the code to handle such * intricacies. - liu 8/20/98 * UPDATE: No longer true, since we have pulled in the limit values on * the year. - Liu 11/6/00 */ switch (field) { case UCAL_YEAR: /* The year computation is no different, in principle, from the * others, however, the range of possible maxima is large. In * addition, the way we know we've exceeded the range is different. * For these reasons, we use the special case code below to handle * this field. * * The actual maxima for YEAR depend on the type of calendar: * * Gregorian = May 17, 292275056 BC - Aug 17, 292278994 AD * Julian = Dec 2, 292269055 BC - Jan 3, 292272993 AD * Hybrid = Dec 2, 292269055 BC - Aug 17, 292278994 AD * * We know we've exceeded the maximum when either the month, date, * time, or era changes in response to setting the year. We don't * check for month, date, and time here because the year and era are * sufficient to detect an invalid year setting. NOTE: If code is * added to check the month and date in the future for some reason, * Feb 29 must be allowed to shift to Mar 1 when setting the year. */ { if(U_FAILURE(status)) return 0; Calendar *cal = clone(); if(!cal) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } cal->setLenient(TRUE); int32_t era = cal->get(UCAL_ERA, status); UDate d = cal->getTime(status); /* Perform a binary search, with the invariant that lowGood is a * valid year, and highBad is an out of range year. */ int32_t lowGood = kGregorianCalendarLimits[UCAL_YEAR][1]; int32_t highBad = kGregorianCalendarLimits[UCAL_YEAR][2]+1; while ((lowGood + 1) < highBad) { int32_t y = (lowGood + highBad) / 2; cal->set(UCAL_YEAR, y); if (cal->get(UCAL_YEAR, status) == y && cal->get(UCAL_ERA, status) == era) { lowGood = y; } else { highBad = y; cal->setTime(d, status); // Restore original fields } } delete cal; return lowGood; } default: return Calendar::getActualMaximum(field,status); } } int32_t GregorianCalendar::handleGetExtendedYear() { int32_t year = kEpochYear; switch(resolveFields(kYearPrecedence)) { case UCAL_EXTENDED_YEAR: year = internalGet(UCAL_EXTENDED_YEAR, kEpochYear); break; case UCAL_YEAR: { // The year defaults to the epoch start, the era to AD int32_t era = internalGet(UCAL_ERA, AD); if (era == BC) { year = 1 - internalGet(UCAL_YEAR, 1); // Convert to extended year } else { year = internalGet(UCAL_YEAR, kEpochYear); } } break; case UCAL_YEAR_WOY: year = handleGetExtendedYearFromWeekFields(internalGet(UCAL_YEAR_WOY), internalGet(UCAL_WEEK_OF_YEAR)); #if defined (U_DEBUG_CAL) // if(internalGet(UCAL_YEAR_WOY) != year) { fprintf(stderr, "%s:%d: hGEYFWF[%d,%d] -> %d\n", __FILE__, __LINE__,internalGet(UCAL_YEAR_WOY),internalGet(UCAL_WEEK_OF_YEAR),year); //} #endif break; default: year = kEpochYear; } return year; } int32_t GregorianCalendar::handleGetExtendedYearFromWeekFields(int32_t yearWoy, int32_t woy) { // convert year to extended form int32_t era = internalGet(UCAL_ERA, AD); if(era == BC) { yearWoy = 1 - yearWoy; } return Calendar::handleGetExtendedYearFromWeekFields(yearWoy, woy); } // ------------------------------------- UBool GregorianCalendar::inDaylightTime(UErrorCode& status) const { if (U_FAILURE(status) || !getTimeZone().useDaylightTime()) return FALSE; // Force an update of the state of the Calendar. ((GregorianCalendar*)this)->complete(status); // cast away const return (UBool)(U_SUCCESS(status) ? (internalGet(UCAL_DST_OFFSET) != 0) : FALSE); } // ------------------------------------- /** * Return the ERA. We need a special method for this because the * default ERA is AD, but a zero (unset) ERA is BC. */ int32_t GregorianCalendar::internalGetEra() const { return isSet(UCAL_ERA) ? internalGet(UCAL_ERA) : (int32_t)AD; } const char * GregorianCalendar::getType() const { //static const char kGregorianType = "gregorian"; return "gregorian"; } const UDate GregorianCalendar::fgSystemDefaultCentury = DBL_MIN; const int32_t GregorianCalendar::fgSystemDefaultCenturyYear = -1; UDate GregorianCalendar::fgSystemDefaultCenturyStart = DBL_MIN; int32_t GregorianCalendar::fgSystemDefaultCenturyStartYear = -1; UBool GregorianCalendar::haveDefaultCentury() const { return TRUE; } UDate GregorianCalendar::defaultCenturyStart() const { return internalGetDefaultCenturyStart(); } int32_t GregorianCalendar::defaultCenturyStartYear() const { return internalGetDefaultCenturyStartYear(); } UDate GregorianCalendar::internalGetDefaultCenturyStart() const { // lazy-evaluate systemDefaultCenturyStart UBool needsUpdate; { Mutex m; needsUpdate = (fgSystemDefaultCenturyStart == fgSystemDefaultCentury); } if (needsUpdate) { initializeSystemDefaultCentury(); } // use defaultCenturyStart unless it's the flag value; // then use systemDefaultCenturyStart return fgSystemDefaultCenturyStart; } int32_t GregorianCalendar::internalGetDefaultCenturyStartYear() const { // lazy-evaluate systemDefaultCenturyStartYear UBool needsUpdate; { Mutex m; needsUpdate = (fgSystemDefaultCenturyStart == fgSystemDefaultCentury); } if (needsUpdate) { initializeSystemDefaultCentury(); } // use defaultCenturyStart unless it's the flag value; // then use systemDefaultCenturyStartYear return fgSystemDefaultCenturyStartYear; } void GregorianCalendar::initializeSystemDefaultCentury() { // initialize systemDefaultCentury and systemDefaultCenturyYear based // on the current time. They'll be set to 80 years before // the current time. // No point in locking as it should be idempotent. if (fgSystemDefaultCenturyStart == fgSystemDefaultCentury) { UErrorCode status = U_ZERO_ERROR; Calendar *calendar = new GregorianCalendar(status); if (calendar != NULL && U_SUCCESS(status)) { calendar->setTime(Calendar::getNow(), status); calendar->add(UCAL_YEAR, -80, status); UDate newStart = calendar->getTime(status); int32_t newYear = calendar->get(UCAL_YEAR, status); { Mutex m; fgSystemDefaultCenturyStart = newStart; fgSystemDefaultCenturyStartYear = newYear; } delete calendar; } // We have no recourse upon failure unless we want to propagate the failure // out. } } U_NAMESPACE_END #endif /* #if !UCONFIG_NO_FORMATTING */ //eof
[ "(no author)@251d0590-4201-4cf1-90de-194747b24ca1" ]
(no author)@251d0590-4201-4cf1-90de-194747b24ca1
24d654981ac97b37a0d5a38e8c0254c09484511b
092c77a5e7c2f766f79b1b176dc9629ab3a5060e
/src/Keyboard.cpp
8d230dbfd9d33853aa30bd8f92b334f112e181ee
[]
no_license
MatillaMartin/Arcanoid
6cb83c1b61a8ddd1cc91e4916842e57219d8a988
48ffe7cdee9cce48e49c9a41b27fcc369e23a2de
refs/heads/master
2021-01-17T15:51:15.814563
2017-03-08T08:39:18
2017-03-08T08:39:18
84,114,355
1
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
#include "Keyboard.h" #include "ofEvent.h" Keyboard::Keyboard() { ofAddListener(ofEvents().keyPressed, this, &Keyboard::onKeyPress); ofAddListener(ofEvents().keyReleased, this, &Keyboard::onKeyRelease); } void Keyboard::onKeyPress(ofKeyEventArgs & key) { m_keys[(char)key.key] = true; } void Keyboard::onKeyRelease(ofKeyEventArgs & key) { m_keys[(char)key.key] = false; } const std::map<char, bool> & Keyboard::getKeys() { return m_keys; }
c1e63864d738005259092d541beebe8797950691
157fd7fe5e541c8ef7559b212078eb7a6dbf51c6
/TRiAS/TRiASDB/TRiASDB/DatabaseFeatureMap.cpp
686ccc182cb5b88f9371005b282632aa92fc4480
[]
no_license
15831944/TRiAS
d2bab6fd129a86fc2f06f2103d8bcd08237c49af
840946b85dcefb34efc219446240e21f51d2c60d
refs/heads/master
2020-09-05T05:56:39.624150
2012-11-11T02:24:49
2012-11-11T02:24:49
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,533
cpp
// $Header: $ // Copyright© 1998 TRiAS GmbH Potsdam, All rights reserved // Created: 08/26/1998 11:46:12 PM // // @doc // @module DatabaseFeatureMap.cpp | Implementation of the <c CDatabaseFeatureMap> class #include "stdafx.h" #include "Strings.h" #include "Wrapper.h" #include "GlobalVars.h" #include <Com/PropertyHelper.h> #include "DatabaseFeatureMap.h" #if defined(_DEBUG) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // _DEBUG ///////////////////////////////////////////////////////////////////////////// // RUNTIME_OBJECT_MAP RT_OBJECT_ENTRY(CLSID_DatabaseFeatureMap, CDatabaseFeatureMap) ///////////////////////////////////////////////////////////////////////////// // CDatabaseFeatureMap DefineSmartInterface(TRiASDatabase); DefineSmartInterface(TRiASProperties); DefineSmartInterface(TRiASObjectHandleMap); ///////////////////////////////////////////////////////////////////////////// // PropertySupport // Callback-interface, welches für die Konkretheit der Properties zuständig ist STDMETHODIMP CDatabaseFeatureMap::PutValue (BSTR Name, VARIANT Value) { AFX_MANAGE_STATE(AfxGetStaticModuleState()) return E_NOTIMPL; } STDMETHODIMP CDatabaseFeatureMap::GetValue (BSTR Name, VARIANT *pVal) { AFX_MANAGE_STATE(AfxGetStaticModuleState()) if (NULL == Name || NULL == pVal) return REPORT_DBERROR_ROUT(TRIASDB_E_INVALID_PARAMETER, "CDatabaseFeatureMap::GetValue"); _ASSERTE(!wcscmp (Name, g_cbFeatureMap)); // muß "FeatureMap" sein if (wcscmp (Name, g_cbFeatureMap)) return REPORT_DBERROR_ROUT(TRIASDB_E_INVALID_PARAMETER, "CDatabaseFeatureMap::GetValue"); return GetDatabaseFeatureMap (pVal); } STDMETHODIMP CDatabaseFeatureMap::PutType (BSTR Name, PROPERTY_TYPE Value) { AFX_MANAGE_STATE(AfxGetStaticModuleState()) return E_NOTIMPL; } STDMETHODIMP CDatabaseFeatureMap::GetType (BSTR Name, PROPERTY_TYPE *pVal) { AFX_MANAGE_STATE(AfxGetStaticModuleState()) if (NULL == Name || NULL == pVal) return REPORT_DBERROR_ROUT(TRIASDB_E_INVALID_PARAMETER, "CDatabaseFeatureMap::GetType"); _ASSERTE(!wcscmp (Name, g_cbFeatureMap)); // muß "FeatureMap" sein if (wcscmp (Name, g_cbFeatureMap)) return REPORT_DBERROR_ROUT(TRIASDB_E_INVALID_PARAMETER, "CDatabaseFeatureMap::GetValue"); *pVal = PROPERTY_TYPE(PROPERTY_TYPE_Dynamic|PROPERTY_TYPE_ReadOnly); return S_OK; } STDMETHODIMP CDatabaseFeatureMap::PutValueAndType(BSTR Name, VARIANT Val, PROPERTY_TYPE Type) { AFX_MANAGE_STATE(AfxGetStaticModuleState()) return E_NOTIMPL; } STDMETHODIMP CDatabaseFeatureMap::GetValueAndType(BSTR Name, VARIANT * pVal, PROPERTY_TYPE * pType) { AFX_MANAGE_STATE(AfxGetStaticModuleState()) if (NULL == Name || NULL == pVal || NULL == pType) return REPORT_DBERROR_ROUT(TRIASDB_E_INVALID_PARAMETER, "CDatabaseFeatureMap::GetType"); _ASSERTE(!wcscmp (Name, g_cbFeatureMap)); // muß "FeatureMap" sein if (wcscmp (Name, g_cbFeatureMap)) return REPORT_DBERROR_ROUT(TRIASDB_E_INVALID_PARAMETER, "CDatabaseFeatureMap::GetValue"); *pType = PROPERTY_TYPE(PROPERTY_TYPE_Dynamic|PROPERTY_TYPE_ReadOnly); return GetDatabaseFeatureMap (pVal); } /////////////////////////////////////////////////////////////////////////////// // IObjectWithSite STDMETHODIMP CDatabaseFeatureMap::SetSite (IUnknown *pISite) { AFX_MANAGE_STATE(AfxGetStaticModuleState()) if (NULL != pISite) return pISite -> QueryInterface(m_Objs.ppi()); else { m_Objs.Assign(NULL); return S_OK; } } STDMETHODIMP CDatabaseFeatureMap::GetSite (REFIID riid, void **ppvSite) { AFX_MANAGE_STATE(AfxGetStaticModuleState()) if (!m_Objs) return REPORT_DBERROR(TRIASDB_E_PROPERTY_NOT_INITIALIZED); return m_Objs -> QueryInterface (riid, ppvSite); } STDMETHODIMP CDatabaseFeatureMap::Refresh(BSTR bstrName) { AFX_MANAGE_STATE(AfxGetStaticModuleState()) return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // Helper HRESULT CDatabaseFeatureMap::GetDatabaseFeatureMap (VARIANT *pVal) { if (!m_Objs.IsValid()) return REPORT_DBERROR(TRIASDB_E_PROPERTY_NOT_INITIALIZED); COM_TRY { WTRiASDatabase Parent; THROW_FAILED_HRESULT(FindSpecificParent (m_Objs, Parent.ppi())); WTRiASObjectHandleMap Map (GetPropertyFrom (Parent, g_cbFeatureMap, (IDispatch *)NULL), false); // GetProperty liefert AddRef'ed ab CComVariant Val (Map); THROW_FAILED_HRESULT(Val.Detach(pVal)); } COM_CATCH; return S_OK; }
[ "Windows Live ID\\[email protected]" ]
Windows Live ID\[email protected]
702eb22e68ff7866d841916c9cf04d77ab4102e4
81028f0cf4e470303c95f94be1189c59e416f95f
/URI/1023.cpp
839559a9f503fc3ba8192ae8d024f10661a73293
[]
no_license
vandersonmr/ProgrammingContest
d82a1a429abd58773eebc83bc238430c649004f2
10936bd030c16efdc7cb59b3eb961287f6102cc0
refs/heads/master
2021-01-18T07:51:50.419599
2015-08-03T01:34:55
2015-08-03T01:34:55
12,670,094
3
2
null
null
null
null
UTF-8
C++
false
false
952
cpp
#include <cstdio> #include <utility> #include <iostream> #include <map> #include <vector> #include <iostream> #include <iomanip> #include <algorithm> using namespace std; class Cidade { public: int n; int totalPessoas; int soma; map<int, int> v; }; int main() { int p = 0; while(true) { Cidade c; c.v.clear(); int n; scanf("%d", &n); if(n == 0) break; if(p) printf("\n"); p++; c.soma = 0; c.totalPessoas = 0; c.n = p; int a,b; for(int i=0;i < n; i++){ scanf("%d %d", &a, &b); c.soma += b; c.totalPessoas += a; c.v[b/a] += a; } printf("Cidade# %d:\n", c.n); auto t = c.v.begin(); printf("%d-%d", t->second, t->first); for(++t; t != c.v.end(); ++t) printf(" %d-%d", t->second, t->first); double media = floor(100.0 * c.soma / c.totalPessoas) / 100; printf("\nConsumo medio: %.2lf m3.\n", media); } return 0; }
bfee2b99dac7080502220b7acbfad98afdfce169
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_new_log_542.cpp
ee9ce4abbb607bfd5f94e5e7814a8e6a0961ddf2
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
87
cpp
storeAppendPrintf(sentry, "syscalls.sock.binds = %f/sec\n", stats.syscalls_sock_binds);
569b745487cb4231f4e1b7ffce3394b8274c2142
797f08fe318cb9b483133693b850ffeff9d9fa20
/hull3D.h
b5ec8af94e763a4a27ceceb571d27a7cf5f64072
[]
no_license
SpexGuy/MinkowskiHull3D
27c084aa7ac22e0863647ac0ae5a66fff03246ca
c0e56ae91e7de255fc3cd96de8081f7e43e7572c
refs/heads/master
2021-01-19T20:11:43.534575
2017-03-07T06:02:51
2017-03-07T06:02:51
83,741,606
1
0
null
null
null
null
UTF-8
C++
false
false
2,344
h
// // Created by Martin Wickham on 3/2/17. // #ifndef MINKOWSKIHULL3D_HULL3D_H #define MINKOWSKIHULL3D_HULL3D_H #include <glm/glm.hpp> #include <vector> #include <cstdint> struct Collider3D { virtual glm::vec3 findSupport(glm::vec3 direction) = 0; }; struct AddCollider3D : public Collider3D { Collider3D *a; Collider3D *b; glm::vec3 findSupport(glm::vec3 direction) override { return a->findSupport(direction) + b->findSupport(direction); } }; struct SubCollider3D : public Collider3D { Collider3D *a; Collider3D *b; glm::vec3 findSupport(glm::vec3 direction) override { return a->findSupport(direction) - b->findSupport(-direction); } }; struct PointCollider3D : public Collider3D { glm::vec3 point; glm::vec3 findSupport(glm::vec3 direction) override { return point; } }; struct SphereCollider3D : public Collider3D { float radius; glm::vec3 findSupport(glm::vec3 direction) override { return radius * glm::normalize(direction); } }; struct PointHullCollider3D : public Collider3D { std::vector<glm::vec3> points; glm::vec3 findSupport(glm::vec3 direction) override { glm::vec3 best; float bestDot = -std::numeric_limits<float>::infinity(); for (glm::vec3 &vec : points) { float d = glm::dot(direction, vec); if (d > bestDot) { bestDot = d; best = vec; } } return best; } }; struct HalfEdge { uint16_t vertex; uint16_t opposite; }; struct Triangle { uint32_t flags; HalfEdge edges[3]; }; inline uint16_t prevEdge(uint16_t edge) { edge--; return uint16_t((edge & 3) == 0 ? edge + 3 : edge); } struct SurfaceState { Collider3D *object; float epsilon; std::vector<glm::vec3> points; std::vector<Triangle> triangles; uint16_t current; void init(); void step(); inline bool done() { return current >= triangles.size(); } inline HalfEdge *edges() { static_assert(sizeof(Triangle) == 4 * sizeof(HalfEdge), "Four HalfEdges must be the same size as a Triangle."); // this is necessary for the indexing scheme return reinterpret_cast<HalfEdge *>(&triangles[0]); } void maybeSwapEdge(uint16_t edge); }; #endif //MINKOWSKIHULL3D_HULL3D_H
f9f2ed01b5b617faa9806c769055779dab6c2c72
ded3a8f1ae2ff59a0c28fc23dd22daeaa064609f
/2.3_Digital_Inputs/2.3_Digital_Inputs.ino
4859d126ec6c18141f6b715e2a9778780f5c5672
[]
no_license
acbarker19/Arduino-ELEGOO-Tutorials
c70f46c4668d2376cc6c1521f623bdeae1b416b0
4834b5964c8f1b6853230bdfdb90fbfdeae299b0
refs/heads/main
2023-05-12T00:42:02.385057
2021-06-02T01:35:52
2021-06-02T01:35:52
361,579,961
2
1
null
null
null
null
UTF-8
C++
false
false
384
ino
//www.elegoo.com //2016.12.08 int ledPin = 5; int buttonApin = 9; int buttonBpin = 8; void setup() { pinMode(ledPin, OUTPUT); pinMode(buttonApin, INPUT_PULLUP); pinMode(buttonBpin, INPUT_PULLUP); } void loop() { if (digitalRead(buttonApin) == LOW) { digitalWrite(ledPin, HIGH); } if (digitalRead(buttonBpin) == LOW) { digitalWrite(ledPin, LOW); } }
51ed7f66c138b87d0768ccad79c1159fe55699cf
57ae15e1079e3b6cf85d6a5cfb21689665021866
/coupled/event/eventCallback.cpp
501529638fca000296d7c542a856bc967c987f70
[]
no_license
Wonshtrum/TeraGen
65fa878b8afad14bdb8f7221d9ab5fddcbf532c1
8416379f3f06435bac84bfc3e3e19ca9872092ff
refs/heads/master
2022-11-10T05:29:07.963070
2020-07-02T11:42:46
2020-07-02T11:42:46
273,426,017
1
0
null
null
null
null
UTF-8
C++
false
false
2,004
cpp
#include <GL/glew.h> #include <GLFW/glfw3.h> #include "event.h" #include "graphics/view.h" #define GET_HOOK GLFWHook& hook = *(GLFWHook*)glfwGetWindowUserPointer(window) void setWindowEventsCallback(GLFWwindow* window) { glfwSetWindowCloseCallback(window, [](GLFWwindow* window) { GET_HOOK; WindowCloseEvent event; hook.callback(event); }); glfwSetWindowSizeCallback(window, [](GLFWwindow* window, int width, int height) { GET_HOOK; WindowResizeEvent event(width, height); hook.callback(event); }); glfwSetWindowFocusCallback(window, [](GLFWwindow* window, int focused) { GET_HOOK; if (focused) { WindowFocusEvent event; hook.callback(event); } else { WindowLoseFocusEvent event; hook.callback(event); } }); glfwSetWindowPosCallback(window, [](GLFWwindow* window, int x, int y) { GET_HOOK; WindowMoveEvent event(x, y); hook.callback(event); }); glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int scanCode, int action, int mods) { GET_HOOK; switch (action) { case GLFW_PRESS: { KeyPressEvent event(key, 0); hook.callback(event); break; } case GLFW_REPEAT: { KeyPressEvent event(key, 1); hook.callback(event); break; } case GLFW_RELEASE: { KeyReleaseEvent event(key); hook.callback(event); break; } } }); glfwSetMouseButtonCallback(window, [](GLFWwindow* window, int button, int action, int mods) { GET_HOOK; switch (action) { case GLFW_PRESS: { MouseButtonPressEvent event(button); hook.callback(event); break; } case GLFW_RELEASE: { MouseButtonReleaseEvent event(button); hook.callback(event); break; } } }); glfwSetScrollCallback(window, [](GLFWwindow* window, double dx, double dy) { GET_HOOK; MouseScrollEvent event((float)dx, (float)dy); hook.callback(event); }); glfwSetCursorPosCallback(window, [](GLFWwindow* window, double x, double y) { GET_HOOK; MouseMoveEvent event((int)x, (int)y); hook.callback(event); }); }
511445f066d30ec0deba5e82f1790f244c87116d
2ca63305557cb780e7258cf03844a420d885a0af
/EpServerEngine2.0/EpServerEngine/Sources/epBaseServerObject.cpp
19cbdfac93772aafb74564c7ac3290d46d6f89a7
[ "MIT" ]
permissive
wangscript007/EpServerEngine
e0181d493ad9f46209536ad77a52d86bdadce7f1
2a79ddbfc118d3d653f5b0a4110eae2fc287b965
refs/heads/master
2021-09-13T02:37:20.025331
2018-04-24T01:51:04
2018-04-24T01:51:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,782
cpp
/*! BaseServerObject for the EpServerEngine The MIT License (MIT) Copyright (c) 2012-2013 Woong Gyu La <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "epBaseServerObject.h" #include "epServerObjectList.h" #if defined(_DEBUG) && defined(EP_ENABLE_CRTDBG) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // defined(_DEBUG) && defined(EP_ENABLE_CRTDBG) using namespace epse; BaseServerObject::BaseServerObject(unsigned int waitTimeMilliSec,epl::LockPolicy lockPolicyType):epl::SmartObject(lockPolicyType),epl::Thread(EP_THREAD_PRIORITY_NORMAL,lockPolicyType) { m_waitTime=waitTimeMilliSec; m_lockPolicy=lockPolicyType; m_container=NULL; switch(lockPolicyType) { case epl::LOCK_POLICY_CRITICALSECTION: m_containerLock=EP_NEW epl::CriticalSectionEx(); break; case epl::LOCK_POLICY_MUTEX: m_containerLock=EP_NEW epl::Mutex(); break; case epl::LOCK_POLICY_NONE: m_containerLock=EP_NEW epl::NoLock(); break; default: m_containerLock=NULL; break; } } BaseServerObject::BaseServerObject(const BaseServerObject& b):SmartObject(b),Thread(b) { m_waitTime=b.m_waitTime; m_container=b.m_container; m_lockPolicy=b.m_lockPolicy; switch(m_lockPolicy) { case epl::LOCK_POLICY_CRITICALSECTION: m_containerLock=EP_NEW epl::CriticalSectionEx(); break; case epl::LOCK_POLICY_MUTEX: m_containerLock=EP_NEW epl::Mutex(); break; case epl::LOCK_POLICY_NONE: m_containerLock=EP_NEW epl::NoLock(); break; default: m_containerLock=NULL; break; } } BaseServerObject::~BaseServerObject() { if(m_containerLock) EP_DELETE m_containerLock; m_containerLock=NULL; } BaseServerObject & BaseServerObject::operator=(const BaseServerObject&b) { if(this!=&b) { if(m_containerLock) EP_DELETE m_containerLock; m_containerLock=NULL; Thread::operator=(b); SmartObject::operator =(b); m_waitTime=b.m_waitTime; m_container=b.m_container; m_lockPolicy=b.m_lockPolicy; switch(m_lockPolicy) { case epl::LOCK_POLICY_CRITICALSECTION: m_containerLock=EP_NEW epl::CriticalSectionEx(); break; case epl::LOCK_POLICY_MUTEX: m_containerLock=EP_NEW epl::Mutex(); break; case epl::LOCK_POLICY_NONE: m_containerLock=EP_NEW epl::NoLock(); break; default: m_containerLock=NULL; break; } } return *this; } void BaseServerObject::SetWaitTime(unsigned int milliSec) { m_waitTime=milliSec; } unsigned int BaseServerObject::GetWaitTime() const { return m_waitTime; } void BaseServerObject::setContainer(ServerObjectList *container) { LockObj lock(m_containerLock); m_container=container; } bool BaseServerObject::removeSelfFromContainer() { LockObj lock(m_containerLock); bool ret=false; if(m_container) ret=m_container->Remove(this); m_container=NULL; return ret; }
cdc978b0c341cc77de9f93f73fabaa688a4a5937
a04701966913695a1cbc003bf4b609754b62ed1c
/src/utest/utestXMLTables.cpp
3abcd913f4721d3e8a6b376149e2c567daaf9c3b
[ "BSD-2-Clause" ]
permissive
anto35/tsduck
b80c7bed9138f78d402534fbf94f1635fd9d0c4a
6aa32ce5a59865d8d5509fd22a0c7cd110f79dc0
refs/heads/master
2021-08-30T22:45:45.542104
2017-12-18T22:26:32
2017-12-18T22:26:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,849
cpp
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2017, Thierry Lelegard // 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. // //---------------------------------------------------------------------------- // // CppUnit test suite for XML tables and descriptors. // //---------------------------------------------------------------------------- #include "tsSectionFile.h" #include "tsTables.h" #include "tsSysUtils.h" #include "tsBinaryTable.h" #include "tsCerrReport.h" #include "utestCppUnitTest.h" TSDUCK_SOURCE; #include "tables/psi_pat1_xml.h" #include "tables/psi_pat1_sections.h" #include "tables/psi_all_xml.h" #include "tables/psi_all_sections.h" //---------------------------------------------------------------------------- // The test fixture //---------------------------------------------------------------------------- class XMLTablesTest: public CppUnit::TestFixture { public: virtual void setUp() override; virtual void tearDown() override; void testConfigurationFile(); void testGenericDescriptor(); void testGenericShortTable(); void testGenericLongTable(); void testPAT1(); void testAllTables(); CPPUNIT_TEST_SUITE(XMLTablesTest); CPPUNIT_TEST(testConfigurationFile); CPPUNIT_TEST(testGenericDescriptor); CPPUNIT_TEST(testGenericShortTable); CPPUNIT_TEST(testGenericLongTable); CPPUNIT_TEST(testPAT1); CPPUNIT_TEST(testAllTables); CPPUNIT_TEST_SUITE_END(); private: // Unitary test for one table. void testTable(const char* name, const ts::UChar* ref_xml, const uint8_t* ref_sections, size_t ref_sections_size); ts::Report& report(); }; CPPUNIT_TEST_SUITE_REGISTRATION(XMLTablesTest); //---------------------------------------------------------------------------- // Initialization. //---------------------------------------------------------------------------- // Test suite initialization method. void XMLTablesTest::setUp() { } // Test suite cleanup method. void XMLTablesTest::tearDown() { } ts::Report& XMLTablesTest::report() { if (utest::DebugMode()) { return CERR; } else { return NULLREP; } } //---------------------------------------------------------------------------- // Unitary tests from XML tables. //---------------------------------------------------------------------------- #define TESTTABLE(name, data) \ void XMLTablesTest::test##name() \ { \ testTable(#name, psi_##data##_xml, psi_##data##_sections, sizeof(psi_##data##_sections)); \ } TESTTABLE(PAT1, pat1) TESTTABLE(AllTables, all) void XMLTablesTest::testTable(const char* name, const ts::UChar* ref_xml, const uint8_t* ref_sections, size_t ref_sections_size) { utest::Out() << "XMLTablesTest: Testing " << name << std::endl; // Convert XML reference content to binary tables. ts::SectionFile xml; CPPUNIT_ASSERT(xml.parseXML(ref_xml, CERR)); // Serialize binary tables to section data. std::ostringstream strm; CPPUNIT_ASSERT(ts::BinaryTable::SaveFile(xml.tables(), strm, CERR)); // Compare serialized section data to reference section data. const std::string sections(strm.str()); CPPUNIT_ASSERT_EQUAL(ref_sections_size, sections.size()); CPPUNIT_ASSERT_EQUAL(0, ::memcmp(ref_sections, sections.data(), ref_sections_size)); // Convert binary tables to XML. CPPUNIT_ASSERT_USTRINGS_EQUAL(ref_xml, xml.toText(CERR)); } //---------------------------------------------------------------------------- // Other unitary tests. //---------------------------------------------------------------------------- void XMLTablesTest::testConfigurationFile() { const ts::UString conf(ts::SearchConfigurationFile(u"tsduck.xml")); utest::Out() << "XMLTablesTest::testConfigurationFile: " << conf << std::endl; CPPUNIT_ASSERT(ts::FileExists(conf)); } void XMLTablesTest::testGenericDescriptor() { static const uint8_t descData[] = { 0x72, // tag 0x07, // length 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; ts::Descriptor desc(descData, sizeof(descData)); CPPUNIT_ASSERT(desc.isValid()); CPPUNIT_ASSERT_EQUAL(0x72, int(desc.tag())); CPPUNIT_ASSERT_EQUAL(9, int(desc.size())); CPPUNIT_ASSERT_EQUAL(7, int(desc.payloadSize())); ts::xml::Document doc(report()); ts::xml::Element* root = doc.initialize(u"test"); CPPUNIT_ASSERT(root != 0); CPPUNIT_ASSERT(desc.toXML(root, 0, true) != 0); ts::UString text(doc.toString()); utest::Out() << "XMLTablesTest::testGenericDescriptor: " << text << std::endl; CPPUNIT_ASSERT_USTRINGS_EQUAL( u"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" u"<test>\n" u" <generic_descriptor tag=\"0x72\">\n" u" 01 02 03 04 05 06 07\n" u" </generic_descriptor>\n" u"</test>\n", text); ts::xml::Document doc2(report()); CPPUNIT_ASSERT(doc2.parse(text)); root = doc2.rootElement(); CPPUNIT_ASSERT(root != 0); CPPUNIT_ASSERT_USTRINGS_EQUAL(u"test", root->name()); ts::xml::ElementVector children; CPPUNIT_ASSERT(root->getChildren(children, u"generic_descriptor", 1, 1)); CPPUNIT_ASSERT_EQUAL(size_t(1), children.size()); ts::ByteBlock payload; CPPUNIT_ASSERT(children[0]->getHexaText(payload)); CPPUNIT_ASSERT_EQUAL(size_t(7), payload.size()); CPPUNIT_ASSERT(payload == ts::ByteBlock(descData + 2, sizeof(descData) - 2)); ts::Descriptor desc2; CPPUNIT_ASSERT(desc2.fromXML(children[0])); CPPUNIT_ASSERT_EQUAL(ts::DID(0x72), desc2.tag()); CPPUNIT_ASSERT_EQUAL(size_t(7), desc2.payloadSize()); CPPUNIT_ASSERT(ts::ByteBlock(desc2.payload(), desc2.payloadSize()) == ts::ByteBlock(descData + 2, sizeof(descData) - 2)); } void XMLTablesTest::testGenericShortTable() { static const uint8_t refData[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; const ts::SectionPtr refSection(new ts::Section(0xAB, false, refData, sizeof(refData))); CPPUNIT_ASSERT(!refSection.isNull()); CPPUNIT_ASSERT(refSection->isValid()); ts::BinaryTable refTable; refTable.addSection(refSection); CPPUNIT_ASSERT(refTable.isValid()); CPPUNIT_ASSERT_EQUAL(size_t(1), refTable.sectionCount()); ts::xml::Document doc(report()); ts::xml::Element* root = doc.initialize(u"test"); CPPUNIT_ASSERT(root != 0); CPPUNIT_ASSERT(refTable.toXML(root, true) != 0); ts::UString text(doc.toString()); utest::Out() << "XMLTablesTest::testGenericShortTable: " << text << std::endl; CPPUNIT_ASSERT_USTRINGS_EQUAL( u"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" u"<test>\n" u" <generic_short_table table_id=\"0xAB\" private=\"false\">\n" u" 01 02 03 04 05 06\n" u" </generic_short_table>\n" u"</test>\n", text); ts::xml::Document doc2(report()); CPPUNIT_ASSERT(doc2.parse(text)); root = doc2.rootElement(); CPPUNIT_ASSERT(root != 0); CPPUNIT_ASSERT_USTRINGS_EQUAL(u"test", root->name()); ts::xml::ElementVector children; CPPUNIT_ASSERT(root->getChildren(children, u"GENERIC_SHORT_TABLE", 1, 1)); CPPUNIT_ASSERT_EQUAL(size_t(1), children.size()); ts::BinaryTable tab; CPPUNIT_ASSERT(tab.fromXML(children[0])); CPPUNIT_ASSERT(tab.isValid()); CPPUNIT_ASSERT(tab.isShortSection()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xAB), tab.tableId()); CPPUNIT_ASSERT_EQUAL(size_t(1), tab.sectionCount()); ts::SectionPtr sec(tab.sectionAt(0)); CPPUNIT_ASSERT(!sec.isNull()); CPPUNIT_ASSERT(sec->isValid()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xAB), sec->tableId()); CPPUNIT_ASSERT(sec->isShortSection()); CPPUNIT_ASSERT(!sec->isPrivateSection()); CPPUNIT_ASSERT_EQUAL(size_t(6), sec->payloadSize()); CPPUNIT_ASSERT(ts::ByteBlock(sec->payload(), sec->payloadSize()) == ts::ByteBlock(refData, sizeof(refData))); } void XMLTablesTest::testGenericLongTable() { static const uint8_t refData0[] = {0x01, 0x02, 0x03, 0x04, 0x05}; static const uint8_t refData1[] = {0x11, 0x12, 0x13, 0x14}; ts::BinaryTable refTable; refTable.addSection(new ts::Section(0xCD, true, 0x1234, 7, true, 0, 0, refData0, sizeof(refData0))); refTable.addSection(new ts::Section(0xCD, true, 0x1234, 7, true, 1, 1, refData1, sizeof(refData1))); CPPUNIT_ASSERT(refTable.isValid()); CPPUNIT_ASSERT(!refTable.isShortSection()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xCD), refTable.tableId()); CPPUNIT_ASSERT_EQUAL(uint16_t(0x1234), refTable.tableIdExtension()); CPPUNIT_ASSERT_EQUAL(size_t(2), refTable.sectionCount()); ts::xml::Document doc(report()); ts::xml::Element* root = doc.initialize(u"test"); CPPUNIT_ASSERT(root != 0); CPPUNIT_ASSERT(refTable.toXML(root, true) != 0); ts::UString text(doc.toString()); utest::Out() << "XMLTablesTest::testGenericLongTable: " << text << std::endl; CPPUNIT_ASSERT_USTRINGS_EQUAL( u"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" u"<test>\n" u" <generic_long_table table_id=\"0xCD\" table_id_ext=\"0x1234\" version=\"7\" current=\"true\" private=\"true\">\n" u" <section>\n" u" 01 02 03 04 05\n" u" </section>\n" u" <section>\n" u" 11 12 13 14\n" u" </section>\n" u" </generic_long_table>\n" u"</test>\n", text); ts::xml::Document doc2(report()); CPPUNIT_ASSERT(doc2.parse(text)); root = doc2.rootElement(); CPPUNIT_ASSERT(root != 0); CPPUNIT_ASSERT_USTRINGS_EQUAL(u"test", root->name()); ts::xml::ElementVector children; CPPUNIT_ASSERT(root->getChildren(children, u"GENERIC_long_TABLE", 1, 1)); CPPUNIT_ASSERT_EQUAL(size_t(1), children.size()); ts::BinaryTable tab; CPPUNIT_ASSERT(tab.fromXML(children[0])); CPPUNIT_ASSERT(tab.isValid()); CPPUNIT_ASSERT(!tab.isShortSection()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xCD), tab.tableId()); CPPUNIT_ASSERT_EQUAL(uint16_t(0x1234), tab.tableIdExtension()); CPPUNIT_ASSERT_EQUAL(size_t(2), tab.sectionCount()); ts::SectionPtr sec(tab.sectionAt(0)); CPPUNIT_ASSERT(!sec.isNull()); CPPUNIT_ASSERT(sec->isValid()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xCD), sec->tableId()); CPPUNIT_ASSERT_EQUAL(uint16_t(0x1234), sec->tableIdExtension()); CPPUNIT_ASSERT_EQUAL(uint8_t(7), sec->version()); CPPUNIT_ASSERT(!sec->isShortSection()); CPPUNIT_ASSERT(sec->isPrivateSection()); CPPUNIT_ASSERT(sec->isCurrent()); CPPUNIT_ASSERT_EQUAL(sizeof(refData0), sec->payloadSize()); CPPUNIT_ASSERT(ts::ByteBlock(sec->payload(), sec->payloadSize()) == ts::ByteBlock(refData0, sizeof(refData0))); sec = tab.sectionAt(1); CPPUNIT_ASSERT(!sec.isNull()); CPPUNIT_ASSERT(sec->isValid()); CPPUNIT_ASSERT_EQUAL(ts::TID(0xCD), sec->tableId()); CPPUNIT_ASSERT_EQUAL(uint16_t(0x1234), sec->tableIdExtension()); CPPUNIT_ASSERT_EQUAL(uint8_t(7), sec->version()); CPPUNIT_ASSERT(!sec->isShortSection()); CPPUNIT_ASSERT(sec->isPrivateSection()); CPPUNIT_ASSERT(sec->isCurrent()); CPPUNIT_ASSERT_EQUAL(sizeof(refData1), sec->payloadSize()); CPPUNIT_ASSERT(ts::ByteBlock(sec->payload(), sec->payloadSize()) == ts::ByteBlock(refData1, sizeof(refData1))); }
70b138b53aca2d65013cb65b582c4e97e8397443
8887b5be57228aa0b1ab7cbc834266c346c63055
/src/logger.h
0542b38c836acb7b9250cd56fea178b465fe2cb9
[ "MIT" ]
permissive
tobykurien/fishfeeder
a8a589f5312a061c60e25c75df721ea039fd5248
285ba347fb81d872d45fbede1cfed6ef42b620df
refs/heads/master
2018-11-22T08:45:27.059374
2018-09-30T09:15:18
2018-09-30T09:15:18
114,918,925
0
0
MIT
2018-09-30T09:15:19
2017-12-20T18:34:25
C++
UTF-8
C++
false
false
1,691
h
#include <Arduino.h> #include <EEPROM.h> #include <RTClib.h> #include "config.h" #ifndef __LOGGER__ #define __LOGGER__ #define CHECK_BYTE 0xA3 // update this if data structures change // Number of logs to keep for feedings and temperature // NOTE: current code relies on byte wrap-around to implement // a circular buffer, so it will need to change if this value // is changed. #define MAX_HISTORY 255 struct Settings { uint8_t feedingScheme; uint8_t feedingAmount; uint8_t feedingDays; // each bit from lowest = day of week }; struct Feeding { uint32_t timestamp; uint8_t amount; float temperature; }; struct Temperature { uint32_t timestamp; float temperature; }; // EEPROM data structure for all saved data struct DataStruct { Settings settings; uint8_t latestFeeding; Feeding feedings[MAX_HISTORY]; uint8_t latestTemperature; Temperature temperatures[MAX_HISTORY]; }; class Logger { public: Logger(); void start(); void stop(); // logging void logFeeding(byte amount); void logTemperature(); // settings void saveSettings(); Settings* getSettings(); // get data structures (logging, settings) DataStruct* getData(); Feeding* getLastFeeding(); Temperature* getLastTemperature(); // time functions String getTime(); String getTime(uint32_t time); uint32_t getCurrentTime(); void setTime(DateTime time); // temperature float getTemperature(); private: RTC_DS3231 rtc; DataStruct logData; void writeLogData(); }; #endif
71023473824f8d799e1f0e692054fb19c1974dd4
875d602b2417deddf0f0d6a8345603750fe58bce
/src/net.cpp
d5c378f1e8c836816aa915023c4d2dbea9842a82
[ "MIT" ]
permissive
richardyc/rcoin
39de1cc33499f90ae7a0ede2c301e271db912938
7f3504c7f1aad21995bd3fcdfc3024b6b3d5563c
refs/heads/master
2021-08-29T18:12:19.723852
2017-12-14T14:59:31
2017-12-14T14:59:31
106,858,992
1
0
null
null
null
null
UTF-8
C++
false
false
64,032
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "db.h" #include "net.h" #include "init.h" #include "addrman.h" #include "ui_interface.h" #include "script.h" #ifdef WIN32 #include <string.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniwget.h> #include <miniupnpc/miniupnpc.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif // Dump addresses to peers.dat every 15 minutes (900s) #define DUMP_ADDRESSES_INTERVAL 900 using namespace std; using namespace boost; static const int MAX_OUTBOUND_CONNECTIONS = 8; bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false); struct LocalServiceInfo { int nScore; int nPort; }; // // Global state variables // bool fDiscover = true; uint64 nLocalServices = NODE_NETWORK; static CCriticalSection cs_mapLocalHost; static map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; static CNode* pnodeSync = NULL; uint64 nLocalHostNonce = 0; static std::vector<SOCKET> vhListenSocket; CAddrMan addrman; int nMaxConnections = 125; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; limitedmap<CInv, int64> mapAlreadyAskedFor(MAX_INV_SZ); static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; vector<std::string> vAddedNodes; CCriticalSection cs_vAddedNodes; static CSemaphore *semOutbound = NULL; void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", GetDefaultPort())); } void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd) { // Filter out duplicate requests if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd) return; pindexLastGetBlocksBegin = pindexBegin; hashLastGetBlocksEnd = hashEnd; PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (fNoListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress CAddress GetLocalAddress(const CNetAddr *paddrPeer) { CAddress ret(CService("0.0.0.0",0),0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); } return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; loop { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { boost::this_thread::interruption_point(); if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed printf("socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); printf("recv failed: %d\n", nErr); return false; } } } } // used when scores of local addresses may have changed // pushes better local address to peers void static AdvertizeLocal() { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal) { pnode->PushAddress(addrLocal); pnode->addrLocal = addrLocal; } } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } AdvertizeLocal(); return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } AdvertizeLocal(); return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { LOCK(cs_mapLocalHost); enum Network net = addr.GetNetwork(); return vfReachable[net] && !vfLimited[net]; } bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet) { SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str()); send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL); string strLine; while (RecvLine(hSocket, strLine)) { if (strLine.empty()) // HTTP response is separated from headers by blank line { loop { if (!RecvLine(hSocket, strLine)) { closesocket(hSocket); return false; } if (pszKeyword == NULL) break; if (strLine.find(pszKeyword) != string::npos) { strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword)); break; } } closesocket(hSocket); if (strLine.find("<") != string::npos) strLine = strLine.substr(0, strLine.find("<")); strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r")); while (strLine.size() > 0 && isspace(strLine[strLine.size()-1])) strLine.resize(strLine.size()-1); CService addr(strLine,0,true); printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str()); if (!addr.IsValid() || !addr.IsRoutable()) return false; ipRet.SetIP(addr); return true; } } closesocket(hSocket); return error("GetMyExternalIP() : connection closed"); } bool GetMyExternalIP(CNetAddr& ipRet) { CService addrConnect; const char* pszGet; const char* pszKeyword; for (int nLookup = 0; nLookup <= 1; nLookup++) for (int nHost = 1; nHost <= 1; nHost++) { // We should be phasing out our use of sites like these. If we need // replacements, we should ask for volunteers to put this simple // php file on their web server that prints the client IP: // <?php echo $_SERVER["REMOTE_ADDR"]; ?> if (nHost == 1) { addrConnect = CService("91.198.22.70", 80); // checkip.dyndns.org if (nLookup == 1) { CService addrIP("checkip.dyndns.org", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET / HTTP/1.1\r\n" "Host: checkip.dyndns.org\r\n" "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = "Address:"; } if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet)) return true; } return false; } void ThreadGetMyExternalIP(void* parg) { // Make this thread recognisable as the external IP detection thread RenameThread("bitcoin-ext-ip"); CNetAddr addrLocalHost; if (GetMyExternalIP(addrLocalHost)) { printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str()); AddLocal(addrLocalHost, LOCAL_HTTP); } } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } CNode* FindNode(const CNetAddr& ip) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); return NULL; } CNode* FindNode(std::string addrName) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CService)pnode->addr == addr) return (pnode); return NULL; } CNode* ConnectNode(CAddress addrConnect, const char *pszDest) { if (pszDest == NULL) { if (IsLocal(addrConnect)) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->AddRef(); return pnode; } } /// debug print printf("trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString().c_str(), pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Connect SOCKET hSocket; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket)) { addrman.Attempt(addrConnect); /// debug print printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str()); // Set to non-blocking #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError()); #else if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno); #endif // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); return pnode; } else { return NULL; } } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { printf("disconnecting node %s\n", addrName.c_str()); closesocket(hSocket); hSocket = INVALID_SOCKET; } // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); // if this was the sync node, we'll need a new one if (this == pnodeSync) pnodeSync = NULL; } void CNode::Cleanup() { } void CNode::PushVersion() { /// when NTP implemented, change to just nTime = GetAdjustedTime() int64 nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0))); CAddress addrMe = GetLocalAddress(&addr); RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str()); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight); } std::map<CNetAddr, int64> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map<CNetAddr, int64>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64 t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Misbehaving(int howmuch) { if (addr.IsLocal()) { printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch); return false; } nMisbehavior += howmuch; if (nMisbehavior >= GetArg("-banscore", 100)) { int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior); { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } CloseSocketDisconnect(); return true; } else printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior); return false; } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); X(cleanSubVer); X(fInbound); X(nStartingHeight); X(nMisbehavior); X(nSendBytes); X(nRecvBytes); X(nBlocksRequested); stats.fSyncNode = (this == pnodeSync); } #undef X // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; pch += handled; nBytes -= handled; } return true; } int CNetMessage::readHeader(const char *pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (std::exception &e) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; vRecv.resize(hdr.nMessageSize); return nCopy; } int CNetMessage::readData(const char *pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode *pnode) { std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData &data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { printf("socket send error %d\n", nErr); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } static list<CNode*> vNodesDisconnected; void ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; loop { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); pnode->Cleanup(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if (vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(vNodes.size()); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) { FD_SET(hListenSocket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); have_fds = true; // Implement the following logic: // * If there is data to send, select() for sending data. As this only // happens when optimistic write failed, we choose to first drain the // write buffer in this case before receiving more. This avoids // needlessly queueing received data, if the remote peer is not themselves // receiving data. This means properly utilizing TCP flow control signalling. // * Otherwise, if there is no (complete) message in the receive buffer, // or there is space left in the buffer, select() for receiving data. // * (if neither of the above applies, there is certainly one message // in the receiver buffer ready to be processed). // Together, that means that at least one of the following is always possible, // so we don't deadlock: // * We send some data. // * We wait for data to be received (and disconnect after timeout). // * We process a message in the buffer (message handler thread). { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend && !pnode->vSendMsg.empty()) { FD_SET(pnode->hSocket, &fdsetSend); continue; } } { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv && ( pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() || pnode->GetTotalRecvSize() <= ReceiveFloodSize())) FD_SET(pnode->hSocket, &fdsetRecv); } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); boost::this_thread::interruption_point(); if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); printf("socket select error %d\n", nErr); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec/1000); } // // Accept new connections // BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv)) { #ifdef USE_IPV6 struct sockaddr_storage sockaddr; #else struct sockaddr sockaddr; #endif socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) printf("Warning: Unknown socket family\n"); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) printf("socket error accept failed: %d\n", nErr); } else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) { { LOCK(cs_setservAddNodeAddresses); if (!setservAddNodeAddresses.count(addr)) closesocket(hSocket); } } else if (CNode::IsBanned(addr)) { printf("connection from %s dropped (banned)\n", addr.ToString().c_str()); closesocket(hSocket); } else { printf("accepted connection %s\n", addr.ToString().c_str()); CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH(CNode* pnode, vNodesCopy) { boost::this_thread::interruption_point(); // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) printf("socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) printf("socket recv error %d\n", nErr); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // if (pnode->vSendMsg.empty()) pnode->nLastSendEmpty = GetTime(); if (GetTime() - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60) { printf("socket not sending\n"); pnode->fDisconnect = true; } else if (GetTime() - pnode->nLastRecv > 90*60) { printf("socket inactivity timeout\n"); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } MilliSleep(10); } } #ifdef USE_UPNP void ThreadMapPort() { std::string port = strprintf("%u", GetListenPort()); const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #else /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) printf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if(externalIPAddress[0]) { printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else printf("UPnP: GetExternalIPAddress failed.\n"); } } string strDesc = "Rcoin " + FormatFullVersion(); try { loop { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port.c_str(), port.c_str(), lanaddr, r, strupnperror(r)); else printf("UPnP Port Mapping successful.\n");; MilliSleep(20*60*1000); // Refresh every 20 minutes } } catch (boost::thread_interrupted) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); printf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); throw; } } else { printf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static boost::thread* upnp_thread = NULL; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; } upnp_thread = new boost::thread(boost::bind(&TraceThread<boost::function<void()> >, "upnp", &ThreadMapPort)); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; upnp_thread = NULL; } } #else void MapPort(bool) { // Intentionally left blank. } #endif // DNS seeds // Each pair gives a source name and a seed name. // The first name is used as information source for addrman. // The second name should resolve to a list of seed addresses. static const char *strMainNetDNSSeed[][2] = { {"rcointools.com", "35.197.88.62"}, {NULL, NULL} }; static const char *strTestNetDNSSeed[][2] = { {"rcointools.com", "testnet-seed.rcointools.com"}, {"xurious.com", "testnet-seed.ltc.xurious.com"}, {"wemine-testnet.com", "dnsseed.wemine-testnet.com"}, {NULL, NULL} }; void ThreadDNSAddressSeed() { static const char *(*strDNSSeed)[2] = fTestNet ? strTestNetDNSSeed : strMainNetDNSSeed; int found = 0; printf("Loading addresses from DNS seeds (could take a while)\n"); for (unsigned int seed_idx = 0; strDNSSeed[seed_idx][0] != NULL; seed_idx++) { if (HaveNameProxy()) { AddOneShot(strDNSSeed[seed_idx][1]); } else { vector<CNetAddr> vaddr; vector<CAddress> vAdd; if (LookupHost(strDNSSeed[seed_idx][1], vaddr)) { BOOST_FOREACH(CNetAddr& ip, vaddr) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true)); } } printf("%d addresses found from DNS seeds\n", found); } unsigned int pnSeed[] = { 0x38a9b992, 0x73d4f3a2, 0x43eda52e, 0xa1c4a2b2, 0x73c41955, 0x6992f3a2, 0x729cb992, 0x8b53b205, 0xb651ec36, 0x8b422e4e, 0x0fe421b2, 0x83c1a2b2, 0xbd432705, 0x2e11b018, 0x281544c1, 0x8b72f3a2, 0xb934555f, 0x2ba02e4e, 0x6ab7c936, 0x8728555f, 0x03bfd143, 0x0a73df5b, 0xcd2b5a50, 0x746df3a2, 0x7481bb25, 0x6f4d4550, 0x78582f4e, 0xa03a0f46, 0xe8b0e2bc, 0xa2d17042, 0x718a09b0, 0xdaffd4a2, 0xbb1a175e, 0xb21f09b0, 0xb5549bc0, 0xe404c755, 0x95d882c3, 0xfff3692e, 0x3777d9c7, 0x425b2746, 0x497990c6, 0xb2782dcc, 0xf9352225, 0xa75cd443, 0x4c05fb94, 0x44c91c2e, 0x47c6a5bc, 0xd606fb94, 0xc1b9e2bc, 0x32acd23e, 0x89560da2, 0x5bebdad8, 0x3a210e08, 0xbdc5795b, 0xcc86bb25, 0xbe9f28bc, 0xef3ff3a2, 0xca29df59, 0xe4fd175e, 0x1f3eaa6b, 0xacdbaa6b, 0xb05f042e, 0x81ed6cd8, 0x9a3c0cc3, 0x4200175e, 0x5a017ebc, 0x42ef4c90, 0x8abfd143, 0x24fbf3a2, 0x140846a6, 0x4f7d9553, 0xeea5d151, 0xe67c0905, 0x52d8048e, 0xcabd2e4e, 0xe276692e, 0x07dea445, 0xdde3f3a2, 0x6c47bb25, 0xae0efb94, 0xf5e15a51, 0xaebdd25b, 0xf341175e, 0x46532705, 0xc47728bc, 0xe4e14c90, 0x9dc8f752, 0x050c042e, 0x1c84bb25, 0x4f163b25, 0x1a017ebc, 0xa5282e4e, 0x8c667e60, 0xc7113b25, 0xf0b44832, 0xf1a134d0, 0x973212d4, 0xd35cbb25, 0xd5123b25, 0x68220254, 0x7ad43e32, 0x9268e32e, 0xdf143b25, 0xaf04c436, 0xaded0051, 0xfa86d454, 0x09db048e, 0x26003b25, 0x58764c90, 0x9a2f555f, 0x0c24ec97, 0x92123b25, 0x0526d35f, 0x17db048e, 0xd2e42f4e, 0x38cca5bc, 0xc6320ab9, 0xe28ac836, 0xc560aa6b, 0xa5c16041, 0x70a6f1c0, 0x011ec8c1, 0xd6e9c332, 0x131263c0, 0xa15a4450, 0xef218abc, 0x2729f948, 0x02835443, 0x5614336c, 0xb12aacb2, 0xe368aa6b, 0x3cc6ffad, 0x36206494, 0x2c90e9c1, 0x32bb53d4, 0xca03de5c, 0x775c1955, 0x19ef1ba3, 0x0b00dc1f, 0x244d0f40, 0x54d9e2bc, 0x25ced152, 0x967b03ad, 0x951c555f, 0x4c3f3b25, 0x13f6f3a2, 0x17fca5bc, 0x0e2d306c, 0xacd8764b, 0xca230bcc, 0x8569d3c6, 0x3264d8a2, 0xe8630905, 0x25e02a64, 0x3aba1fb0, 0x6bbdd25b, 0xee9a4c90, 0xcda25982, 0x8b3e804e, 0xf043fb94, 0x4b05fb94, 0x0c44c052, 0xf403f45c, 0x4333aa6b, 0xc193484d, 0x3fbf5d4c, 0x0bd7f74d, 0x150e3fb2, 0x8e2eddb0, 0x09daf150, 0x8a67c7c6, 0x22a9e52e, 0x05cff476, 0xc99b2f4e, 0x0f183b25, 0xd0358953, 0x20f232c6, 0x0ce9e217, 0x09f55d18, 0x0555795b, 0x5ed2fa59, 0x2ec85917, 0x2bf61fb0, 0x024ef54d, 0x3c53b859, 0x441cbb25, 0x50c8aa6b, 0x1b79175e, 0x3125795b, 0x27fc1fb0, 0xbcd53e32, 0xfc781718, 0x7a8ec345, 0x1da6985d, 0x34bd1f32, 0xcb00edcf, 0xf9a5fdce, 0x21ccdbac, 0xb7730118, 0x6a43f6cc, 0x6e65e262, 0x21ca1f3d, 0x10143b25, 0xc8dea132, 0xaf076693, 0x7e431bc6, 0xaa3df5c6, 0x44f0c536, 0xeea80925, 0x262371d4, 0xc85c895b, 0xa6611bc6, 0x1844e47a, 0x49084c90, 0xf3d95157, 0x63a4a844, 0x00477c70, 0x2934d35f, 0xe8d24465, 0x13df88b7, 0x8fcb7557, 0xa591bd5d, 0xc39453d4, 0xd5c49452, 0xc8de1a56, 0x3cdd0608, 0x3c147a55, 0x49e6cf4a, 0xb38c8705, 0x0bef3479, 0x01540f48, 0xd9c3ec57, 0xed6d4c90, 0xa529fb94, 0xe1c81955, 0xfde617c6, 0x72d18932, 0x9d61bb6a, 0x6d5cb258, 0x27c7d655, 0xc5644c90, 0x31fae3bc, 0x3afaf25e, 0x98efe2bc, 0x91020905, 0xb566795b, 0xaf91bd5d, 0xb164d655, 0x72eb47d4, 0xae62f3a2, 0xb4193b25, 0x0613fb94, 0xa6db048e, 0xf002464b, 0xc15ebb6a, 0x8a51f3a2, 0x485e2ed5, 0x119675a3, 0x1f3f555f, 0x39dbc082, 0x09dea445, 0x74382446, 0x3e836c4e, 0x6e43f6cc, 0x134dd9a2, 0x5876f945, 0x3516f725, 0x670c81d4, 0xaf7f170c, 0xb0e31155, 0xe271894e, 0x615e175e, 0xb3446fd0, 0x13d58ac1, 0x07cff476, 0xe601e405, 0x8321277d, 0x0997548d, 0xdb55336c, 0xa1271d73, 0x582463c0, 0xc2543025, 0xf6851c73, 0xe75d32ae, 0xf916b4dd, 0xf558fb94, 0x52111d73, 0x2bc8615d, 0xd4dcaf42, 0x65e30979, 0x2e1b2360, 0x0da01d73, 0x3f1263c0, 0xd15c735d, 0x9cf2134c, 0x20d0048e, 0x48cf0125, 0xf585bf5d, 0x12d7645e, 0xd5ace2bc, 0x0c6220b2, 0xbe13bb25, 0x88d0a52e, 0x559425b0, 0x24079e3d, 0xfaa37557, 0xf219b96a, 0x07e61e4c, 0x3ea1d295, 0x24e0d852, 0xdde212df, 0x44c37758, 0x55c243a4, 0xe77dd35f, 0x10c19a5f, 0x14d1048e, 0x1d50fbc6, 0x1570456c, 0x567c692e, 0x641d6d5b, 0xab0c0cc6, 0xab6803c0, 0x136f21b2, 0x6a72545d, 0x21d031b2, 0xff8b5fad, 0xfd0096b2, 0x5f469ac3, 0x3f6ffa62, 0x7501f863, 0x48471f60, 0xcccff3a2, 0x7f772e44, 0xc1de7757, 0x0c94c3cb, 0x620ac658, 0x520f1d25, 0x37366c5f, 0x7594b159, 0x3804f23c, 0xb81ff054, 0x96dd32c6, 0x928228bc, 0xf4006e41, 0x0241c244, 0x8dbdf243, 0x26d1b247, 0xd5381c73, 0xf3136e41, 0x4afa9bc0, 0xa3abf8ce, 0x464ce718, 0xbd9d017b, 0xf4f26132, 0x141b32d4, 0x2ec50c18, 0x4df119d9, 0x93f81772, 0xd9607c70, 0x3522b648, 0xf2006e41, 0x761fe550, 0x40104836, 0x55dffe96, 0xc45db158, 0xe75e4836, 0x8dfab7ad, 0xe3eff3a2, 0x6a6eaa6b, 0x2177d9c7, 0x724ce953, 0xafe918b9, 0xf9368a55, 0xdc0a555f, 0xa4b2d35f, 0x4d87b0b8, 0x93496a54, 0x5a5c967b, 0xd47028bc, 0x3c44e47a, 0x11c363c0, 0x28107c70, 0xb756a558, 0xb82bbb6a, 0x285d49ad, 0x3b0ce85c, 0xe53eb45f, 0xa836e23c, 0x409f63c0, 0xc80fbd44, 0x3447f677, 0xe4ca983b, 0x20673774, 0x96471ed9, 0x4c1d09b0, 0x91d5685d, 0x55beec4d, 0x1008be48, 0x660455d0, 0xf8170fda, 0x3c21dd3a, 0x8239bb36, 0x9fe7e2bc, 0x900c47ae, 0x6a355643, 0x03dcb318, 0xefca123d, 0x6af8c4d9, 0x5195e1a5, 0x32e89925, 0x0adc51c0, 0x45d7164c, 0x02495177, 0x8131175e, 0x681b5177, 0x41b6aa6b, 0x55a9603a, 0x1a0c1c1f, 0xdb4da043, 0x3b9b1632, 0x37e08368, 0x8b54e260, 0xcd14d459, 0x82a663c0, 0x05adc7dd, 0xe683f3a2, 0x4cddb150, 0x67a1a62e, 0x8c0acd25, 0x07f01f3e, 0x3111296c, 0x2d0fda2e, 0xa4f163c0, 0xca6db982, 0x78ed2359, 0x7eaa21c1, 0x62e4f3a2, 0x50b81d73, 0xcd074a3a, 0xcb2d904b, 0x9b3735ce, 0xab67f25c, 0xa0eb5036, 0x62ae5344, 0xe2569bb2, 0xc4422e4e, 0xab5ec8d5, 0xaa81e8dd, 0xa39264c6, 0xf391563d, 0xb79bbb25, 0x174a7857, 0x0fd4aa43, 0x3e158c32, 0x3ae8b982, 0xea342225, 0x48d1a842, 0xa52bf0da, 0x4bcb4a4c, 0xa6d3c15b, 0x49a0d35f, 0x97131b4c, 0xf197e252, 0xfe3ebd18, 0x156dacb8, 0xf63328bc, 0x8e95b84c, 0x560455d0, 0xee918c4e, 0x1d3e435f, 0xe1292f50, 0x0f1ec018, 0x7d70c60e, 0x6a29d5be, 0xf5fecb18, 0xd6da1f63, 0xccce1c2e, 0x7a289f5e, 0x2775ae47, 0x696df560, 0x4dbe00ae, 0x474e6c5c, 0x604141d5, 0xaed0c718, 0x8acfd23e, 0x7ff4b84c, 0x4b44fc60, 0xdf58aa4f, 0x9b7440c0, 0xb811c854, 0xd90ec24e, 0xcff75c46, 0xa5a9cc57, 0xb3d21e4c, 0x794779d9, 0xe5613d46, 0x9478be43, 0xc5d11152, 0xe85fbb6a, 0x3e1ed052, 0xf747e418, 0x3b9c61c2, 0xb2532949, 0x43077432, 0xa3db0b68, 0xb3b6e35a, 0x70361b6c, 0x3a8bad3e, 0x23079e3d, 0x09314c32, 0x92f90053, 0x4fc31955, 0xa59b0905, 0x924128bc, 0x4e63c444, 0x344dc236, 0x43055fcb, 0xdc1a1c73, 0x38aaaa6b, 0xa61cf554, 0x6d8f63c0, 0x24800a4c, 0x2406f953, 0x9558bb6a, 0x1d281660, 0x054c4954, 0x2de4d418, 0x5fdaf043, 0xb681356c, 0xf8c3febc, 0x8854f950, 0x55b45d32, 0xde07bcd1, 0x156e4bda, 0x924cf718, 0xc34a0d47, 0xdd5e1c45, 0x4a0d63c0, 0xaf4b88d5, 0x7852b958, 0x6f205fc0, 0x838af043, 0x45ac795b, 0x43bbaa6b, 0x998d1c73, 0x11c1d558, 0x749ec444, 0x9a38c232, 0xad2f8c32, 0x3446c658, 0x8fe7a52e, 0x4e846b61, 0x064b2d05, 0x0fd09740, 0x7a81a743, 0xf1f08e3f, 0x35ca1967, 0x24bdb17d, 0x144c2d05, 0x5505bb46, 0x13fd1bb9, 0x25de2618, 0xc80a8b4b, 0xcec0fd6c, 0xdc30ad4c, 0x4009f3a2, 0x472f3fb2, 0x5e69c936, 0x0380796d, 0xa463f8a2, 0xa46fbdc7, 0x3b0cc547, 0xb6644f46, 0x4b90fc47, 0x39e3f563, 0x72d81e56, 0xe177d9c7, 0x95bff743, 0xea985542, 0xc210ec55, 0xeef70b67, 0xc9eb175e, 0x844d38ad, 0x65afa247, 0x72da6d26, 0xed165dbc, 0xe8c83ad0, 0x9a8f37d8, 0x925adf50, 0x6b6ac162, 0x4b969e32, 0x735e1c45, 0x4423ff60, 0xfa57ec6d, 0xcde2fb65, 0x11093257, 0x4748cd5b, 0x720c03dd, 0x8c7b0905, 0xba8b2e48 }; void DumpAddresses() { int64 nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n", addrman.size(), GetTimeMillis() - nStart); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections() { // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64 nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); } } MilliSleep(500); } } // Initiate network connections int64 nStart = GetTime(); loop { ProcessOneShot(); MilliSleep(500); CSemaphoreGrant grant(*semOutbound); boost::this_thread::interruption_point(); // Add seed nodes if IRC isn't working if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet) { std::vector<CAddress> vAdd; for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64 nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek; vAdd.push_back(addr); } addrman.Add(vAdd, CNetAddr("127.0.0.1")); } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64 nANow = GetAdjustedTime(); int nTries = 0; loop { // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections) CAddress addr = addrman.Select(10 + min(nOutbound,8)*10); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections() { { LOCK(cs_vAddedNodes); vAddedNodes = mapMultiArgs["-addnode"]; } if (HaveNameProxy()) { while(true) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } BOOST_FOREACH(string& strAddNode, lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } for (unsigned int i = 0; true; i++) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } list<vector<CService> > lservAddressesToAdd(0); BOOST_FOREACH(string& strAddNode, lAddresses) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH(CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) BOOST_FOREACH(CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); it--; break; } } BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot) { // // Initiate outbound network connection // boost::this_thread::interruption_point(); if (!strDest) if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort().c_str())) return false; if (strDest && FindNode(strDest)) return false; CNode* pnode = ConnectNode(addrConnect, strDest); boost::this_thread::interruption_point(); if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } // for now, use a very simple selection metric: the node from which we received // most recently double static NodeSyncScore(const CNode *pnode) { return -pnode->nLastRecv; } void static StartSync(const vector<CNode*> &vNodes) { CNode *pnodeNewSync = NULL; double dBestScore = 0; // fImporting and fReindex are accessed out of cs_main here, but only // as an optimization - they are checked again in SendMessages. if (fImporting || fReindex) return; // Iterate over all nodes BOOST_FOREACH(CNode* pnode, vNodes) { // check preconditions for allowing a sync if (!pnode->fClient && !pnode->fOneShot && !pnode->fDisconnect && pnode->fSuccessfullyConnected && (pnode->nStartingHeight > (nBestHeight - 144)) && (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) { // if ok, compare node's score with the best so far double dScore = NodeSyncScore(pnode); if (pnodeNewSync == NULL || dScore > dBestScore) { pnodeNewSync = pnode; dBestScore = dScore; } } } // if a new sync candidate was found, start sync! if (pnodeNewSync) { pnodeNewSync->fStartSync = true; pnodeSync = pnodeNewSync; } } void ThreadMessageHandler() { SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (true) { bool fHaveSyncNode = false; vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { pnode->AddRef(); if (pnode == pnodeSync) fHaveSyncNode = true; } } if (!fHaveSyncNode) StartSync(vNodesCopy); // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; bool fSleep = true; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (!ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); if (pnode->nSendSize < SendBufferSize()) { if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) { fSleep = false; } } } } boost::this_thread::interruption_point(); // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SendMessages(pnode, pnode == pnodeTrickle); } boost::this_thread::interruption_point(); } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } if (fSleep) MilliSleep(100); } } bool BindListenPort(const CService &addrBind, string& strError) { strError = ""; int nOne = 1; // Create socket for listening for incoming connections #ifdef USE_IPV6 struct sockaddr_storage sockaddr; #else struct sockaddr sockaddr; #endif socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str()); printf("%s\n", strError.c_str()); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif #ifndef WIN32 // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif #ifdef WIN32 // Set to non-blocking, incoming connections will also inherit this if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR) #else if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) #endif { strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef USE_IPV6 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */; int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */; // this call is allowed to fail setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int)); #endif } #endif if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. Rcoin is probably already running."), addrBind.ToString().c_str()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr)); printf("%s\n", strError.c_str()); return false; } printf("Bound to %s\n", addrBind.ToString().c_str()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } vhListenSocket.push_back(hListenSocket); if (addrBind.IsRoutable() && fDiscover) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover() { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[1000] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr &addr, vaddr) { AddLocal(addr, LOCAL_IF); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } #ifdef USE_IPV6 else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } #endif } freeifaddrs(myaddrs); } #endif // Don't use external IPv4 discovery, when -onlynet="IPv6" if (!IsLimited(NET_IPV4)) NewThread(ThreadGetMyExternalIP, NULL); } void StartNode(boost::thread_group& threadGroup) { if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(); // // Start threads // if (!GetBoolArg("-dnsseed", true)) printf("DNS seeding disabled\n"); else threadGroup.create_thread(boost::bind(&TraceThread<boost::function<void()> >, "dnsseed", &ThreadDNSAddressSeed)); #ifdef USE_UPNP // Map ports with UPnP MapPort(GetBoolArg("-upnp", USE_UPNP)); #endif // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler)); // Initiate outbound connections from -addnode threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections)); // Initiate outbound connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections)); // Process messages threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler)); // Dump network addresses threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000)); } bool StopNode() { printf("StopNode()\n"); GenerateBitcoins(false, NULL); MapPort(false); nTransactionsUpdated++; if (semOutbound) for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); MilliSleep(50); DumpAddresses(); return true; } class CNetCleanup { public: CNetCleanup() { } ~CNetCleanup() { // Close sockets BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) closesocket(pnode->hSocket); BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET) if (closesocket(hListenSocket) == SOCKET_ERROR) printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError()); // clean up some globals (to help leak detection) BOOST_FOREACH(CNode *pnode, vNodes) delete pnode; BOOST_FOREACH(CNode *pnode, vNodesDisconnected) delete pnode; vNodes.clear(); vNodesDisconnected.clear(); delete semOutbound; semOutbound = NULL; delete pnodeLocalHost; pnodeLocalHost = NULL; #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void RelayTransaction(const CTransaction& tx, const uint256& hash) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, hash, ss); } void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss) { CInv inv(MSG_TX, hash); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if(!pnode->fRelayTxes) continue; LOCK(pnode->cs_filter); if (pnode->pfilter) { if (pnode->pfilter->IsRelevantAndUpdate(tx, hash)) pnode->PushInventory(inv); } else pnode->PushInventory(inv); } }
f515323a9cfc8317cf3a6eb7a7f13c41371ba82f
07e88c109af86db6aa3194cbb71c41d449f1a805
/Code/m3alps/optimizer.h
585eb6b3c53b97762bb7cde9cf12d0878f3e1b0b
[]
no_license
jbongard/ISCS
2a7fe528140aa24631022807c5af34d7442a122d
a7f7196a2a729564bd033abc13cdf4acb172edfb
refs/heads/master
2016-09-05T08:44:10.630025
2011-08-17T15:31:58
2011-08-17T15:31:58
2,222,304
1
1
null
null
null
null
UTF-8
C++
false
false
3,616
h
/* The algorithm that optimizes the robots. This can be replaced with whatever optimization algorithm the user prefers. This one instantiates a hill climber. The genomes are encoded as two-dimensional matrices with each element in the range [0,1]. */ #ifndef _OPTIMIZER_H #define _OPTIMIZER_H #include "matrix.h" #include "neuralNetwork.h" class OPTIMIZER { public: int timer; int evaluationPeriod; private: long nextGenomeID; NEURAL_NETWORK **genomes; NEURAL_NETWORK *genomeUnderEvaluation; int populationSize; int nextVictimOnFirstLayer; int layerIndex; int genomesEvaluated; MATRIX *ageCaps; MATRIX *worstFitnesses; int numSensors; int numMotors; double mutationProbability; public: OPTIMIZER(int numberOfSensors, int numberOfMotors); OPTIMIZER(ifstream *inFile); ~OPTIMIZER(void); void EvaluationPeriod_Decrease(void); void EvaluationPeriod_Increase(void); void Fitness_Receive(double fitness); void Genome_Discard_Being_Evaluated(void); NEURAL_NETWORK *Genome_Get_Best(void); NEURAL_NETWORK *Genome_Get_Curr_To_Evaluate(void); NEURAL_NETWORK *Genome_Get_Next_To_Evaluate(void); void Load(ifstream *inFile); void MutationProbability_Decrease(void); void MutationProbability_Increase(void); void Print(void); void Reset(void); int Robot_Failed_On_Layer(double currFit); void Save(ofstream *outFile); int Time_Elapsed(void); void Timer_Reset(void); void Timer_Update(void); private: void Destroy(void); void Destroy_Age_Caps(void); void Destroy_Worst_Fitnesses(void); int FlipCoin(void); int Genome_Age(int layerIndex, int genomeIndex); NEURAL_NETWORK *Genome_Copy(int parentID); void Genome_Create_Random(int layerIndex, int genomeIndex); void Genome_Destroy(int layerIndex, int genomeIndex); int Genome_Evaluated(int genomeIndex); NEURAL_NETWORK *Genome_Find_Next_Not_Evaluated(void); NEURAL_NETWORK *Genome_Get(int layerIndex, int genomeIndex); int Genome_Index(int layerIndex, int genomeIndex); void Genome_Load(int layerIndex, int genomeIndex, ifstream *inFile); void Genome_Print(int layerIndex, int genomeIndex); NEURAL_NETWORK *Genome_Spawn(void); void Genome_Spawn_From_First_Layer(int layerIndex); void Genome_Spawn_From_Upper_Layer(int layerIndex); int Genome_Too_Old(int layerIndex, int genomeIndex); int Genomes_All_Evaluated(void); void Genomes_Create(void); void Genomes_Destroy(void); void Genomes_Load(ifstream *inFile); void Genomes_Print(void); void Genomes_Save(ofstream *outFile); void Initialize(void); void Initialize_Age_Caps(void); void Initialize_Worst_Fitnesses(void); int Layer_Age_Cap(int layerIndex); int Layer_All_Evaluated(int layerIndex); int Layer_All_Of_Age(int layerIndex); int Layer_Find_Clone(int layerIndex, double aggressorFitness); int Layer_Find_Dominated(int layerIndex, double aggressorFitness); int Layer_Find_Too_Old(int layerIndex); int Layer_Find_Victim(int layerIndex, double aggressorFitness); int Layer_First_Index(int layerIndex); int Layer_Get_Parent_Index(int layerIndex); int Layer_Get_Random(void); int Layer_Last_Index(int layerIndex); NEURAL_NETWORK *Layer_Most_Fit_Genome(int layerIndex); int Layer_Most_Fit_Genome_Index(int layerIndex); int Layer_Random_Genome_Index(int layerIndex); void Layer_Sort(int layerIndex); int Layer_Top(int layerIndex); double Layer_Worst_Fitness(int layerIndex); double Rand(double min, double max); int RandInt(int min, int max); void TryMoveUp(int layerIndex); }; #endif
09d4583ac6ed5dd984ef5e3b933a82839692ad39
ae3e9b36f901570026cbc2be553ee1e5db818d66
/Compressor/Compressors/Beta/ArithmeticCoder.h
fc60e647b64dbe9676151f809232d8bd66b2055d
[]
no_license
OmarBazaraa/Bitifier
34210bdbb272502307f7f1a429007e355b3fca6c
35669c292c11fd07a8df6ee489046b010af29ac7
refs/heads/master
2021-03-19T14:29:48.611043
2018-12-06T15:45:05
2018-12-06T15:45:05
89,235,697
0
0
null
null
null
null
UTF-8
C++
false
false
1,209
h
#pragma once #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <set> #include "../BitConcatenator.h" using namespace std; typedef unsigned char uchar; class ArithmeticCoder { private: const int ALPHA_SIZE = 256; int dataIdx; string binaryStr; vector<int> symbolsFrq; vector<int> symbolsFrqPrefixSum; // ============================================================================== // // Encoding functions // public: /** * Encode the passed data by generating shorter code words for * more frequent symbols */ void encode(const vector<uchar>& data, vector<uchar>& encodedData); private: void encodeSymbols(vector<uchar>& encodedData); void _encode(const vector<uchar>& data); // ============================================================================== // // Decoding functions // public: /** * Decode the passed data by retrieving the code word table and mapping each code * to its corresponding symbol */ void decode(const vector<uchar>& data, vector<uchar>& decodedData); private: void decodeSymbols(const vector<uchar>& data); // // Helper functions // private: string byteToBinaryString(uchar byte); };
af9c59be139400a606b4b8b32d5a06106275ce83
2108fc8a2be2d2bc79efc5aca5c9e89a9676e333
/logger.h
97a01f431cc560d1099ee03828d6816f9fab968f
[ "Apache-2.0" ]
permissive
frank0098/distributedsystem
7060de13aa33af41933c35a5ae913f273bf9a15c
72373208d0ba00af443c43a68350bb62ded7a0b5
refs/heads/master
2021-03-27T09:31:04.143325
2018-08-06T04:53:44
2018-08-06T04:53:44
90,808,370
0
0
null
null
null
null
UTF-8
C++
false
false
595
h
#ifndef LOGGER_H #define LOGGER_H #include <string> #include <iostream> #include <fstream> #include <utility> #include <stdio.h> #include <vector> #include <mutex> #include <sys/stat.h> using std::vector; using std::string; using std::cout; using std::endl; class Logger{ public: Logger(){}; Logger(int peer_id); void start(); void stop(); void write(string str); void iniailize(int peer_id); private: std::string _path; std::mutex _write_lock; int _peerid; bool _started; std::ofstream _log_stream; }; extern Logger* logger(); extern void initialize_log(int peer_id); #endif
59048728c78beb786b0887330f12fad6d34dfa91
f6f973a71896ccb5990812d77449248e5e8db247
/Notes/Book.h
d826cc089e6bf8fa75e54f03df5769e7a1319f92
[]
no_license
browningspencer/cs235
6ee8b2f2e81c5161c20e4b26e501297b5c7a1da5
10c18291a95e32a17370df352b514fd847848ca0
refs/heads/master
2021-06-08T01:23:54.415586
2016-12-02T19:15:23
2016-12-02T19:15:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
805
h
//Standard practice is to avoid using "using namespace std;", you have to call them //everytime (ex. std::vector) (ex. std::cout) #pragma once //allows any file that includes Book.h to share #includes #include <iostream> #include <string> class Book { private: //Only includes variables string title; string author; public: // only includes functions bool operator < (Book b2) { //Defines the comparison called by sort() return this->title < b2.title; //that's called in Test.cpp. }// Pointers ^ use -> instead of . (ex "this->title", not "this.title") Book(string t, string a) : title(t), author(a) {} string getTitle() const { return title; } string getAuthor() const { return author; } void setTitle(string title); void setAuthor(string author); string toString() const; };
f5610764dc3ec9b59abfcc57d9ae1d87f2190bd9
031d401559cfbe8e9a2516823e84b3e95acbd171
/codeforces/670_Div2/B.cpp
f365578a13f26211203732f86e4cfaef971e3fa8
[]
no_license
rajat2004/programming
e05d95d7523481ddaf81c44ab275f834f2731d44
62e15615dab311edfe68e694a4f97adab23b6725
refs/heads/master
2023-04-18T07:51:22.979076
2021-05-03T06:03:44
2021-05-03T06:03:44
234,147,423
0
0
null
2020-12-03T06:23:47
2020-01-15T18:38:09
C++
UTF-8
C++
false
false
1,867
cpp
#pragma GCC optimize ("-O3") #include<bits/stdc++.h> using namespace std; typedef long long int ll; typedef long long unsigned lluu; typedef long double ld; typedef pair<int,int> p32; typedef pair<ll,ll> p64; typedef pair<double,double> pdd; typedef vector<ll> v64; typedef vector<int> v32; typedef vector<vector<int> > vv32; typedef vector<vector<ll> > vv64; typedef vector<p64> vp64; typedef vector<p32> vp32; ll MOD = 998244353; ll NUM = 1e9+7; #define forn(i,e) for(ll i = 0; i < e; i++) #define forsn(i,s,e) for(ll i = s; i < e; i++) #define rforn(i,s) for(ll i = s; i >= 0; i--) #define rforsn(i,s,e) for(ll i = s; i >= e; i--) #define ln "\n" #define dbg(x) cout<<#x<<" = "<<x<<ln #define mp make_pair #define pb push_back #define ff first #define ss second #define INF 1e18 #define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) #define all(x) (x).begin(), (x).end() #define sz(x) ((ll)(x).size()) #define zer ll(0) #define printarr(arr,n) forn(i,n) cout << arr[i] << " " #define input(arr,n) forn(i,n) cin >> arr[i] ll maxProd(const v64& v) { int n=v.size(); ll prod=1; if (v[n-1]==0) { return 0; } if (v[n-1]<0) { for(int i=n-1; i>=n-5; i--) prod*=v[i]; return prod; } int i=0,j=n-1; if (v[n-1]>0) { prod*=v[n-1]; j--; } int k2=2; // 2 pairs while(k2--) { ll left=v[i]*v[i+1], right=v[j]*v[j-1]; if (left>right) { prod*=left; i+=2; } else { prod*=right; j-=2; } } return prod; } void solve() { int n; cin >> n; v64 v(n); input(v,n); sort(v.begin(), v.end()); cout << maxProd(v) << ln; } int main() { fast_cin(); int t; cin >> t; while(t--) { solve(); } return 0; }
c6e5d8923e1eb29f4df2cc63d22c6082f36ed88c
8d9b75e974f72d79d04972a758fb31a52c0d6ab0
/codejam21/Inconsistent ordering.cpp
b708883322f58fec70574b2b4b8adc96264f6c1b
[]
no_license
Nidita/Competitive-Programming
b321d9adfe734818b1d7b8db2d7aa2a92a8e4270
42638e45a4456dd523ca51685ae8357137a29c46
refs/heads/main
2023-06-30T13:33:22.153217
2021-08-10T10:51:36
2021-08-10T10:51:36
394,616,222
0
0
null
null
null
null
UTF-8
C++
false
false
1,695
cpp
#include <bits/stdc++.h> using namespace std; int main() { int t,j=1; cin>>t; for(int k=0;k<t;k++) { string s; s+='A'; int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } for(int i=0;i<n;i++) { char c='B',c1; if(i==n-1) { for(int l=1;l<=arr[i];l++) { if(i%2==0) { s+=c; c++; } else { s+=c1; c1--; } } } else { for(int l=1;l<=arr[i];l++) { if(i%2==0) { if(l==arr[i]) { if(arr[i+1]>arr[i]) { c+=arr[i+1]-arr[i]; c1=c-1; } else { c1='A'+arr[i+1]-1; } s+=c; } else { s+=c; c++; } } else { s+=c1; c1--; } } } } cout<<"Case #"<<k+1<<": "<<s<<endl; } }
ae343b0a9846ebae662010dba19dc2c03e5f07c6
72dd80965026d8797f75c8d79a619cf1d2f02b89
/Binary Trees/Sum_Of_BinaryTree.cpp
856747757a4ba3769353183450a8d9bdf6277016
[]
no_license
hanzohasashi33/DSA
99be005041a68f3b1239d496e6e568f409696103
733316ba7192d6e493389182e5da2a3edc1224f2
refs/heads/master
2022-12-20T10:14:46.897461
2020-07-07T16:37:32
2020-07-07T16:37:32
236,500,936
11
11
null
2020-10-06T21:02:03
2020-01-27T13:51:20
C++
UTF-8
C++
false
false
1,390
cpp
#include <bits/stdc++.h> using namespace std; struct Node { int key; struct Node *left; struct Node *right; Node(int x){ key = x; left = NULL; right = NULL; } }; Node* make_tree() { int n; cin>>n; Node* head=NULL; queue <Node*> q; for( ; n>0 ; n-=2 ) { int a,b; char c; cin>> a >> b >> c; if(!head) { head = new Node(a); q.push(head); } Node* pick = q.front(); q.pop(); if(c == 'L') { pick->left = new Node(b); q.push( pick->left ); } cin>> a >> b >> c; if(c == 'R') { pick->right = new Node(b); q.push( pick->right ); } } return head; } long int sumBT(Node* root); int main() { int t;cin>>t;while(t--){ Node* head = make_tree(); cout<<sumBT(head)<<endl; } return 1; } // } Driver Code Ends /*Structure of the node of the binary tree struct Node { int key; Node* left, *right; }; */ // Function should return the sum of all the elements // of the binary tree long int sumBT(Node* root) { // Code here queue <Node *> q; q.push(root); int sum = 0; while(!q.empty()) { Node * temp = q.front(); q.pop(); sum += temp->key; if(temp->right) { q.push(temp->right); } if(temp->left) { q.push(temp->left); } } return sum; }
3ea1ec1ccbd455a594ac8c589a09ea3f76c600dd
651e464d18db5d0cab098ab6ffec59bf8f910a33
/libraries/I2CDev_ms5611/I2Cdev.cpp
54b008f35a54cf8221031f0f6d25286e20732b2e
[]
no_license
van-hurlu/arduino-variometer
6020e1b7c9c7421f7eabcc89ff781500a3807e29
3296d8704b71bdf4c1ae9fcd7a30c29a497f2b59
refs/heads/master
2021-07-04T16:20:19.397457
2017-09-25T13:42:33
2017-09-25T13:42:33
104,784,258
2
0
null
2017-09-25T18:04:01
2017-09-25T18:04:00
null
UTF-8
C++
false
false
57,161
cpp
// I2Cdev library collection - Main I2C device class // Abstracts bit and byte I2C R/W functions into a convenient class // 6/9/2012 by Jeff Rowberg <[email protected]> // // Changelog: // 2013-05-06 - add Francesco Ferrara's Fastwire v0.24 implementation with small modifications // 2013-05-05 - fix issue with writing bit values to words (Sasquatch/Farzanegan) // 2012-06-09 - fix major issue with reading > 32 bytes at a time with Arduino Wire // - add compiler warnings when using outdated or IDE or limited I2Cdev implementation // 2011-11-01 - fix write*Bits mask calculation (thanks sasquatch @ Arduino forums) // 2011-10-03 - added automatic Arduino version detection for ease of use // 2011-10-02 - added Gene Knight's NBWire TwoWire class implementation with small modifications // 2011-08-31 - added support for Arduino 1.0 Wire library (methods are different from 0.x) // 2011-08-03 - added optional timeout parameter to read* methods to easily change from default // 2011-08-02 - added support for 16-bit registers // - fixed incorrect Doxygen comments on some methods // - added timeout value for read operations (thanks mem @ Arduino forums) // 2011-07-30 - changed read/write function structures to return success or byte counts // - made all methods static for multi-device memory savings // 2011-07-28 - initial release /* ============================================ I2Cdev device library code is placed under the MIT license Copyright (c) 2013 Jeff Rowberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================== */ #include "I2Cdev.h" #include <ms5611.h> #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE #ifdef I2CDEV_IMPLEMENTATION_WARNINGS #if ARDUINO < 100 #warning Using outdated Arduino IDE with Wire library is functionally limiting. #warning Arduino IDE v1.0.1+ with I2Cdev Fastwire implementation is recommended. #warning This I2Cdev implementation does not support: #warning - Repeated starts conditions #warning - Timeout detection (some Wire requests block forever) #elif ARDUINO == 100 #warning Using outdated Arduino IDE with Wire library is functionally limiting. #warning Arduino IDE v1.0.1+ with I2Cdev Fastwire implementation is recommended. #warning This I2Cdev implementation does not support: #warning - Repeated starts conditions #warning - Timeout detection (some Wire requests block forever) #elif ARDUINO > 100 #warning Using current Arduino IDE with Wire library is functionally limiting. #warning Arduino IDE v1.0.1+ with I2CDEV_BUILTIN_FASTWIRE implementation is recommended. #warning This I2Cdev implementation does not support: #warning - Timeout detection (some Wire requests block forever) #endif #endif #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE //#error The I2CDEV_BUILTIN_FASTWIRE implementation is known to be broken right now. Patience, Iago! #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE #ifdef I2CDEV_IMPLEMENTATION_WARNINGS #warning Using I2CDEV_BUILTIN_NBWIRE implementation may adversely affect interrupt detection. #warning This I2Cdev implementation does not support: #warning - Repeated starts conditions #endif // NBWire implementation based heavily on code by Gene Knight <[email protected]> // Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html // Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html TwoWire Wire; #endif /** Default constructor. */ I2Cdev::I2Cdev() { } /** Read a single bit from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitNum Bit position to read (0-7) * @param data Container for single bit value * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int8_t I2Cdev::readBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data, uint16_t timeout) { uint8_t b; uint8_t count = readByte(devAddr, regAddr, &b, timeout); *data = b & (1 << bitNum); return count; } /** Read a single bit from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitNum Bit position to read (0-15) * @param data Container for single bit value * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int8_t I2Cdev::readBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t *data, uint16_t timeout) { uint16_t b; uint8_t count = readWord(devAddr, regAddr, &b, timeout); *data = b & (1 << bitNum); return count; } /** Read multiple bits from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitStart First bit position to read (0-7) * @param length Number of bits to read (not more than 8) * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05) * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int8_t I2Cdev::readBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data, uint16_t timeout) { // 01101001 read byte // 76543210 bit numbers // xxx args: bitStart=4, length=3 // 010 masked // -> 010 shifted uint8_t count, b; if ((count = readByte(devAddr, regAddr, &b, timeout)) != 0) { uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1); b &= mask; b >>= (bitStart - length + 1); *data = b; } return count; } /** Read multiple bits from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitStart First bit position to read (0-15) * @param length Number of bits to read (not more than 16) * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05) * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (1 = success, 0 = failure, -1 = timeout) */ int8_t I2Cdev::readBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t *data, uint16_t timeout) { // 1101011001101001 read byte // fedcba9876543210 bit numbers // xxx args: bitStart=12, length=3 // 010 masked // -> 010 shifted uint8_t count; uint16_t w; if ((count = readWord(devAddr, regAddr, &w, timeout)) != 0) { uint16_t mask = ((1 << length) - 1) << (bitStart - length + 1); w &= mask; w >>= (bitStart - length + 1); *data = w; } return count; } /** Read single byte from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param data Container for byte value read from device * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int8_t I2Cdev::readByte(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint16_t timeout) { return readBytes(devAddr, regAddr, 1, data, timeout); } /** Read single word from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param data Container for word value read from device * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int8_t I2Cdev::readWord(uint8_t devAddr, uint8_t regAddr, uint16_t *data, uint16_t timeout) { return readWords(devAddr, regAddr, 1, data, timeout); } /** Read multiple bytes from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr First register regAddr to read from * @param length Number of bytes to read * @param data Buffer to store read data in * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Number of bytes read (-1 indicates failure) */ int8_t I2Cdev::readBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data, uint16_t timeout, boolean lockMS5611) { /* lock the ms5611 */ if( lockMS5611 ) { ms5611_lock(); } #ifdef I2CDEV_SERIAL_DEBUG Serial.print("I2C (0x"); Serial.print(devAddr, HEX); Serial.print(") reading "); Serial.print(length, DEC); Serial.print(" bytes from 0x"); Serial.print(regAddr, HEX); Serial.print("..."); #endif int8_t count = 0; uint32_t t1 = millis(); #if (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE) #if (ARDUINO < 100) // Arduino v00xx (before v1.0), Wire library // I2C/TWI subsystem uses internal buffer that breaks with large data requests // so if user requests more than BUFFER_LENGTH bytes, we have to do it in // smaller chunks instead of all at once for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) { Wire.beginTransmission(devAddr); Wire.send(regAddr); Wire.endTransmission(); Wire.beginTransmission(devAddr); Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH)); for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) { data[count] = Wire.receive(); #ifdef I2CDEV_SERIAL_DEBUG Serial.print(data[count], HEX); if (count + 1 < length) Serial.print(" "); #endif } Wire.endTransmission(); } #elif (ARDUINO == 100) // Arduino v1.0.0, Wire library // Adds standardized write() and read() stream methods instead of send() and receive() // I2C/TWI subsystem uses internal buffer that breaks with large data requests // so if user requests more than BUFFER_LENGTH bytes, we have to do it in // smaller chunks instead of all at once for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) { Wire.beginTransmission(devAddr); Wire.write(regAddr); Wire.endTransmission(); Wire.beginTransmission(devAddr); Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH)); for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) { data[count] = Wire.read(); #ifdef I2CDEV_SERIAL_DEBUG Serial.print(data[count], HEX); if (count + 1 < length) Serial.print(" "); #endif } Wire.endTransmission(); } #elif (ARDUINO > 100) // Arduino v1.0.1+, Wire library // Adds official support for repeated start condition, yay! // I2C/TWI subsystem uses internal buffer that breaks with large data requests // so if user requests more than BUFFER_LENGTH bytes, we have to do it in // smaller chunks instead of all at once for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) { Wire.beginTransmission(devAddr); Wire.write(regAddr); Wire.endTransmission(); Wire.beginTransmission(devAddr); Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH)); for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) { data[count] = Wire.read(); #ifdef I2CDEV_SERIAL_DEBUG Serial.print(data[count], HEX); if (count + 1 < length) Serial.print(" "); #endif } } #endif #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE) // Fastwire library // no loop required for fastwire uint8_t status = Fastwire::readBuf(devAddr << 1, regAddr, data, length); if (status == 0) { count = length; // success } else { count = -1; // error } #endif // check for timeout if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout #ifdef I2CDEV_SERIAL_DEBUG Serial.print(". Done ("); Serial.print(count, DEC); Serial.println(" read)."); #endif /* unlock the ms5611 */ if( lockMS5611 ) { ms5611_release(); } return count; } /** Read multiple words from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr First register regAddr to read from * @param length Number of words to read * @param data Buffer to store read data in * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Number of words read (-1 indicates failure) */ int8_t I2Cdev::readWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data, uint16_t timeout, boolean lockMS5611) { /* lock the ms5611 */ if( lockMS5611 ) { ms5611_lock(); } #ifdef I2CDEV_SERIAL_DEBUG Serial.print("I2C (0x"); Serial.print(devAddr, HEX); Serial.print(") reading "); Serial.print(length, DEC); Serial.print(" words from 0x"); Serial.print(regAddr, HEX); Serial.print("..."); #endif int8_t count = 0; uint32_t t1 = millis(); #if (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE) #if (ARDUINO < 100) // Arduino v00xx (before v1.0), Wire library // I2C/TWI subsystem uses internal buffer that breaks with large data requests // so if user requests more than BUFFER_LENGTH bytes, we have to do it in // smaller chunks instead of all at once for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) { Wire.beginTransmission(devAddr); Wire.send(regAddr); Wire.endTransmission(); Wire.beginTransmission(devAddr); Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes bool msb = true; // starts with MSB, then LSB for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) { if (msb) { // first byte is bits 15-8 (MSb=15) data[count] = Wire.receive() << 8; } else { // second byte is bits 7-0 (LSb=0) data[count] |= Wire.receive(); #ifdef I2CDEV_SERIAL_DEBUG Serial.print(data[count], HEX); if (count + 1 < length) Serial.print(" "); #endif count++; } msb = !msb; } Wire.endTransmission(); } #elif (ARDUINO == 100) // Arduino v1.0.0, Wire library // Adds standardized write() and read() stream methods instead of send() and receive() // I2C/TWI subsystem uses internal buffer that breaks with large data requests // so if user requests more than BUFFER_LENGTH bytes, we have to do it in // smaller chunks instead of all at once for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) { Wire.beginTransmission(devAddr); Wire.write(regAddr); Wire.endTransmission(); Wire.beginTransmission(devAddr); Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes bool msb = true; // starts with MSB, then LSB for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) { if (msb) { // first byte is bits 15-8 (MSb=15) data[count] = Wire.read() << 8; } else { // second byte is bits 7-0 (LSb=0) data[count] |= Wire.read(); #ifdef I2CDEV_SERIAL_DEBUG Serial.print(data[count], HEX); if (count + 1 < length) Serial.print(" "); #endif count++; } msb = !msb; } Wire.endTransmission(); } #elif (ARDUINO > 100) // Arduino v1.0.1+, Wire library // Adds official support for repeated start condition, yay! // I2C/TWI subsystem uses internal buffer that breaks with large data requests // so if user requests more than BUFFER_LENGTH bytes, we have to do it in // smaller chunks instead of all at once for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) { Wire.beginTransmission(devAddr); Wire.write(regAddr); Wire.endTransmission(); Wire.beginTransmission(devAddr); Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes bool msb = true; // starts with MSB, then LSB for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) { if (msb) { // first byte is bits 15-8 (MSb=15) data[count] = Wire.read() << 8; } else { // second byte is bits 7-0 (LSb=0) data[count] |= Wire.read(); #ifdef I2CDEV_SERIAL_DEBUG Serial.print(data[count], HEX); if (count + 1 < length) Serial.print(" "); #endif count++; } msb = !msb; } Wire.endTransmission(); } #endif #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE) // Fastwire library // no loop required for fastwire uint16_t intermediate[(uint8_t)length]; uint8_t status = Fastwire::readBuf(devAddr << 1, regAddr, (uint8_t *)intermediate, (uint8_t)(length * 2)); if (status == 0) { count = length; // success for (uint8_t i = 0; i < length; i++) { data[i] = (intermediate[2*i] << 8) | intermediate[2*i + 1]; } } else { count = -1; // error } #endif if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout #ifdef I2CDEV_SERIAL_DEBUG Serial.print(". Done ("); Serial.print(count, DEC); Serial.println(" read)."); #endif /* unlock the ms5611 */ if( lockMS5611 ) { ms5611_release(); } return count; } /** write a single bit in an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to write to * @param bitNum Bit position to write (0-7) * @param value New bit value to write * @return Status of operation (true = success) */ bool I2Cdev::writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data) { uint8_t b; readByte(devAddr, regAddr, &b); b = (data != 0) ? (b | (1 << bitNum)) : (b & ~(1 << bitNum)); return writeByte(devAddr, regAddr, b); } /** write a single bit in a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to write to * @param bitNum Bit position to write (0-15) * @param value New bit value to write * @return Status of operation (true = success) */ bool I2Cdev::writeBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t data) { uint16_t w; readWord(devAddr, regAddr, &w); w = (data != 0) ? (w | (1 << bitNum)) : (w & ~(1 << bitNum)); return writeWord(devAddr, regAddr, w); } /** Write multiple bits in an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to write to * @param bitStart First bit position to write (0-7) * @param length Number of bits to write (not more than 8) * @param data Right-aligned value to write * @return Status of operation (true = success) */ bool I2Cdev::writeBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data) { // 010 value to write // 76543210 bit numbers // xxx args: bitStart=4, length=3 // 00011100 mask byte // 10101111 original value (sample) // 10100011 original & ~mask // 10101011 masked | value uint8_t b; if (readByte(devAddr, regAddr, &b) != 0) { uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1); data <<= (bitStart - length + 1); // shift data into correct position data &= mask; // zero all non-important bits in data b &= ~(mask); // zero all important bits in existing byte b |= data; // combine data with existing byte return writeByte(devAddr, regAddr, b); } else { return false; } } /** Write multiple bits in a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to write to * @param bitStart First bit position to write (0-15) * @param length Number of bits to write (not more than 16) * @param data Right-aligned value to write * @return Status of operation (true = success) */ bool I2Cdev::writeBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t data) { // 010 value to write // fedcba9876543210 bit numbers // xxx args: bitStart=12, length=3 // 0001110000000000 mask word // 1010111110010110 original value (sample) // 1010001110010110 original & ~mask // 1010101110010110 masked | value uint16_t w; if (readWord(devAddr, regAddr, &w) != 0) { uint16_t mask = ((1 << length) - 1) << (bitStart - length + 1); data <<= (bitStart - length + 1); // shift data into correct position data &= mask; // zero all non-important bits in data w &= ~(mask); // zero all important bits in existing word w |= data; // combine data with existing word return writeWord(devAddr, regAddr, w); } else { return false; } } /** Write single byte to an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register address to write to * @param data New byte value to write * @return Status of operation (true = success) */ bool I2Cdev::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data) { return writeBytes(devAddr, regAddr, 1, &data); } /** Write single word to a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register address to write to * @param data New word value to write * @return Status of operation (true = success) */ bool I2Cdev::writeWord(uint8_t devAddr, uint8_t regAddr, uint16_t data) { return writeWords(devAddr, regAddr, 1, &data); } /** Write multiple bytes to an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr First register address to write to * @param length Number of bytes to write * @param data Buffer to copy new data from * @return Status of operation (true = success) */ bool I2Cdev::writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t* data, boolean lockMS5611) { /* lock the ms5611 */ if( lockMS5611 ) { ms5611_lock(); } #ifdef I2CDEV_SERIAL_DEBUG Serial.print("I2C (0x"); Serial.print(devAddr, HEX); Serial.print(") writing "); Serial.print(length, DEC); Serial.print(" bytes to 0x"); Serial.print(regAddr, HEX); Serial.print("..."); #endif uint8_t status = 0; #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE) Wire.beginTransmission(devAddr); Wire.send((uint8_t) regAddr); // send address #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) Wire.beginTransmission(devAddr); Wire.write((uint8_t) regAddr); // send address #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE) Fastwire::beginTransmission(devAddr); Fastwire::write(regAddr); #endif for (uint8_t i = 0; i < length; i++) { #ifdef I2CDEV_SERIAL_DEBUG Serial.print(data[i], HEX); if (i + 1 < length) Serial.print(" "); #endif #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE) Wire.send((uint8_t) data[i]); #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) Wire.write((uint8_t) data[i]); #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE) Fastwire::write((uint8_t) data[i]); #endif } #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE) Wire.endTransmission(); #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) status = Wire.endTransmission(); #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE) Fastwire::stop(); //status = Fastwire::endTransmission(); #endif #ifdef I2CDEV_SERIAL_DEBUG Serial.println(". Done."); #endif /* unlock the ms5611 */ if( lockMS5611 ) { ms5611_release(); } return status == 0; } /** Write multiple words to a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr First register address to write to * @param length Number of words to write * @param data Buffer to copy new data from * @return Status of operation (true = success) */ bool I2Cdev::writeWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t* data, boolean lockMS5611) { /* lock the ms5611 */ if( lockMS5611 ) { ms5611_lock(); } #ifdef I2CDEV_SERIAL_DEBUG Serial.print("I2C (0x"); Serial.print(devAddr, HEX); Serial.print(") writing "); Serial.print(length, DEC); Serial.print(" words to 0x"); Serial.print(regAddr, HEX); Serial.print("..."); #endif uint8_t status = 0; #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE) Wire.beginTransmission(devAddr); Wire.send(regAddr); // send address #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) Wire.beginTransmission(devAddr); Wire.write(regAddr); // send address #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE) Fastwire::beginTransmission(devAddr); Fastwire::write(regAddr); #endif for (uint8_t i = 0; i < length * 2; i++) { #ifdef I2CDEV_SERIAL_DEBUG Serial.print(data[i], HEX); if (i + 1 < length) Serial.print(" "); #endif #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE) Wire.send((uint8_t)(data[i] >> 8)); // send MSB Wire.send((uint8_t)data[i++]); // send LSB #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) Wire.write((uint8_t)(data[i] >> 8)); // send MSB Wire.write((uint8_t)data[i++]); // send LSB #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE) Fastwire::write((uint8_t)(data[i] >> 8)); // send MSB status = Fastwire::write((uint8_t)data[i++]); // send LSB if (status != 0) break; #endif } #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE) Wire.endTransmission(); #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100) status = Wire.endTransmission(); #elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE) Fastwire::stop(); //status = Fastwire::endTransmission(); #endif #ifdef I2CDEV_SERIAL_DEBUG Serial.println(". Done."); #endif /* unlock the ms5611 */ if( lockMS5611 ) { ms5611_release(); } return status == 0; } /** Default timeout value for read operations. * Set this to 0 to disable timeout detection. */ uint16_t I2Cdev::readTimeout = I2CDEV_DEFAULT_READ_TIMEOUT; #if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE // I2C library ////////////////////// // Copyright(C) 2012 // Francesco Ferrara // ferrara[at]libero[point]it ////////////////////// /* FastWire - 0.24 added stop - 0.23 added reset This is a library to help faster programs to read I2C devices. Copyright(C) 2012 Francesco Ferrara occhiobello at gmail dot com [used by Jeff Rowberg for I2Cdevlib with permission] */ boolean Fastwire::waitInt() { int l = 250; while (!(TWCR & (1 << TWINT)) && l-- > 0); return l > 0; } void Fastwire::setup(int khz, boolean pullup) { TWCR = 0; #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__) // activate internal pull-ups for twi (PORTC bits 4 & 5) // as per note from atmega8 manual pg167 if (pullup) PORTC |= ((1 << 4) | (1 << 5)); else PORTC &= ~((1 << 4) | (1 << 5)); #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) // activate internal pull-ups for twi (PORTC bits 0 & 1) if (pullup) PORTC |= ((1 << 0) | (1 << 1)); else PORTC &= ~((1 << 0) | (1 << 1)); #else // activate internal pull-ups for twi (PORTD bits 0 & 1) // as per note from atmega128 manual pg204 if (pullup) PORTD |= ((1 << 0) | (1 << 1)); else PORTD &= ~((1 << 0) | (1 << 1)); #endif TWSR = 0; // no prescaler => prescaler = 1 TWBR = ((16000L / khz) - 16) / 2; // change the I2C clock rate TWCR = 1 << TWEN; // enable twi module, no interrupt } // added by Jeff Rowberg 2013-05-07: // Arduino Wire-style "beginTransmission" function // (takes 7-bit device address like the Wire method, NOT 8-bit: 0x68, not 0xD0/0xD1) byte Fastwire::beginTransmission(byte device) { byte twst, retry; retry = 2; do { TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA); if (!waitInt()) return 1; twst = TWSR & 0xF8; if (twst != TW_START && twst != TW_REP_START) return 2; //Serial.print(device, HEX); //Serial.print(" "); TWDR = device << 1; // send device address without read bit (1) TWCR = (1 << TWINT) | (1 << TWEN); if (!waitInt()) return 3; twst = TWSR & 0xF8; } while (twst == TW_MT_SLA_NACK && retry-- > 0); if (twst != TW_MT_SLA_ACK) return 4; return 0; } byte Fastwire::writeBuf(byte device, byte address, byte *data, byte num) { byte twst, retry; retry = 2; do { TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA); if (!waitInt()) return 1; twst = TWSR & 0xF8; if (twst != TW_START && twst != TW_REP_START) return 2; //Serial.print(device, HEX); //Serial.print(" "); TWDR = device & 0xFE; // send device address without read bit (1) TWCR = (1 << TWINT) | (1 << TWEN); if (!waitInt()) return 3; twst = TWSR & 0xF8; } while (twst == TW_MT_SLA_NACK && retry-- > 0); if (twst != TW_MT_SLA_ACK) return 4; //Serial.print(address, HEX); //Serial.print(" "); TWDR = address; // send data to the previously addressed device TWCR = (1 << TWINT) | (1 << TWEN); if (!waitInt()) return 5; twst = TWSR & 0xF8; if (twst != TW_MT_DATA_ACK) return 6; for (byte i = 0; i < num; i++) { //Serial.print(data[i], HEX); //Serial.print(" "); TWDR = data[i]; // send data to the previously addressed device TWCR = (1 << TWINT) | (1 << TWEN); if (!waitInt()) return 7; twst = TWSR & 0xF8; if (twst != TW_MT_DATA_ACK) return 8; } //Serial.print("\n"); return 0; } byte Fastwire::write(byte value) { byte twst; //Serial.println(value, HEX); TWDR = value; // send data TWCR = (1 << TWINT) | (1 << TWEN); if (!waitInt()) return 1; twst = TWSR & 0xF8; if (twst != TW_MT_DATA_ACK) return 2; return 0; } byte Fastwire::readBuf(byte device, byte address, byte *data, byte num) { byte twst, retry; retry = 2; do { TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA); if (!waitInt()) return 16; twst = TWSR & 0xF8; if (twst != TW_START && twst != TW_REP_START) return 17; //Serial.print(device, HEX); //Serial.print(" "); TWDR = device & 0xfe; // send device address to write TWCR = (1 << TWINT) | (1 << TWEN); if (!waitInt()) return 18; twst = TWSR & 0xF8; } while (twst == TW_MT_SLA_NACK && retry-- > 0); if (twst != TW_MT_SLA_ACK) return 19; //Serial.print(address, HEX); //Serial.print(" "); TWDR = address; // send data to the previously addressed device TWCR = (1 << TWINT) | (1 << TWEN); if (!waitInt()) return 20; twst = TWSR & 0xF8; if (twst != TW_MT_DATA_ACK) return 21; /***/ retry = 2; do { TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA); if (!waitInt()) return 22; twst = TWSR & 0xF8; if (twst != TW_START && twst != TW_REP_START) return 23; //Serial.print(device, HEX); //Serial.print(" "); TWDR = device | 0x01; // send device address with the read bit (1) TWCR = (1 << TWINT) | (1 << TWEN); if (!waitInt()) return 24; twst = TWSR & 0xF8; } while (twst == TW_MR_SLA_NACK && retry-- > 0); if (twst != TW_MR_SLA_ACK) return 25; for (uint8_t i = 0; i < num; i++) { if (i == num - 1) TWCR = (1 << TWINT) | (1 << TWEN); else TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA); if (!waitInt()) return 26; twst = TWSR & 0xF8; if (twst != TW_MR_DATA_ACK && twst != TW_MR_DATA_NACK) return twst; data[i] = TWDR; //Serial.print(data[i], HEX); //Serial.print(" "); } //Serial.print("\n"); stop(); return 0; } void Fastwire::reset() { TWCR = 0; } byte Fastwire::stop() { TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO); if (!waitInt()) return 1; return 0; } #endif #if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE // NBWire implementation based heavily on code by Gene Knight <[email protected]> // Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html // Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html /* call this version 1.0 Offhand, the only funky part that I can think of is in nbrequestFrom, where the buffer length and index are set *before* the data is actually read. The problem is that these are variables local to the TwoWire object, and by the time we actually have read the data, and know what the length actually is, we have no simple access to the object's variables. The actual bytes read *is* given to the callback function, though. The ISR code for a slave receiver is commented out. I don't have that setup, and can't verify it at this time. Save it for 2.0! The handling of the read and write processes here is much like in the demo sketch code: the process is broken down into sequential functions, where each registers the next as a callback, essentially. For example, for the Read process, twi_read00 just returns if TWI is not yet in a ready state. When there's another interrupt, and the interface *is* ready, then it sets up the read, starts it, and registers twi_read01 as the function to call after the *next* interrupt. twi_read01, then, just returns if the interface is still in a "reading" state. When the reading is done, it copies the information to the buffer, cleans up, and calls the user-requested callback function with the actual number of bytes read. The writing is similar. Questions, comments and problems can go to [email protected]. Thumbs Up! Gene Knight */ uint8_t TwoWire::rxBuffer[NBWIRE_BUFFER_LENGTH]; uint8_t TwoWire::rxBufferIndex = 0; uint8_t TwoWire::rxBufferLength = 0; uint8_t TwoWire::txAddress = 0; uint8_t TwoWire::txBuffer[NBWIRE_BUFFER_LENGTH]; uint8_t TwoWire::txBufferIndex = 0; uint8_t TwoWire::txBufferLength = 0; //uint8_t TwoWire::transmitting = 0; void (*TwoWire::user_onRequest)(void); void (*TwoWire::user_onReceive)(int); static volatile uint8_t twi_transmitting; static volatile uint8_t twi_state; static uint8_t twi_slarw; static volatile uint8_t twi_error; static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH]; static volatile uint8_t twi_masterBufferIndex; static uint8_t twi_masterBufferLength; static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH]; static volatile uint8_t twi_rxBufferIndex; //static volatile uint8_t twi_Interrupt_Continue_Command; static volatile uint8_t twi_Return_Value; static volatile uint8_t twi_Done; void (*twi_cbendTransmissionDone)(int); void (*twi_cbreadFromDone)(int); void twi_init() { // initialize state twi_state = TWI_READY; // activate internal pull-ups for twi // as per note from atmega8 manual pg167 sbi(PORTC, 4); sbi(PORTC, 5); // initialize twi prescaler and bit rate cbi(TWSR, TWPS0); // TWI Status Register - Prescaler bits cbi(TWSR, TWPS1); /* twi bit rate formula from atmega128 manual pg 204 SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR)) note: TWBR should be 10 or higher for master mode It is 72 for a 16mhz Wiring board with 100kHz TWI */ TWBR = ((CPU_FREQ / TWI_FREQ) - 16) / 2; // bitrate register // enable twi module, acks, and twi interrupt TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA); /* TWEN - TWI Enable Bit TWIE - TWI Interrupt Enable TWEA - TWI Enable Acknowledge Bit TWINT - TWI Interrupt Flag TWSTA - TWI Start Condition */ } typedef struct { uint8_t address; uint8_t* data; uint8_t length; uint8_t wait; uint8_t i; } twi_Write_Vars; twi_Write_Vars *ptwv = 0; static void (*fNextInterruptFunction)(void) = 0; void twi_Finish(byte bRetVal) { if (ptwv) { free(ptwv); ptwv = 0; } twi_Done = 0xFF; twi_Return_Value = bRetVal; fNextInterruptFunction = 0; } uint8_t twii_WaitForDone(uint16_t timeout) { uint32_t endMillis = millis() + timeout; while (!twi_Done && (timeout == 0 || millis() < endMillis)) continue; return twi_Return_Value; } void twii_SetState(uint8_t ucState) { twi_state = ucState; } void twii_SetError(uint8_t ucError) { twi_error = ucError ; } void twii_InitBuffer(uint8_t ucPos, uint8_t ucLength) { twi_masterBufferIndex = 0; twi_masterBufferLength = ucLength; } void twii_CopyToBuf(uint8_t* pData, uint8_t ucLength) { uint8_t i; for (i = 0; i < ucLength; ++i) { twi_masterBuffer[i] = pData[i]; } } void twii_CopyFromBuf(uint8_t *pData, uint8_t ucLength) { uint8_t i; for (i = 0; i < ucLength; ++i) { pData[i] = twi_masterBuffer[i]; } } void twii_SetSlaRW(uint8_t ucSlaRW) { twi_slarw = ucSlaRW; } void twii_SetStart() { TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA); } void twi_write01() { if (TWI_MTX == twi_state) return; // blocking test twi_transmitting = 0 ; if (twi_error == 0xFF) twi_Finish (0); // success else if (twi_error == TW_MT_SLA_NACK) twi_Finish (2); // error: address send, nack received else if (twi_error == TW_MT_DATA_NACK) twi_Finish (3); // error: data send, nack received else twi_Finish (4); // other twi error if (twi_cbendTransmissionDone) return twi_cbendTransmissionDone(twi_Return_Value); return; } void twi_write00() { if (TWI_READY != twi_state) return; // blocking test if (TWI_BUFFER_LENGTH < ptwv -> length) { twi_Finish(1); // end write with error 1 return; } twi_Done = 0x00; // show as working twii_SetState(TWI_MTX); // to transmitting twii_SetError(0xFF); // to No Error twii_InitBuffer(0, ptwv -> length); // pointer and length twii_CopyToBuf(ptwv -> data, ptwv -> length); // get the data twii_SetSlaRW((ptwv -> address << 1) | TW_WRITE); // write command twii_SetStart(); // start the cycle fNextInterruptFunction = twi_write01; // next routine return twi_write01(); } void twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait) { uint8_t i; ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars)); ptwv -> address = address; ptwv -> data = data; ptwv -> length = length; ptwv -> wait = wait; fNextInterruptFunction = twi_write00; return twi_write00(); } void twi_read01() { if (TWI_MRX == twi_state) return; // blocking test if (twi_masterBufferIndex < ptwv -> length) ptwv -> length = twi_masterBufferIndex; twii_CopyFromBuf(ptwv -> data, ptwv -> length); twi_Finish(ptwv -> length); if (twi_cbreadFromDone) return twi_cbreadFromDone(twi_Return_Value); return; } void twi_read00() { if (TWI_READY != twi_state) return; // blocking test if (TWI_BUFFER_LENGTH < ptwv -> length) twi_Finish(0); // error return twi_Done = 0x00; // show as working twii_SetState(TWI_MRX); // reading twii_SetError(0xFF); // reset error twii_InitBuffer(0, ptwv -> length - 1); // init to one less than length twii_SetSlaRW((ptwv -> address << 1) | TW_READ); // read command twii_SetStart(); // start cycle fNextInterruptFunction = twi_read01; return twi_read01(); } void twi_readFrom(uint8_t address, uint8_t* data, uint8_t length) { uint8_t i; ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars)); ptwv -> address = address; ptwv -> data = data; ptwv -> length = length; fNextInterruptFunction = twi_read00; return twi_read00(); } void twi_reply(uint8_t ack) { // transmit master read ready signal, with or without ack if (ack){ TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA); } else { TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT); } } void twi_stop(void) { // send stop condition TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO); // wait for stop condition to be exectued on bus // TWINT is not set after a stop condition! while (TWCR & _BV(TWSTO)) { continue; } // update twi state twi_state = TWI_READY; } void twi_releaseBus(void) { // release bus TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT); // update twi state twi_state = TWI_READY; } SIGNAL(TWI_vect) { switch (TW_STATUS) { // All Master case TW_START: // sent start condition case TW_REP_START: // sent repeated start condition // copy device address and r/w bit to output register and ack TWDR = twi_slarw; twi_reply(1); break; // Master Transmitter case TW_MT_SLA_ACK: // slave receiver acked address case TW_MT_DATA_ACK: // slave receiver acked data // if there is data to send, send it, otherwise stop if (twi_masterBufferIndex < twi_masterBufferLength) { // copy data to output register and ack TWDR = twi_masterBuffer[twi_masterBufferIndex++]; twi_reply(1); } else { twi_stop(); } break; case TW_MT_SLA_NACK: // address sent, nack received twi_error = TW_MT_SLA_NACK; twi_stop(); break; case TW_MT_DATA_NACK: // data sent, nack received twi_error = TW_MT_DATA_NACK; twi_stop(); break; case TW_MT_ARB_LOST: // lost bus arbitration twi_error = TW_MT_ARB_LOST; twi_releaseBus(); break; // Master Receiver case TW_MR_DATA_ACK: // data received, ack sent // put byte into buffer twi_masterBuffer[twi_masterBufferIndex++] = TWDR; case TW_MR_SLA_ACK: // address sent, ack received // ack if more bytes are expected, otherwise nack if (twi_masterBufferIndex < twi_masterBufferLength) { twi_reply(1); } else { twi_reply(0); } break; case TW_MR_DATA_NACK: // data received, nack sent // put final byte into buffer twi_masterBuffer[twi_masterBufferIndex++] = TWDR; case TW_MR_SLA_NACK: // address sent, nack received twi_stop(); break; // TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case // Slave Receiver (NOT IMPLEMENTED YET) /* case TW_SR_SLA_ACK: // addressed, returned ack case TW_SR_GCALL_ACK: // addressed generally, returned ack case TW_SR_ARB_LOST_SLA_ACK: // lost arbitration, returned ack case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack // enter slave receiver mode twi_state = TWI_SRX; // indicate that rx buffer can be overwritten and ack twi_rxBufferIndex = 0; twi_reply(1); break; case TW_SR_DATA_ACK: // data received, returned ack case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack // if there is still room in the rx buffer if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) { // put byte in buffer and ack twi_rxBuffer[twi_rxBufferIndex++] = TWDR; twi_reply(1); } else { // otherwise nack twi_reply(0); } break; case TW_SR_STOP: // stop or repeated start condition received // put a null char after data if there's room if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) { twi_rxBuffer[twi_rxBufferIndex] = 0; } // sends ack and stops interface for clock stretching twi_stop(); // callback to user defined callback twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex); // since we submit rx buffer to "wire" library, we can reset it twi_rxBufferIndex = 0; // ack future responses and leave slave receiver state twi_releaseBus(); break; case TW_SR_DATA_NACK: // data received, returned nack case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack // nack back at master twi_reply(0); break; // Slave Transmitter case TW_ST_SLA_ACK: // addressed, returned ack case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack // enter slave transmitter mode twi_state = TWI_STX; // ready the tx buffer index for iteration twi_txBufferIndex = 0; // set tx buffer length to be zero, to verify if user changes it twi_txBufferLength = 0; // request for txBuffer to be filled and length to be set // note: user must call twi_transmit(bytes, length) to do this twi_onSlaveTransmit(); // if they didn't change buffer & length, initialize it if (0 == twi_txBufferLength) { twi_txBufferLength = 1; twi_txBuffer[0] = 0x00; } // transmit first byte from buffer, fall through case TW_ST_DATA_ACK: // byte sent, ack returned // copy data to output register TWDR = twi_txBuffer[twi_txBufferIndex++]; // if there is more to send, ack, otherwise nack if (twi_txBufferIndex < twi_txBufferLength) { twi_reply(1); } else { twi_reply(0); } break; case TW_ST_DATA_NACK: // received nack, we are done case TW_ST_LAST_DATA: // received ack, but we are done already! // ack future responses twi_reply(1); // leave slave receiver state twi_state = TWI_READY; break; */ // all case TW_NO_INFO: // no state information break; case TW_BUS_ERROR: // bus error, illegal stop/start twi_error = TW_BUS_ERROR; twi_stop(); break; } if (fNextInterruptFunction) return fNextInterruptFunction(); } TwoWire::TwoWire() { } void TwoWire::begin(void) { rxBufferIndex = 0; rxBufferLength = 0; txBufferIndex = 0; txBufferLength = 0; twi_init(); } void TwoWire::beginTransmission(uint8_t address) { //beginTransmission((uint8_t)address); // indicate that we are transmitting twi_transmitting = 1; // set address of targeted slave txAddress = address; // reset tx buffer iterator vars txBufferIndex = 0; txBufferLength = 0; } uint8_t TwoWire::endTransmission(uint16_t timeout) { // transmit buffer (blocking) //int8_t ret = twi_cbendTransmissionDone = NULL; twi_writeTo(txAddress, txBuffer, txBufferLength, 1); int8_t ret = twii_WaitForDone(timeout); // reset tx buffer iterator vars txBufferIndex = 0; txBufferLength = 0; // indicate that we are done transmitting // twi_transmitting = 0; return ret; } void TwoWire::nbendTransmission(void (*function)(int)) { twi_cbendTransmissionDone = function; twi_writeTo(txAddress, txBuffer, txBufferLength, 1); return; } void TwoWire::send(uint8_t data) { if (twi_transmitting) { // in master transmitter mode // don't bother if buffer is full if (txBufferLength >= NBWIRE_BUFFER_LENGTH) { return; } // put byte in tx buffer txBuffer[txBufferIndex] = data; ++txBufferIndex; // update amount in buffer txBufferLength = txBufferIndex; } else { // in slave send mode // reply to master //twi_transmit(&data, 1); } } uint8_t TwoWire::receive(void) { // default to returning null char // for people using with char strings uint8_t value = 0; // get each successive byte on each call if (rxBufferIndex < rxBufferLength) { value = rxBuffer[rxBufferIndex]; ++rxBufferIndex; } return value; } uint8_t TwoWire::requestFrom(uint8_t address, int quantity, uint16_t timeout) { // clamp to buffer length if (quantity > NBWIRE_BUFFER_LENGTH) { quantity = NBWIRE_BUFFER_LENGTH; } // perform blocking read into buffer twi_cbreadFromDone = NULL; twi_readFrom(address, rxBuffer, quantity); uint8_t read = twii_WaitForDone(timeout); // set rx buffer iterator vars rxBufferIndex = 0; rxBufferLength = read; return read; } void TwoWire::nbrequestFrom(uint8_t address, int quantity, void (*function)(int)) { // clamp to buffer length if (quantity > NBWIRE_BUFFER_LENGTH) { quantity = NBWIRE_BUFFER_LENGTH; } // perform blocking read into buffer twi_cbreadFromDone = function; twi_readFrom(address, rxBuffer, quantity); //uint8_t read = twii_WaitForDone(); // set rx buffer iterator vars //rxBufferIndex = 0; //rxBufferLength = read; rxBufferIndex = 0; rxBufferLength = quantity; // this is a hack return; //read; } uint8_t TwoWire::available(void) { return rxBufferLength - rxBufferIndex; } #endif
f5d9b53f8c0a6a9d65dc2346eff555a1c9d94d33
c67b629c170cbaa451f671e3924ad2b281518eef
/src/Utils/Tools.hpp
8286cc981be655aa106ce5f52a1d1901043900d5
[]
no_license
LuhJunior/ody-unplugged-framework
491d37574a625324457647945cf63dccf2571f95
7e06955e73e04b87bd6b32c38c3730dfe7f3358b
refs/heads/master
2020-08-03T12:59:08.709495
2019-09-30T03:02:13
2019-09-30T03:02:26
211,760,243
0
0
null
null
null
null
UTF-8
C++
false
false
312
hpp
#ifndef TOOLS_H #define TOOLS_H #include <string> #include <algorithm> #include <bitset> #define find_val(v, val) find(v.begin(), v.end(), val); #define find_val_if(v, fn) find_if(v.begin(), v.end(), fn); using namespace std; class Tools { public: static string toBinary(int); }; #endif
c9273f0903f4ea9c8d6ccc606a1ae26832f8f478
44effb0a52482700ba06c067125d40fb8bea4b1e
/problems/Sith/main.cpp
f00f9f5c005cf8ba08e0bb9acf83db5c4f5b02f9
[]
no_license
elwin/algolab
1a1b91f0a0933d47494de5f8a87bbd073a6c7d4a
2030c2a97fae896666a408005122edee7ff8c666
refs/heads/master
2023-03-02T21:02:47.345039
2021-02-04T13:49:15
2021-02-04T13:49:15
297,578,975
0
0
null
null
null
null
UTF-8
C++
false
false
3,779
cpp
// After a given amount of time has passed, the largest possible score // that can be achieved corresponds to the either the time itself // or the largest connected subcomponent in the remaining graph, // whichever is smaller. // The largest connected subcomponent can be retrieved using // BFS after we've constructed a graph (either quadratically // or logarithmically using Delanauy, since we care for the // closest neighbors anyway). // Now to figure out how much time should pass we can use // binary search: The optimum is when score = time, since // at that point increasing time would decrease the availablee // nodes and thus score, decreasing time would decrease the // maximum possible score as well (since it is capped // using min(score, time)). // Note that score is a (non-strictly) monotonic increasing // function. Now, whenever the score is lower than time, // we can try to get closer to the maximum by // decreasing the maximum. Conversely, when // the score is higher than time, we can // get closer to the optimum by increaing time. #include <iostream> #include <vector> #include <queue> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Delaunay_triangulation_2.h> #include <CGAL/Triangulation_vertex_base_with_info_2.h> typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Triangulation_vertex_base_with_info_2<bool, K> Vb; typedef CGAL::Triangulation_face_base_2<K> Fb; typedef CGAL::Triangulation_data_structure_2<Vb,Fb> Tds; typedef CGAL::Delaunay_triangulation_2<K,Tds> Triangulation; size_t possible(std::vector<K::Point_2> &points, size_t time, long sqrt_dist) { Triangulation t; t.insert(points.begin() + time, points.end()); size_t max_score = 0; for (Triangulation::Vertex_iterator v = t.finite_vertices_begin(); v != t.finite_vertices_end(); ++v) { v->info() = false; } for (Triangulation::Vertex_iterator v = t.finite_vertices_begin(); v != t.finite_vertices_end(); ++v) { if (v->info() == true) continue; size_t cur_score = 0; std::queue<Triangulation::Vertex_handle> q; q.push(v); while (!q.empty()) { auto cur = q.front(); q.pop(); if (cur->info() == true) continue; cur->info() = true; cur_score++; Triangulation::Vertex_circulator next = t.incident_vertices(cur); do { if (t.is_infinite(next) || next->info() == true) continue; if (CGAL::squared_distance(cur->point(), next->point()) > sqrt_dist) continue; q.push(next); } while (++next != t.incident_vertices(cur)); } max_score = std::max(max_score, cur_score); } return max_score; } size_t testcase() { size_t n, r; std::cin >> n >> r; std::vector<K::Point_2> points(n); for (size_t i = 0; i < n; ++i) { int x, y; std::cin >> x >> y; points[i] = K::Point_2(x, y); } size_t low = 1; size_t high = n / 2; while (low < high) { size_t mid = low + (high - low) / 2; size_t score = possible(points, mid, r * r); // Found optimimum - can't do better than that // Increasing time would decrease the score, // decreasing time would decrease it naturally as well if (score == mid) return score; // Score is too low, can potentially improve by // lowering time if (score < mid) { high = mid - 1; } // Score is too high, looking for closer solution // by increasing time else { low = mid + 1; } } // Handle off by one error or so size_t score1 = std::min(low - 1, possible(points, low - 1, r * r)); size_t score2 = std::min(low, possible(points, low, r * r)); size_t score3 = std::min(low + 1, possible(points, low + 1, r * r)); return std::max(score1, std::max(score2, score3)); } int main() { std::ios_base::sync_with_stdio(false); size_t t; std::cin >> t; while (t--) std::cout << testcase() << std::endl; }
7fe72026f85310a7248b8ff61644eef96285cbc8
0835f475d673ecd1bed49a55e8f1abc8e39b8324
/drawingApp/src/ofApp.h
d04897b1c07c25ad9880edb0391e8a3b35714654
[]
no_license
terrybu/OpenFrameworksPracticeProjects
a486dd1beea4df5108e25a9c37c151da61573bcf
cd810b53f27c39f293f3a0fa10bfa9b0d773e892
refs/heads/master
2021-01-20T03:30:48.730172
2015-03-27T19:23:16
2015-03-27T19:23:16
33,005,102
0
0
null
null
null
null
UTF-8
C++
false
false
819
h
#pragma once #include "ofMain.h" #include "ofxiOS.h" #include "ofxiOSExtras.h" class ofApp : public ofxiOSApp { public: void setup(); void update(); void draw(); void exit(); void touchDown(ofTouchEventArgs & touch); void touchMoved(ofTouchEventArgs & touch); void touchUp(ofTouchEventArgs & touch); void touchDoubleTap(ofTouchEventArgs & touch); void touchCancelled(ofTouchEventArgs & touch); void lostFocus(); void gotFocus(); void gotMemoryWarning(); void deviceOrientationChanged(int newOrientation); ofPoint touchLoc; //画面をタッチしている場所 ofPoint lastTouchLoc; //ひとつ前のタッチしている場所 bool drawing; //ドロー中かどうか };
2dd07db27276d81e05afc137e1cf855d3de0b3fa
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_384_squid-3.4.14.cpp
c02ea882b1414769eaf4cef51e43d5df0467f33d
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
105
cpp
int Check_ifuserallowed(char *ConnectingUser) { return Check_userlist(&AllowUsers, ConnectingUser); }
8abb7f2c146d53de62309825a1e0c90cd8d98d77
4eb06b3b1808484da7dbd84d63a975a610459899
/src/ia32/lithium-ia32.h
1c490bb57160d52a82ef4722e170a9cce1eab3f2
[ "BSD-3-Clause", "bzip2-1.0.6" ]
permissive
playbar/v8-3.17.16.2
158ebaa7cc5f16fabf9f75ecc5310af59a9c944f
abd07495f67da323a5998d039b7b4326836ad1fb
refs/heads/master
2023-01-06T23:15:28.397273
2015-06-26T07:09:18
2015-06-26T07:09:18
37,173,453
0
1
NOASSERTION
2022-12-19T19:16:17
2015-06-10T03:34:20
C++
UTF-8
C++
false
false
80,395
h
// Copyright 2012 the V8 project authors. 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef V8_IA32_LITHIUM_IA32_H_ #define V8_IA32_LITHIUM_IA32_H_ #include "hydrogen.h" #include "lithium-allocator.h" #include "lithium.h" #include "safepoint-table.h" #include "utils.h" namespace v8 { namespace internal { // Forward declarations. class LCodeGen; #define LITHIUM_CONCRETE_INSTRUCTION_LIST(V) \ V(AccessArgumentsAt) \ V(AddI) \ V(Allocate) \ V(AllocateObject) \ V(ApplyArguments) \ V(ArgumentsElements) \ V(ArgumentsLength) \ V(ArithmeticD) \ V(ArithmeticT) \ V(ArrayLiteral) \ V(BitI) \ V(BitNotI) \ V(BoundsCheck) \ V(Branch) \ V(CallConstantFunction) \ V(CallFunction) \ V(CallGlobal) \ V(CallKeyed) \ V(CallKnownGlobal) \ V(CallNamed) \ V(CallNew) \ V(CallNewArray) \ V(CallRuntime) \ V(CallStub) \ V(CheckFunction) \ V(CheckInstanceType) \ V(CheckMaps) \ V(CheckNonSmi) \ V(CheckPrototypeMaps) \ V(CheckSmi) \ V(ClampDToUint8) \ V(ClampIToUint8) \ V(ClampTToUint8) \ V(ClassOfTestAndBranch) \ V(CmpIDAndBranch) \ V(CmpObjectEqAndBranch) \ V(CmpMapAndBranch) \ V(CmpT) \ V(CmpConstantEqAndBranch) \ V(ConstantD) \ V(ConstantI) \ V(ConstantT) \ V(Context) \ V(DeclareGlobals) \ V(DeleteProperty) \ V(Deoptimize) \ V(DivI) \ V(DoubleToI) \ V(DummyUse) \ V(ElementsKind) \ V(FastLiteral) \ V(FixedArrayBaseLength) \ V(FunctionLiteral) \ V(GetCachedArrayIndex) \ V(GlobalObject) \ V(GlobalReceiver) \ V(Goto) \ V(HasCachedArrayIndexAndBranch) \ V(HasInstanceTypeAndBranch) \ V(In) \ V(InstanceOf) \ V(InstanceOfKnownGlobal) \ V(InstanceSize) \ V(InstructionGap) \ V(Integer32ToDouble) \ V(Uint32ToDouble) \ V(InvokeFunction) \ V(IsConstructCallAndBranch) \ V(IsNilAndBranch) \ V(IsObjectAndBranch) \ V(IsStringAndBranch) \ V(IsSmiAndBranch) \ V(IsUndetectableAndBranch) \ V(Label) \ V(LazyBailout) \ V(LoadContextSlot) \ V(LoadElements) \ V(LoadExternalArrayPointer) \ V(LoadFunctionPrototype) \ V(LoadGlobalCell) \ V(LoadGlobalGeneric) \ V(LoadKeyed) \ V(LoadKeyedGeneric) \ V(LoadNamedField) \ V(LoadNamedFieldPolymorphic) \ V(LoadNamedGeneric) \ V(MapEnumLength) \ V(MathExp) \ V(MathFloorOfDiv) \ V(MathMinMax) \ V(MathPowHalf) \ V(MathRound) \ V(ModI) \ V(MulI) \ V(NumberTagD) \ V(NumberTagI) \ V(NumberTagU) \ V(NumberUntagD) \ V(ObjectLiteral) \ V(OsrEntry) \ V(OuterContext) \ V(Parameter) \ V(Power) \ V(Random) \ V(PushArgument) \ V(RegExpLiteral) \ V(Return) \ V(SeqStringSetChar) \ V(ShiftI) \ V(SmiTag) \ V(SmiUntag) \ V(StackCheck) \ V(StoreContextSlot) \ V(StoreGlobalCell) \ V(StoreGlobalGeneric) \ V(StoreKeyed) \ V(StoreKeyedGeneric) \ V(StoreNamedField) \ V(StoreNamedGeneric) \ V(StringAdd) \ V(StringCharCodeAt) \ V(StringCharFromCode) \ V(StringCompareAndBranch) \ V(StringLength) \ V(SubI) \ V(TaggedToI) \ V(ThisFunction) \ V(Throw) \ V(ToFastProperties) \ V(TransitionElementsKind) \ V(TrapAllocationMemento) \ V(Typeof) \ V(TypeofIsAndBranch) \ V(UnaryMathOperation) \ V(UnknownOSRValue) \ V(ValueOf) \ V(ForInPrepareMap) \ V(ForInCacheArray) \ V(CheckMapValue) \ V(LoadFieldByIndex) \ V(DateField) \ V(WrapReceiver) \ V(Drop) \ V(InnerAllocatedObject) #define DECLARE_CONCRETE_INSTRUCTION(type, mnemonic) \ virtual Opcode opcode() const { return LInstruction::k##type; } \ virtual void CompileToNative(LCodeGen* generator); \ virtual const char* Mnemonic() const { return mnemonic; } \ static L##type* cast(LInstruction* instr) { \ ASSERT(instr->Is##type()); \ return reinterpret_cast<L##type*>(instr); \ } #define DECLARE_HYDROGEN_ACCESSOR(type) \ H##type* hydrogen() const { \ return H##type::cast(hydrogen_value()); \ } class LInstruction: public ZoneObject { public: LInstruction() : environment_(NULL), hydrogen_value_(NULL), is_call_(false) { } virtual ~LInstruction() { } virtual void CompileToNative(LCodeGen* generator) = 0; virtual const char* Mnemonic() const = 0; virtual void PrintTo(StringStream* stream); virtual void PrintDataTo(StringStream* stream); virtual void PrintOutputOperandTo(StringStream* stream); enum Opcode { // Declare a unique enum value for each instruction. #define DECLARE_OPCODE(type) k##type, LITHIUM_CONCRETE_INSTRUCTION_LIST(DECLARE_OPCODE) kNumberOfInstructions #undef DECLARE_OPCODE }; virtual Opcode opcode() const = 0; // Declare non-virtual type testers for all leaf IR classes. #define DECLARE_PREDICATE(type) \ bool Is##type() const { return opcode() == k##type; } LITHIUM_CONCRETE_INSTRUCTION_LIST(DECLARE_PREDICATE) #undef DECLARE_PREDICATE // Declare virtual predicates for instructions that don't have // an opcode. virtual bool IsGap() const { return false; } virtual bool IsControl() const { return false; } void set_environment(LEnvironment* env) { environment_ = env; } LEnvironment* environment() const { return environment_; } bool HasEnvironment() const { return environment_ != NULL; } void set_pointer_map(LPointerMap* p) { pointer_map_.set(p); } LPointerMap* pointer_map() const { return pointer_map_.get(); } bool HasPointerMap() const { return pointer_map_.is_set(); } void set_hydrogen_value(HValue* value) { hydrogen_value_ = value; } HValue* hydrogen_value() const { return hydrogen_value_; } virtual void SetDeferredLazyDeoptimizationEnvironment(LEnvironment* env) { } void MarkAsCall() { is_call_ = true; } // Interface to the register allocator and iterators. bool ClobbersTemps() const { return is_call_; } bool ClobbersRegisters() const { return is_call_; } virtual bool ClobbersDoubleRegisters() const { return is_call_ || !CpuFeatures::IsSupported(SSE2); } virtual bool HasResult() const = 0; virtual LOperand* result() = 0; LOperand* FirstInput() { return InputAt(0); } LOperand* Output() { return HasResult() ? result() : NULL; } #ifdef DEBUG void VerifyCall(); #endif private: // Iterator support. friend class InputIterator; virtual int InputCount() = 0; virtual LOperand* InputAt(int i) = 0; friend class TempIterator; virtual int TempCount() = 0; virtual LOperand* TempAt(int i) = 0; LEnvironment* environment_; SetOncePointer<LPointerMap> pointer_map_; HValue* hydrogen_value_; bool is_call_; }; // R = number of result operands (0 or 1). // I = number of input operands. // T = number of temporary operands. template<int R, int I, int T> class LTemplateInstruction: public LInstruction { public: // Allow 0 or 1 output operands. STATIC_ASSERT(R == 0 || R == 1); virtual bool HasResult() const { return R != 0; } void set_result(LOperand* operand) { results_[0] = operand; } LOperand* result() { return results_[0]; } protected: EmbeddedContainer<LOperand*, R> results_; EmbeddedContainer<LOperand*, I> inputs_; EmbeddedContainer<LOperand*, T> temps_; private: // Iterator support. virtual int InputCount() { return I; } virtual LOperand* InputAt(int i) { return inputs_[i]; } virtual int TempCount() { return T; } virtual LOperand* TempAt(int i) { return temps_[i]; } }; class LGap: public LTemplateInstruction<0, 0, 0> { public: explicit LGap(HBasicBlock* block) : block_(block) { parallel_moves_[BEFORE] = NULL; parallel_moves_[START] = NULL; parallel_moves_[END] = NULL; parallel_moves_[AFTER] = NULL; } // Can't use the DECLARE-macro here because of sub-classes. virtual bool IsGap() const { return true; } virtual void PrintDataTo(StringStream* stream); static LGap* cast(LInstruction* instr) { ASSERT(instr->IsGap()); return reinterpret_cast<LGap*>(instr); } bool IsRedundant() const; HBasicBlock* block() const { return block_; } enum InnerPosition { BEFORE, START, END, AFTER, FIRST_INNER_POSITION = BEFORE, LAST_INNER_POSITION = AFTER }; LParallelMove* GetOrCreateParallelMove(InnerPosition pos, Zone* zone) { if (parallel_moves_[pos] == NULL) { parallel_moves_[pos] = new(zone) LParallelMove(zone); } return parallel_moves_[pos]; } LParallelMove* GetParallelMove(InnerPosition pos) { return parallel_moves_[pos]; } private: LParallelMove* parallel_moves_[LAST_INNER_POSITION + 1]; HBasicBlock* block_; }; class LInstructionGap: public LGap { public: explicit LInstructionGap(HBasicBlock* block) : LGap(block) { } virtual bool ClobbersDoubleRegisters() const { return false; } DECLARE_CONCRETE_INSTRUCTION(InstructionGap, "gap") }; class LGoto: public LTemplateInstruction<0, 0, 0> { public: explicit LGoto(int block_id) : block_id_(block_id) { } DECLARE_CONCRETE_INSTRUCTION(Goto, "goto") virtual void PrintDataTo(StringStream* stream); virtual bool IsControl() const { return true; } int block_id() const { return block_id_; } private: int block_id_; }; class LLazyBailout: public LTemplateInstruction<0, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(LazyBailout, "lazy-bailout") }; class LDummyUse: public LTemplateInstruction<1, 1, 0> { public: explicit LDummyUse(LOperand* value) { inputs_[0] = value; } DECLARE_CONCRETE_INSTRUCTION(DummyUse, "dummy-use") }; class LDeoptimize: public LTemplateInstruction<0, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(Deoptimize, "deoptimize") }; class LLabel: public LGap { public: explicit LLabel(HBasicBlock* block) : LGap(block), replacement_(NULL) { } DECLARE_CONCRETE_INSTRUCTION(Label, "label") virtual void PrintDataTo(StringStream* stream); int block_id() const { return block()->block_id(); } bool is_loop_header() const { return block()->IsLoopHeader(); } Label* label() { return &label_; } LLabel* replacement() const { return replacement_; } void set_replacement(LLabel* label) { replacement_ = label; } bool HasReplacement() const { return replacement_ != NULL; } private: Label label_; LLabel* replacement_; }; class LParameter: public LTemplateInstruction<1, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(Parameter, "parameter") }; class LCallStub: public LTemplateInstruction<1, 1, 0> { public: explicit LCallStub(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(CallStub, "call-stub") DECLARE_HYDROGEN_ACCESSOR(CallStub) TranscendentalCache::Type transcendental_type() { return hydrogen()->transcendental_type(); } }; class LUnknownOSRValue: public LTemplateInstruction<1, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(UnknownOSRValue, "unknown-osr-value") }; template<int I, int T> class LControlInstruction: public LTemplateInstruction<0, I, T> { public: virtual bool IsControl() const { return true; } int SuccessorCount() { return hydrogen()->SuccessorCount(); } HBasicBlock* SuccessorAt(int i) { return hydrogen()->SuccessorAt(i); } int true_block_id() { return hydrogen()->SuccessorAt(0)->block_id(); } int false_block_id() { return hydrogen()->SuccessorAt(1)->block_id(); } private: HControlInstruction* hydrogen() { return HControlInstruction::cast(this->hydrogen_value()); } }; class LWrapReceiver: public LTemplateInstruction<1, 2, 1> { public: LWrapReceiver(LOperand* receiver, LOperand* function, LOperand* temp) { inputs_[0] = receiver; inputs_[1] = function; temps_[0] = temp; } LOperand* receiver() { return inputs_[0]; } LOperand* function() { return inputs_[1]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(WrapReceiver, "wrap-receiver") }; class LApplyArguments: public LTemplateInstruction<1, 4, 0> { public: LApplyArguments(LOperand* function, LOperand* receiver, LOperand* length, LOperand* elements) { inputs_[0] = function; inputs_[1] = receiver; inputs_[2] = length; inputs_[3] = elements; } LOperand* function() { return inputs_[0]; } LOperand* receiver() { return inputs_[1]; } LOperand* length() { return inputs_[2]; } LOperand* elements() { return inputs_[3]; } DECLARE_CONCRETE_INSTRUCTION(ApplyArguments, "apply-arguments") }; class LAccessArgumentsAt: public LTemplateInstruction<1, 3, 0> { public: LAccessArgumentsAt(LOperand* arguments, LOperand* length, LOperand* index) { inputs_[0] = arguments; inputs_[1] = length; inputs_[2] = index; } LOperand* arguments() { return inputs_[0]; } LOperand* length() { return inputs_[1]; } LOperand* index() { return inputs_[2]; } DECLARE_CONCRETE_INSTRUCTION(AccessArgumentsAt, "access-arguments-at") virtual void PrintDataTo(StringStream* stream); }; class LArgumentsLength: public LTemplateInstruction<1, 1, 0> { public: explicit LArgumentsLength(LOperand* elements) { inputs_[0] = elements; } LOperand* elements() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(ArgumentsLength, "arguments-length") }; class LArgumentsElements: public LTemplateInstruction<1, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(ArgumentsElements, "arguments-elements") DECLARE_HYDROGEN_ACCESSOR(ArgumentsElements) }; class LModI: public LTemplateInstruction<1, 2, 1> { public: LModI(LOperand* left, LOperand* right, LOperand* temp) { inputs_[0] = left; inputs_[1] = right; temps_[0] = temp; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(ModI, "mod-i") DECLARE_HYDROGEN_ACCESSOR(Mod) }; class LDivI: public LTemplateInstruction<1, 2, 1> { public: LDivI(LOperand* left, LOperand* right, LOperand* temp) { inputs_[0] = left; inputs_[1] = right; temps_[0] = temp; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } bool is_flooring() { return hydrogen_value()->IsMathFloorOfDiv(); } DECLARE_CONCRETE_INSTRUCTION(DivI, "div-i") DECLARE_HYDROGEN_ACCESSOR(Div) }; class LMathFloorOfDiv: public LTemplateInstruction<1, 2, 1> { public: LMathFloorOfDiv(LOperand* left, LOperand* right, LOperand* temp = NULL) { inputs_[0] = left; inputs_[1] = right; temps_[0] = temp; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(MathFloorOfDiv, "math-floor-of-div") DECLARE_HYDROGEN_ACCESSOR(MathFloorOfDiv) }; class LMulI: public LTemplateInstruction<1, 2, 1> { public: LMulI(LOperand* left, LOperand* right, LOperand* temp) { inputs_[0] = left; inputs_[1] = right; temps_[0] = temp; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(MulI, "mul-i") DECLARE_HYDROGEN_ACCESSOR(Mul) }; class LCmpIDAndBranch: public LControlInstruction<2, 0> { public: LCmpIDAndBranch(LOperand* left, LOperand* right) { inputs_[0] = left; inputs_[1] = right; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(CmpIDAndBranch, "cmp-id-and-branch") DECLARE_HYDROGEN_ACCESSOR(CompareIDAndBranch) Token::Value op() const { return hydrogen()->token(); } bool is_double() const { return hydrogen()->representation().IsDouble(); } virtual void PrintDataTo(StringStream* stream); }; class LUnaryMathOperation: public LTemplateInstruction<1, 2, 0> { public: LUnaryMathOperation(LOperand* context, LOperand* value) { inputs_[1] = context; inputs_[0] = value; } LOperand* context() { return inputs_[1]; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(UnaryMathOperation, "unary-math-operation") DECLARE_HYDROGEN_ACCESSOR(UnaryMathOperation) virtual void PrintDataTo(StringStream* stream); BuiltinFunctionId op() const { return hydrogen()->op(); } }; class LMathExp: public LTemplateInstruction<1, 1, 2> { public: LMathExp(LOperand* value, LOperand* temp1, LOperand* temp2) { inputs_[0] = value; temps_[0] = temp1; temps_[1] = temp2; ExternalReference::InitializeMathExpData(); } LOperand* value() { return inputs_[0]; } LOperand* temp1() { return temps_[0]; } LOperand* temp2() { return temps_[1]; } DECLARE_CONCRETE_INSTRUCTION(MathExp, "math-exp") virtual void PrintDataTo(StringStream* stream); }; class LMathPowHalf: public LTemplateInstruction<1, 2, 1> { public: LMathPowHalf(LOperand* context, LOperand* value, LOperand* temp) { inputs_[1] = context; inputs_[0] = value; temps_[0] = temp; } LOperand* context() { return inputs_[1]; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(MathPowHalf, "math-pow-half") virtual void PrintDataTo(StringStream* stream); }; class LMathRound: public LTemplateInstruction<1, 2, 1> { public: LMathRound(LOperand* context, LOperand* value, LOperand* temp) { inputs_[1] = context; inputs_[0] = value; temps_[0] = temp; } LOperand* context() { return inputs_[1]; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(MathRound, "math-round") DECLARE_HYDROGEN_ACCESSOR(UnaryMathOperation) virtual void PrintDataTo(StringStream* stream); }; class LCmpObjectEqAndBranch: public LControlInstruction<2, 0> { public: LCmpObjectEqAndBranch(LOperand* left, LOperand* right) { inputs_[0] = left; inputs_[1] = right; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(CmpObjectEqAndBranch, "cmp-object-eq-and-branch") }; class LCmpConstantEqAndBranch: public LControlInstruction<1, 0> { public: explicit LCmpConstantEqAndBranch(LOperand* left) { inputs_[0] = left; } LOperand* left() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(CmpConstantEqAndBranch, "cmp-constant-eq-and-branch") DECLARE_HYDROGEN_ACCESSOR(CompareConstantEqAndBranch) }; class LIsNilAndBranch: public LControlInstruction<1, 1> { public: LIsNilAndBranch(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(IsNilAndBranch, "is-nil-and-branch") DECLARE_HYDROGEN_ACCESSOR(IsNilAndBranch) EqualityKind kind() const { return hydrogen()->kind(); } NilValue nil() const { return hydrogen()->nil(); } virtual void PrintDataTo(StringStream* stream); }; class LIsObjectAndBranch: public LControlInstruction<1, 1> { public: LIsObjectAndBranch(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(IsObjectAndBranch, "is-object-and-branch") virtual void PrintDataTo(StringStream* stream); }; class LIsStringAndBranch: public LControlInstruction<1, 1> { public: LIsStringAndBranch(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(IsStringAndBranch, "is-string-and-branch") virtual void PrintDataTo(StringStream* stream); }; class LIsSmiAndBranch: public LControlInstruction<1, 0> { public: explicit LIsSmiAndBranch(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(IsSmiAndBranch, "is-smi-and-branch") DECLARE_HYDROGEN_ACCESSOR(IsSmiAndBranch) virtual void PrintDataTo(StringStream* stream); }; class LIsUndetectableAndBranch: public LControlInstruction<1, 1> { public: LIsUndetectableAndBranch(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(IsUndetectableAndBranch, "is-undetectable-and-branch") virtual void PrintDataTo(StringStream* stream); }; class LStringCompareAndBranch: public LControlInstruction<3, 0> { public: LStringCompareAndBranch(LOperand* context, LOperand* left, LOperand* right) { inputs_[0] = context; inputs_[1] = left; inputs_[2] = right; } LOperand* left() { return inputs_[1]; } LOperand* right() { return inputs_[2]; } DECLARE_CONCRETE_INSTRUCTION(StringCompareAndBranch, "string-compare-and-branch") DECLARE_HYDROGEN_ACCESSOR(StringCompareAndBranch) virtual void PrintDataTo(StringStream* stream); Token::Value op() const { return hydrogen()->token(); } }; class LHasInstanceTypeAndBranch: public LControlInstruction<1, 1> { public: LHasInstanceTypeAndBranch(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(HasInstanceTypeAndBranch, "has-instance-type-and-branch") DECLARE_HYDROGEN_ACCESSOR(HasInstanceTypeAndBranch) virtual void PrintDataTo(StringStream* stream); }; class LGetCachedArrayIndex: public LTemplateInstruction<1, 1, 0> { public: explicit LGetCachedArrayIndex(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(GetCachedArrayIndex, "get-cached-array-index") DECLARE_HYDROGEN_ACCESSOR(GetCachedArrayIndex) }; class LHasCachedArrayIndexAndBranch: public LControlInstruction<1, 0> { public: explicit LHasCachedArrayIndexAndBranch(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(HasCachedArrayIndexAndBranch, "has-cached-array-index-and-branch") virtual void PrintDataTo(StringStream* stream); }; class LIsConstructCallAndBranch: public LControlInstruction<0, 1> { public: explicit LIsConstructCallAndBranch(LOperand* temp) { temps_[0] = temp; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(IsConstructCallAndBranch, "is-construct-call-and-branch") }; class LClassOfTestAndBranch: public LControlInstruction<1, 2> { public: LClassOfTestAndBranch(LOperand* value, LOperand* temp, LOperand* temp2) { inputs_[0] = value; temps_[0] = temp; temps_[1] = temp2; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } LOperand* temp2() { return temps_[1]; } DECLARE_CONCRETE_INSTRUCTION(ClassOfTestAndBranch, "class-of-test-and-branch") DECLARE_HYDROGEN_ACCESSOR(ClassOfTestAndBranch) virtual void PrintDataTo(StringStream* stream); }; class LCmpT: public LTemplateInstruction<1, 3, 0> { public: LCmpT(LOperand* context, LOperand* left, LOperand* right) { inputs_[0] = context; inputs_[1] = left; inputs_[2] = right; } DECLARE_CONCRETE_INSTRUCTION(CmpT, "cmp-t") DECLARE_HYDROGEN_ACCESSOR(CompareGeneric) Token::Value op() const { return hydrogen()->token(); } }; class LInstanceOf: public LTemplateInstruction<1, 3, 0> { public: LInstanceOf(LOperand* context, LOperand* left, LOperand* right) { inputs_[0] = context; inputs_[1] = left; inputs_[2] = right; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(InstanceOf, "instance-of") }; class LInstanceOfKnownGlobal: public LTemplateInstruction<1, 2, 1> { public: LInstanceOfKnownGlobal(LOperand* context, LOperand* value, LOperand* temp) { inputs_[0] = context; inputs_[1] = value; temps_[0] = temp; } LOperand* value() { return inputs_[1]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(InstanceOfKnownGlobal, "instance-of-known-global") DECLARE_HYDROGEN_ACCESSOR(InstanceOfKnownGlobal) Handle<JSFunction> function() const { return hydrogen()->function(); } LEnvironment* GetDeferredLazyDeoptimizationEnvironment() { return lazy_deopt_env_; } virtual void SetDeferredLazyDeoptimizationEnvironment(LEnvironment* env) { lazy_deopt_env_ = env; } private: LEnvironment* lazy_deopt_env_; }; class LInstanceSize: public LTemplateInstruction<1, 1, 0> { public: explicit LInstanceSize(LOperand* object) { inputs_[0] = object; } LOperand* object() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(InstanceSize, "instance-size") DECLARE_HYDROGEN_ACCESSOR(InstanceSize) }; class LBoundsCheck: public LTemplateInstruction<0, 2, 0> { public: LBoundsCheck(LOperand* index, LOperand* length) { inputs_[0] = index; inputs_[1] = length; } LOperand* index() { return inputs_[0]; } LOperand* length() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(BoundsCheck, "bounds-check") DECLARE_HYDROGEN_ACCESSOR(BoundsCheck) }; class LBitI: public LTemplateInstruction<1, 2, 0> { public: LBitI(LOperand* left, LOperand* right) { inputs_[0] = left; inputs_[1] = right; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(BitI, "bit-i") DECLARE_HYDROGEN_ACCESSOR(Bitwise) Token::Value op() const { return hydrogen()->op(); } }; class LShiftI: public LTemplateInstruction<1, 2, 0> { public: LShiftI(Token::Value op, LOperand* left, LOperand* right, bool can_deopt) : op_(op), can_deopt_(can_deopt) { inputs_[0] = left; inputs_[1] = right; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(ShiftI, "shift-i") Token::Value op() const { return op_; } bool can_deopt() const { return can_deopt_; } private: Token::Value op_; bool can_deopt_; }; class LSubI: public LTemplateInstruction<1, 2, 0> { public: LSubI(LOperand* left, LOperand* right) { inputs_[0] = left; inputs_[1] = right; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(SubI, "sub-i") DECLARE_HYDROGEN_ACCESSOR(Sub) }; class LConstantI: public LTemplateInstruction<1, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(ConstantI, "constant-i") DECLARE_HYDROGEN_ACCESSOR(Constant) int32_t value() const { return hydrogen()->Integer32Value(); } }; class LConstantD: public LTemplateInstruction<1, 0, 1> { public: explicit LConstantD(LOperand* temp) { temps_[0] = temp; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(ConstantD, "constant-d") DECLARE_HYDROGEN_ACCESSOR(Constant) double value() const { return hydrogen()->DoubleValue(); } }; class LConstantT: public LTemplateInstruction<1, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(ConstantT, "constant-t") DECLARE_HYDROGEN_ACCESSOR(Constant) Handle<Object> value() const { return hydrogen()->handle(); } }; class LBranch: public LControlInstruction<1, 1> { public: LBranch(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(Branch, "branch") DECLARE_HYDROGEN_ACCESSOR(Branch) virtual void PrintDataTo(StringStream* stream); }; class LCmpMapAndBranch: public LTemplateInstruction<0, 1, 0> { public: explicit LCmpMapAndBranch(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(CmpMapAndBranch, "cmp-map-and-branch") DECLARE_HYDROGEN_ACCESSOR(CompareMap) virtual bool IsControl() const { return true; } Handle<Map> map() const { return hydrogen()->map(); } int true_block_id() const { return hydrogen()->FirstSuccessor()->block_id(); } int false_block_id() const { return hydrogen()->SecondSuccessor()->block_id(); } }; class LFixedArrayBaseLength: public LTemplateInstruction<1, 1, 0> { public: explicit LFixedArrayBaseLength(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(FixedArrayBaseLength, "fixed-array-base-length") DECLARE_HYDROGEN_ACCESSOR(FixedArrayBaseLength) }; class LMapEnumLength: public LTemplateInstruction<1, 1, 0> { public: explicit LMapEnumLength(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(MapEnumLength, "map-enum-length") }; class LElementsKind: public LTemplateInstruction<1, 1, 0> { public: explicit LElementsKind(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(ElementsKind, "elements-kind") DECLARE_HYDROGEN_ACCESSOR(ElementsKind) }; class LValueOf: public LTemplateInstruction<1, 1, 1> { public: LValueOf(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(ValueOf, "value-of") DECLARE_HYDROGEN_ACCESSOR(ValueOf) }; class LDateField: public LTemplateInstruction<1, 1, 1> { public: LDateField(LOperand* date, LOperand* temp, Smi* index) : index_(index) { inputs_[0] = date; temps_[0] = temp; } LOperand* date() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(DateField, "date-field") DECLARE_HYDROGEN_ACCESSOR(DateField) Smi* index() const { return index_; } private: Smi* index_; }; class LSeqStringSetChar: public LTemplateInstruction<1, 3, 0> { public: LSeqStringSetChar(String::Encoding encoding, LOperand* string, LOperand* index, LOperand* value) : encoding_(encoding) { inputs_[0] = string; inputs_[1] = index; inputs_[2] = value; } String::Encoding encoding() { return encoding_; } LOperand* string() { return inputs_[0]; } LOperand* index() { return inputs_[1]; } LOperand* value() { return inputs_[2]; } DECLARE_CONCRETE_INSTRUCTION(SeqStringSetChar, "seq-string-set-char") DECLARE_HYDROGEN_ACCESSOR(SeqStringSetChar) private: String::Encoding encoding_; }; class LThrow: public LTemplateInstruction<0, 2, 0> { public: LThrow(LOperand* context, LOperand* value) { inputs_[0] = context; inputs_[1] = value; } LOperand* context() { return inputs_[0]; } LOperand* value() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(Throw, "throw") }; class LBitNotI: public LTemplateInstruction<1, 1, 0> { public: explicit LBitNotI(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(BitNotI, "bit-not-i") }; class LAddI: public LTemplateInstruction<1, 2, 0> { public: LAddI(LOperand* left, LOperand* right) { inputs_[0] = left; inputs_[1] = right; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(AddI, "add-i") DECLARE_HYDROGEN_ACCESSOR(Add) }; class LMathMinMax: public LTemplateInstruction<1, 2, 0> { public: LMathMinMax(LOperand* left, LOperand* right) { inputs_[0] = left; inputs_[1] = right; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(MathMinMax, "min-max") DECLARE_HYDROGEN_ACCESSOR(MathMinMax) }; class LPower: public LTemplateInstruction<1, 2, 0> { public: LPower(LOperand* left, LOperand* right) { inputs_[0] = left; inputs_[1] = right; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(Power, "power") DECLARE_HYDROGEN_ACCESSOR(Power) }; class LRandom: public LTemplateInstruction<1, 1, 0> { public: explicit LRandom(LOperand* global_object) { inputs_[0] = global_object; } LOperand* global_object() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(Random, "random") DECLARE_HYDROGEN_ACCESSOR(Random) }; class LArithmeticD: public LTemplateInstruction<1, 2, 0> { public: LArithmeticD(Token::Value op, LOperand* left, LOperand* right) : op_(op) { inputs_[0] = left; inputs_[1] = right; } LOperand* left() { return inputs_[0]; } LOperand* right() { return inputs_[1]; } Token::Value op() const { return op_; } virtual Opcode opcode() const { return LInstruction::kArithmeticD; } virtual void CompileToNative(LCodeGen* generator); virtual const char* Mnemonic() const; private: Token::Value op_; }; class LArithmeticT: public LTemplateInstruction<1, 3, 0> { public: LArithmeticT(Token::Value op, LOperand* context, LOperand* left, LOperand* right) : op_(op) { inputs_[0] = context; inputs_[1] = left; inputs_[2] = right; } LOperand* context() { return inputs_[0]; } LOperand* left() { return inputs_[1]; } LOperand* right() { return inputs_[2]; } virtual Opcode opcode() const { return LInstruction::kArithmeticT; } virtual void CompileToNative(LCodeGen* generator); virtual const char* Mnemonic() const; Token::Value op() const { return op_; } private: Token::Value op_; }; class LReturn: public LTemplateInstruction<0, 3, 0> { public: explicit LReturn(LOperand* value, LOperand* context, LOperand* parameter_count) { inputs_[0] = value; inputs_[1] = context; inputs_[2] = parameter_count; } bool has_constant_parameter_count() { return parameter_count()->IsConstantOperand(); } LConstantOperand* constant_parameter_count() { ASSERT(has_constant_parameter_count()); return LConstantOperand::cast(parameter_count()); } LOperand* parameter_count() { return inputs_[2]; } DECLARE_CONCRETE_INSTRUCTION(Return, "return") }; class LLoadNamedField: public LTemplateInstruction<1, 1, 0> { public: explicit LLoadNamedField(LOperand* object) { inputs_[0] = object; } LOperand* object() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(LoadNamedField, "load-named-field") DECLARE_HYDROGEN_ACCESSOR(LoadNamedField) }; class LLoadNamedFieldPolymorphic: public LTemplateInstruction<1, 2, 0> { public: LLoadNamedFieldPolymorphic(LOperand* context, LOperand* object) { inputs_[0] = context; inputs_[1] = object; } LOperand* context() { return inputs_[0]; } LOperand* object() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(LoadNamedField, "load-named-field-polymorphic") DECLARE_HYDROGEN_ACCESSOR(LoadNamedFieldPolymorphic) }; class LLoadNamedGeneric: public LTemplateInstruction<1, 2, 0> { public: LLoadNamedGeneric(LOperand* context, LOperand* object) { inputs_[0] = context; inputs_[1] = object; } LOperand* context() { return inputs_[0]; } LOperand* object() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(LoadNamedGeneric, "load-named-generic") DECLARE_HYDROGEN_ACCESSOR(LoadNamedGeneric) Handle<Object> name() const { return hydrogen()->name(); } }; class LLoadFunctionPrototype: public LTemplateInstruction<1, 1, 1> { public: LLoadFunctionPrototype(LOperand* function, LOperand* temp) { inputs_[0] = function; temps_[0] = temp; } LOperand* function() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(LoadFunctionPrototype, "load-function-prototype") DECLARE_HYDROGEN_ACCESSOR(LoadFunctionPrototype) }; class LLoadElements: public LTemplateInstruction<1, 1, 0> { public: explicit LLoadElements(LOperand* object) { inputs_[0] = object; } LOperand* object() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(LoadElements, "load-elements") }; class LLoadExternalArrayPointer: public LTemplateInstruction<1, 1, 0> { public: explicit LLoadExternalArrayPointer(LOperand* object) { inputs_[0] = object; } LOperand* object() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(LoadExternalArrayPointer, "load-external-array-pointer") }; class LLoadKeyed: public LTemplateInstruction<1, 2, 0> { public: LLoadKeyed(LOperand* elements, LOperand* key) { inputs_[0] = elements; inputs_[1] = key; } LOperand* elements() { return inputs_[0]; } LOperand* key() { return inputs_[1]; } ElementsKind elements_kind() const { return hydrogen()->elements_kind(); } bool is_external() const { return hydrogen()->is_external(); } virtual bool ClobbersDoubleRegisters() const { return !CpuFeatures::IsSupported(SSE2) && !IsDoubleOrFloatElementsKind(hydrogen()->elements_kind()); } DECLARE_CONCRETE_INSTRUCTION(LoadKeyed, "load-keyed") DECLARE_HYDROGEN_ACCESSOR(LoadKeyed) virtual void PrintDataTo(StringStream* stream); uint32_t additional_index() const { return hydrogen()->index_offset(); } bool key_is_smi() { return hydrogen()->key()->representation().IsTagged(); } }; inline static bool ExternalArrayOpRequiresTemp( Representation key_representation, ElementsKind elements_kind) { // Operations that require the key to be divided by two to be converted into // an index cannot fold the scale operation into a load and need an extra // temp register to do the work. return key_representation.IsTagged() && (elements_kind == EXTERNAL_BYTE_ELEMENTS || elements_kind == EXTERNAL_UNSIGNED_BYTE_ELEMENTS || elements_kind == EXTERNAL_PIXEL_ELEMENTS); } class LLoadKeyedGeneric: public LTemplateInstruction<1, 3, 0> { public: LLoadKeyedGeneric(LOperand* context, LOperand* obj, LOperand* key) { inputs_[0] = context; inputs_[1] = obj; inputs_[2] = key; } LOperand* context() { return inputs_[0]; } LOperand* object() { return inputs_[1]; } LOperand* key() { return inputs_[2]; } DECLARE_CONCRETE_INSTRUCTION(LoadKeyedGeneric, "load-keyed-generic") }; class LLoadGlobalCell: public LTemplateInstruction<1, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(LoadGlobalCell, "load-global-cell") DECLARE_HYDROGEN_ACCESSOR(LoadGlobalCell) }; class LLoadGlobalGeneric: public LTemplateInstruction<1, 2, 0> { public: LLoadGlobalGeneric(LOperand* context, LOperand* global_object) { inputs_[0] = context; inputs_[1] = global_object; } LOperand* context() { return inputs_[0]; } LOperand* global_object() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(LoadGlobalGeneric, "load-global-generic") DECLARE_HYDROGEN_ACCESSOR(LoadGlobalGeneric) Handle<Object> name() const { return hydrogen()->name(); } bool for_typeof() const { return hydrogen()->for_typeof(); } }; class LStoreGlobalCell: public LTemplateInstruction<0, 1, 0> { public: explicit LStoreGlobalCell(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(StoreGlobalCell, "store-global-cell") DECLARE_HYDROGEN_ACCESSOR(StoreGlobalCell) }; class LStoreGlobalGeneric: public LTemplateInstruction<0, 3, 0> { public: LStoreGlobalGeneric(LOperand* context, LOperand* global_object, LOperand* value) { inputs_[0] = context; inputs_[1] = global_object; inputs_[2] = value; } LOperand* context() { return inputs_[0]; } LOperand* global_object() { return inputs_[1]; } LOperand* value() { return inputs_[2]; } DECLARE_CONCRETE_INSTRUCTION(StoreGlobalGeneric, "store-global-generic") DECLARE_HYDROGEN_ACCESSOR(StoreGlobalGeneric) Handle<Object> name() const { return hydrogen()->name(); } StrictModeFlag strict_mode_flag() { return hydrogen()->strict_mode_flag(); } }; class LLoadContextSlot: public LTemplateInstruction<1, 1, 0> { public: explicit LLoadContextSlot(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(LoadContextSlot, "load-context-slot") DECLARE_HYDROGEN_ACCESSOR(LoadContextSlot) int slot_index() { return hydrogen()->slot_index(); } virtual void PrintDataTo(StringStream* stream); }; class LStoreContextSlot: public LTemplateInstruction<0, 2, 1> { public: LStoreContextSlot(LOperand* context, LOperand* value, LOperand* temp) { inputs_[0] = context; inputs_[1] = value; temps_[0] = temp; } LOperand* context() { return inputs_[0]; } LOperand* value() { return inputs_[1]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(StoreContextSlot, "store-context-slot") DECLARE_HYDROGEN_ACCESSOR(StoreContextSlot) int slot_index() { return hydrogen()->slot_index(); } virtual void PrintDataTo(StringStream* stream); }; class LPushArgument: public LTemplateInstruction<0, 1, 0> { public: explicit LPushArgument(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(PushArgument, "push-argument") }; class LDrop: public LTemplateInstruction<0, 0, 0> { public: explicit LDrop(int count) : count_(count) { } int count() const { return count_; } DECLARE_CONCRETE_INSTRUCTION(Drop, "drop") private: int count_; }; class LInnerAllocatedObject: public LTemplateInstruction<1, 1, 0> { public: explicit LInnerAllocatedObject(LOperand* base_object) { inputs_[0] = base_object; } LOperand* base_object() { return inputs_[0]; } int offset() { return hydrogen()->offset(); } virtual void PrintDataTo(StringStream* stream); DECLARE_CONCRETE_INSTRUCTION(InnerAllocatedObject, "sub-allocated-object") DECLARE_HYDROGEN_ACCESSOR(InnerAllocatedObject) }; class LThisFunction: public LTemplateInstruction<1, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(ThisFunction, "this-function") DECLARE_HYDROGEN_ACCESSOR(ThisFunction) }; class LContext: public LTemplateInstruction<1, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(Context, "context") DECLARE_HYDROGEN_ACCESSOR(Context) }; class LOuterContext: public LTemplateInstruction<1, 1, 0> { public: explicit LOuterContext(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(OuterContext, "outer-context") }; class LDeclareGlobals: public LTemplateInstruction<0, 1, 0> { public: explicit LDeclareGlobals(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(DeclareGlobals, "declare-globals") DECLARE_HYDROGEN_ACCESSOR(DeclareGlobals) }; class LGlobalObject: public LTemplateInstruction<1, 1, 0> { public: explicit LGlobalObject(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(GlobalObject, "global-object") }; class LGlobalReceiver: public LTemplateInstruction<1, 1, 0> { public: explicit LGlobalReceiver(LOperand* global_object) { inputs_[0] = global_object; } LOperand* global() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(GlobalReceiver, "global-receiver") }; class LCallConstantFunction: public LTemplateInstruction<1, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(CallConstantFunction, "call-constant-function") DECLARE_HYDROGEN_ACCESSOR(CallConstantFunction) virtual void PrintDataTo(StringStream* stream); Handle<JSFunction> function() { return hydrogen()->function(); } int arity() const { return hydrogen()->argument_count() - 1; } }; class LInvokeFunction: public LTemplateInstruction<1, 2, 0> { public: LInvokeFunction(LOperand* context, LOperand* function) { inputs_[0] = context; inputs_[1] = function; } LOperand* context() { return inputs_[0]; } LOperand* function() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(InvokeFunction, "invoke-function") DECLARE_HYDROGEN_ACCESSOR(InvokeFunction) virtual void PrintDataTo(StringStream* stream); int arity() const { return hydrogen()->argument_count() - 1; } Handle<JSFunction> known_function() { return hydrogen()->known_function(); } }; class LCallKeyed: public LTemplateInstruction<1, 2, 0> { public: LCallKeyed(LOperand* context, LOperand* key) { inputs_[0] = context; inputs_[1] = key; } LOperand* context() { return inputs_[0]; } LOperand* key() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(CallKeyed, "call-keyed") DECLARE_HYDROGEN_ACCESSOR(CallKeyed) virtual void PrintDataTo(StringStream* stream); int arity() const { return hydrogen()->argument_count() - 1; } }; class LCallNamed: public LTemplateInstruction<1, 1, 0> { public: explicit LCallNamed(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(CallNamed, "call-named") DECLARE_HYDROGEN_ACCESSOR(CallNamed) virtual void PrintDataTo(StringStream* stream); Handle<String> name() const { return hydrogen()->name(); } int arity() const { return hydrogen()->argument_count() - 1; } }; class LCallFunction: public LTemplateInstruction<1, 2, 0> { public: explicit LCallFunction(LOperand* context, LOperand* function) { inputs_[0] = context; inputs_[1] = function; } LOperand* context() { return inputs_[0]; } LOperand* function() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(CallFunction, "call-function") DECLARE_HYDROGEN_ACCESSOR(CallFunction) int arity() const { return hydrogen()->argument_count() - 1; } }; class LCallGlobal: public LTemplateInstruction<1, 1, 0> { public: explicit LCallGlobal(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(CallGlobal, "call-global") DECLARE_HYDROGEN_ACCESSOR(CallGlobal) virtual void PrintDataTo(StringStream* stream); Handle<String> name() const {return hydrogen()->name(); } int arity() const { return hydrogen()->argument_count() - 1; } }; class LCallKnownGlobal: public LTemplateInstruction<1, 0, 0> { public: DECLARE_CONCRETE_INSTRUCTION(CallKnownGlobal, "call-known-global") DECLARE_HYDROGEN_ACCESSOR(CallKnownGlobal) virtual void PrintDataTo(StringStream* stream); Handle<JSFunction> target() const { return hydrogen()->target(); } int arity() const { return hydrogen()->argument_count() - 1; } }; class LCallNew: public LTemplateInstruction<1, 2, 0> { public: LCallNew(LOperand* context, LOperand* constructor) { inputs_[0] = context; inputs_[1] = constructor; } LOperand* context() { return inputs_[0]; } LOperand* constructor() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(CallNew, "call-new") DECLARE_HYDROGEN_ACCESSOR(CallNew) virtual void PrintDataTo(StringStream* stream); int arity() const { return hydrogen()->argument_count() - 1; } }; class LCallNewArray: public LTemplateInstruction<1, 2, 0> { public: LCallNewArray(LOperand* context, LOperand* constructor) { inputs_[0] = context; inputs_[1] = constructor; } LOperand* context() { return inputs_[0]; } LOperand* constructor() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(CallNewArray, "call-new-array") DECLARE_HYDROGEN_ACCESSOR(CallNewArray) virtual void PrintDataTo(StringStream* stream); int arity() const { return hydrogen()->argument_count() - 1; } }; class LCallRuntime: public LTemplateInstruction<1, 1, 0> { public: explicit LCallRuntime(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(CallRuntime, "call-runtime") DECLARE_HYDROGEN_ACCESSOR(CallRuntime) const Runtime::Function* function() const { return hydrogen()->function(); } int arity() const { return hydrogen()->argument_count(); } }; class LInteger32ToDouble: public LTemplateInstruction<1, 1, 0> { public: explicit LInteger32ToDouble(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(Integer32ToDouble, "int32-to-double") }; class LUint32ToDouble: public LTemplateInstruction<1, 1, 1> { public: explicit LUint32ToDouble(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(Uint32ToDouble, "uint32-to-double") }; class LNumberTagI: public LTemplateInstruction<1, 1, 0> { public: explicit LNumberTagI(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(NumberTagI, "number-tag-i") }; class LNumberTagU: public LTemplateInstruction<1, 1, 0> { public: explicit LNumberTagU(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(NumberTagU, "number-tag-u") }; class LNumberTagD: public LTemplateInstruction<1, 1, 1> { public: LNumberTagD(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(NumberTagD, "number-tag-d") DECLARE_HYDROGEN_ACCESSOR(Change) }; // Sometimes truncating conversion from a tagged value to an int32. class LDoubleToI: public LTemplateInstruction<1, 1, 1> { public: LDoubleToI(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(DoubleToI, "double-to-i") DECLARE_HYDROGEN_ACCESSOR(UnaryOperation) bool truncating() { return hydrogen()->CanTruncateToInt32(); } }; // Truncating conversion from a tagged value to an int32. class LTaggedToI: public LTemplateInstruction<1, 1, 1> { public: LTaggedToI(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(TaggedToI, "tagged-to-i") DECLARE_HYDROGEN_ACCESSOR(UnaryOperation) bool truncating() { return hydrogen()->CanTruncateToInt32(); } }; class LSmiTag: public LTemplateInstruction<1, 1, 0> { public: explicit LSmiTag(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(SmiTag, "smi-tag") }; class LNumberUntagD: public LTemplateInstruction<1, 1, 1> { public: explicit LNumberUntagD(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(NumberUntagD, "double-untag") DECLARE_HYDROGEN_ACCESSOR(Change); }; class LSmiUntag: public LTemplateInstruction<1, 1, 0> { public: LSmiUntag(LOperand* value, bool needs_check) : needs_check_(needs_check) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(SmiUntag, "smi-untag") bool needs_check() const { return needs_check_; } private: bool needs_check_; }; class LStoreNamedField: public LTemplateInstruction<0, 2, 2> { public: LStoreNamedField(LOperand* obj, LOperand* val, LOperand* temp, LOperand* temp_map) { inputs_[0] = obj; inputs_[1] = val; temps_[0] = temp; temps_[1] = temp_map; } LOperand* object() { return inputs_[0]; } LOperand* value() { return inputs_[1]; } LOperand* temp() { return temps_[0]; } LOperand* temp_map() { return temps_[1]; } DECLARE_CONCRETE_INSTRUCTION(StoreNamedField, "store-named-field") DECLARE_HYDROGEN_ACCESSOR(StoreNamedField) virtual void PrintDataTo(StringStream* stream); Handle<Object> name() const { return hydrogen()->name(); } bool is_in_object() { return hydrogen()->is_in_object(); } int offset() { return hydrogen()->offset(); } Handle<Map> transition() const { return hydrogen()->transition(); } }; class LStoreNamedGeneric: public LTemplateInstruction<0, 3, 0> { public: LStoreNamedGeneric(LOperand* context, LOperand* object, LOperand* value) { inputs_[0] = context; inputs_[1] = object; inputs_[2] = value; } LOperand* context() { return inputs_[0]; } LOperand* object() { return inputs_[1]; } LOperand* value() { return inputs_[2]; } DECLARE_CONCRETE_INSTRUCTION(StoreNamedGeneric, "store-named-generic") DECLARE_HYDROGEN_ACCESSOR(StoreNamedGeneric) virtual void PrintDataTo(StringStream* stream); Handle<Object> name() const { return hydrogen()->name(); } StrictModeFlag strict_mode_flag() { return hydrogen()->strict_mode_flag(); } }; class LStoreKeyed: public LTemplateInstruction<0, 3, 0> { public: LStoreKeyed(LOperand* obj, LOperand* key, LOperand* val) { inputs_[0] = obj; inputs_[1] = key; inputs_[2] = val; } bool is_external() const { return hydrogen()->is_external(); } LOperand* elements() { return inputs_[0]; } LOperand* key() { return inputs_[1]; } LOperand* value() { return inputs_[2]; } ElementsKind elements_kind() const { return hydrogen()->elements_kind(); } DECLARE_CONCRETE_INSTRUCTION(StoreKeyed, "store-keyed") DECLARE_HYDROGEN_ACCESSOR(StoreKeyed) virtual void PrintDataTo(StringStream* stream); uint32_t additional_index() const { return hydrogen()->index_offset(); } bool NeedsCanonicalization() { return hydrogen()->NeedsCanonicalization(); } }; class LStoreKeyedGeneric: public LTemplateInstruction<0, 4, 0> { public: LStoreKeyedGeneric(LOperand* context, LOperand* object, LOperand* key, LOperand* value) { inputs_[0] = context; inputs_[1] = object; inputs_[2] = key; inputs_[3] = value; } LOperand* context() { return inputs_[0]; } LOperand* object() { return inputs_[1]; } LOperand* key() { return inputs_[2]; } LOperand* value() { return inputs_[3]; } DECLARE_CONCRETE_INSTRUCTION(StoreKeyedGeneric, "store-keyed-generic") DECLARE_HYDROGEN_ACCESSOR(StoreKeyedGeneric) virtual void PrintDataTo(StringStream* stream); StrictModeFlag strict_mode_flag() { return hydrogen()->strict_mode_flag(); } }; class LTransitionElementsKind: public LTemplateInstruction<0, 2, 2> { public: LTransitionElementsKind(LOperand* object, LOperand* context, LOperand* new_map_temp, LOperand* temp) { inputs_[0] = object; inputs_[1] = context; temps_[0] = new_map_temp; temps_[1] = temp; } LOperand* context() { return inputs_[1]; } LOperand* object() { return inputs_[0]; } LOperand* new_map_temp() { return temps_[0]; } LOperand* temp() { return temps_[1]; } DECLARE_CONCRETE_INSTRUCTION(TransitionElementsKind, "transition-elements-kind") DECLARE_HYDROGEN_ACCESSOR(TransitionElementsKind) virtual void PrintDataTo(StringStream* stream); Handle<Map> original_map() { return hydrogen()->original_map(); } Handle<Map> transitioned_map() { return hydrogen()->transitioned_map(); } ElementsKind from_kind() { return hydrogen()->from_kind(); } ElementsKind to_kind() { return hydrogen()->to_kind(); } }; class LTrapAllocationMemento : public LTemplateInstruction<0, 1, 1> { public: LTrapAllocationMemento(LOperand* object, LOperand* temp) { inputs_[0] = object; temps_[0] = temp; } LOperand* object() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(TrapAllocationMemento, "trap-allocation-memento") }; class LStringAdd: public LTemplateInstruction<1, 3, 0> { public: LStringAdd(LOperand* context, LOperand* left, LOperand* right) { inputs_[0] = context; inputs_[1] = left; inputs_[2] = right; } LOperand* context() { return inputs_[0]; } LOperand* left() { return inputs_[1]; } LOperand* right() { return inputs_[2]; } DECLARE_CONCRETE_INSTRUCTION(StringAdd, "string-add") DECLARE_HYDROGEN_ACCESSOR(StringAdd) }; class LStringCharCodeAt: public LTemplateInstruction<1, 3, 0> { public: LStringCharCodeAt(LOperand* context, LOperand* string, LOperand* index) { inputs_[0] = context; inputs_[1] = string; inputs_[2] = index; } LOperand* context() { return inputs_[0]; } LOperand* string() { return inputs_[1]; } LOperand* index() { return inputs_[2]; } DECLARE_CONCRETE_INSTRUCTION(StringCharCodeAt, "string-char-code-at") DECLARE_HYDROGEN_ACCESSOR(StringCharCodeAt) }; class LStringCharFromCode: public LTemplateInstruction<1, 2, 0> { public: LStringCharFromCode(LOperand* context, LOperand* char_code) { inputs_[0] = context; inputs_[1] = char_code; } LOperand* context() { return inputs_[0]; } LOperand* char_code() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(StringCharFromCode, "string-char-from-code") DECLARE_HYDROGEN_ACCESSOR(StringCharFromCode) }; class LStringLength: public LTemplateInstruction<1, 1, 0> { public: explicit LStringLength(LOperand* string) { inputs_[0] = string; } LOperand* string() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(StringLength, "string-length") DECLARE_HYDROGEN_ACCESSOR(StringLength) }; class LCheckFunction: public LTemplateInstruction<0, 1, 0> { public: explicit LCheckFunction(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(CheckFunction, "check-function") DECLARE_HYDROGEN_ACCESSOR(CheckFunction) }; class LCheckInstanceType: public LTemplateInstruction<0, 1, 1> { public: LCheckInstanceType(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* value() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(CheckInstanceType, "check-instance-type") DECLARE_HYDROGEN_ACCESSOR(CheckInstanceType) }; class LCheckMaps: public LTemplateInstruction<0, 1, 0> { public: explicit LCheckMaps(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(CheckMaps, "check-maps") DECLARE_HYDROGEN_ACCESSOR(CheckMaps) }; class LCheckPrototypeMaps: public LTemplateInstruction<1, 0, 1> { public: explicit LCheckPrototypeMaps(LOperand* temp) { temps_[0] = temp; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(CheckPrototypeMaps, "check-prototype-maps") DECLARE_HYDROGEN_ACCESSOR(CheckPrototypeMaps) ZoneList<Handle<JSObject> >* prototypes() const { return hydrogen()->prototypes(); } ZoneList<Handle<Map> >* maps() const { return hydrogen()->maps(); } }; class LCheckSmi: public LTemplateInstruction<0, 1, 0> { public: explicit LCheckSmi(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(CheckSmi, "check-smi") }; class LClampDToUint8: public LTemplateInstruction<1, 1, 0> { public: explicit LClampDToUint8(LOperand* value) { inputs_[0] = value; } LOperand* unclamped() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(ClampDToUint8, "clamp-d-to-uint8") }; class LClampIToUint8: public LTemplateInstruction<1, 1, 0> { public: explicit LClampIToUint8(LOperand* value) { inputs_[0] = value; } LOperand* unclamped() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(ClampIToUint8, "clamp-i-to-uint8") }; class LClampTToUint8: public LTemplateInstruction<1, 1, 1> { public: LClampTToUint8(LOperand* value, LOperand* temp) { inputs_[0] = value; temps_[0] = temp; } LOperand* unclamped() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(ClampTToUint8, "clamp-t-to-uint8") }; class LCheckNonSmi: public LTemplateInstruction<0, 1, 0> { public: explicit LCheckNonSmi(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(CheckNonSmi, "check-non-smi") }; class LAllocateObject: public LTemplateInstruction<1, 1, 1> { public: LAllocateObject(LOperand* context, LOperand* temp) { inputs_[0] = context; temps_[0] = temp; } LOperand* context() { return inputs_[0]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(AllocateObject, "allocate-object") DECLARE_HYDROGEN_ACCESSOR(AllocateObject) }; class LAllocate: public LTemplateInstruction<1, 2, 1> { public: LAllocate(LOperand* context, LOperand* size, LOperand* temp) { inputs_[0] = context; inputs_[1] = size; temps_[0] = temp; } LOperand* context() { return inputs_[0]; } LOperand* size() { return inputs_[1]; } LOperand* temp() { return temps_[0]; } DECLARE_CONCRETE_INSTRUCTION(Allocate, "allocate") DECLARE_HYDROGEN_ACCESSOR(Allocate) }; class LFastLiteral: public LTemplateInstruction<1, 1, 0> { public: explicit LFastLiteral(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(FastLiteral, "fast-literal") DECLARE_HYDROGEN_ACCESSOR(FastLiteral) }; class LArrayLiteral: public LTemplateInstruction<1, 1, 0> { public: explicit LArrayLiteral(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(ArrayLiteral, "array-literal") DECLARE_HYDROGEN_ACCESSOR(ArrayLiteral) }; class LObjectLiteral: public LTemplateInstruction<1, 1, 0> { public: explicit LObjectLiteral(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(ObjectLiteral, "object-literal") DECLARE_HYDROGEN_ACCESSOR(ObjectLiteral) }; class LRegExpLiteral: public LTemplateInstruction<1, 1, 0> { public: explicit LRegExpLiteral(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(RegExpLiteral, "regexp-literal") DECLARE_HYDROGEN_ACCESSOR(RegExpLiteral) }; class LFunctionLiteral: public LTemplateInstruction<1, 1, 0> { public: explicit LFunctionLiteral(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(FunctionLiteral, "function-literal") DECLARE_HYDROGEN_ACCESSOR(FunctionLiteral) Handle<SharedFunctionInfo> shared_info() { return hydrogen()->shared_info(); } }; class LToFastProperties: public LTemplateInstruction<1, 1, 0> { public: explicit LToFastProperties(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(ToFastProperties, "to-fast-properties") DECLARE_HYDROGEN_ACCESSOR(ToFastProperties) }; class LTypeof: public LTemplateInstruction<1, 2, 0> { public: LTypeof(LOperand* context, LOperand* value) { inputs_[0] = context; inputs_[1] = value; } LOperand* context() { return inputs_[0]; } LOperand* value() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(Typeof, "typeof") }; class LTypeofIsAndBranch: public LControlInstruction<1, 0> { public: explicit LTypeofIsAndBranch(LOperand* value) { inputs_[0] = value; } LOperand* value() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(TypeofIsAndBranch, "typeof-is-and-branch") DECLARE_HYDROGEN_ACCESSOR(TypeofIsAndBranch) Handle<String> type_literal() { return hydrogen()->type_literal(); } virtual void PrintDataTo(StringStream* stream); }; class LDeleteProperty: public LTemplateInstruction<1, 3, 0> { public: LDeleteProperty(LOperand* context, LOperand* obj, LOperand* key) { inputs_[0] = context; inputs_[1] = obj; inputs_[2] = key; } LOperand* context() { return inputs_[0]; } LOperand* object() { return inputs_[1]; } LOperand* key() { return inputs_[2]; } DECLARE_CONCRETE_INSTRUCTION(DeleteProperty, "delete-property") }; class LOsrEntry: public LTemplateInstruction<0, 0, 0> { public: LOsrEntry(); DECLARE_CONCRETE_INSTRUCTION(OsrEntry, "osr-entry") LOperand** SpilledRegisterArray() { return register_spills_; } LOperand** SpilledDoubleRegisterArray() { return double_register_spills_; } void MarkSpilledRegister(int allocation_index, LOperand* spill_operand); void MarkSpilledDoubleRegister(int allocation_index, LOperand* spill_operand); private: // Arrays of spill slot operands for registers with an assigned spill // slot, i.e., that must also be restored to the spill slot on OSR entry. // NULL if the register has no assigned spill slot. Indexed by allocation // index. LOperand* register_spills_[Register::kMaxNumAllocatableRegisters]; LOperand* double_register_spills_[ DoubleRegister::kMaxNumAllocatableRegisters]; }; class LStackCheck: public LTemplateInstruction<0, 1, 0> { public: explicit LStackCheck(LOperand* context) { inputs_[0] = context; } LOperand* context() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(StackCheck, "stack-check") DECLARE_HYDROGEN_ACCESSOR(StackCheck) Label* done_label() { return &done_label_; } private: Label done_label_; }; class LIn: public LTemplateInstruction<1, 3, 0> { public: LIn(LOperand* context, LOperand* key, LOperand* object) { inputs_[0] = context; inputs_[1] = key; inputs_[2] = object; } LOperand* context() { return inputs_[0]; } LOperand* key() { return inputs_[1]; } LOperand* object() { return inputs_[2]; } DECLARE_CONCRETE_INSTRUCTION(In, "in") }; class LForInPrepareMap: public LTemplateInstruction<1, 2, 0> { public: LForInPrepareMap(LOperand* context, LOperand* object) { inputs_[0] = context; inputs_[1] = object; } LOperand* context() { return inputs_[0]; } LOperand* object() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(ForInPrepareMap, "for-in-prepare-map") }; class LForInCacheArray: public LTemplateInstruction<1, 1, 0> { public: explicit LForInCacheArray(LOperand* map) { inputs_[0] = map; } LOperand* map() { return inputs_[0]; } DECLARE_CONCRETE_INSTRUCTION(ForInCacheArray, "for-in-cache-array") int idx() { return HForInCacheArray::cast(this->hydrogen_value())->idx(); } }; class LCheckMapValue: public LTemplateInstruction<0, 2, 0> { public: LCheckMapValue(LOperand* value, LOperand* map) { inputs_[0] = value; inputs_[1] = map; } LOperand* value() { return inputs_[0]; } LOperand* map() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(CheckMapValue, "check-map-value") }; class LLoadFieldByIndex: public LTemplateInstruction<1, 2, 0> { public: LLoadFieldByIndex(LOperand* object, LOperand* index) { inputs_[0] = object; inputs_[1] = index; } LOperand* object() { return inputs_[0]; } LOperand* index() { return inputs_[1]; } DECLARE_CONCRETE_INSTRUCTION(LoadFieldByIndex, "load-field-by-index") }; class LChunkBuilder; class LPlatformChunk: public LChunk { public: LPlatformChunk(CompilationInfo* info, HGraph* graph) : LChunk(info, graph), num_double_slots_(0) { } int GetNextSpillIndex(bool is_double); LOperand* GetNextSpillSlot(bool is_double); int num_double_slots() const { return num_double_slots_; } private: int num_double_slots_; }; class LChunkBuilder BASE_EMBEDDED { public: LChunkBuilder(CompilationInfo* info, HGraph* graph, LAllocator* allocator) : chunk_(NULL), info_(info), graph_(graph), zone_(graph->zone()), status_(UNUSED), current_instruction_(NULL), current_block_(NULL), next_block_(NULL), argument_count_(0), allocator_(allocator), position_(RelocInfo::kNoPosition), instruction_pending_deoptimization_environment_(NULL), pending_deoptimization_ast_id_(BailoutId::None()) { } // Build the sequence for the graph. LPlatformChunk* Build(); // Declare methods that deal with the individual node types. #define DECLARE_DO(type) LInstruction* Do##type(H##type* node); HYDROGEN_CONCRETE_INSTRUCTION_LIST(DECLARE_DO) #undef DECLARE_DO static HValue* SimplifiedDividendForMathFloorOfDiv(HValue* val); static HValue* SimplifiedDivisorForMathFloorOfDiv(HValue* val); private: enum Status { UNUSED, BUILDING, DONE, ABORTED }; LPlatformChunk* chunk() const { return chunk_; } CompilationInfo* info() const { return info_; } HGraph* graph() const { return graph_; } Zone* zone() const { return zone_; } bool is_unused() const { return status_ == UNUSED; } bool is_building() const { return status_ == BUILDING; } bool is_done() const { return status_ == DONE; } bool is_aborted() const { return status_ == ABORTED; } void Abort(const char* reason); // Methods for getting operands for Use / Define / Temp. LUnallocated* ToUnallocated(Register reg); LUnallocated* ToUnallocated(XMMRegister reg); LUnallocated* ToUnallocated(X87TopOfStackRegister reg); // Methods for setting up define-use relationships. MUST_USE_RESULT LOperand* Use(HValue* value, LUnallocated* operand); MUST_USE_RESULT LOperand* UseFixed(HValue* value, Register fixed_register); MUST_USE_RESULT LOperand* UseFixedDouble(HValue* value, XMMRegister fixed_register); // A value that is guaranteed to be allocated to a register. // Operand created by UseRegister is guaranteed to be live until the end of // instruction. This means that register allocator will not reuse it's // register for any other operand inside instruction. // Operand created by UseRegisterAtStart is guaranteed to be live only at // instruction start. Register allocator is free to assign the same register // to some other operand used inside instruction (i.e. temporary or // output). MUST_USE_RESULT LOperand* UseRegister(HValue* value); MUST_USE_RESULT LOperand* UseRegisterAtStart(HValue* value); // An input operand in a register that may be trashed. MUST_USE_RESULT LOperand* UseTempRegister(HValue* value); // An input operand in a register or stack slot. MUST_USE_RESULT LOperand* Use(HValue* value); MUST_USE_RESULT LOperand* UseAtStart(HValue* value); // An input operand in a register, stack slot or a constant operand. MUST_USE_RESULT LOperand* UseOrConstant(HValue* value); MUST_USE_RESULT LOperand* UseOrConstantAtStart(HValue* value); // An input operand in a register or a constant operand. MUST_USE_RESULT LOperand* UseRegisterOrConstant(HValue* value); MUST_USE_RESULT LOperand* UseRegisterOrConstantAtStart(HValue* value); // An input operand in register, stack slot or a constant operand. // Will not be moved to a register even if one is freely available. MUST_USE_RESULT LOperand* UseAny(HValue* value); // Temporary operand that must be in a register. MUST_USE_RESULT LUnallocated* TempRegister(); MUST_USE_RESULT LOperand* FixedTemp(Register reg); MUST_USE_RESULT LOperand* FixedTemp(XMMRegister reg); // Methods for setting up define-use relationships. // Return the same instruction that they are passed. template<int I, int T> LInstruction* Define(LTemplateInstruction<1, I, T>* instr, LUnallocated* result); template<int I, int T> LInstruction* DefineAsRegister(LTemplateInstruction<1, I, T>* instr); template<int I, int T> LInstruction* DefineAsSpilled(LTemplateInstruction<1, I, T>* instr, int index); template<int I, int T> LInstruction* DefineSameAsFirst(LTemplateInstruction<1, I, T>* instr); template<int I, int T> LInstruction* DefineFixed(LTemplateInstruction<1, I, T>* instr, Register reg); template<int I, int T> LInstruction* DefineFixedDouble(LTemplateInstruction<1, I, T>* instr, XMMRegister reg); template<int I, int T> LInstruction* DefineX87TOS(LTemplateInstruction<1, I, T>* instr); // Assigns an environment to an instruction. An instruction which can // deoptimize must have an environment. LInstruction* AssignEnvironment(LInstruction* instr); // Assigns a pointer map to an instruction. An instruction which can // trigger a GC or a lazy deoptimization must have a pointer map. LInstruction* AssignPointerMap(LInstruction* instr); enum CanDeoptimize { CAN_DEOPTIMIZE_EAGERLY, CANNOT_DEOPTIMIZE_EAGERLY }; // Marks a call for the register allocator. Assigns a pointer map to // support GC and lazy deoptimization. Assigns an environment to support // eager deoptimization if CAN_DEOPTIMIZE_EAGERLY. LInstruction* MarkAsCall( LInstruction* instr, HInstruction* hinstr, CanDeoptimize can_deoptimize = CANNOT_DEOPTIMIZE_EAGERLY); LEnvironment* CreateEnvironment(HEnvironment* hydrogen_env, int* argument_index_accumulator); void VisitInstruction(HInstruction* current); void DoBasicBlock(HBasicBlock* block, HBasicBlock* next_block); LInstruction* DoShift(Token::Value op, HBitwiseBinaryOperation* instr); LInstruction* DoArithmeticD(Token::Value op, HArithmeticBinaryOperation* instr); LInstruction* DoArithmeticT(Token::Value op, HArithmeticBinaryOperation* instr); LPlatformChunk* chunk_; CompilationInfo* info_; HGraph* const graph_; Zone* zone_; Status status_; HInstruction* current_instruction_; HBasicBlock* current_block_; HBasicBlock* next_block_; int argument_count_; LAllocator* allocator_; int position_; LInstruction* instruction_pending_deoptimization_environment_; BailoutId pending_deoptimization_ast_id_; DISALLOW_COPY_AND_ASSIGN(LChunkBuilder); }; #undef DECLARE_HYDROGEN_ACCESSOR #undef DECLARE_CONCRETE_INSTRUCTION } } // namespace v8::internal #endif // V8_IA32_LITHIUM_IA32_H_
b20fab30eb27f06bf8ac38bd4345a2eb658a6ad8
ebde8cc28fc579626bf36c418e648fbc046b3308
/lib_acl_cpp/src/hsocket/hspool.cpp
93d4589377f0a1f2af1b83a321258fe6ed02b6aa
[]
no_license
rabbitqyh/acl
7b34e1255f7d656aa5731974551ef8000cf84636
541a2ab401de70bff61d12a53f50a34ec5dc0275
refs/heads/master
2021-01-13T08:44:40.819460
2013-06-23T12:56:58
2013-06-23T12:56:58
null
0
0
null
null
null
null
GB18030
C++
false
false
2,580
cpp
#include "acl_stdafx.hpp" #include "acl_cpp/stdlib/locker.hpp" #include "acl_cpp/hsocket/hsclient.hpp" #include "acl_cpp/hsocket/hspool.hpp" namespace acl { hspool::hspool(const char* addr_rw, const char* addr_rd, bool cache_enable /* = true */, bool retry_enable /* = true */) : cache_enable_(cache_enable) , retry_enable_(retry_enable) { acl_assert(addr_rw); addr_rw_ = acl_mystrdup(addr_rw); if (addr_rd != NULL) addr_rd_ = acl_mystrdup(addr_rd); else addr_rd_ = addr_rw_; locker_ = NEW locker(true); } hspool::~hspool() { if (addr_rd_ != addr_rw_) acl_myfree(addr_rd_); acl_myfree(addr_rw_); std::list<hsclient*>::iterator it = pool_.begin(); for (; it != pool_.end(); ++it) delete (*it); pool_.clear(); delete locker_; } hsclient* hspool::peek(const char* dbn, const char* tbl, const char* idx, const char* flds, bool readonly /* = false */) { hsclient* client; const char* addr; if (readonly) addr = addr_rd_; else addr = addr_rw_; locker_->lock(); // 先顺序查询符合表字段条件的连接对象 std::list<hsclient*>::iterator it = pool_.begin(); for (; it != pool_.end(); ++it) { // 如果地址不匹配查跳过,地址必须匹配 if (strcmp((*it)->get_addr(), addr) != 0) continue; // 打开已经打开的表,查询表字段是否符合 if ((*it)->open_tbl(dbn, tbl, idx, flds, false)) { client = *it; pool_.erase(it); locker_->unlock(); return (client); } } // 查询地址匹配的连接对象,如果存在一个匹配的连接对象,则 // 打开新的表 it = pool_.begin(); std::list<hsclient*>::iterator it_next = it; for (; it != pool_.end(); it = it_next) { ++it_next; // 如果地址不匹配查跳过,地址必须匹配 if (strcmp((*it)->get_addr(), addr) != 0) continue; client = *it; pool_.erase(it); // 从连接池中删除 // 打开新的表 if (client->open_tbl(dbn, tbl, idx, flds, true)) { locker_->unlock(); return (client); } // 打开失败,则需要删除该连接对象 delete client; } locker_->unlock(); client = NEW hsclient(addr, cache_enable_, retry_enable_); if (client->open_tbl(dbn, tbl, idx, flds) == false) { delete client; return (false); } return (client); } void hspool::put(hsclient* client) { acl_assert(client); locker_->lock(); pool_.push_back(client); locker_->unlock(); } }
a53101359b5122a2645678b659f96842ba909287
efed5d60bf0e4b9cca6a64dc4d5da460848eac46
/jp2_pc/Source/GUIApp/GUIAppDlg.cpp
e72e50f088990d86f54569b133a29c7b00c939d2
[]
no_license
Rikoshet-234/JurassicParkTrespasser
515b2e0d967384a312d972e9e3278954a7440f63
42f886d99ece2054ff234c017c07e336720534d5
refs/heads/master
2022-04-24T01:16:37.700865
2020-03-28T01:21:14
2020-03-28T01:21:14
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
191,948
cpp
/********************************************************************************************* * * Copyright © DreamWorks Interactive, 1996 * * Contents: Implementation of 'GUIAppDlg.h.' * ********************************************************************************************** * * $Log: /JP2_PC/Source/GUIApp/GUIAppDlg.cpp $ * * 598 98.10.03 11:07p Mmouni * Disabled setup for self modifying code. * * 597 9/26/98 8:09p Pkeet * Added stats for Kyle. * * 596 98/09/25 1:39 Speter * In silly T debug code, use rTINHeight function rather than more * dangerous one. * * 595 98.09.20 7:21p Mmouni * Removed reduntant main clut add code. * * 594 98/09/19 14:35 Speter * Damn third-person view now uses correct damn distance. * * 593 98.09.19 1:58a Mmouni * Made console buffer bigger so I can see all the fucking stats. * * 592 9/18/98 11:04p Agrant * don't delete the main palette- let the palette database take care of * it * * 591 9/18/98 2:02a Rwyatt * New function to return a resource as a string * * 590 9/17/98 11:12p Shernd * First pass on updating during d3d surface setup * * 589 9/17/98 10:23p Pkeet * Made the stats dump work again. * * 588 9/17/98 5:37p Pkeet * Changed way the main clut is built. * * 587 9/16/98 12:32a Agrant * removed obsolete implementation of smack selected * * 586 98.09.15 8:52p Mmouni * Fixed problem with switching on stats after gong full screen. * * 585 9/14/98 4:43p Mlange * Drag select is now on CTRL instead of SHIFT. * * 584 9/14/98 12:09a Rwyatt * Added CTRL-F7 key to flush audio caches * * 583 98.09.12 12:18a Mmouni * Changed shape query to render type query. * * 582 98/09/09 12:52 Speter * Give us us stow. * * 581 9/09/98 12:02p Pkeet * Activated texture tracking using 'Shift F3.' * *********************************************************************************************/ // // Includes. // #include "stdafx.h" #include "Lib/W95/Direct3D.hpp" #include "Lib/GeomDBase/PartitionPriv.hpp" #include "mmsystem.h" #include "Lib/Audio/SoundTypes.hpp" #include "Lib/Audio/Audio.hpp" #include "GUIAppDlg.h" #include "GUIApp.h" #include "PreDefinedShapes.hpp" #include "GUIPipeLine.hpp" #include "GUITools.hpp" #include "LightProperties.hpp" #include "CameraProperties.hpp" #include "Background.hpp" #include "DialogFog.hpp" #include "DialogString.hpp" #include "SoundPropertiesDlg.hpp" #include "DialogMemLog.hpp" #include "DialogRenderCache.hpp" #include "Toolbar.hpp" #include "Lib/Sys/ProcessorDetect.hpp" #include "Lib/Sys/PerformanceCount.hpp" #include "Lib/Sys/DebugConsole.hpp" #include "Shell/WinRenderTools.hpp" #include "Lib/Control/Control.hpp" #include "Lib/EntityDBase/GameLoop.hpp" #include "Lib/EntityDBase/EntityLight.hpp" #include "Lib/EntityDBase/Replay.hpp" #include "Lib/EntityDBase/Animal.hpp" #include "Lib/EntityDBase/AnimationScript.hpp" #include "Lib/EntityDBase/Query/QRenderer.hpp" #include "Lib/EntityDBase/Query/QMessage.hpp" #include "Lib/EntityDBase/Query/QTerrain.hpp" #include "Lib/EntityDBase/MessageTypes/MsgControl.hpp" #include "Lib/EntityDBase/MessageTypes/MsgSystem.hpp" #include "Lib/EntityDBase/MessageTypes/MsgCollision.hpp" #include "Lib/EntityDBase/MessageTypes/MsgSystem.hpp" #include "Game/DesignDaemon/Gun.hpp" #include "Lib/GeomDBase/Skeleton.hpp" #include "Lib/GeomDBase/WaveletDataFormat.hpp" #include "Lib/GeomDBase/WaveletQuadTree.hpp" #include "Lib/Groff/GroffIO.hpp" #include "Lib/Loader/Loader.hpp" #include "Lib/Loader/DataDaemon.hpp" #include "Lib/Loader/LoadTexture.hpp" #include "Lib/Physics/PhysicsSystem.hpp" #include "Lib/Physics/Xob_bc.hpp" #include "Lib/Physics/PhysicsImport.hpp" #include "Lib/Renderer/PipeLine.hpp" #include "Lib/Sys/Textout.hpp" #include "Lib/Sys/W95/Render.hpp" #include "Lib/Sys/Profile.hpp" #include "Lib/W95/Dd.hpp" #include "Lib/EntityDBase/PhysicsInfo.hpp" #include "DialogObject.h" #include "DialogMagnet.h" #include "DialogGamma.hpp" #include "DialogGore.hpp" #include "DialogPhysics.hpp" #include "DialogSky.hpp" #include "DialogTexturePack.hpp" #include "PerspectiveSubdivideDialog.hpp" #include "Lib/Renderer/RenderCacheInterface.hpp" #include "DialogDepthSort.hpp" #include "DialogOcclusion.hpp" #include "DialogGun.hpp" #include "DialogScheduler.hpp" #include "DialogVM.hpp" #include "DialogBumpPack.hpp" #include "DialogTexturePackOptions.hpp" #include "QualityDialog.hpp" #include "AI Dialogs2Dlg.h" #include "ParameterDlg.h" #include "DialogCulling.hpp" #include "DialogSoundMaterial.hpp" #include "DialogTeleport.h" #include "TerrainTest.hpp" #include "Lib/EntityDBase/PhysicsInfo.hpp" #include "Game/AI/AIMain.hpp" #include "Game/AI/AIInfo.hpp" #include "Game/AI/Brain.hpp" #include "Game/AI/MentalState.hpp" #include "Game/DesignDaemon/Daemon.hpp" #include "Lib/Renderer/DepthSort.hpp" #include "Lib/Sys/StdDialog.hpp" #include "Lib/Sys/ConIO.hpp" #include "DialogTerrain.hpp" #include "DialogWater.hpp" #include "Lib/Sys/FileEx.hpp" #include "DialogMipmap.hpp" #include "Lib/GeomDBase/TerrainLoad.hpp" #include "Lib/GeomDBase/TerrainTexture.hpp" #include "Lib/Physics/InfoSkeleton.hpp" #include "Lib/Physics/Magnet.hpp" // the joystick support stuff #include "mmsystem.h" #include "Lib/Audio/AudioDaemon.hpp" #include "Lib/Audio/Audio.hpp" #include "Lib/Audio/Material.hpp" #include "Lib/EntityDBase/RenderDB.hpp" #include "Lib/EntityDBase/Query/QRenderer.hpp" #include "Lib/EntityDBase/MovementPrediction.hpp" #include "Lib/View/RasterFile.hpp" #include "Lib/Renderer/LightBlend.hpp" #include "DialogAlphaColour.hpp" #include "Lib/Renderer/Primitives/FastBumpTable.hpp" #include "Lib/Sys/ExePageModify.hpp" #include "Lib/Renderer/Occlude.hpp" #include "Lib/Renderer/Sky.hpp" #include "Lib/Sys/Scheduler.hpp" #include "Lib/Sys/FixedHeap.hpp" #include "Lib/Sys/RegInit.hpp" #include "Lib/EntityDBase/RenderDB.hpp" #include "Lib/EntityDBase/Water.hpp" #include "Lib/Renderer/RenderCache.hpp" #include "Lib/Std/Hash.hpp" #include "Lib/Trigger/Trigger.hpp" #include "Lib/sys/Reg.h" #include "lib/sys/reginit.hpp" #include "lib/loader/LoadTexture.hpp" #include <stdio.h> #include <stdlib.h> #ifndef PFNWORLDLOADNOTIFY typedef uint32 (__stdcall * PFNWORLDLOADNOTIFY)(uint32 dwContext, uint32 dwParam1, uint32 dwParam2, uint32 dwParam3); #endif PFNWORLDLOADNOTIFY g_pfnWorldLoadNotify; uint32 g_u4NotifyParam; bool bIsTrespasser = false; bool bInvertMouse = false; // Check to determine which version of the compiler we are running. If anything less than 4.2, // Don't include this file. Consequences are unknown??? #if _MSC_VER > 1019 #include <exception> #endif // // Statistics dump for Kyle. // #define bDUMP_STATS (0) extern CProfileStat psRenderShapeReg; extern CProfileStat psRenderShapeBio; extern CProfileStat psRenderShapeTrr; extern CProfileStat psRenderShapeImc; //proProfile.psPresort //proProfile.psDrawPolygon extern CProfileStatParent psPixels; // Replace this macro with the stat you want printed out as "other." #define psOTHER_STAT psPixels // // Constants. // // Default timer. const int iDEFAULT_TIMER = 1; // Default timer step in milliseconds. const int iDEFAULT_TIMER_STEP = 33; // // Default strength for non-ambient lights added. // You can have multiple lights of maximum strength, as they use fCombine to combine. // const TLightVal lvDEFAULT = 1.0; const char* strLAST_SCENE_FILE = "LastScene.scn"; // Amount to change viewport by. const float fViewDeltaIncrease = 1.1f; const float fViewDeltaDecrease = 1.0f / fViewDeltaIncrease; // // Module variables. // extern CProfileStat psCacheSched; // How far do we move with debug movement (time corrected)??? TReal rDebugStepDistance = 6.7f; TReal rDebugTurnAngle = 120.0f; // Pointer to the toolbar. CTool* pdlgToolbar = 0; CDialogGamma* pdlgobjDialogGamma = 0; CDialogGore* pdlgobjDialogGore = 0; // Pointer to the perspective correction properties dialog. CPerspectiveSubdivideDialog* pdlgPerspectiveSubdivide = 0; // Pointer to the object properties dialog. CDialogRenderCache* pdlgrcDialogRenderCache = 0; // Pointer to the object properties dialog. CDialogObject* pdlgobjDialogObject = 0; // Pointer to the material properties dialog. CDialog* pdlgDialogMaterial = 0; CDialog* newCDialogMaterial(CInstance* pins); // Pointer to the magnet properties dialog. CDialogMagnet* pdlgmagDialogMagnet = 0; // Pointer to the player properties dialog. CDialog* pdlgDialogPlayer = 0; CDialog* newCDialogPlayer(); // Pointer to the physics dialog. CDialogPhysics* pdlgphyDialogPhysics = 0; // Pointer to the camera properties dialog. CCameraProperties* pcamdlgCameraProperties = 0; // Pointer to the light properties dialog. CLightProperties* pltdlgLightProperties = 0; // Pointer to the background dialog box. CBackground* pbackdlgBackground = 0; // Pointer to the occlusion dialog box. CDialogOcclusion* pdlgOcclusion = 0; // Pointer to the scheduler dialog box. CDialogScheduler* pdlgScheduler = 0; // Pointer to the Gun dialog box. CDialogGun* pdlgGun = 0; // Pointer to the sky settings dialog box CDialogSky* pdlgSky = 0; // Pointer to the VM settings dialog box CDialogVM* pdlgVM = 0; CDialogQuality* pdlgQuality = 0; // Pointer to the alpha colour settings dialog box. CDialogAlphaColour* pdlgAlphaColour = 0; // Pointer to the terrain dialog. CDialogTerrain* pdlgtDialogTerrain = 0; // Pointer to the water dialog. CDialogWater* pdlgtDialogWater = 0; // Pointer to the fog properties dialog box. CDialogFog* pfogdlgFogProperties = 0; CDialogDepthSort* pdepthdlgProperties = 0; CDialogSoundProp* psounddlgProperties = 0; CDialogMipmap* pdlgMipmap = 0; CDialogTexturePack* pdlgTexturePack = 0; CDialogSoundMaterial* pdlgSoundMaterial = 0; CString csProfileName = "Profile - Time"; // Initial camera position is 2m above sea level. // (This variable is altered by the command line). CVector3<> v3InitCamPos(0.0, 0.0, 2.0); TSec sWanderStop = -1.0f; bool bWanderDurationInSecs = true; // Do we actually want to create the output files bool bUseOutputFiles = TRUE; bool bUseReplayFile = TRUE; // Static wander variables (file scope to allow reset). static CRandom randWander; static float fWanderAngleRate = 0; // Rate of angular of rotation about Z. // Art stats maximums. int i_max_total_polys = 0; int i_max_cache_polys = 0; int i_max_terrain_polys = 0; CGUIAppDlg* pgui = 0; // // Externally defined variables. // extern int iNumPixelsIterated; extern int iNumPixelsSolid; bool bExiting = false; bool bScreensaver = false; FILE* fileStats = 0; // // Forward declarations of module functions. // //********************************************************************************************* // void SendMessageToWindow ( CWnd* pwnd, // Window to receive message. uint u_message // Windows message id. ); // // Sends a WM_CLOSE message to the specified window. // //************************************** //********************************************************************************************* // bool bVKey ( uint u_virtualkey // Virtual key to sample. ) // // Returns 'true' if the virtual key is being pressed. // //************************************** { return (GetAsyncKeyState(u_virtualkey) & (SHORT)0xFFFE) != 0; } //+-------------------------------------------------------------------------- // // Function: CreateDirAlongPath // // Synopsis: Create the directories necessary along the path. We pick // off the file name then iteratively create the directories // // Arguments: [pszPath] -- file name to create the directories based // off of // [bFileIsPath] -- if the pszPath is just a path with no // file name at the end // // Returns: BOOL -- TRUE -- if successful // FALSE -- if NOT successful // // History: 10-Oct-95 SHernd Created // //--------------------------------------------------------------------------- BOOL CreateDirAlongPath(LPSTR pszPath, BOOL bFileIsPath = TRUE) { char szDir[_MAX_PATH]; char szPath[_MAX_PATH]; char szDrive[_MAX_DRIVE]; LPSTR pszEnd; LPSTR psz; LPSTR pszTemp; BOOL bRet; DWORD dw; if (!bFileIsPath) { _splitpath(pszPath, szDrive, szPath, NULL , NULL); strcpy(szDir, szDrive); strcat(szDir, szPath); } else { strcpy(szDir, pszPath); if (szDir[strlen(szDir) - 1] != '\\') { strcat(szDir, "\\"); } } pszEnd = strchr(szDir, '\0'); psz = szDir; pszTemp = strchr(psz, '\\'); for (pszTemp = strchr(pszTemp + 1, '\\'); (pszTemp != pszEnd) && (pszTemp != NULL); psz = pszTemp + 1, pszTemp = strchr(psz, '\\')) { *pszTemp = '\0'; dw = GetFileAttributes(szDir); if (dw == (DWORD)-1) { if (!CreateDirectory(szDir, NULL)) { goto Error; } } *pszTemp = '\\'; } bRet = TRUE; Cleanup: return bRet; Error: bRet = FALSE; goto Cleanup; } // // Class implementation. // //********************************************************************************************* // // Dialog message map. // #define WM_KICKIDLE 0x036A // private to MFC. BEGIN_MESSAGE_MAP(CGUIAppDlg, CDialog) //{{AFX_MSG_MAP(CGUIAppDlg) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_DROPFILES() ON_WM_CREATE() ON_WM_SIZE() ON_WM_LBUTTONDOWN() ON_WM_RBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_RBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_LBUTTONDBLCLK() ON_WM_CLOSE() ON_COMMAND(MENU_EDIT_GAMMA, OnEditGamma) ON_COMMAND(MENU_GORE, OnEditGore) ON_COMMAND(MENU_ZBUFFER, OnZbuffer) ON_COMMAND(MENU_SCREENCLIP, OnScreenclip) ON_COMMAND(MENU_SCREENCULL, OnScreencull) ON_COMMAND(MENU_LIGHT, OnLight) ON_COMMAND(MENU_LIGHT_SHADE, OnLightShade) ON_COMMAND(MENU_FOG, OnFog) ON_COMMAND(MENU_FOG_SHADE, OnFogShade) ON_COMMAND(MENU_COLOURED, OnColoured) ON_COMMAND(MENU_TEXTURE, OnTexture) ON_COMMAND(MENU_TRANSPARENT, OnTransparent) ON_COMMAND(MENU_BUMP, OnBump) ON_COMMAND(MENU_WIREFRAME, OnWireFrame) ON_COMMAND(MENU_ALPHA_COLOUR, OnAlphaColour) ON_COMMAND(MENU_ALPHA_SHADE, OnAlphaShade) ON_COMMAND(MENU_ALPHA_TEXTURE, OnAlphaTexture) ON_COMMAND(MENU_TRAPEZOIDS, OnTrapezoids) ON_COMMAND(MENU_SUBPIXEL, OnSubpixel) ON_COMMAND(MENU_PERSPECTIVE, OnPerspective) ON_COMMAND(MENU_MIPMAP, OnMipMap) ON_COMMAND(MENU_DITHER, OnDither) ON_COMMAND(MENU_FILTER, OnFilter) ON_COMMAND(MENU_FILTER_EDGES, OnFilterEdges) ON_COMMAND(MENU_SPECULAR, OnSpecular) ON_COMMAND(MENU_SHADOWS, OnShadows) ON_COMMAND(MENU_SHADOW_TERRAIN, OnShadowTerrain) ON_COMMAND(MENU_SHADOW_TERRAIN_MOVING, OnShadowTerrainMove) ON_COMMAND(MENU_RENDER_CACHE, OnRenderCache) ON_COMMAND(MENU_RENDER_CACHE_TEST, OnRenderCacheTest) ON_COMMAND(MENU_SET_MIPMAP, OnMipMapSettings) ON_COMMAND(MENU_DETAIL, OnDetail) ON_COMMAND(MENU_CONSOLE, OnShowConsole) ON_COMMAND(MENU_STATS, OnShowStats) ON_COMMAND(MENU_AVG_STATS, OnAvgStats) ON_COMMAND(MENU_FPS, OnShowFPS) ON_COMMAND(MENU_CACHE_STATS, OnShowCacheStats) ON_COMMAND(MENU_STATPHYSICS, OnStatPhysics) ON_COMMAND(MENU_VIEW_HAIRS, OnViewHairs) ON_COMMAND(MENU_VIEW_CROSSHAIR_RADIUS, OnCrosshairRadius) ON_COMMAND(MENU_VIEW_CROSSHAIR_VEGETATION, OnCrosshairVegetation) ON_COMMAND(MENU_VIEW_CROSSHAIR_TERRAINTEXTURES, OnCrosshairTerrainTexture) ON_COMMAND(MENU_VIEW_SPHERES, OnViewSpheres) ON_COMMAND(MENU_VIEW_WIRE, OnViewWire) ON_COMMAND(MENU_VIEW_PINHEAD, OnViewPinhead) ON_COMMAND(MENU_VIEW_BONES, OnViewBones) ON_COMMAND(MENU_VIEW_BONES_BOXES, OnViewBonesBoxes) ON_COMMAND(MENU_VIEW_BONES_PHYSICS, OnViewBonesCollide) ON_COMMAND(MENU_VIEW_BONES_WAKE, OnViewBonesWake) ON_COMMAND(MENU_VIEW_BONES_QUERY, OnViewBonesQuery) ON_COMMAND(MENU_VIEW_BONES_MAGNETS, OnViewBonesMagnets) ON_COMMAND(MENU_VIEW_BONES_SKELETONS, OnViewBonesSkeletons) ON_COMMAND(MENU_VIEW_BONES_ATTACH, OnViewBonesAttach) ON_COMMAND(MENU_VIEW_BONES_WATER, OnViewBonesWater) ON_COMMAND(MENU_VIEW_BONES_RAYCAST, OnViewBonesRaycast) ON_COMMAND(MENU_VIEW_QUADS, OnViewQuads) ON_COMMAND(MENU_ALPHA_SETTINGS, OnAlphaColourSettings) ON_COMMAND(MENU_PLAYERPHYSICS, OnPlayerPhysics) ON_COMMAND(MENU_PLAYERINVULNERABLE, OnPlayerInvulnerable) ON_COMMAND(MENU_PHYSICS_SLEEP, OnPhysicsSleep) ON_COMMAND(MENU_PHYSICS_STEP, OnPhysicsStep) ON_COMMAND(MENU_PHYSICS_PUTTOSLEEP, OnPhysicsPutToSleep) ON_COMMAND(MENU_SMACKSELECTED, OnSmackSelected) ON_COMMAND(MENU_MAGNET_BREAK, OnMagnetBreak) ON_COMMAND(MENU_MAGNET_NOBREAK, OnMagnetNoBreak) ON_COMMAND(MENU_DEMAGNET, OnDeMagnet) ON_COMMAND(MENU_REDRAW_TERRAIN, OnRedrawTerrain) ON_COMMAND(MENU_CAMERAPLAYER, OnCameraPlayer) ON_COMMAND(MENU_CAMERASELECTED, OnCameraSelected) ON_COMMAND(MENU_CAMERASELECTEDHEAD, OnCameraSelectedHead) ON_COMMAND(MENU_CAMERA2M, OnCamera2m) ON_COMMAND(MENU_CAMERAFREE, OnCameraFree) ON_COMMAND(MENU_OPEN_SCENE, OnLoadScene) ON_COMMAND_RANGE(MENU_OPEN_LAST, MENU_OPEN_LAST+4, OnLoadRecentFile) ON_COMMAND(MENU_SAVE_SCENE, OnSaveScene) ON_COMMAND(MENU_SAVE_AS_SCENE, OnSaveAsScene) ON_COMMAND(MENU_TEXTSAVE, OnTextSave) ON_COMMAND(MENU_REPLAYSAVE, OnReplaySave) ON_COMMAND(MENU_REPLAYLOAD, OnReplayLoad) ON_COMMAND(MENU_LOADANIM, OnLoadAnim) ON_COMMAND(MENU_CONTROLS_DEFAULTCONTROLS,OnDefaultControls) ON_COMMAND(MENU_CONTROLS_STANDARDJOYSTICK,OnStandardJoystick) ON_COMMAND(MENU_PLAYER_PROP, OnPlayerProperties) ON_COMMAND(MENU_MATERIAL_PROP, OnMaterialProperties) ON_COMMAND(MENU_PHYSICS_PROP, OnPhysicsProperties) ON_COMMAND(MENU_SOUND_MATERIAL, OnSoundMaterialProp) ON_COMMAND(MENU_CHANGE_SMAT, OnChangeSMat) ON_COMMAND(IDM_TELEPORT, OnTeleport) ON_WM_TIMER() ON_WM_KEYDOWN() ON_WM_RBUTTONDBLCLK() ON_COMMAND(MENU_SYSTEM_MEM, OnSystemMem) ON_COMMAND(MENU_TERRAIN, OnMenuTerrain) ON_COMMAND(MENU_ADD_SKELETON, OnMenuAddSkeleton) ON_COMMAND(MENU_AI, OnAI) ON_COMMAND(MENU_PHYSICS, OnPhysics) ON_COMMAND(MENU_RESET, OnReset) ON_COMMAND(MENU_RESET_SELECTED, OnResetSelected) ON_COMMAND(MENU_ARTSTATS, OnArtStats) ON_COMMAND(MENU_PREDICTMOVEMENT, OnPredictMovement) ON_COMMAND(MENU_STAT_CLOCKS, OnStatClocks) ON_COMMAND(MENU_STAT_MSR0, OnStatMSR0) ON_COMMAND(MENU_STAT_MSR1, OnStatMSR1) ON_COMMAND(MENU_STAT_RING3, OnStatRing3) ON_COMMAND(MENU_STAT_RING0, OnStatRing0) ON_COMMAND_RANGE(MENU_PROFILE_STAT, MENU_PROFILE_STAT+249, OnChangeStatCounter0) ON_COMMAND_RANGE(MENU_PROFILE_STAT+250, MENU_PROFILE_STAT+500, OnChangeStatCounter1) ON_COMMAND(MENU_TEXTUREPACK, OnTexturePack) ON_COMMAND(MENU_MEMLOG_STATS, OnMemStats) ON_COMMAND(MENU_GIVEMEALIGHTL, OnGiveMeALight) ON_COMMAND(MENU_ZONLYEDIT, OnZOnlyEdit) ON_COMMAND(MENU_NAMESELECT, OnNameSelect) ON_COMMAND(MENU_SMALLMOVESTEPS, OnSmallMoveSteps) ON_COMMAND(ID_EDIT_TERRAIN_TERRAINSOUNDS, OnTerrainSound) ON_COMMAND(MENU_SKY_DISABLE, OnSkyDisable) ON_COMMAND(MENU_SKY_REMOVE, OnSkyRemove) ON_COMMAND(MENU_SKY_TEXTURE, OnSkyTexture) ON_COMMAND(MENU_SKY_FILL, OnSkyFill) ON_COMMAND(MENU_SKY_SETTINGS, OnSkySettings) ON_COMMAND(MENU_VM_SETTINGS, OnVMSettings) ON_COMMAND(MENU_BUMP_PACK, OnBumpPacking) ON_COMMAND(MENU_PACK_OPTIONS, OnPackOptions) ON_COMMAND(MENU_EDIT_AI, OnEditAI) ON_COMMAND(MENU_EDIT_AI_EMOTIONS, OnEditAIEmotions) ON_COMMAND(MENU_DRAWPHYSICS, OnDrawPhysics) ON_COMMAND(MENU_DRAWAI, OnDrawAI) ON_COMMAND(MENU_ROTATE_WORLDZ, OnRotateWorldZ) ON_COMMAND(MENU_RESET_START_TRIGGERS, OnResetStartTriggers) ON_COMMAND(MENU_RESTORE_DEFAULTS, OnRestoreSubsystemDefaults) ON_COMMAND(MENU_SETTINGS_RENDERQUALITY, OnRenderQualitySettings) ON_MESSAGE(WM_KICKIDLE, OnIdle) //}}AFX_MSG_MAP END_MESSAGE_MAP() //********************************************************************************************* // // CGUIAppDlg implementation. // // The onexit guy. void GUIAppOnExit() { // Close the buffer for printing framerate stats out. if (fileStats) { fclose(fileStats); fileStats = 0; } // Purge the world database to ensure that all the instances are deleted before the // static variables are deleted. if (pwWorld) pwWorld->Purge(); dprintf("Leftover CMeshes: %d\n", ulGetMemoryLogCounter(emlMeshes) ); dprintf("Leftover CPhysicsInfos: %d\n", ulGetMemoryLogCounter(emlTotalPhysicsInfo) ); dprintf("Leftover CAIInfos: %d\n", ulGetMemoryLogCounter(emlTotalAIInfo) ); dprintf("Leftover CInfos: %d\n", ulGetMemoryLogCounter(emlTotalCInfo) -1); // Delete memory associated with any instantiated dialog boxes. delete pdlgToolbar; delete pcamdlgCameraProperties; delete pdlgPerspectiveSubdivide; delete pdlgobjDialogObject; delete pdlgmagDialogMagnet; delete pdlgDialogPlayer; delete pdlgDialogMaterial; delete pdlgrcDialogRenderCache; delete pdlgphyDialogPhysics; delete pltdlgLightProperties; delete pbackdlgBackground; delete pdlgOcclusion; delete pdlgScheduler; delete pdlgGun; delete pdlgAlphaColour; delete pdlgtDialogTerrain; delete pdlgtDialogWater; delete pfogdlgFogProperties; delete pdlgMipmap; delete pdepthdlgProperties; // Delete the audio system delete CAudio::pcaAudio; // Deallocate memory for the mipmap directory file string. DeleteMipDirectoryString(); delete pwWorld; bExiting = true; // Reactivate the screen saver. if (bScreensaver) SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, TRUE, 0, SPIF_SENDWININICHANGE); // if there is a main palette, delete its CPal // NO don't. It's handled in the pcdbMain destructor // if (pcdbMain.pceMainPalClut) // delete pcdbMain.pceMainPalClut->ppalPalette; } //********************************************************************************************* static CGUIAppDlg* pguiRepaint = 0; void PaintShellWindow() { Assert(pguiRepaint) pguiRepaint->PaintWindow(); } //********************************************************************************************* // // CGUIAppDlg Constructor. // CGUIAppDlg::CGUIAppDlg(CWnd* pParent /*=NULL*/) : CDialog(CGUIAppDlg::IDD, pParent), conProfile("Profile", 0, 68, 64) { //{{AFX_DATA_INIT(CGUIAppDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); // Set the default background fill colour. // clrBackground = CColour(0, 0, 0); iScreenMode = -1; // Default is window mode. bSystemMem = VER_DEBUG; // Default system memory flag depends on debug mode. if (bGetD3D()) bSystemMem = false; bShowConsole = false; bShowStats = false; bShowHardwareStats = false; bShowFPS = false; bShowHairs = true; bCrosshairRadius = false; rCrosshairRadius = 50.0f; bCrosshairVegetation = true; bShowSpheres = false; bShowWire = false; bShowPinhead = false; bAvgStats = false; bShowToolbar = false; bJustMoved = false; bFastMode = false; bFastModeRequest = false; bGameModeRequest = false; bReplayRequest = false; bLoadRequest = false; bDelaunayTest = false; bTerrainTest = false; bCameraFloating = false; bWander = false; bPhysicsStep = false; bAllowDebugMovement = true; bZOnlyEdit = false; bSmallMoveSteps = false; bTerrainSound = true; bConvertTerrain = false; bRotateAboutWorldZ = true; *strLoadFile = 0; // Cleanup code! Assert(pgui == 0); pgui = this; pguiRepaint = this; AlwaysAssert(!atexit(GUIAppOnExit)); // Initing the static objects here. CInitStaticObjects InitStaticObjects; // Verify color resolution. HDC hdc = ::GetDC(0); int i_bits = ::GetDeviceCaps(hdc, BITSPIXEL) * ::GetDeviceCaps(hdc, PLANES); if (!(i_bits == 16 || i_bits == 15)) { ::MessageBox(0,"Must be in 15 or 16 bit color mode!", "GUIApp Error", MB_OK | MB_ICONERROR); ::ReleaseDC(0,hdc); exit(0); } ::ReleaseDC(0,hdc); } //********************************************************************************************* void CGUIAppDlg::operator delete(void *pv_mem) { } //********************************************************************************************* // // ClassWizard generated functions.. // //********************************************************************************************* // void CGUIAppDlg::Step(TSec s_step) // // Perform a step in the system. // //************************************** { CCycleTimer ctmr; if (bGDIMode) return; if (crpReplay.bLoadActive()) { // // if we are playing a replay the call then Replay member of // the GameLoop class. // we do not need to worry abou the timing info // gmlGameLoop.Replay(s_step); } else { // // Call the normal main game loop if we are not playing a replay // gmlGameLoop.Step(s_step); } // Add the time to both the step stat and the frame stat. TCycles cy = ctmr(); proProfile.psStep.Add(cy, 1); proProfile.psFrame.Add(cy); // Redraw the screen. PaintWindow(); } //********************************************************************************************* // void CGUIAppDlg::OnTimer ( UINT nIDEvent ) // // Timer for the main game loop. // //************************************** { // Do nothing if the world database is locked. if (wWorld.bIsLocked() || wWorld.bHasBeenPurged) return; // For now, allow debug movement at all times. CInstance* pins_move = pcamGetCamera()->pinsAttached() ? pcamGetCamera()->pinsAttached() : pcamGetCamera(); DebugMovement(pins_move, pcamGetCamera()); OnIdle(0, 0); } //********************************************************************************************* LRESULT CGUIAppDlg::OnIdle(WPARAM wParam, LPARAM lParam) // // Executes the main game loop. // //************************************** { // Do nothing if the world database is locked. if (wWorld.bIsLocked()) return 1; // Do nothing if the game loop cannot step. if (!gmlGameLoop.bCanStep()) return 0; // Check for pending save. if (wWorld.bIsSavePending()) { const string &strName = wWorld.strGetPendingSave(); // Stop simulation. CMessageSystem(escSTOP_SIM).Dispatch(); // Save the level. if (!wWorld.bSaveWorld(strName.c_str())) MessageBox("Cannot save scene!", "Save Error", MB_OK); // Start simulation. CMessageSystem(escSTART_SIM).Dispatch(); } // Check for pending level load. if (wWorld.bIsLoadPending()) { const string &strName = wWorld.strGetPendingLoad(); char szFile[_MAX_PATH]; // HACK: to get data drive location. GetRegString(REG_KEY_DATA_DRIVE, szFile, sizeof(szFile), ""); // Add on data sub-directoy to path. if (*szFile) strcat(szFile, "data\\"); // Append file name. strcat(szFile, strName.c_str()); // Stop simulation. CMessageSystem(escSTOP_SIM).Dispatch(); // Load a new level. if (!wWorld.bLoadScene(szFile)) MessageBox("Cannot load file!", "Load Error", MB_OK); else // Remember the last loaded scene. strcpy(strLoadFile, szFile); // Start simulation. CMessageSystem(escSTART_SIM).Dispatch(); // Don't step just now. return 1; } Step(bPhysicsStep ? MAX_TIMESTEP : -1.0); return 1; } //********************************************************************************************* void CGUIAppDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CGUIAppDlg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } //********************************************************************************************* // BOOL CGUIAppDlg::OnInitDialog ( ) // // Initialize the dialog. // //************************************** { CDialog::OnInitDialog(); SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon DragAcceptFiles(); return TRUE; // return TRUE unless you set the focus to a control } //********************************************************************************************* // void CGUIAppDlg::OnPaint ( ) // // Handle the WM_PAINT message. // //************************************** { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); // Set fast render mode if requested. if (bFastModeRequest) { bFastModeRequest = false; ToggleFastMode(); return; } if (bGameModeRequest) { bGameModeRequest = false; EnterGameMode(); } if (bReplayRequest) { bReplayRequest = false; // RestoreGamePath(); // open the replay file now so it cannot be used for savinging as well if (crpReplay.bOpenReadReplay(acReplayFileName)==FALSE) { // // we cannot open the selected file, either it does not exist // or it is not a replay file. // SetMenuItemState(MENU_REPLAYLOAD, FALSE); crpReplay.SetLoad(FALSE); return; } // we now have a valid relay filename so enable replays // tick the menu SetMenuItemState(MENU_REPLAYLOAD, TRUE); crpReplay.SetLoad(TRUE); } if (bLoadRequest) { CLoadWorld lw(strLoadFile); bLoadRequest = false; } if (!gmlGameLoop.bCanStep()) { // Paint the window only if we are not in run mode. PaintWindow(); } } } //********************************************************************************************* // HCURSOR CGUIAppDlg::OnQueryDragIcon() // // Returns the icon handle. // //************************************** { return (HCURSOR)m_hIcon; } //********************************************************************************************* // LRESULT CGUIAppDlg::DefWindowProc ( UINT message, WPARAM wParam, LPARAM lParam ) // // Main window message handling loop. Generated by ClassWizard, and overridden to catch the // WM_ERASEBKGND message to stop flickering. // //************************************** { // Prevent the background of the dialog from being redrawn and causing flicker. if (message == WM_ERASEBKGND && !bGDIMode) return (LRESULT)0; // Enter a menu drawing mode if required. if (message == WM_ENTERMENULOOP || message == WM_SYSKEYDOWN) SetGDIMode(true); return CDialog::DefWindowProc(message, wParam, lParam); } //********************************************************************************************* // int CGUIAppDlg::OnCreate ( LPCREATESTRUCT lpCreateStruct ) // // Handles the WM_CREATE message. Created by AppWizard. Code is added here for first-time // initialization of the renderer and pipeline. // //************************************** { CCPUDetect detProcessor; if (CDialog::OnCreate(lpCreateStruct) == -1) return -1; // // Disable the screensaver. // SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, FALSE, &bScreensaver, 0); if (bScreensaver) SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, FALSE, 0, SPIF_SENDWININICHANGE); // // Add a palette from a resource bitmap. // // Create the main palette if there isn't one. if (!pcdbMain.ppalMain) { pcdbMain.ppalMain = ppalGetPaletteFromResource(AfxGetInstanceHandle(), IDB_PALETTE); } // Create the main clut if there isn't one. pcdbMain.CreateMainClut(); char szInstalledDir[_MAX_PATH]; GetRegString(REG_KEY_INSTALLED_DIR, szInstalledDir, sizeof(szInstalledDir), ""); if (strlen(szInstalledDir) == 0) { dprintf("Trespasser is not installed\r\n"); strcpy(szInstalledDir, "C:\\program files\\DreamWorks Interactive\\Trespasser\\"); SetRegString(REG_KEY_INSTALLED_DIR, szInstalledDir); CreateDirAlongPath(szInstalledDir); } // // THE WORLD IS INITIALIZED HERE AND NOT IN THE CONSTRUCTOR. THIS IS BECAUSE THE WINDOW HANDLE // OF THIS CLASS IS NOT VALID UNTIL THE ABOVE CALL. // // Create the audio entities. extern void* hwndGetMainHwnd(); CAudio* pca_audio = ::new CAudio(hwndGetMainHwnd(), (bool)GetRegValue(REG_KEY_AUDIO_ENABLE, TRUE), (bool)GetRegValue(REG_KEY_AUDIO_ENABLE3D, TRUE) ); pwWorld = new CWorld(); #if defined(__MWERKS__) SetupForSelfModifyingCode(AfxGetInstanceHandle()); #endif // Open the performance monitoring system // set all performance timers to read clock ticks iPSInit(); bGDIMode = false; // Create the renderer. prnshMain = new CRenderShell(m_hWnd, AfxGetApp()->m_hInstance, false); // Initialize the pipeline. pipeMain.Init(); // Add direct draw screen modes to the menu. SetDriverMenu(GetSubMenu(GetSubMenu(GetMenu()->m_hMenu, 5), 0), 0, MENU_DRIVER_FIRST); SetScreenModeMenu(GetSubMenu(GetMenu()->m_hMenu, 6), 5, MENU_WINDOW + 1); // Set the full screen flag. bIsFullScreen = FALSE; // // If the application is using the registry, set the full screen flag based on the // registry entry. // if (bGetInitFlag(FALSE)) bIsFullScreen = bGetFullScreen(); // Create an instance of the toolbar. pdlgToolbar = 0; // Set the message capture flags. bLeftCapture = false; bRightCapture = false; bDragRect = false; // Set the menu. UpdateRecentFiles(); SetMenuState(); // Start the timer. SetTimer(iDEFAULT_TIMER, iDEFAULT_TIMER_STEP, 0); MoveCameraToInitPosition(); // Add the shell to the world database. wWorld.AddShell(this); // // Set the default position of the window. // SetWindowPos(&wndTop, iGUIAPP_DEFAULT_OFFSET, iGUIAPP_DEFAULT_OFFSET, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOREDRAW); // Set the default window size. SetWindowSize(iGUIAPP_DEFAULT_SIZEMODE); // Flatten the world. wWorld.FlattenPartitions(); // Parse those wacky options. void ParseOptionFile(char *); ParseOptionFile("options.txt"); // Make the toolbar visible, but wait until after parsing the file. //ShowToolbar(bShowToolbar); // Initialize the world database for render caching. wWorld.InitializePartitions(); // Initialize the menu state. SetMenuState(); // have we managed to detect the type of the local processor?? if ( detProcessor.bProcessorDetected() ) { dprintf("LOCAL PROCESSOR: %s\n",detProcessor.strLocalProcessorName() ); //****************************************************************************************** #if TARGET_PROCESSOR == PROCESSOR_PENTIUM dprintf("TARGET PROCESSOR: Intel Pentium\n"); #elif TARGET_PROCESSOR == PROCESSOR_PENTIUMPRO dprintf("TARGET PROCESSOR: Intel Pentium Pro/Pentium II\n"); #elif TARGET_PROCESSOR == PROCESSOR_K6_3D dprintf("TARGET PROCESSOR: AMD-K6 3D\n"); #else #error Invalid [No] target processor specified #endif //****************************************************************************************** } else { dprintf("Failed to detect type of local processor - check DLL\n"); } StatsMenuState(detProcessor); // Another crude hack - convert terrain file if user requested this from command line. if (bConvertTerrain) { if (!conTerrain.bIsActive()) ToggleConTerrain(); conTerrain.CloseFileSession(); // Redraw the screen. PaintWindow(); string str_full = strConvertTRRFileName; int i_first_colon_pos = str_full.find(':'); int i_second_colon_pos = str_full.find(':', i_first_colon_pos + 1); // Remove extension from filename. string str_filename = str_full.substr(0, str_full.find('.')); string str_filename_ext = str_full.substr(str_full.find('.') + 1, 3); if (str_filename_ext == "trr") { AlwaysAssert(i_second_colon_pos == -1); string str_number = str_full.substr(i_first_colon_pos + 1); char* str_dummy; double d_number = strtod(str_number.c_str(), &str_dummy); ConvertTerrainData(str_filename.c_str(), d_number, conTerrain); } else if (str_filename_ext == "wtd") { AlwaysAssert(i_second_colon_pos != -1); string str_number = str_full.substr(i_first_colon_pos + 1, i_second_colon_pos - i_first_colon_pos - 1); char* str_dummy; double d_number = strtod(str_number.c_str(), &str_dummy); bool b_ratio = str_full.substr(i_second_colon_pos + 1) == "ratio"; bool b_conform = false; int i_third_colon_pos = str_full.find(':', i_second_colon_pos + 1); if (i_third_colon_pos != -1) b_conform = str_full.substr(i_third_colon_pos + 1) == "conform"; SaveTerrainTriangulation(str_filename.c_str(), d_number, b_ratio, b_conform, conTerrain); } else // Unrecognised extension. AlwaysAssert(false); conTerrain.CloseFileSession(); PostQuitMessage(0); } int i_qual = GetRegValue("RenderQuality", iDEFAULT_QUALITY_SETTING); SetQualitySetting(i_qual); return 0; } #if VER_TIMING_STATS //********************************************************************************************* void CGUIAppDlg::StatsMenuState(CCPUDetect& detProcessor) { //default for all processors is to use RDTSC to obtain stats SetMenuItemState(MENU_STAT_CLOCKS,true, true); gbMSRProfile = true; // we can use MSRs gbUseRDTSC = true; // we are using RDTSC gbNormalizeStats = true; // stats is MS // if processor was not detected or performance driver was not found then disable // any access to the advanced profile options if ((detProcessor.bProcessorDetected() == false) || (bPSGoing() == false)) { SetMenuItemState(MENU_STAT_MSR0,false, false); SetMenuItemState(MENU_STAT_MSR1,false, false); SetMenuItemState(MENU_STAT_RING0,false, false); SetMenuItemState(MENU_STAT_RING3,false, false); SetMenuItemState(MENU_STAT_SETMSR0,false, false); SetMenuItemState(MENU_STAT_SETMSR1,false, false); gbMSRProfile = false; return; } switch (detProcessor.cpumanProcessorMake()) { // With intel processors we must have a pentium pro or pentium with MMX case cpumanINTEL: switch ( detProcessor.cpufamProcessorModel() ) { // only pentiums with MMX support RDPMC case cpufamPENTIUM: if ((detProcessor.u4ProcessorFlags() & CPU_MMX) == 0) { // no MMX, no RDPMC.. SetMenuItemState(MENU_STAT_MSR0,false, false); SetMenuItemState(MENU_STAT_MSR1,false, false); SetMenuItemState(MENU_STAT_RING0,false, false); SetMenuItemState(MENU_STAT_RING3,false, false); SetMenuItemState(MENU_STAT_SETMSR0,false, false); SetMenuItemState(MENU_STAT_SETMSR1,false, false); gbMSRProfile = false; return; } SetMenuItemState(MENU_STAT_RING3,bPSRing3(), gbMSRProfile); SetMenuItemState(MENU_STAT_RING0,bPSRing0(), gbMSRProfile); break; // all pentium pros support RDPMC instruction case cpufamPENTIUMPRO: SetMenuItemState(MENU_STAT_RING3,bPSRing3(), gbMSRProfile); SetMenuItemState(MENU_STAT_RING0,bPSRing0(), gbMSRProfile); break; // if it is a processor that we do not know about then disable the MSRs default: SetMenuItemState(MENU_STAT_MSR0,false, false); SetMenuItemState(MENU_STAT_MSR1,false, false); SetMenuItemState(MENU_STAT_RING0,false, false); SetMenuItemState(MENU_STAT_RING3,false, false); SetMenuItemState(MENU_STAT_SETMSR0,false, false); SetMenuItemState(MENU_STAT_SETMSR1,false, false); gbMSRProfile = false; return; } break; // AMD have no performance MSRs so disable the whole thing case cpumanAMD: default: SetMenuItemState(MENU_STAT_MSR0,false, false); SetMenuItemState(MENU_STAT_MSR1,false, false); SetMenuItemState(MENU_STAT_RING0,false, false); SetMenuItemState(MENU_STAT_RING3,false, false); SetMenuItemState(MENU_STAT_SETMSR0,false, false); SetMenuItemState(MENU_STAT_SETMSR1,false, false); gbMSRProfile = false; return; } MENUITEMINFO mii; mii.cbSize = sizeof(MENUITEMINFO); mii.fMask = MIIM_SUBMENU; mii.hSubMenu = PSMakeProcessorMenuCounter0(MENU_PROFILE_STAT); SetMenuItemInfo(GetSubMenu(GetMenu()->m_hMenu, 2), MENU_STAT_SETMSR0, false, &mii); mii.cbSize = sizeof(MENUITEMINFO); mii.fMask = MIIM_SUBMENU; mii.hSubMenu = PSMakeProcessorMenuCounter1(MENU_PROFILE_STAT+250); SetMenuItemInfo(GetSubMenu(GetMenu()->m_hMenu, 2), MENU_STAT_SETMSR1, false, &mii); } #else //********************************************************************************************* void CGUIAppDlg::StatsMenuState(CCPUDetect& detProcessor) { //default for all processors is to use RDTSC to obtain stats SetMenuItemState(MENU_STAT_CLOCKS,true, true); SetMenuItemState(MENU_STAT_MSR0,false, false); SetMenuItemState(MENU_STAT_MSR1,false, false); SetMenuItemState(MENU_STAT_RING0,false, false); SetMenuItemState(MENU_STAT_RING3,false, false); SetMenuItemState(MENU_STAT_SETMSR0,false, false); SetMenuItemState(MENU_STAT_SETMSR1,false, false); } #endif //********************************************************************************************* void CGUIAppDlg::OnStatClocks() { #if VER_TIMING_STATS gbUseRDTSC = true; SetMenuItemState(MENU_STAT_CLOCKS,true, true); if (gbMSRProfile) { SetMenuItemState(MENU_STAT_MSR0,false, gbMSRProfile); SetMenuItemState(MENU_STAT_MSR1,false, gbMSRProfile); SetMenuItemState(MENU_STAT_RING0,bPSRing0(), gbMSRProfile); SetMenuItemState(MENU_STAT_RING3,bPSRing3(), gbMSRProfile); SetMenuItemState(MENU_STAT_SETMSR0,false, gbMSRProfile); SetMenuItemState(MENU_STAT_SETMSR1,false, gbMSRProfile); } if (gbUseRDTSC) { csProfileName = "Profile - Time"; gbNormalizeStats = true; conProfile.SetWindowText(csProfileName); } #endif } //********************************************************************************************* void CGUIAppDlg::OnStatMSR0() { #if VER_TIMING_STATS if (gbMSRProfile) { gbUseRDTSC = false; gu4MSRProfileTimerSelect = 0; SetMenuItemState(MENU_STAT_CLOCKS,false, true); SetMenuItemState(MENU_STAT_MSR0,true, gbMSRProfile); SetMenuItemState(MENU_STAT_MSR1,false, gbMSRProfile); SetMenuItemState(MENU_STAT_RING0,bPSRing0(), gbMSRProfile); SetMenuItemState(MENU_STAT_RING3,bPSRing3(), gbMSRProfile); SetMenuItemState(MENU_STAT_SETMSR0,false, gbMSRProfile); SetMenuItemState(MENU_STAT_SETMSR1,false, gbMSRProfile); } if ((!gbUseRDTSC) && (gu4MSRProfileTimerSelect == 0)) { csProfileName = "Profile - Event Counter 0 - "; gbNormalizeStats = false; csProfileName += strPSGetMenuText(0); conProfile.SetWindowText(csProfileName); } #endif } //********************************************************************************************* void CGUIAppDlg::OnStatMSR1() { #if VER_TIMING_STATS if (gbMSRProfile) { gbUseRDTSC = false; gu4MSRProfileTimerSelect = 1; SetMenuItemState(MENU_STAT_CLOCKS,false, true); SetMenuItemState(MENU_STAT_MSR0,false, gbMSRProfile); SetMenuItemState(MENU_STAT_MSR1,true, gbMSRProfile); SetMenuItemState(MENU_STAT_RING0,bPSRing0(), gbMSRProfile); SetMenuItemState(MENU_STAT_RING3,bPSRing3(), gbMSRProfile); SetMenuItemState(MENU_STAT_SETMSR0,false, gbMSRProfile); SetMenuItemState(MENU_STAT_SETMSR1,false, gbMSRProfile); } if ((!gbUseRDTSC) && (gu4MSRProfileTimerSelect == 1)) { csProfileName = "Profile - Event Counter 1 - "; gbNormalizeStats = false; csProfileName += strPSGetMenuText(1); conProfile.SetWindowText(csProfileName); } #endif } //********************************************************************************************* void CGUIAppDlg::OnStatRing3() { #if VER_TIMING_STATS if (gbMSRProfile) { PSRing3(!bPSRing3()); SetMenuItemState(MENU_STAT_RING3,bPSRing3(), gbMSRProfile); } #endif } //********************************************************************************************* void CGUIAppDlg::OnStatRing0() { #if VER_TIMING_STATS if (gbMSRProfile) { PSRing0(!bPSRing0()); SetMenuItemState(MENU_STAT_RING0,bPSRing0(), gbMSRProfile); } #endif } //********************************************************************************************* void CGUIAppDlg::OnChangeStatCounter0(UINT uID) { #if VER_TIMING_STATS uID -= MENU_PROFILE_STAT; PSMenu0Click(uID); if ((!gbUseRDTSC) && (gu4MSRProfileTimerSelect == 0)) { csProfileName = "Profile - Event Counter 0 - "; csProfileName += strPSGetMenuText(0); conProfile.SetWindowText(csProfileName); } #endif } //********************************************************************************************* void CGUIAppDlg::OnChangeStatCounter1(UINT uID) { #if VER_TIMING_STATS uID -= MENU_PROFILE_STAT; uID -= 250; PSMenu1Click(uID); if ((!gbUseRDTSC) && (gu4MSRProfileTimerSelect == 1)) { csProfileName = "Profile - Event Counter 1 - "; csProfileName += strPSGetMenuText(1); conProfile.SetWindowText(csProfileName); } #endif } //********************************************************************************************* void CGUIAppDlg::MoveCameraToInitPosition() { // // Move the camera to the location specified by the command line. // pcamGetCamera()->Move(CPlacement3<>(CRotate3<>(), v3InitCamPos)); } //********************************************************************************************* // void CGUIAppDlg::OnSize ( UINT nType, int cx, int cy ) // // Handles an WM_SIZE message. Resizes the main screen and raster. // //************************************** { d3dDriver.Purge(); if (prnshMain == 0 || prnshMain->iIgnoreWinCommands || bExiting) return; if (padAudioDaemon) padAudioDaemon->RemoveSubtitle(); CDialog::OnSize(nType, cx, cy); if (nType == SIZE_MINIMIZED) { } else { // Resize the direct draw surfaces. if (bGetInitFlag(FALSE)) { int i_width; int i_height; // Find the video mode matching the requested mode. bGetDimensions(i_width, i_height); Video::SetToValidMode(i_width, i_height); int i_id; for (i_id = 0; i_id <= Video::iModes; ++i_id) { if (Video::ascrmdList[i_id].iW == i_width && Video::ascrmdList[i_id].iH == i_height && Video::ascrmdList[i_id].iBits == 16) break; } Assert(i_id <= Video::iModes); CMessageNewRaster msgnewr ( i_id, bGetSystemMem(), true ); msgnewr.Dispatch(); } else { CMessageNewRaster msgnewr(-1, bSystemMem, true); msgnewr.Dispatch(); } SetMenuState(); } } //********************************************************************************************* // void CGUIAppDlg::OnLButtonDown ( UINT nFlags, CPoint point ) // // Handles the WM_LBUTTONDOWN message by setting the capture mode for left mouse button // capture. // //************************************** { // Don't do anything unless in debug mode. if (!gmlGameLoop.bDebug()) { //Fire(); } else { // Use the left mouse button to turn the GDI mode off. if (bGDIMode) SetGDIMode(false); // Transform coordinates to window-relative positions. AdjustMousePos(point); // Cache coordinates. pntCaptureMouse = point; pntCaptureCurrent = point; /* // THIS MESSAGE WAS JUST USED FOR WATER DEBUGGING. // Don't do anything unless in debug mode. if (!gmlGameLoop.bDebug()) { ptr<CCamera> pcam = CWDbQueryActiveCamera().tGet(); // Send this message to any interested entities. CMessageInput msginput ( VK_LBUTTON, pcam->campropGetProperties().vpViewport.vcVirtualX(point.x), pcam->campropGetProperties().vpViewport.vcVirtualY(point.y) ); msginput.Dispatch(); return; } */ // Don't do anything if a capture is already being performed. if (bLeftCapture || bRightCapture) return; bDragRect = !!(GetAsyncKeyState(VK_CONTROL) & 0xFFFE) && (pipeMain.iSelectedCount() == 0); if (!bDragRect) { bool b_augment = GetAsyncKeyState(VK_CONTROL) & 0xFFFE; pipeMain.bSelect(point.x, point.y, b_augment); // Keep the AI up to date. if (pipeMain.ppartLastSelected()) { CInstance* pins = ptCast<CInstance>(pipeMain.ppartLastSelected()); if (pins && pins->paniGetOwner()) gaiSystem.pinsSelected = (CInstance*)pins->paniGetOwner(); } } // Start capture. bLeftCapture = true; SetCapture(); if (bIsFullScreen) ShowCursor(FALSE); // Redraw the window. Invalidate(); } // Call base class function. CDialog::OnLButtonDown(nFlags, point); } //********************************************************************************************* // void CGUIAppDlg::OnRButtonDown ( UINT nFlags, CPoint point ) // // Handles the WM_RBUTTONDOWN message by setting the right_capture flag. // //************************************** { // Don't do anything unless in debug mode. if (!gmlGameLoop.bDebug()) return; // Don't do anything if a capture is already being performed. if (bLeftCapture || bRightCapture) return; // Transform coordinates to window-relative positions. AdjustMousePos(point); // Cache coordinates. pntCaptureMouse = point; pntCaptureCurrent = point; bool b_augment = GetAsyncKeyState(VK_CONTROL) & 0xFFFE; pipeMain.bSelect(point.x, point.y, b_augment); // Start capture. bRightCapture = true; SetCapture(); if (bIsFullScreen) ShowCursor(FALSE); // Redraw the window. Invalidate(); // Call base class function. CDialog::OnRButtonDown(nFlags, point); } //********************************************************************************************* // void CGUIAppDlg::OnLButtonUp ( UINT nFlags, CPoint point ) // // Handles the WM_LBUTTONUP message by releasing the capture. // //************************************** { bDragRect = false; // End capture. if (bLeftCapture) { bLeftCapture = false; ReleaseMouseCapture(); if (pphSystem->bShowBones) // Redraw with bones, which were temporarily disabled. Invalidate(); } // Call base class function. CDialog::OnLButtonUp(nFlags, point); } //********************************************************************************************* // void CGUIAppDlg::OnRButtonUp ( UINT nFlags, CPoint point ) // // Handles the WM_RBUTTONUP message by releasing the capture. // //************************************** { // End capture. if (bRightCapture) { bRightCapture = false; ReleaseMouseCapture(); if (pphSystem->bShowBones) // Redraw with bones, which were temporarily disabled. Invalidate(); } // Call base class function. CDialog::OnRButtonUp(nFlags, point); } //********************************************************************************************* // void CGUIAppDlg::ReleaseMouseCapture() // // Releases the mouse from capture mode. // //************************************** { // Make sure capture flags have been turned off. if (bLeftCapture || bRightCapture) { return; } // Release message capture. ReleaseCapture(); /* // // Move the mouse to a position reflecting its use. // int i_x = 0; int i_y = 0; RECT rect; // Window position. // Get the window position. GetWindowRect(&rect); if (!prnshMain->bIsFullScreen) { rect.top += GetSystemMetrics(SM_CYMENU) + GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYSIZEFRAME); rect.left += GetSystemMetrics(SM_CXSIZEFRAME); } // Move the cursor position depending on movement mode. switch (egiuMode) { case egiuCAMERA: // Position in the centre of the camera. i_x = prasMainScreen->iWidth / 2; i_y = prasMainScreen->iHeight / 2; break; case egiuOBJECT: // Position over the object crosshair. pipeMain.bGetCentreofSelectedObject(i_x, i_y); break; } // Adjust position to be relative to the edge of the main window. i_x += rect.left; i_y += rect.top; if (pipeMain.pinsSelectedShape) // Move the cursor. SetCursorPos(i_x, i_y); //ClipCursor(NULL); */ if (bIsFullScreen) ShowCursor(TRUE); } //********************************************************************************************* // void CGUIAppDlg::OnMouseMove ( UINT nFlags, CPoint point ) // // Handles the WM_MOUSEMOVE message by manipulating the object or camera. // //************************************** { int i_screen_width; int i_screen_height; // Don't do anything if no capture is being performed. if (!bLeftCapture && !bRightCapture) return; // Transform coordinates to window-relative positions. AdjustMousePos(point); // // Get the mouse positions based on unit screen measurements. // if (bDragRect) { pipeMain.Select(pntCaptureMouse, pntCaptureCurrent); } else { GetWindowSize(m_hWnd, i_screen_width, i_screen_height); float f_mouse_x = (float)(point.x - pntCaptureCurrent.x) / (float)i_screen_width; float f_mouse_y = (float)(point.y - pntCaptureCurrent.y) / (float)i_screen_height; // Move the camera or an object. if (pipeMain.iSelectedCount()) MoveObjects(f_mouse_x, f_mouse_y); else MoveCamera(f_mouse_x, f_mouse_y); } pntCaptureCurrent = point; // Flag to disable bones, etc while moving. bJustMoved = true; // Redraw the window. Invalidate(); // Call base class function. CDialog::OnMouseMove(nFlags, point); } //********************************************************************************************* // void CGUIAppDlg::OnLButtonDblClk ( UINT nFlags, CPoint point ) // // Handles the WM_LMOUSEDBLCLK message by editing the object or camera. // //************************************** { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // // End capture. // if (bLeftCapture || bRightCapture) { ReleaseCapture(); //ClipCursor(NULL); if (bIsFullScreen) ShowCursor(TRUE); } bLeftCapture = false; bRightCapture = false; if (nFlags & MK_SHIFT) { OnSoundMaterialProp(); } else { // Edit object. EditObject(); } // Call base class member function. CDialog::OnLButtonDblClk(nFlags, point); } //********************************************************************************************* bool CGUIAppDlg::bSetScreenMode(int i_mode, bool b_system_mem, bool b_force) { if (padAudioDaemon) padAudioDaemon->RemoveSubtitle(); if (bWithin(i_mode, -1, Video::iModes-1)) { if (!b_force && iScreenMode == i_mode && bSystemMem == b_system_mem) return true; iScreenMode = i_mode; int i_width; int i_height; int i_bitdepth; if (i_mode == -1) { if (bIsFullScreen) { // Set window flags to windowed mode. SetWindowMode(m_hWnd, false); // Move the window to stored positions. MoveWindow(&rectWindowedPos, TRUE); bIsFullScreen = false; } // // Get the client area of the main window if in windowed mode. // GetWindowSize(m_hWnd, i_width, i_height); i_bitdepth = 0; } else { i_width = Video::ascrmdList[i_mode].iW; i_height = Video::ascrmdList[i_mode].iH; i_bitdepth = Video::ascrmdList[i_mode].iBits; // // Set window mode and store window position only if the application was // previously in windowed mode. // if (!bIsFullScreen) { GetWindowRect(&rectWindowedPos); SetWindowMode(m_hWnd, true); bIsFullScreen = true; ShowToolbar(FALSE); } } // Create the raster. Assert(prnshMain); prnshMain->bCreateScreen(i_width, i_height, i_bitdepth, b_system_mem); SetGDIMode(false); // Get the background colour. clrBackground = prenMain->pSettings->clrBackground; bSystemMem = !prasMainScreen->bVideoMem; // Return flag indicating command was successful. lbAlphaConstant.Setup(prasMainScreen.ptPtrRaw()); lbAlphaTerrain.CreateBlend(prasMainScreen.ptPtrRaw(), clrDefEndDepth); lbAlphaWater.CreateBlendForWater(prasMainScreen.ptPtrRaw()); abAlphaTexture.Setup(prasMainScreen.ptPtrRaw()); return true; } return false; } //********************************************************************************************* bool CGUIAppDlg::bSetRenderer(uint u_id) { int i_mode_id = (int)u_id - MENU_DRIVER_FIRST; // Screen mode ID. return prnshMain->bChangeRenderer(i_mode_id); } //********************************************************************************************* void CGUIAppDlg::SetMenuItemState(int i_id, bool b_checked, bool b_enabled) { CMenu* pmenu = GetMenu(); Assert(pmenu); pmenu->EnableMenuItem(i_id, MF_BYCOMMAND | (b_enabled ? MF_ENABLED : MF_GRAYED)); pmenu->CheckMenuItem(i_id, MF_BYCOMMAND | (b_checked ? MF_CHECKED : MF_UNCHECKED)); } //********************************************************************************************* void CGUIAppDlg::SetRenderFeatureState(int i_id, ERenderFeature erf) { if (prenMain) SetMenuItemState(i_id, prenMain->pSettings->seterfState[erf], prenMain->pScreenRender->seterfModify()[erf]); } //********************************************************************************************* static UINT AFXAPI AfxGetFileName(LPCTSTR lpszPathName, LPTSTR lpszTitle, UINT nMax) { ASSERT(lpszTitle == NULL || AfxIsValidAddress(lpszTitle, _MAX_FNAME)); ASSERT(AfxIsValidString(lpszPathName, FALSE)); // always capture the complete file name including extension (if present) LPTSTR lpszTemp = (LPTSTR)lpszPathName; for (LPCTSTR lpsz = lpszPathName; *lpsz != '\0'; lpsz = _tcsinc(lpsz)) { // remember last directory/drive separator if (*lpsz == '\\' || *lpsz == '/' || *lpsz == ':') lpszTemp = (LPTSTR)_tcsinc(lpsz); } // lpszTitle can be NULL which just returns the number of bytes if (lpszTitle == NULL) return lstrlen(lpszTemp)+1; // otherwise copy it into the buffer provided lstrcpyn(lpszTitle, lpszTemp, nMax); return 0; } //********************************************************************************************* static void AbbreviateName(LPTSTR lpszCanon, int cchMax, BOOL bAtLeastName) { int cchFullPath, cchFileName, cchVolName; const TCHAR* lpszCur; const TCHAR* lpszBase; const TCHAR* lpszFileName; lpszBase = lpszCanon; cchFullPath = lstrlen(lpszCanon); cchFileName = AfxGetFileName(lpszCanon, NULL, 0) - 1; lpszFileName = lpszBase + (cchFullPath-cchFileName); // If cchMax is more than enough to hold the full path name, we're done. // This is probably a pretty common case, so we'll put it first. if (cchMax >= cchFullPath) return; // If cchMax isn't enough to hold at least the basename, we're done if (cchMax < cchFileName) { lstrcpy(lpszCanon, (bAtLeastName) ? lpszFileName : &afxChNil); return; } // Calculate the length of the volume name. Normally, this is two characters // (e.g., "C:", "D:", etc.), but for a UNC name, it could be more (e.g., // "\\server\share"). // // If cchMax isn't enough to hold at least <volume_name>\...\<base_name>, the // result is the base filename. lpszCur = lpszBase + 2; // Skip "C:" or leading "\\" if (lpszBase[0] == '\\' && lpszBase[1] == '\\') // UNC pathname { // First skip to the '\' between the server name and the share name, while (*lpszCur != '\\') { lpszCur = _tcsinc(lpszCur); ASSERT(*lpszCur != '\0'); } } // if a UNC get the share name, if a drive get at least one directory ASSERT(*lpszCur == '\\'); // make sure there is another directory, not just c:\filename.ext if (cchFullPath - cchFileName > 3) { lpszCur = _tcsinc(lpszCur); while (*lpszCur != '\\') { lpszCur = _tcsinc(lpszCur); ASSERT(*lpszCur != '\0'); } } ASSERT(*lpszCur == '\\'); cchVolName = lpszCur - lpszBase; if (cchMax < cchVolName + 5 + cchFileName) { lstrcpy(lpszCanon, lpszFileName); return; } // Now loop through the remaining directory components until something // of the form <volume_name>\...\<one_or_more_dirs>\<base_name> fits. // // Assert that the whole filename doesn't fit -- this should have been // handled earlier. ASSERT(cchVolName + (int)lstrlen(lpszCur) > cchMax); while (cchVolName + 4 + (int)lstrlen(lpszCur) > cchMax) { do { lpszCur = _tcsinc(lpszCur); ASSERT(*lpszCur != '\0'); } while (*lpszCur != '\\'); } // Form the resultant string and we're done. lpszCanon[cchVolName] = '\0'; lstrcat(lpszCanon, _T("\\...")); lstrcat(lpszCanon, lpszCur); } //********************************************************************************************* // void CGUIAppDlg::UpdateRecentFiles() // // Update the recent file list. // //************************************** { CMenu* pmenu = GetMenu(); if (pmenu == 0) return; // // Setup the recent file list. // int i; for (i = 0; i <= 5; i++) pmenu->RemoveMenu(MENU_OPEN_LAST+i, MF_BYCOMMAND); for (i = 0; i < 5; i++) { char str_key[32]; char str_name[512]; sprintf(str_key, "LastFileOpened%d", i); GetRegString(str_key, str_name, sizeof(str_name), ""); if (strlen(str_name)) { AbbreviateName(str_name, 32, TRUE); pmenu->InsertMenu(MENU_RESET, MF_BYCOMMAND | MF_STRING, MENU_OPEN_LAST+i, str_name); } } // Insert seperator. pmenu->InsertMenu(MENU_RESET, MF_BYCOMMAND | MF_SEPARATOR, MENU_OPEN_LAST+i); // Re-draw the menu. DrawMenuBar(); } //********************************************************************************************* // void CGUIAppDlg::AddRecentFile(char *str_name) // // Add a file to the recent file list. // //************************************** { char str_last_key[32]; char str_key[32]; char str_filename[512]; sprintf(str_last_key, "LastFileOpened%d", 0); // Push items down. for (int i = 1; i < 5; i++) { sprintf(str_key, "LastFileOpened%d", i); GetRegString(str_key, str_filename, sizeof(str_filename), ""); SetRegString(str_last_key, str_filename); strcpy(str_last_key, str_key); } // Add this item. SetRegString(str_key, str_name); UpdateRecentFiles(); } //********************************************************************************************* void CGUIAppDlg::ShowLoadedFile(char *str_name) { CString cstr_title; // Get current title. GetWindowText(cstr_title); // Append file name (file part only). int i_index = 0; for (int i = 0; str_name[i] != '\0'; i++) if (str_name[i] == '\\' || str_name[i] == '/' || str_name[i] == ':') i_index = i+1; cstr_title += " - "; cstr_title += (str_name + i_index); // Set title. SetWindowText(cstr_title); } //********************************************************************************************* void CGUIAppDlg::SetMenuState() { // // Set the presorting menu items. // if (prenMain) { SetMenuItemState(MENU_DEPTHSORT, prenMain->pSettings->esSortMethod == esDepthSort, true); SetMenuItemState(MENU_PRESORT_NONE, prenMain->pSettings->esSortMethod == esNone, true); SetMenuItemState(MENU_PRESORT_FTOB, prenMain->pSettings->esSortMethod == esPresortFrontToBack, true); SetMenuItemState(MENU_PRESORT_BTF, prenMain->pSettings->esSortMethod == esPresortBackToFront, true); SetMenuItemState(MENU_SHADOWS, prenMain->pSettings->bShadow, true); SetMenuItemState(MENU_DETAIL, prenMain->pSettings->bDetailReduce); SetMenuItemState(MENU_DOUBLEV, prenMain->pSettings->bDoubleVertical); SetMenuItemState(MENU_HALFSCAN, prenMain->pSettings->bHalfScanlines); SetMenuItemState(MENU_SKY_DISABLE, prenMain->pSettings->bDrawSky); } SetMenuItemState(MENU_CACHE_INTERSECT, rcsRenderCacheSettings.bAddIntersectingObjects); SetMenuItemState(MENU_SHADOW_TERRAIN, NMultiResolution::CTextureNode::bEnableShadows); SetMenuItemState(MENU_SHADOW_TERRAIN_MOVING, NMultiResolution::CTextureNode::bEnableMovingShadows); SetMenuItemState(MENU_PRELOAD, gmlGameLoop.bPreload); SetMenuItemState(MENU_FREEZECACHES, rcsRenderCacheSettings.bFreezeCaches); // // Set the game control menu items. // SetMenuItemState(MENU_PLAY, gmlGameLoop.egmGameMode == egmPLAY); SetMenuItemState(MENU_DEBUG, gmlGameLoop.egmGameMode == egmDEBUG); SetMenuItemState(MENU_PAUSE, gmlGameLoop.bPauseGame, gmlGameLoop.egmGameMode == egmPLAY); SetMenuItemState(MENU_AI, gaiSystem.bActive); SetMenuItemState(MENU_PHYSICS, pphSystem->bActive); SetMenuItemState(MENU_ZONLYEDIT, bZOnlyEdit); // Direct3D menu. SetMenuItemState(MENU_ACCELERATION, d3dDriver.bUseD3D(), d3dDriver.bInitEnabled()); // Set the view states. SetMenuItemState(MENU_CONSOLE, bShowConsole); SetMenuItemState(MENU_STATS, bShowStats); SetMenuItemState(MENU_HARDWARE_STATS, bShowHardwareStats); SetMenuItemState(MENU_AVG_STATS, bAvgStats); SetMenuItemState(MENU_FPS, bShowFPS); SetMenuItemState(MENU_CACHE_STATS, rcstCacheStats.bKeepStats); SetMenuItemState(MENU_VIEW_SPHERES, bShowSpheres); SetMenuItemState(MENU_VIEW_WIRE, bShowWire); SetMenuItemState(MENU_VIEW_PINHEAD, bShowPinhead); SetMenuItemState(MENU_VIEW_BONES, pphSystem->bShowBones); SetMenuItemState(MENU_VIEW_QUADS, NMultiResolution::CTextureNode::bOutlineNodes); SetMenuItemState(MENU_VIEW_TRIGGERS, CRenderContext::bRenderTriggers); // Set the crosshair states. SetMenuItemState(MENU_VIEW_HAIRS, bShowHairs); SetMenuItemState(MENU_STATIC_HANDLES, bStaticHandles); SetMenuItemState(MENU_VIEW_CROSSHAIR_RADIUS, bCrosshairRadius); SetMenuItemState(MENU_VIEW_CROSSHAIR_VEGETATION, bCrosshairVegetation); extern bool bEditTrnObjs; SetMenuItemState(MENU_VIEW_CROSSHAIR_TERRAINTEXTURES, bEditTrnObjs); // Set the bones sub-states. SetMenuItemState(MENU_VIEW_BONES_BOXES, CPhysicsInfo::setedfMain[edfBOXES]); SetMenuItemState(MENU_VIEW_BONES_PHYSICS, CPhysicsInfo::setedfMain[edfBOXES_PHYSICS]); SetMenuItemState(MENU_VIEW_BONES_WAKE, CPhysicsInfo::setedfMain[edfBOXES_WAKE]); SetMenuItemState(MENU_VIEW_BONES_QUERY, CPhysicsInfo::setedfMain[edfBOXES_QUERY]); SetMenuItemState(MENU_VIEW_BONES_MAGNETS, CPhysicsInfo::setedfMain[edfMAGNETS]); SetMenuItemState(MENU_VIEW_BONES_SKELETONS, CPhysicsInfo::setedfMain[edfSKELETONS]); SetMenuItemState(MENU_VIEW_BONES_ATTACH, CPhysicsInfo::setedfMain[edfATTACHMENTS]); SetMenuItemState(MENU_VIEW_BONES_WATER, CPhysicsInfo::setedfMain[edfWATER]); SetMenuItemState(MENU_VIEW_BONES_RAYCAST, CPhysicsInfo::setedfMain[edfRAYCASTS]); // Set the camera state. CInstance* pins_attach = pcamGetCamera()->pinsAttached(); SetMenuItemState(MENU_CAMERAPLAYER, ptCast<CPlayer>(pins_attach) != 0); SetMenuItemState(MENU_CAMERASELECTED, pins_attach && !ptCast<CPlayer>(pins_attach) && !pcamGetCamera()->bHead()); SetMenuItemState(MENU_CAMERASELECTEDHEAD, pins_attach && !ptCast<CPlayer>(pins_attach) && pcamGetCamera()->bHead()); SetMenuItemState(MENU_CAMERAFREE, !pins_attach); SetMenuItemState(MENU_CAMERA2M, bCameraFloating); SetMenuItemState(MENU_ROTATE_WORLDZ, bRotateAboutWorldZ); // Set the physics player state. SetMenuItemState(MENU_PLAYERPHYSICS, gpPlayer && gpPlayer->bPhysics); SetMenuItemState(MENU_PLAYERINVULNERABLE, gpPlayer->bInvulnerable); SetMenuItemState(MENU_PHYSICS_SLEEP, pphSystem->bAllowSleep); SetMenuItemState(MENU_PHYSICS_STEP, bPhysicsStep); // // Set the screenmode menu. // // Set the Windowed menu. SetMenuItemState(MENU_WINDOW, !bIsFullScreen); SetMenuItemState(MENU_SYSTEM_MEM, bSystemMem); // Set Rendering options menu. SetRenderFeatureState(MENU_SCREENCLIP, erfRASTER_CLIP); SetRenderFeatureState(MENU_SCREENCULL, erfRASTER_CULL); SetRenderFeatureState(MENU_ZBUFFER, erfZ_BUFFER); SetRenderFeatureState(MENU_LIGHT, erfLIGHT); SetRenderFeatureState(MENU_LIGHT_SHADE, erfLIGHT_SHADE); SetRenderFeatureState(MENU_FOG, erfFOG); SetRenderFeatureState(MENU_FOG_SHADE, erfFOG_SHADE); SetRenderFeatureState(MENU_SPECULAR, erfSPECULAR); SetRenderFeatureState(MENU_COLOURED, erfCOLOURED_LIGHTS); SetRenderFeatureState(MENU_TEXTURE, erfTEXTURE); SetRenderFeatureState(MENU_TRANSPARENT, erfTRANSPARENT); SetRenderFeatureState(MENU_BUMP, erfBUMP); SetRenderFeatureState(MENU_WIREFRAME, erfWIRE); SetRenderFeatureState(MENU_ALPHA_COLOUR, erfALPHA_COLOUR); SetRenderFeatureState(MENU_TRAPEZOIDS, erfTRAPEZOIDS); SetRenderFeatureState(MENU_SUBPIXEL, erfSUBPIXEL); SetRenderFeatureState(MENU_PERSPECTIVE, erfPERSPECTIVE); SetRenderFeatureState(MENU_MIPMAP, erfMIPMAP); SetRenderFeatureState(MENU_DITHER, erfDITHER); SetRenderFeatureState(MENU_FILTER, erfFILTER); SetRenderFeatureState(MENU_FILTER_EDGES,erfFILTER_EDGES); SetMenuItemState(MENU_FILTER_CACHES, d3dDriver.bFilterImageCaches()); SetRenderFeatureState(MENU_RENDER_CACHE, erfCOPY); SetMenuItemState(MENU_WATER_ALPHA, CEntityWater::bAlpha); SetMenuItemState(MENU_WATER_INTERPOLATE, CEntityWater::bInterp); // Set the render cache menus. switch (rcsRenderCacheSettings.erctMode) { case ercmCACHE_OFF: SetMenuItemState(MENU_RENDER_CACHE, false); SetMenuItemState(MENU_RENDER_CACHE_TEST, false); break; case ercmCACHE_ON: SetMenuItemState(MENU_RENDER_CACHE, true); SetMenuItemState(MENU_RENDER_CACHE_TEST, false); break; default: Assert(0); } // Image cache state. SetMenuItemState(MENU_CONVEXCACHES, rcsRenderCacheSettings.bUseConvexPolygons); SetMenuItemState(MENU_FORCEINTERSECTING, rcsRenderCacheSettings.bForceIntersecting); // Image cache border. SetMenuItemState(MENU_FASTMODE, bFastMode); // Occlusion state. SetMenuItemState(MENU_OCCLUDE_OBJECTS, COcclude::bUseObjectOcclusion); SetMenuItemState(MENU_OCCLUDE_POLYGONS, COcclude::bUsePolygonOcclusion); SetMenuItemState(MENU_OCCLUDE_OCCLUDE, COcclude::bRemoveOccluded); SetMenuItemState(MENU_OCCLUDE_CAMERAVIEWTEST, COcclude::bTestCameraView); // Scheduler state. SetMenuItemState(MENU_SCHEDULER_USE, CScheduler::bUseScheduler); // Delaunay test code. SetMenuItemState(MENU_DELAUNAYTEST, bDelaunayTest); // Terrain test code. SetMenuItemState(MENU_TERRAINTEST, bTerrainTest); // Console windows. SetMenuItemState(MENU_CONPHYSICS, conPhysics.bIsActive()); SetMenuItemState(MENU_DRAWPHYSICS, pdldrPhysics && pdldrPhysics->bIsVisible()); SetMenuItemState(MENU_AI, gaiSystem.bShow3DInfluences); SetMenuItemState(MENU_ARTSTATS, conArtStats.bIsActive()); SetMenuItemState(MENU_PREDICTMOVEMENT, conPredictMovement.bIsActive()); // Mipmap submenu state. SetMenuItemState(MENU_MIPMAP_NORMAL, false); SetMenuItemState(MENU_MIPMAP_SMALLEST, false); SetMenuItemState(MENU_MIPMAP_NO_LARGEST, false); switch (CTexture::emuMipUse) { case emuNORMAL: SetMenuItemState(MENU_MIPMAP_NORMAL, true); break; case emuSMALLEST: SetMenuItemState(MENU_MIPMAP_SMALLEST, true); break; case emuNO_LARGEST: SetMenuItemState(MENU_MIPMAP_NO_LARGEST, true); break; default: Assert(0); } // Terrain flags. CWDbQueryTerrain wqtrr; SetMenuItemState(ID_EDIT_TERRAIN_TERRAINSOUNDS, bTerrainSound); switch (gpInputDeemone->ecmGetControlMethod()) { case ecm_DefaultControls: SetMenuItemState(MENU_CONTROLS_DEFAULTCONTROLS,TRUE); SetMenuItemState(MENU_CONTROLS_STANDARDJOYSTICK,FALSE); break; case ecm_Joystick: SetMenuItemState(MENU_CONTROLS_DEFAULTCONTROLS,FALSE); SetMenuItemState(MENU_CONTROLS_STANDARDJOYSTICK,TRUE); break; } if (gpskyRender==NULL) { SetMenuItemState(MENU_SKY_TEXTURE, true); SetMenuItemState(MENU_SKY_FILL, false); } else { SetMenuItemState(MENU_SKY_TEXTURE, gpskyRender->bSkyTextured()); SetMenuItemState(MENU_SKY_FILL, gpskyRender->bSkyFill()); } // Set the automatic scene save state. SetMenuItemState(MENU_ASSERTSAVE, bGetAutoSave()); SetMenuItemState(MENU_IGNORE_MSG_RECIPIENTS, CMessage::bIgnoreRegisteredRecipients); // Redraw the screen. Invalidate(); } #if VER_TIMING_STATS // Timer for FPS count. static CCycleTimer ctmrFPS; #endif //__int64 i8FrameStart = 0; //__int64 i8FrameStop = 0; //********************************************************************************************* // void CGUIAppDlg::PaintWindow ( ) // // Code to draw a window or surface. // //************************************** { CCycleTimer ctmr; // Don't paint if the renderer has not yet been set up. if (prnshMain == 0) return; // Enforce GDI shit. if (bGDIMode) { Assert(bIsFullScreen); prasMainScreen->FlipToGDISurface(); DrawMenuBar(); RedrawWindow(0, 0, RDW_FRAME); return; } if (!prnshMain->bBeginPaint()) return; //prasMainScreen->ClearBorder(); pipeMain.Paint(); // Draw dragging rectangle if necessary. if (bDragRect) { CDraw draw(prasMainScreen); draw.Style(PS_DOT); draw.Colour(CColour(1.0f, 0.0f, 0.0f)); draw.Line(pntCaptureMouse.x, pntCaptureMouse.y, pntCaptureCurrent.x, pntCaptureMouse.y); draw.Line(pntCaptureMouse.x, pntCaptureCurrent.y, pntCaptureCurrent.x, pntCaptureCurrent.y); draw.Line(pntCaptureMouse.x, pntCaptureMouse.y, pntCaptureMouse.x, pntCaptureCurrent.y); draw.Line(pntCaptureCurrent.x, pntCaptureMouse.y, pntCaptureCurrent.x, pntCaptureCurrent.y); } // Draw various object adornments, such as crosshairs and bounding spheres. pipeMain.MarkObjects ( prasMainScreen, gmlGameLoop.bDebug() && (bShowHairs || bLeftCapture || bRightCapture), // Cross-hairs. bShowSpheres, bShowWire, bShowPinhead ); bJustMoved = false; // Add the total time for painting to the frame stat. proProfile.psFrame.Add(ctmr(), 1); #if bDUMP_STATS // Finish rendering and flip surfaces. prnshMain->EndPaint(); StatsDump(); #else StatsDisplay(); // Finish rendering and flip surfaces. prnshMain->EndPaint(); // Add additional time to the frame stat. proProfile.psFrame.Add(ctmr()); #endif } //********************************************************************************************* // void CGUIAppDlg::DisplayCacheStats() // // Displays render cache stats. // //************************************** { // Do nothing if render cache stats are not being maintained. if (!rcstCacheStats.bKeepStats) return; static CConsoleBuffer con_cache(48, 24); con_cache.SetActive(true); // Display the number of caches. con_cache.Print("Num Caches: %ld\n", iNumCaches()); // Display the average number of objects per cache. if (iNumCaches() > 0) { con_cache.Print ( "Avg Objs per Cache: %1.1f\n", float(rcstCacheStats.iNumCachedObjects) / float(iNumCaches()) ); // Display the number of updated caches. con_cache.Print ( "Caches Updated: %1.1f%%\n", float(rcstCacheStats.iNumCachesUpdated) / float(iNumCaches()) * 100.0f ); con_cache.Print ( "Avg Age of Caches: %1.1f\n", float(rcstCacheStats.iTotalCacheAge) / float(iNumCaches()) ); // Display the number of euthanized caches. con_cache.Print ( "Euthanized Caches: %ld\n", rcstCacheStats.iNumCachesEuthanized ); // Display the amount of memory associated with caches. int i_cachemem = iCacheMemoryUsed(); if (i_cachemem >= 1024) con_cache.Print ( "Cache Memory Used: %ld kb\n", i_cachemem >> 10 ); else con_cache.Print ( "Cache Memory Used: %ld bytes\n", i_cachemem ); } // Display stats associated with the cache heap. { int i_num_nodes; // Number of memory allocations. int i_mem_used; // Amount of memory allocated. // Get the info about the heap used for the cache. fxhHeap.GetInfo(i_num_nodes, i_mem_used); // Display the number of memory nodes allocated. con_cache.Print("Heap Nodes: %ld\n", i_num_nodes); // Display the amount of memory allocated. con_cache.Print("Heap Mem (kb): %ld\n", i_mem_used >> 10); } // Reset render cache statistics. rcstCacheStats.Reset(); prnshMain->ShowConsoleOnScreen(con_cache); con_cache.ClearScreen(); } //********************************************************************************************* // void CGUIAppDlg::ShowToolbar ( bool b_show ) // // Displays the toolbar in windowed mode if the toolbar is not already displayed. // //************************************** { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Show the toolbar only if not in full screen mode. if (bIsFullScreen) return; if (!pdlgToolbar) { // Create an instance of the toolbar. pdlgToolbar = new CTool(); } // Make sure the toolbar isn't already showing. pdlgToolbar->DestroyWindow(); // Show the toolbar if the b_show flag is 'true.' if (b_show) { pdlgToolbar->Create((UINT)IDD_FLOATTOOLS, this); pdlgToolbar->ShowWindow(SW_SHOWNORMAL); } } //********************************************************************************************* // void CGUIAppDlg::MoveCamera ( float f_mouse_x, float f_mouse_y ) // // Moves the camera using mouse input. // //************************************** { // // Get key states. // bool b_shift_key = (GetAsyncKeyState(VK_SHIFT) & (SHORT)0xFFFE) != 0; CPlacement3<> p3_cam = pcamGetCamera()->p3GetPlacement(); if (bLeftCapture) { // Create the direction and rotation vectors. CVector3<> v3_camdir; if (b_shift_key) v3_camdir = CVector3<> (2.0f * f_mouse_x, 0.0f, 2.0f * f_mouse_y); else v3_camdir = CVector3<> (2.0f * f_mouse_x, 2.0f * f_mouse_y, 0.0f); // Move the camera in the camera's direction. p3_cam.v3Pos += v3_camdir * p3_cam.r3Rot; } else if (bRightCapture) { // // If the right mouse button is down, perform xz rotations. // First rotate around local Z, then local X. // Local rotations are performed by pre-concatentating them to the current rotation. // CRotate3<> r3_cam = CRotate3<>(-d3XAxis, (CAngle)(dDegreesToRadians(90.0f) * f_mouse_y)) * CRotate3<>((b_shift_key ? d3YAxis : -d3ZAxis), (CAngle)(dDegreesToRadians(90.0f) * f_mouse_x)); p3_cam.r3Rot = r3_cam * p3_cam.r3Rot; } pcamGetCamera()->Move(p3_cam); } //********************************************************************************************* // void CGUIAppDlg::MoveObjects ( float f_mouse_x, float f_mouse_y ) // // Moves all selected objects' positions or orientations using mouse input. // //************************************** { // // Get key states. // bool b_shift_key = (GetAsyncKeyState(VK_SHIFT) & (SHORT)0xFFFE) != 0; bool b_alt_key = (GetAsyncKeyState(VK_MENU) & (SHORT)0xFFFE) != 0; // // Scale object. // if (bLeftCapture && b_alt_key) { // Scale me! Scales each object separately. float f_scale = 1.0f + (f_mouse_x - f_mouse_y) * 0.5f; if (f_scale < 0.5) f_scale = 0.5f; // Apply the rotation to the objects. forall (pipeMain.lsppartSelected, TSelectedList, itppart) { // This is dangerous, as it violates some abstraction barrier. CPartition* ppart = (*itppart); ppart->SetScale(ppart->fGetScale() * f_scale); // Move it to ensure that the partitions are current. ppart->Move(ppart->pr3Presence()); } return; } // // Translate position or rotate in position. // if (bLeftCapture) { CVector3<> v3_objdir; if (!b_shift_key) { // // If the shift key is down, perform xy translations. // // Get the translation vector. v3_objdir = CVector3<>(f_mouse_x, -f_mouse_y, 0.0); } else { // // If the shift key is not down, perform xz translations. // // Get the translation vector. v3_objdir = CVector3<>(f_mouse_x, 0.0, -f_mouse_y); } // Translate it from camera to world space. v3_objdir *= pcamGetCamera()->r3Rot(); // Scale it by distance from camera. v3_objdir *= (pcamGetCamera()->v3Pos() - pipeMain.ppartLastSelected()->v3Pos()).tLen(); // If in Z Edit only mode, keep only the Z part. if (bZOnlyEdit) { v3_objdir.tX = 0.0f; v3_objdir.tY = 0.0f; } // Apply the vector to the objects. forall (pipeMain.lsppartSelected, TSelectedList, itppart) { // Move the object in the world partitioning structure, and physics system. CPlacement3<> p3 = (*itppart)->pr3Presence(); p3.v3Pos += v3_objdir; (*itppart)->Move(p3); } } else { // // If the shift key is down, perform yx rotations, else zx rotations. // CRotate3<> r3_objrot = CRotate3<>((b_shift_key ? d3YAxis : d3ZAxis), CAngle(dPI * f_mouse_x)) * CRotate3<>(d3XAxis, CAngle(dPI * f_mouse_y)); // Make the rotation camera-relative by transforming it from world to camera space, and back. r3_objrot = ~pcamGetCamera()->r3Rot() * r3_objrot * pcamGetCamera()->r3Rot(); // In Z edit only mode, use only a Z edit. if (bZOnlyEdit) r3_objrot = CRotate3<>(d3ZAxis, CAngle(dPI * f_mouse_x)); // Centre the rotation on the last-selected object. CPlacement3<> p3_objrot = TransformAt(r3_objrot, pipeMain.ppartLastSelected()->v3Pos()); // Apply the rotation to the objects. forall (pipeMain.lsppartSelected, TSelectedList, itppart) { // Move the object in the world partitioning structure, and physics system. CPlacement3<> p3 = (*itppart)->pr3Presence().p3Placement() * p3_objrot; (*itppart)->Move(p3); } } } //********************************************************************************************* // void CGUIAppDlg::AdjustMousePos ( CPoint& point // The mouse position relative to the window. ) // // Adjusts the mouse coordinates to account for full screen mode. This function only does // something in full screen mode. // //************************************** { // Do something only if in full screen mode. if (!bIsFullScreen) return; // Add the menu bar size if in full screen mode. point.y += GetSystemMetrics(SM_CYMENUSIZE); } //********************************************************************************************* void CGUIAppDlg::OpenLightProperties(rptr<CLight> plt) { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Create the light properties dialog box. if (pltdlgLightProperties == 0) { pltdlgLightProperties = new CLightProperties(); } // Destroy any open light properties dialog to ensure the dialog is sized properly. pltdlgLightProperties->DestroyWindow(); // Create and display the light properties dialog. pltdlgLightProperties->Create(IDD_LIGHT_PROPERTIES, this); pltdlgLightProperties->Show(plt); } //********************************************************************************************* void CGUIAppDlg::OpenCameraProperties() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pcamdlgCameraProperties == 0) { pcamdlgCameraProperties = new CCameraProperties(); pcamdlgCameraProperties->Create(IDD_CAMERA_PROPERTIES, this); } pcamdlgCameraProperties->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OpenObjectDialogProperties(CInstance* pins) { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; Assert(pins); if (pdlgobjDialogObject == 0) { pdlgobjDialogObject = new CDialogObject(); pdlgobjDialogObject->Create(IDD_OBJECT_PROPERTIES, this); } pdlgobjDialogObject->SetInstance(pins); pdlgobjDialogObject->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OnMaterialProperties() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; CInstance* pins = ptCast<CInstance>(pipeMain.ppartLastSelected()); if (!pins) return; if (pdlgDialogMaterial == 0) { pdlgDialogMaterial = newCDialogMaterial(pins); pdlgDialogMaterial->Create(IDD_MATERIAL, this); } else pdlgDialogMaterial = newCDialogMaterial(pins); pdlgDialogMaterial->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OpenMagnetProperties(CMagnetPair* pmp) { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; Assert(pmp); if (pdlgmagDialogMagnet == 0) { pdlgmagDialogMagnet = new CDialogMagnet(); pdlgmagDialogMagnet->Create(IDD_MAGNET, this); } pdlgmagDialogMagnet->SetMagnet(pmp); pdlgmagDialogMagnet->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OnPlayerProperties() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pdlgDialogPlayer == 0) { pdlgDialogPlayer = newCDialogPlayer(); pdlgDialogPlayer->Create(IDD_PLAYER, this); } pdlgDialogPlayer->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OpenPerspectiveDialog() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pdlgPerspectiveSubdivide == 0) { pdlgPerspectiveSubdivide = new CPerspectiveSubdivideDialog(); pdlgPerspectiveSubdivide->Create(IDD_PERSPECTIVE, this); } pdlgPerspectiveSubdivide->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OnPhysicsProperties() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; CInstance* pins = ptCast<CInstance>(pipeMain.ppartLastSelected()); // Don't do anything if no object is selected. if (pins == 0) return; // // End capture. // if (bLeftCapture || bRightCapture) { ReleaseCapture(); //ClipCursor(NULL); if (bIsFullScreen) ShowCursor(TRUE); } bLeftCapture = false; bRightCapture = false; if (pdlgphyDialogPhysics == 0) { pdlgphyDialogPhysics = new CDialogPhysics(); pdlgphyDialogPhysics->Create(IDD_DIALOG_PHYSICS, this); } pdlgphyDialogPhysics->SetInstance(pins); pdlgphyDialogPhysics->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::EditObject() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Do nothing if no object is currently selected. CPartition* ppart = pipeMain.ppartLastSelected(); if (ppart == 0) return; CInstance* pins = ptCast<CInstance>(ppart); if (pins) { // // If the currently selected object has a light attached, edit the light // properties. // CInstance* pins_light = pipeMain.pinsGetLight(ptCast<CInstance>(ppart)); if (pins_light) { OpenLightProperties( rptr_dynamic_cast( CLight, rptr_nonconst( pins_light->prdtGetRenderInfo() ) ) ); } else { // Otherwise edit the material of an object. OpenObjectDialogProperties(pins); } } else { CMagnetPair* pmp = dynamic_cast<CMagnetPair*>(ppart); if (pmp) { OpenMagnetProperties(pmp); } } Invalidate(); } //********************************************************************************************* // void CGUIAppDlg::OnEditGamma ( ) // // Responds to a MENU_EDIT_GAMMA message by invoking the gamma dialog box. // //************************************** { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pdlgobjDialogGamma == 0) { pdlgobjDialogGamma = new CDialogGamma(); pdlgobjDialogGamma->Create(IDD_GAMMA, this); } pdlgobjDialogGamma->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* // void CGUIAppDlg::OnEditGore ( ) // //************************************** { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pdlgobjDialogGore == 0) { pdlgobjDialogGore = new CDialogGore(); pdlgobjDialogGore->Create(IDD_GORE, this); } pdlgobjDialogGore->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OpenFogProperties() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pfogdlgFogProperties == 0) { pfogdlgFogProperties = new CDialogFog(); pfogdlgFogProperties->Create(IDD_FOG, this); } pfogdlgFogProperties->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::AddObject() { char str_file_name[512]; // Storage for the file name. // Get a filename from the file dialog box. if (!bGetFilename(m_hWnd, str_file_name, sizeof(str_file_name))) { // If no file is selected, then return. return; } // Show what is loaded. ShowLoadedFile(str_file_name); // Create the load world object. CLoadWorld lw(str_file_name); CCycleTimer ctr; dout << "Saving scene file: \n"; // Save the current positions to a standard file name. wWorld.bSaveWorld(strLAST_SCENE_FILE); dout << "Saving scene file: " << ctr() * ctr.fSecondsPerCycle() << " seconds.\n"; } //********************************************************************************************* void CGUIAppDlg::AddDefaultLight() { // This should be taken care of by the WDBase. wWorld.AddDefaultLight(); #if 0 LoadColour(pmshLightDir, CColour(192, 192, 192)); // Add the light with a rendering shape for interface control. CInstance* pins_shape = new CInstance ( CPresence3<> ( // CRotate3<>('x', CAngle(dDegreesToRadians(-150.0))), // Rotation. // Aim light's Z axis at the target. CRotate3<>(d3ZAxis, CDir3<>(v3DEFAULT_LIGHT_TARGET - v3DEFAULT_LIGHT_POS)), 1.0, // Scale. // Don't use v3DEFAULT_LIGHT_POS, because we want the light in front of the viewer. CVector3<>(-25.0f, 50.0f, 17.0f) // Position. ), rptr_cast(CRenderType, pmshLightDir) ); pins_shape->SetInstanceName("Default Light Shape"); pinsLightDirectionalDefaultShape = pins_shape; wWorld.Add(pins_shape); // Create a light with shadowing enabled. rptr<CLightDirectional> pltd_light = rptr_new CLightDirectional(lvDEFAULT, true); // Remember this light. It's important. petltLightDirectionalDefault = new CEntityLight(rptr_cast(CLight, pltd_light), pins_shape); // Add the global light to the wdbase. It's important. wWorld.Add(petltLightDirectionalDefault); #endif } //********************************************************************************************* void CGUIAppDlg::AddDirectionalLight() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; LoadColour(pmshLightPt, CColour(192, 128, 128)); // Add a shape representing the light. CInstance* pins_shape = new CInstance ( CPresence3<> ( CRotate3<>(), 1.0, // Scale. CVector3<>(0, 10.0, 0) * pcamGetCamera()->pr3Presence() // Position: in front of camera. ), rptr_cast(CRenderType, pmshLightDir) ); wWorld.Add(pins_shape); rptr<CLightDirectional> pltd_light = rptr_new CLightDirectional(lvDEFAULT); // Create an entity to contain it, with the shape as its controlling parent. wWorld.Add(new CEntityLight(rptr_cast(CLight, pltd_light), pins_shape)); } //********************************************************************************************* void CGUIAppDlg::AddPointLight() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; LoadColour(pmshLightPt, CColour(192, 128, 128)); // Add the light with a shape for user reference. CInstance* pins_shape = new CInstance ( CPresence3<> ( CRotate3<>(), 0.2, // Scale. CVector3<>(0, 2.0, 0) * pcamGetCamera()->pr3Presence() // Position: in front of camera. ), rptr_cast(CRenderType, pmshLightPt) ); wWorld.Add(pins_shape); rptr<CLightPoint> pltp_light = rptr_new CLightPoint(lvDEFAULT); // Create an entity to contain it, with the shape as its controlling parent. wWorld.Add(new CEntityLight(rptr_cast(CLight, pltp_light), pins_shape)); } //********************************************************************************************* void CGUIAppDlg::AddPointDirectionalLight() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; LoadColour(pmshLightPtDir, CColour(192, 192, 128)); // Add a shape representing the light. CInstance* pins_shape = new CInstance ( CPresence3<> ( CRotate3<>(), 0.5, // Scale. CVector3<>(0, 5.0, 0) * pcamGetCamera()->pr3Presence() // Position: in front of camera. ), rptr_cast(CRenderType, pmshLightPtDir) ); wWorld.Add(pins_shape); rptr<CLightPointDirectional> pltpd_light = rptr_new CLightPointDirectional(lvDEFAULT, CAngle(dDegreesToRadians(22.5f))); // Create an entity to contain it, with the shape as its controlling parent. wWorld.Add(new CEntityLight(rptr_cast(CLight, pltpd_light), pins_shape)); } //********************************************************************************************* void CGUIAppDlg::EditBackground() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Create the background settings dialog box. if (pbackdlgBackground == 0) { pbackdlgBackground = new CBackground(); } // Destroy any open background settings dialog to ensure the dialog is sized properly. pbackdlgBackground->DestroyWindow(); // Create and display the background settings dialog. pbackdlgBackground->Create(IDD_BACKGROUND, this); pbackdlgBackground->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::UpdateBackground() { prenMain->pSettings->bClearBackground = true; prenMain->pSettings->clrBackground = clrBackground; prenMain->UpdateSettings(); } //********************************************************************************************* void CGUIAppDlg::OnClose ( ) // // Responds to a WM_CLOSE message by freeing all memory associated with the main dialog. // //************************************** { if (fileStats) { fclose(fileStats); fileStats = 0; } ExitApp(); CDialog::OnClose(); } //********************************************************************************************* void CGUIAppDlg::ToggleRenderFeature(ERenderFeature erf) { prenMain->pSettings->seterfState ^= erf; SetMenuState(); proProfile.psFrame.Reset(); } //********************************************************************************************* void CGUIAppDlg::OnZbuffer() { ToggleRenderFeature(erfZ_BUFFER); } //********************************************************************************************* void CGUIAppDlg::OnScreenclip() { ToggleRenderFeature(erfRASTER_CLIP); } //********************************************************************************************* void CGUIAppDlg::OnScreencull() { ToggleRenderFeature(erfRASTER_CULL); } //********************************************************************************************* void CGUIAppDlg::OnLight() { ToggleRenderFeature(erfLIGHT); } //********************************************************************************************* void CGUIAppDlg::OnLightShade() { ToggleRenderFeature(erfLIGHT_SHADE); } //********************************************************************************************* void CGUIAppDlg::OnFog() { ToggleRenderFeature(erfFOG); } //********************************************************************************************* void CGUIAppDlg::OnFogShade() { ToggleRenderFeature(erfFOG_SHADE); } //********************************************************************************************* void CGUIAppDlg::OnSpecular() { ToggleRenderFeature(erfSPECULAR); } //********************************************************************************************* void CGUIAppDlg::OnColoured() { ToggleRenderFeature(erfCOLOURED_LIGHTS); } //********************************************************************************************* void CGUIAppDlg::OnTexture() { ToggleRenderFeature(erfTEXTURE); } //********************************************************************************************* void CGUIAppDlg::OnTransparent() { ToggleRenderFeature(erfTRANSPARENT); } //********************************************************************************************* void CGUIAppDlg::OnBump() { ToggleRenderFeature(erfBUMP); } //********************************************************************************************* void CGUIAppDlg::OnWireFrame() { ToggleRenderFeature(erfWIRE); } //********************************************************************************************* void CGUIAppDlg::OnAlphaColour() { ToggleRenderFeature(erfALPHA_COLOUR); } //********************************************************************************************* void CGUIAppDlg::OnAlphaShade() { // ToggleRenderFeature(erfALPHA_SHADE); } //********************************************************************************************* void CGUIAppDlg::OnAlphaTexture() { // ToggleRenderFeature(erfALPHA_TEXTURE); } //********************************************************************************************* void CGUIAppDlg::OnTrapezoids() { ToggleRenderFeature(erfTRAPEZOIDS); } //********************************************************************************************* void CGUIAppDlg::OnSubpixel() { ToggleRenderFeature(erfSUBPIXEL); } //********************************************************************************************* void CGUIAppDlg::OnPerspective() { ToggleRenderFeature(erfPERSPECTIVE); } //********************************************************************************************* void CGUIAppDlg::OnMipMap() { ToggleRenderFeature(erfMIPMAP); } //********************************************************************************************* void CGUIAppDlg::OnDither() { ToggleRenderFeature(erfDITHER); } //********************************************************************************************* void CGUIAppDlg::OnFilter() { ToggleRenderFeature(erfFILTER); // Kill all the terrain textures. if (CWDbQueryTerrain().tGet() != 0) CWDbQueryTerrain().tGet()->Rebuild(false); } //********************************************************************************************* void CGUIAppDlg::OnFilterEdges() { ToggleRenderFeature(erfFILTER_EDGES); } //********************************************************************************************* void CGUIAppDlg::OnShadows() { prenMain->pSettings->bShadow = !prenMain->pSettings->bShadow; SetMenuState(); proProfile.psFrame.Reset(); } //********************************************************************************************* void CGUIAppDlg::OnShadowTerrain() { NMultiResolution::CTextureNode::bEnableShadows ^= 1; SetMenuState(); proProfile.psFrame.Reset(); } //********************************************************************************************* void CGUIAppDlg::OnShadowTerrainMove() { NMultiResolution::CTextureNode::bEnableMovingShadows ^= 1; SetMenuState(); proProfile.psFrame.Reset(); } //********************************************************************************************* void CGUIAppDlg::OnRenderCache() { if (rcsRenderCacheSettings.erctMode == ercmCACHE_ON) rcsRenderCacheSettings.erctMode = ercmCACHE_OFF; else rcsRenderCacheSettings.erctMode = ercmCACHE_ON; proProfile.psFrame.Reset(); SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::AlphaColourTestBar(int i_num_colour) { prasMainScreen->Lock(); lbAlphaConstant.Test(prasMainScreen.ptPtrRaw(), i_num_colour); prasMainScreen->Unlock(); prasMainScreen->Flip(); } //********************************************************************************************* void CGUIAppDlg::OnRenderCacheTest() { // Remove all image caches. PurgeRenderCaches(); if (rcsRenderCacheSettings.erctMode == ercmCACHE_ON) { rcsRenderCacheSettings.erctMode = ercmCACHE_OFF; } else { rcsRenderCacheSettings.erctMode = ercmCACHE_ON; } SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnDetail() { prenMain->pSettings->bDetailReduce = !prenMain->pSettings->bDetailReduce; proProfile.psFrame.Reset(); SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnShowConsole ( ) // // Responds to a MENU_CONSOLE message by showing the generic console. // //************************************** { bShowConsole = !bShowConsole; proProfile.psFrame.Reset(); SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnShowStats ( ) // // Responds to a MENU_STATS message by showing the timing statistics. // //************************************** { bShowStats = !bShowStats; proProfile.psFrame.Reset(); SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnAvgStats() // // Responds to a MENU_AVG_STATS message by toggling the state. // //************************************** { bAvgStats = !bAvgStats; proProfile.psFrame.Reset(); SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnShowFPS ( ) // // Responds to a MENU_FPS message by showing the timing statistics. // //************************************** { bShowFPS = !bShowFPS; proProfile.psFrame.Reset(); SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnShowCacheStats() // // Responds to a MENU_CACHE_STATS message by showing the timing statistics. // //************************************** { // Reset render cache statistics. rcstCacheStats.Reset(); // Toggle render cache stats flag. rcstCacheStats.bKeepStats = !rcstCacheStats.bKeepStats; // Update the menu and screen. SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnViewHairs ( ) // //************************************** { bShowHairs = !bShowHairs; SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnRotateWorldZ ( ) // //************************************** { bRotateAboutWorldZ = !bRotateAboutWorldZ; SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnResetStartTriggers ( ) // //************************************** { CStartTrigger::ResetStartTriggers(); } //********************************************************************************************* // void CGUIAppDlg::OnRestoreSubsystemDefaults ( ) // //************************************** { pwWorld->RestoreSubsystemDefaults(); } //********************************************************************************************* // void CGUIAppDlg::OnCrosshairVegetation ( ) // //************************************** { bCrosshairVegetation = !bCrosshairVegetation; SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnCrosshairTerrainTexture() { extern bool bEditTrnObjs; bEditTrnObjs = !bEditTrnObjs; SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnCrosshairRadius ( ) // //************************************** { bCrosshairRadius = !bCrosshairRadius; SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnViewSpheres ( ) // //************************************** { bShowSpheres = !bShowSpheres; SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnViewWire ( ) // //************************************** { bShowWire = !bShowWire; SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnViewPinhead ( ) // //************************************** { bShowPinhead = !bShowPinhead; SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnViewBones ( ) // //************************************** { pphSystem->bShowBones = !pphSystem->bShowBones; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnViewBonesBoxes() { CPhysicsInfo::setedfMain ^= edfBOXES; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnViewBonesCollide() { CPhysicsInfo::setedfMain ^= edfBOXES_PHYSICS; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnViewBonesWake() { CPhysicsInfo::setedfMain ^= edfBOXES_WAKE; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnViewBonesQuery() { CPhysicsInfo::setedfMain ^= edfBOXES_QUERY; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnViewBonesMagnets() { CPhysicsInfo::setedfMain ^= edfMAGNETS; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnViewBonesSkeletons() { CPhysicsInfo::setedfMain ^= edfSKELETONS; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnViewBonesAttach() { CPhysicsInfo::setedfMain ^= edfATTACHMENTS; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnViewBonesWater() { CPhysicsInfo::setedfMain ^= edfWATER; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnViewBonesRaycast() { CPhysicsInfo::setedfMain ^= edfRAYCASTS; SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnViewQuads ( ) // //************************************** { NMultiResolution::CTextureNode::bOutlineNodes ^= 1; // Invalidate terrain textures to cause re-render. if (CWDbQueryTerrain().tGet() != 0) CWDbQueryTerrain().tGet()->Rebuild(false); SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnRedrawTerrain ( ) // //************************************** { // Invalidate terrain textures to cause re-render. // To do: communicate this via a message instead. if (CWDbQueryTerrain().tGet() != 0) CWDbQueryTerrain().tGet()->Rebuild(true); } //********************************************************************************************* // void CGUIAppDlg::OnPlayerPhysics ( ) // // Responds to a MENU_PLAYERPHYSICS message by toggling the player physics on/off. // //************************************** { if (gpPlayer->pphiGetPhysicsInfo()) { // If we have a valid mesh, or we have a box model, go ahead. if (gpPlayer->prdtGetRenderInfo() || gpPlayer->pphiGetPhysicsInfo()->ppibCast()) { gpPlayer->bPhysics = !gpPlayer->bPhysics; if (gpPlayer->bPhysics) gpPlayer->PhysicsActivate(); else gpPlayer->PhysicsDeactivate(); } } SetMenuState(); } //********************************************************************************************* // void CGUIAppDlg::OnPlayerInvulnerable ( ) // // Responds to a MENU_PLAYERINVULNERABLE message by toggling the player's invulnerability on/off. // //************************************** { gpPlayer->bInvulnerable = !gpPlayer->bInvulnerable; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnPhysicsSleep() { pphSystem->bAllowSleep = !pphSystem->bAllowSleep; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnPhysicsStep() { bPhysicsStep = !bPhysicsStep; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnPhysicsPutToSleep() { pphSystem->DeactivateAll(); } //********************************************************************************************* // void CGUIAppDlg::OnSmackSelected ( ) // // Responds to a MENU_PLAYERINVULNERABLE message by toggling the player's invulnerability on/off. // //************************************** { // No longer used } //********************************************************************************************* void CGUIAppDlg::MagnetSelected(const CMagnet* pmag_type) { // Statically magnet together all the selected objects. // Deactivate all, to avoid hassle. { forall (pipeMain.lsppartSelected, TSelectedList, itppart) { CInstance* pins = ptCast<CInstance>(*itppart); if (pins) pins->PhysicsDeactivate(); } } // Remove any magnets, to avoid duplication. // Inefficient, but OK for GUIApp. { forall (pipeMain.lsppartSelected, TSelectedList, itppart) { CInstance* pins = ptCast<CInstance>(*itppart); if (!pins) continue; if (!pmag_type) // If demagneting, remove any world magnets. NMagnetSystem::RemoveMagnetPair(pins, 0); forall (pipeMain.lsppartSelected, TSelectedList, itppart2) { CInstance* pins2 = ptCast<CInstance>(*itppart2); if (pins2 && pins != pins2) NMagnetSystem::RemoveMagnetPair(pins, pins2); } } } if (!pmag_type) // We just wanted demagneting. return; CInstance* pins_master = 0; int i_magneted = 0; forall (pipeMain.lsppartSelected, TSelectedList, itppart) { CInstance* pins = ptCast<CInstance>(*itppart); if (!pins) continue; if (!pins_master) pins_master = pins; else { // If there is a magnet, magnet this to the master. // Place the magnet between the two magneted objects. CVector3<> v3_mag = (pins_master->v3Pos() + pins->v3Pos()) * 0.5; NMagnetSystem::AddMagnetPair ( pins_master, pins, pmag_type, CPresence3<>(v3_mag) / pins_master->pr3Presence() ); i_magneted++; } } if (pins_master && !i_magneted) { // // Only a single object was selected. // Magnet the master to the world. Can then be edited to turn it into pickup, etc. // We must give the magnet a non-default relative placement, or it won't be selectable // apart from the object. // NMagnetSystem::AddMagnetPair ( pins_master, 0, pmag_type, d3ZAxis * 0.5 ); } } //********************************************************************************************* void CGUIAppDlg::OnMagnetBreak() { // Magnet with a static breakable magnet of unit strength. MagnetSelected(CMagnet::pmagFindShared(CMagnet(Set(emfBREAKABLE), 1.0))); } //********************************************************************************************* void CGUIAppDlg::OnMagnetNoBreak() { // Magnet with a static unbreakable magnet. MagnetSelected(CMagnet::pmagFindShared(CMagnet())); } //********************************************************************************************* void CGUIAppDlg::OnDeMagnet() { MagnetSelected(0); } //********************************************************************************************* void CGUIAppDlg::OnCameraPlayer() { // Attach the camera to the player. Assert(gpPlayer); pcamGetCamera()->SetAttached(gpPlayer, true); bCameraFloating = false; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnCameraSelected() { // Attach the camera to the selected object. if (ptCast<CInstance>(pipeMain.ppartLastSelected())) { pcamGetCamera()->SetAttached(ptCast<CInstance>(pipeMain.ppartLastSelected())); bCameraFloating = false; } SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnCameraSelectedHead() { // Attach the camera to the selected object. if (ptCast<CInstance>(pipeMain.ppartLastSelected())) { pcamGetCamera()->SetAttached(ptCast<CInstance>(pipeMain.ppartLastSelected()), true); bCameraFloating = false; } SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnCameraFree() { // Free the camera (it's attached to nothing). pcamGetCamera()->SetAttached(0); bCameraFloating = false; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnCamera2m() { bCameraFloating = !bCameraFloating; if (bCameraFloating) pcamGetCamera()->SetAttached(0); SetMenuState(); } //********************************************************************************************* const char* strTEXTUREMAP = "BinData/StdTexture.bmp"; const char* strBUMPMAP = "BinData/StdBump.bmp"; void CGUIAppDlg::AddTestBumpmap() { /* // CODE DISABLED DUE TO DELETION OF bLoadTexture. // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Create a new shape. CInstance* pins = new CInstance(rptr_cast(CRenderType, pmshCube)); // Add scale information. pins->SetScale(10.0f); // Add the shape to the root presence. pipeMain.AddObject(pins); // Move the object so that it is large in the viewport. pins->SetPos(CVector3<>(0.0f, pins->fGetScale() * 4.0f, 0.0f) * pcamGetCamera()->pr3Presence()); // Load the texture associated with the shape. if (!bLoadTexture(pmshCube, strTEXTUREMAP, strBUMPMAP)) { // Could not load the texture, so delete the shape. pipeMain.iDeleteSelected(); // Tell the user! MessageBox("Can't find texture file", strBUMPMAP, MB_OK | MB_ICONHAND); } */ } //********************************************************************************************* BOOL CGUIAppDlg::PreTranslateMessage(MSG* pMsg) { // Do nothing if the return or enter key is pressed. if (pMsg) if (pMsg->message == WM_KEYDOWN) if (pMsg->wParam == VK_RETURN) return true; if (prnshMain) prnshMain->ProcessMessage(*pMsg); return CDialog::PreTranslateMessage(pMsg); } //********************************************************************************************* void CGUIAppDlg::SendChildrenMessage(uint u_message) { SendMessageToWindow(pdlgToolbar, u_message); SendMessageToWindow(pcamdlgCameraProperties, u_message); SendMessageToWindow(pdlgobjDialogObject, u_message); SendMessageToWindow(pdlgmagDialogMagnet, u_message); //SendMessageToWindow(pdlgDialogPlayer, u_message); SendMessageToWindow(pdlgDialogMaterial, u_message); SendMessageToWindow(pdlgrcDialogRenderCache, u_message); SendMessageToWindow(pdlgPerspectiveSubdivide, u_message); //SendMessageToWindow(pdlgphyDialogPhysics, u_message); SendMessageToWindow(pltdlgLightProperties, u_message); SendMessageToWindow(pbackdlgBackground, u_message); SendMessageToWindow(pdlgOcclusion, u_message); SendMessageToWindow(pdlgScheduler, u_message); SendMessageToWindow(pdlgGun, u_message); SendMessageToWindow(pdlgAlphaColour, u_message); SendMessageToWindow(pdlgtDialogTerrain, u_message); SendMessageToWindow(pdlgtDialogWater, u_message); SendMessageToWindow(pfogdlgFogProperties, u_message); SendMessageToWindow(pdlgMipmap, u_message); SendMessageToWindow(pdepthdlgProperties, u_message); if (bFullScreen()) { CStdDialog::BroadcastToDialogs(u_message); } } //***************************************************************************************** bool CGUIAppDlg::bCanOpenChild() { if (!bIsFullScreen && gmlGameLoop.bDebug()) return true; return bGDIMode; } //***************************************************************************************** void CGUIAppDlg::SetGDIMode(bool b_gdimode) { // GDI mode is not necessary in windowed mode. if (!bIsFullScreen) { bGDIMode = false; gpInputDeemone->Capture(!gmlGameLoop.bDebug()); return; } // Set the GDI mode flag. bGDIMode = b_gdimode; if (bGDIMode) { // Going into debug mode. gpInputDeemone->Capture(false); // Never capture input in GDI mode. } else { // Going into play mode. SendChildrenMessage(WM_CLOSE); gpInputDeemone->Capture(!gmlGameLoop.bDebug()); } // Redraw the screen. Invalidate(); } //********************************************************************************************* // void CGUIAppDlg::JumpToLookAt(CInstance* pins_mover, CPartition* ppart_target) { if (ppart_target == 0) return; Assert(pins_mover); // Move the mover to the object. pins_mover->Move(CPlacement3<> ( ppart_target->v3Pos() + CVector3<>(0, -3.5f * ppart_target->fGetScale(), 0) )); // Redraw the scene. Invalidate(); } //********************************************************************************************* // void CGUIAppDlg::MoveIntoView(CInstance* pins_viewer, CPartition* ppart_mover) { if (ppart_mover == 0) return; Assert(pins_viewer); // Move the mover to the viewer. ppart_mover->Move(CPlacement3<> ( pins_viewer->v3Pos() - (CVector3<>(0, -3.5f * ppart_mover->fGetScale(), 0) * pins_viewer->r3Rot()) )); // Redraw the scene. Invalidate(); } //***************************************************************************************** void CGUIAppDlg::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { switch (nChar) { case VK_F1: if (bVKey(VK_CONTROL)) { OnStatClocks(); } break; case VK_F2: if (bVKey(VK_CONTROL)) { if (gbMSRProfile) OnStatMSR0(); break; } // Write the spatial partition hierarchy. wWorld.DumpSpatial(); break; case VK_F3: if (bVKey(VK_CONTROL)) { if (gbMSRProfile) OnStatMSR1(); break; } if (bVKey(VK_SHIFT)) { DumpTextureUse(); break; } // Flatten the spatial partition hierarchy. //wWorld.FlattenPartitions(); bRenderTerrain = !bRenderTerrain; Invalidate(); break; case VK_F4: { #if bPARTITION_BUILD if (bVKey(VK_CONTROL)) { // Save the current spatial partition. // wWorld.SaveSpatialPartitions("SpatialPartitions.prt"); break; } if (bVKey(VK_SHIFT)) { // Test load a spatial partition. // wWorld.LoadSpatialPartitions("SpatialPartitions.prt"); wWorld.BuildTerrainPartitions(); wWorld.BuildTriggerPartitions(); break; } // Build an optimized spatial partition hierarchy. wWorld.BuildOptimalPartitions(0); // Redraw the screen. Invalidate(); #else MessageBox("Function not available in Final Mode!", "GUIApp Error", MB_OK | MB_ICONHAND); #endif // bPARTITION_BUILD break; } case VK_F5: { extern bool bDumpPolylist; bDumpPolylist = true; /* // Build an optimized spatial partition hierarchy. CPartition* ppart = wWorld.ppartGetWorldSpace(); Assert(ppart); delete ppart; */ } break; case VK_F6: Invalidate(); break; case VK_F7: if (bVKey(VK_CONTROL)) { padAudioDaemon->KillCollisions(true); } else { OnRenderCacheTest(); } break; // Toggle debug/play if F8 pressed. case VK_F8: if (gmlGameLoop.egmGameMode == egmDEBUG) { SendMessage(WM_COMMAND, MENU_PLAY, 0); } else SendMessage(WM_COMMAND, MENU_DEBUG, 0); break; case VK_F9: // // Edit physics object. // OnPhysicsProperties(); // break; if (bVKey(VK_SHIFT)) { // Alter the default material, and redo the cluts. CMaterial& rmat_default = const_cast<CMaterial&>(matDEFAULT); static int i = 1; switch (i++) { default: rmat_default = matMATTE; i = 1; break; case 1: rmat_default = matMETAL; break; case 2: rmat_default = matSHINY; break; case 3: rmat_default = matWATER; break; } // Remake all the cluts. pcdbMain.UpdateCluts(); Invalidate(); } else if (bVKey(VK_CONTROL)) { static int i_clut_index = 0; // Paint a palette's clut on the screen. CClut* pclut = pcdbMain.pclutGet(i_clut_index); if (!pclut) { i_clut_index = 0; } else { ++i_clut_index; prasMainScreen->Lock(); pclut->Draw(rptr_cast(CRaster, prasMainScreen)); prasMainScreen->Unlock(); prasMainScreen->Flip(); } break; } // Toggle between depth sort and Z buffer modes. case VK_F12: /* if (prenMain->pSettings->esSortMethod == esDepthSort) { prenMain->pSettings->esSortMethod = esPresortFrontToBack; SetMenuState(); break; } if (prenMain->pSettings->esSortMethod == esPresortFrontToBack) { prenMain->pSettings->esSortMethod = esDepthSort; SetMenuState(); break; } */ renclRenderCacheList.Dump(); break; // Toggle pause state if the pause/break key is pressed. case VK_PAUSE: { gmlGameLoop.bPauseGame = !gmlGameLoop.bPauseGame; SetMenuState(); break; } case VK_SCROLL: { // Single-step through the system. // Start the sim. gmlGameLoop.egmGameMode = egmPLAY; CMessageSystem(escSTART_SIM).Dispatch(); if (bVKey(VK_SHIFT)) // Step with default (or replay) time. Step(-1.0); else // Step with the time quantum physics uses. Step(MAX_TIMESTEP); // Stop the sim. CMessageSystem(escSTOP_SIM).Dispatch(); gmlGameLoop.egmGameMode = egmDEBUG; // Do not pass to parent class handler. return; } // If in debug mode, jump camera to an object. case VK_HOME: { if (gmlGameLoop.egmGameMode == egmDEBUG) { if (bVKey(VK_SHIFT)) { // Move last selected into camera view. MoveIntoView(pcamGetCamera(), pipeMain.ppartLastSelected()); } else { // For now, jump camera to look at selected object (takes player or attached with it). JumpToLookAt(pcamGetCamera(), pipeMain.ppartLastSelected()); } } break; } // If in debug mode, iterate through the renderable objects. case VK_SPACE: { if (gmlGameLoop.egmGameMode == egmDEBUG) { // Get all objects in the world with rendering info. CWDbQueryRenderTypes wrt; // Find the selected object. foreach(wrt) { if (wrt.tGet().ppart == pipeMain.ppartLastSelected()) { // Select the next object in the list. wrt++; break; } } if (wrt.bIsNotEnd()) { // We have a valid object! CInstance* pins; wrt.tGet().ppart->Cast(&pins); pipeMain.Select(pins); } else { // We have a bogus object! Select the first one in the WDBase. wrt.Begin(); if (wrt.bIsNotEnd()) { CInstance* pins; wrt.tGet().ppart->Cast(&pins); pipeMain.Select(pins); } else pipeMain.Select(0); } Invalidate(); } break; } // Drop a marker. case 'M': { OnDropMarker(); break; } // Debug info about the selected mesh! case 'O': { forall (pipeMain.lsppartSelected, TSelectedList, itppart) { CInstance* pins = ptCast<CInstance>(*itppart); if (!pins) return; // If an object is selected, print out its info to the debug window. dprintf("\n///////////////////////////////////////////////////\n"); const char *str = pins->strGetInstanceName(); dprintf("Object \"%s\":\n", str); CPresence3<> pr3 = pins->pr3Presence(); dprintf("Origin: %f,\t%f,\t%f\n", pr3.v3Pos.tX, pr3.v3Pos.tY,pr3.v3Pos.tZ); dprintf("Rotate: Vector:%f,\t%f,\t%f\tAngle: %f\n", pr3.r3Rot.v3S.tX, pr3.r3Rot.v3S.tY,pr3.r3Rot.v3S.tZ, pr3.r3Rot.tC); dprintf("Scale: %f\n", pr3.rScale); rptr_const<CRenderType> prdt = pins->prdtGetRenderInfo(); rptr_const<CMesh> pmsh = rptr_const_dynamic_cast(CMesh,prdt); if (pmsh) { dprintf("World Space Verts:\n"); int i_last = pmsh->pav3Points.uLen; for (int i = 0; i < i_last; i++) { CVector3<> v3 = pmsh->pav3Points[i]; v3 = v3 * pins->pr3Presence(); dprintf("%d:\t%f,\t%f,\t%f\n", i, v3.tX, v3.tY, v3.tZ); } } else { dprintf("Object does not have a CMesh rendertype.\n"); } } break; } case 'P': { // P for profile // OnShowStats(); // OnShowFPS(); OnPlayerPhysics(); break; } case 'R': { if (bVKey(VK_CONTROL)) { // Purge on ctrl-alt-r wWorld.Reset(); // Add the shell to the world database. wWorld.AddShell(this); Invalidate(); } else if (bVKey(VK_SHIFT)) { OnReset(); Invalidate(); } break; } case 'T': { if (bVKey(VK_CONTROL)) { extern void PlayerTeleportToNextLocation(); PlayerTeleportToNextLocation(); } else { CTerrain* ptrr = CWDbQueryTerrain().tGet(); if (ptrr) { forall (pipeMain.lsppartSelected, TSelectedList, itppart) { CPresence3<> pr3 = (*itppart)->pr3Presence(); TReal r_height = ptrr->rHeight(pr3.v3Pos.tX, pr3.v3Pos.tY); // Test the terrain height at the selected object's location. dprintf("\nTerrain height: %f, %f, %f\n", pr3.v3Pos.tX, pr3.v3Pos.tY, r_height); } } } Invalidate(); break; } case 'L': { OnGiveMeALight(); break; } // // No, Windows doesn't define a VK_ symbol for punctuation characters, and there // seems to be no relation between the code it returns and the ASCII value. // // case '/' case 0xBF: // '/' + shift = '?' if (bVKey(VK_SHIFT)) bWander = !bWander; break; // case '`': case 0xC0: // Toggle the video overlay. pVideoOverlay->Enable(!pVideoOverlay->bEnabled()); Invalidate(); break; case 0xbb: if (GetAsyncKeyState(VK_CONTROL) < 0) { prnshMain->AdjustViewportRelativeHorizontal(fViewDeltaIncrease, GetSafeHwnd()); break; } if (GetAsyncKeyState(VK_SHIFT) < 0) { prnshMain->AdjustViewportRelativeVertical(fViewDeltaIncrease, GetSafeHwnd()); break; } prnshMain->AdjustViewportRelative(fViewDeltaIncrease, GetSafeHwnd()); break; case 0xbd: // - and _ if (GetAsyncKeyState(VK_CONTROL) < 0) { prnshMain->AdjustViewportRelativeHorizontal(fViewDeltaDecrease, GetSafeHwnd()); break; } if (GetAsyncKeyState(VK_SHIFT) < 0) { prnshMain->AdjustViewportRelativeVertical(fViewDeltaDecrease, GetSafeHwnd()); break; } prnshMain->AdjustViewportRelative(fViewDeltaDecrease, GetSafeHwnd()); break; default: { } } // // Keypad keys position camera relative to attached object, facing the object. // // KP centre centre // KP up forward // KP down back // KP left left // KP right right // KP pgup top // KP pgdown bottom // KP home move closer // KP end move farther // const TReal rDIST_INCREMENT_RATIO = 1.1; const TReal rDEFAULT_DIST_SCALE = 2.0; CCamera* pcam = pcamGetCamera(); CPlacement3<> p3_rel = pcam->p3Relative(); // Preserve distance. TReal r_dist = p3_rel.v3Pos.tLen(); // If no current distance, set to default. if (Fuzzy(r_dist) == 0) { if (pcam->pinsAttached()) r_dist = pcam->pinsAttached()->pbvBoundingVol()->fMaxExtent() * pcam->pinsAttached()->fGetScale(); else r_dist = 5.0f; r_dist = Max(r_dist, 0.5) * rDEFAULT_DIST_SCALE; } bool b_update = true; switch (nChar) { case VK_NUMPAD5: // Null placement. p3_rel = CPlacement3<>(); break; case VK_NUMPAD8: // Forward. p3_rel.v3Pos = d3YAxis * r_dist; p3_rel.r3Rot = CRotate3<>(d3ZAxis, CAngle(dPI)); break; case VK_NUMPAD2: // Back. p3_rel.v3Pos = -d3YAxis * r_dist; p3_rel.r3Rot = CRotate3<>(); break; case VK_NUMPAD4: // Left. p3_rel.v3Pos = -d3XAxis * r_dist; p3_rel.r3Rot = CRotate3<>(d3ZAxis, -CAngle(dPI_2)); break; case VK_NUMPAD6: // Right. p3_rel.v3Pos = d3XAxis * r_dist; p3_rel.r3Rot = CRotate3<>(d3ZAxis, +CAngle(dPI_2)); break; case VK_NUMPAD9: // Top. p3_rel.v3Pos = d3ZAxis * r_dist; p3_rel.r3Rot = CRotate3<>(d3XAxis, -CAngle(dPI_2)); break; case VK_NUMPAD3: // Bottom. p3_rel.v3Pos = -d3ZAxis * r_dist; p3_rel.r3Rot = CRotate3<>(d3XAxis, +CAngle(dPI_2)); break; case VK_NUMPAD7: // Decrease distance. p3_rel.v3Pos /= rDIST_INCREMENT_RATIO; break; case VK_NUMPAD1: // Increase distance. p3_rel.v3Pos *= rDIST_INCREMENT_RATIO; break; default: b_update = false; } if (b_update) { if (!pcam->pinsAttached()) OnCameraPlayer(); pcam->SetRelative(p3_rel); Invalidate(); } CDialog::OnKeyDown(nChar, nRepCnt, nFlags); } //********************************************************************************************* // // Module function implementation. // //********************************************************************************************* void SendMessageToWindow(CWnd* pwnd, uint u_message) { // Do nothing if the window hasn't been instantiated. if (pwnd == 0 || pwnd->m_hWnd == 0) return; // Send the close message. pwnd->SendMessage(u_message); } //********************************************************************************************* // void CGUIAppDlg::DebugMovement ( CInstance* pins, // The instance that is controlled by the move keys. const CInstance* pins_pov // The instance whose point of view is used to interpret the controls. // Usually a camera or the pins itself. ) // // Handles movement while in debug mode. This function maps the following keys: // // Key Function // ----- -------- // shift fast // control strafe // end return to 'home' position (to the origin) // up arrow move forward // down arrow move backward // left arrow turn left (strafe left with control key) // right arrow turn right (strafe right with control key) // plus key move up // minus key move down // page up turn up // page down turn down // insert twist left // delete twist right // //************************************** { static CTimer tmrStep; // The movement timer. if (::GetFocus() != m_hWnd) return; if (!bAllowDebugMovement) return; CVector3<> v3_camdir; // Camera movement vector. CRotate3<> r3_camrot; // Camera rotation. float f_displacement; // Movement amount. float f_delta_angle; // Rotation amount. bool b_update_window = false; // Repaint window flag. CPlacement3<> p3 = pins->pr3Presence(); // Find the real elapsed time, and clamp it to 5fps. TSec s_elapsed = tmrStep.sElapsed(); s_elapsed = Min(s_elapsed, 0.2f); f_displacement = rDebugStepDistance * s_elapsed; f_delta_angle = rDebugTurnAngle * s_elapsed; // Fast or normal movement and rotational values. if (bVKey(VK_SHIFT)) { f_displacement *= 5.0f; f_delta_angle *= 5.0f; } if (bSmallMoveSteps) { f_displacement *= .1f; f_delta_angle *= .1f; } if (gmlGameLoop.bCanStep() && bWander) { // Wander around when in play mode. const float fDECAY_RATE = 0.95; // Ratio that rotation decays each frame. const float fANGLE_RAND_RANGE = 0.02; // Range of random addition to fAngle each frame. const float fANGLE_HOMING_RATE = 0.05; // Range of correction toward home at boundary. if (sWanderStop > 0) { // Check to see if we are done. bool b_done; if (bWanderDurationInSecs) b_done = sWanderStop < CMessageStep::sStaticTotal; else b_done = sWanderStop < CMessageStep::u4Frame; if (b_done) { // Done wandering! bWander = false; sWanderStop = -1.0f; SendMessage(WM_COMMAND, MENU_DEBUG, 0); return; } } // Get the world extents, and compare to the current position, in XY. CVector3<> v3_world_min, v3_world_max; CTerrain* ptrr = CWDbQueryTerrain().tGet(); AlwaysVerify(ptrr->bGetWorldExtents(v3_world_min, v3_world_max)); // Find centre, and adjust extents inward a bit. CVector3<> v3_adjust = (v3_world_max - v3_world_min) * 0.2; v3_world_min += v3_adjust; v3_world_max -= v3_adjust; // Are we close to the edge? if (!bWithin(p3.v3Pos.tX, v3_world_min.tX, v3_world_max.tX) || !bWithin(p3.v3Pos.tY, v3_world_min.tY, v3_world_max.tY)) { // Yes! Turn back to the center. // // Swing the camera around to face toward the centre. // We want an amount proportional to the difference between the current facing vector // and the vector facing the centre of the world. This can be obtained from the // 2D cross-product (sin) of the facing vector and one halfway between it and the // centre vector. // CVector3<> v3_centre = (v3_world_max + v3_world_min) * 0.5; CDir2<> d2_current = d3YAxis * p3.r3Rot; CDir2<> d2_target = v3_centre - p3.v3Pos; TReal r_cross = d2_current ^ (d2_current + d2_target); // Use the cross product to determine direction of turn, but use the difference between the two // vectors to determine turn rate. float f_angle = (r_cross > 0) ? fANGLE_HOMING_RATE : - fANGLE_HOMING_RATE; f_angle *= (d2_current - d2_target).tLenSqr(); p3.r3Rot *= CRotate3<>(d3ZAxis, f_angle); } else { // No! Wander randomly. // Randomly adjust the angular rotation rate. fWanderAngleRate += randWander(-fANGLE_RAND_RANGE, +fANGLE_RAND_RANGE); // Apply exponential decay to rate. fWanderAngleRate *= fDECAY_RATE; // Apply the rotation about the Z axis. p3.r3Rot *= CRotate3<>(d3ZAxis, fWanderAngleRate); } // Move forward based on this rotation. p3.v3Pos += (d3YAxis * p3.r3Rot) * f_displacement; b_update_window = true; } // Move to the 'home' position. if (bVKey(VK_END)) { MoveCameraToSceneCentre(); return; } // Move forward. if (bVKey(VK_UP)) { v3_camdir = CVector3<> (0.0f, f_displacement, 0.0f); p3.v3Pos += v3_camdir * pins_pov->r3Rot(); b_update_window = true; } // Move backward. if (bVKey(VK_DOWN)) { v3_camdir = CVector3<> (0.0f, -f_displacement, 0.0f); p3.v3Pos += v3_camdir * pins_pov->r3Rot(); b_update_window = true; } // Move/strafe left. if (bVKey(VK_LEFT)) { if (bVKey(VK_CONTROL)) { v3_camdir = CVector3<> (-f_displacement, 0.0f, 0.0f); p3.v3Pos += v3_camdir * pins_pov->r3Rot(); } else { // Hack to allow slower turning when moving, even if shifting. if (b_update_window) f_delta_angle = 5.0f; if (bRotateAboutWorldZ) r3_camrot = CRotate3<>(d3ZAxis, CAngle(dDegreesToRadians(f_delta_angle))); else r3_camrot = CRotate3<>(d3ZAxis * pins_pov->r3Rot(), CAngle(dDegreesToRadians(f_delta_angle))); p3.r3Rot *= r3_camrot; } b_update_window = true; } // Move/strafe right. if (bVKey(VK_RIGHT)) { if (bVKey(VK_CONTROL)) { v3_camdir = CVector3<> (f_displacement, 0.0f, 0.0f); p3.v3Pos += v3_camdir * pins_pov->r3Rot(); } else { // Hack to allow slower turning when moving, even if shifting. if (b_update_window) f_delta_angle = 5.0f; if (bRotateAboutWorldZ) r3_camrot = CRotate3<>(d3ZAxis, CAngle(dDegreesToRadians(-f_delta_angle))); else r3_camrot = CRotate3<>(d3ZAxis * pins_pov->r3Rot(), CAngle(dDegreesToRadians(-f_delta_angle))); p3.r3Rot *= r3_camrot; } b_update_window = true; } // Move up. if (bVKey(VK_ADD)) { v3_camdir = CVector3<> (0.0f, 0.0f, f_displacement); p3.v3Pos += v3_camdir * pins_pov->r3Rot(); b_update_window = true; } // Move down. if (bVKey(VK_SUBTRACT)) { v3_camdir = CVector3<> (0.0f, 0.0f, -f_displacement); p3.v3Pos += v3_camdir * pins_pov->r3Rot(); b_update_window = true; } // Hack to allow slower turning when moving, even if shifting. if (b_update_window) f_delta_angle = 5.0f; // Turn up. if (bVKey(VK_PRIOR)) { r3_camrot = CRotate3<>(d3XAxis * pins_pov->r3Rot(), CAngle(dDegreesToRadians(f_delta_angle))); p3.r3Rot *= r3_camrot; b_update_window = true; } // Turn down. if (bVKey(VK_NEXT)) { r3_camrot = CRotate3<>(d3XAxis * pins_pov->r3Rot(), CAngle(dDegreesToRadians(-f_delta_angle))); p3.r3Rot *= r3_camrot; b_update_window = true; } // Twist left. if (bVKey(VK_INSERT)) { r3_camrot = CRotate3<>(d3YAxis * pins_pov->r3Rot(), CAngle(dDegreesToRadians(f_delta_angle))); p3.r3Rot *= r3_camrot; b_update_window = true; } // Twist right. if (bVKey(VK_DELETE)) { r3_camrot = CRotate3<>(d3YAxis * pins_pov->r3Rot(), CAngle(dDegreesToRadians(-f_delta_angle))); p3.r3Rot *= r3_camrot; b_update_window = true; } // Repaint the scene if required. if (b_update_window) { if (bCameraFloating)// && pins == pcamGetCamera()) { // The floating camera hack. p3.v3Pos.tZ = 1.65; CTerrain* ptrr = CWDbQueryTerrain().tGet(); if (ptrr) p3.v3Pos.tZ += ptrr->rHeight(p3.v3Pos.tX, p3.v3Pos.tY); if (pins == gpPlayer) p3.v3Pos.tZ -= gpPlayer->p3HeadPlacement().v3Pos.tZ; } pins->Move(p3); Invalidate(); } } //********************************************************************************************* void CGUIAppDlg::MoveCameraToSceneCentre() { // Restore null placement. pcamGetCamera()->Move(CPlacement3<>()); Invalidate(); } //********************************************************************************************* void CGUIAppDlg::FPSEstimate() { const int iNumFrames = 120; CAngle angDeltaRot(dDegreesToRadians(360.0f / float(iNumFrames))); // Rotational delta angle // Move the camera to the centre of the currently loaded scene. //MoveCameraToSceneCentre(); // Make sure that we are not running in GDI mode when in full screen. SetGDIMode(false); // Set game mode state. EGameMode egm = gmlGameLoop.egmGameMode; gmlGameLoop.egmGameMode = egmPLAY; // Start test. bool b_avg_save = bAvgStats; bool b_fps_save = bShowFPS; bAvgStats = true; bShowFPS = false; // MoveCameraToInitPosition(); proProfile.psFrame.Reset(); // // Get start data for conducting test spin. // float f_radius = CVector3<> ( pcamGetCamera()->v3Pos().tX, pcamGetCamera()->v3Pos().tY, 0.0f ).tLen(); // // Execute the main test loop. // for (int i_frame = 0; i_frame < iNumFrames; i_frame++) { // Rotate the camera. CRotate3<> r3_camrot = pcamGetCamera()->r3Rot() * CRotate3<>(d3ZAxis * pcamGetCamera()->r3Rot(), angDeltaRot); // Reposition the camera based on its rotation. CVector3<> v3_campos(0.0f, -f_radius, pcamGetCamera()->v3Pos().tZ); v3_campos *= r3_camrot; pcamGetCamera()->Move(CPlacement3<>(r3_camrot, v3_campos)); // Update the frame. PaintWindow(); } // Switch to GDI output for outputting the dialog box when in full screen mode. SetGDIMode(true); if (bIsFullScreen) ShowCursor(true); //ClipCursor(0); // Restore game mode state. gmlGameLoop.egmGameMode = egm; // Output the stats. CStrBuffer strbuf(2000); proProfile.psMain.WriteToBuffer(strbuf); bAvgStats = b_avg_save; bShowFPS = b_fps_save; MessageBox(strbuf, "Results of Standard Test"); } //********************************************************************************************* // void CGUIAppDlg::OnRButtonDblClk(UINT nFlags, CPoint point) // // Handles the WM_RMOUSEDBLCLK message by editing the object or camera. // //************************************** { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Edit physics object. OnPhysicsProperties(); // Call base class member function. CDialog::OnRButtonDblClk(nFlags, point); } //********************************************************************************************* void CGUIAppDlg::OpenRenderCacheDialog() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pdlgrcDialogRenderCache == 0) { pdlgrcDialogRenderCache = new CDialogRenderCache(); pdlgrcDialogRenderCache->Create(IDD_RENDERCACHE, this); } pdlgrcDialogRenderCache->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* // BOOL CGUIAppDlg::OnCmdMsg ( UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo ) // // Handles menu commands. // //************************************** { // On IDOK or IDCANCEL we're ending the app, and so should not muck with any windows that // may or may not still be valid. if (nCode != 0 && !(nID == IDCANCEL || nID == IDOK)) { CMessageNewRaster msgnewr(int(nID) - MENU_WINDOW - 1, bSystemMem, false); msgnewr.Dispatch(); // Clear the screen modes menu. for (int i_id = MENU_WINDOW; i_id <= MENU_WINDOW + Video::iModes; i_id++) GetMenu()->CheckMenuItem(i_id, i_id == nID ? MF_CHECKED : MF_UNCHECKED); SetMenuState(); return TRUE; } return CDialog::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); } //********************************************************************************************* void CGUIAppDlg::UpdateScreen() { // Force an update. CMessageNewRaster msgnewr(iScreenMode, bSystemMem, true); msgnewr.Dispatch(); } //********************************************************************************************* void CGUIAppDlg::OnSystemMem() { bool b_system = bSystemMem; if (!bSystemMem && d3dDriver.bUseD3D()) { d3dDriver.Purge(); d3dDriver.Uninitialize(); d3dDriver.SetInitEnable(false); } CMessageNewRaster msgnewr(iScreenMode, !bSystemMem, false); msgnewr.Dispatch(); if (b_system) { d3dDriver.SetInitEnable(true); } // // Use interpolated water for the software rasterizer and non-interpolated water for // hardware rasterizers. // CEntityWater::bInterp = !d3dDriver.bUseD3D(); SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::ToggleFastMode() { if (bFastMode) { RestoreFromFastMode(); return; } // Store render states prior to going to fast mode. erfPrevious = prenMain->pSettings->seterfState; // Set new a new flag combination. prenMain->pSettings->seterfState -= erfCOPY; prenMain->pSettings->seterfState -= erfLIGHT_SHADE; prenMain->pSettings->seterfState -= erfSPECULAR; prenMain->pSettings->seterfState -= erfTEXTURE; prenMain->pSettings->seterfState -= erfBUMP; prenMain->pSettings->seterfState -= erfSUBPIXEL; prenMain->pSettings->seterfState -= erfPERSPECTIVE; prenMain->pSettings->seterfState -= erfDITHER; prenMain->pSettings->seterfState -= erfFILTER; prenMain->pSettings->seterfState -= erfFILTER_EDGES; prenMain->pSettings->seterfState -= erfFOG; prenMain->pSettings->seterfState -= erfFOG_SHADE; prenMain->pSettings->seterfState -= erfTRANSPARENT; // // Set the camera clipping planes to a closer position. // ptr<CCamera> pcam = CWDbQueryActiveCamera().tGet(); CCamera::SProperties camprop = pcam->campropGetProperties(); // Store the old camera property settings. campropProp = camprop; // Try some new settings. camprop.rFarClipPlaneDist = 100.0f; camprop.rNearClipPlaneDist = 0.1f; pcam->SetProperties(camprop); // Set the fast mode flag and redraw screen and menu. bFastMode = true; SetMenuState(); } //***************************************************************************************** // void CGUIAppDlg::RestoreFromFastMode ( ) // // Restores settings prior to going into fast render mode. // //************************************** { bFastMode = false; // Restore render states settings prior to going to fast mode. prenMain->pSettings->seterfState = erfPrevious; // Restore the camera settings prior to going into fast mode. ptr<CCamera> pcam = CWDbQueryActiveCamera().tGet(); pcam->SetProperties(campropProp); // Change the menu and redraw. SetMenuState(); } //***************************************************************************************** void CGUIAppDlg::ToggleDelaunayTest() { /* static CDelaunayTest dlt; CDelaunayTest* pdlt = &dlt; bDelaunayTest = !bDelaunayTest; if (bDelaunayTest) wWorld.Add(pdlt); else wWorld.Remove(pdlt); // Change the menu and redraw. SetMenuState(); */ } //********************************************************************************************* void CGUIAppDlg::OnMenuTerrain() { // Add the test terrain object. // wWorld.Add(new CEntityTerrain()); } //********************************************************************************************* void CGUIAppDlg::ToggleConPhysics() { conPhysics.SetActive(!conPhysics.bIsActive() && !bFullScreen()); // Set a new menu state. SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnStatPhysics() { conPhysicsStats.SetActive(!conPhysicsStats.bIsActive() && !bFullScreen()); // Set a new menu state. SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnDrawPhysics() { if (!pdldrPhysics) { // Open dialog first time. pdldrPhysics = new CDialogDraw("Physics Graph"); pdldrPhysics->ShowWindow(true); } else // Toggle the shown state. pdldrPhysics->ShowWindow(!pdldrPhysics->bIsVisible()); // Set a new menu state. SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnDrawAI() { gaiSystem.bShow3DInfluences = !gaiSystem.bShow3DInfluences; // Set a new menu state. SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::ToggleConShadows() { conShadows.SetActive(!conShadows.bIsActive() && !bFullScreen()); // Set a new menu state. SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::ToggleConTerrain() { conTerrain.SetActive(!conTerrain.bIsActive() && !bFullScreen()); // Set a new menu state. SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::ToggleConAI() { conAI.SetActive(!conAI.bIsActive() && !bFullScreen()); // Set a new menu state. SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::ToggleConDepthSort() { conDepthSort.SetActive(!conDepthSort.bIsActive() && !bFullScreen()); // Set a new menu state. SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnLoadScene() { char str_filename[512]; if (bGetFilename(m_hWnd, str_filename, sizeof(str_filename), "Load Scene", "Game (*.scn;*.grf)\0" "*.scn;*.grf\0" "Scene (*.scn)\0" "*.scn\0" "Groff (*.grf)\0" "*.grf\0" "All (*.*)\0" "*.*\0")) { // Add to recent file list. AddRecentFile(str_filename); // Show what is loaded. ShowLoadedFile(str_filename); if (bMatchExtension(str_filename, "grf")) { // Load a groff file. CLoadWorld lw(str_filename); // Save the current positions to a standard file name. dout << "Saving scene file: \n"; wWorld.bSaveWorld(strLAST_SCENE_FILE); } else { // Assume it's a scene file. if (!wWorld.bLoadScene(str_filename)) MessageBox("Cannot load file!", "Load Error", MB_OK); else // Remember the last loaded scene. strcpy(strLoadFile, str_filename); } // Update menu state. SetMenuState(); } // HACK HACK HACK-- Leave these here for area creation purposes, so folks can use it by simple uncommenting. // extern void FindDuplicates(); // FindDuplicates(); } //********************************************************************************************* void CGUIAppDlg::OnLoadRecentFile(UINT uID) { char str_key[32]; char str_filename[512]; sprintf(str_key, "LastFileOpened%d", uID - MENU_OPEN_LAST); GetRegString(str_key, str_filename, sizeof(str_filename), ""); if (strlen(str_filename)) { // Show what is loaded. ShowLoadedFile(str_filename); if (bMatchExtension(str_filename, "grf")) { // Load a groff file. CLoadWorld lw(str_filename); // Save the current positions to a standard file name. dout << "Saving scene file: \n"; wWorld.bSaveWorld(strLAST_SCENE_FILE); } else { // Assume it's a scene file. if (!wWorld.bLoadScene(str_filename)) MessageBox("Cannot load file!", "Load Error", MB_OK); else // Remember the last loaded scene. strcpy(strLoadFile, str_filename); } } } //********************************************************************************************* void CGUIAppDlg::OnSaveScene() { if (*strLoadFile) { if (!wWorld.bSaveWorld(strLoadFile)) MessageBox("Cannot save file!", "Save Error", MB_OK); } else OnSaveAsScene(); } //********************************************************************************************* void CGUIAppDlg::OnSaveAsScene() { char str_filename[512]; if (bGetSaveFilename(m_hWnd, str_filename, sizeof(str_filename), "Save Scene", "Scene (*.scn)\0*.scn\0All (*.*)\0*.*\0")) { // If no '.' is found, append .scn. if (!strchr(str_filename, '.')) strcat(str_filename, ".scn"); if (!wWorld.bSaveWorld(str_filename)) MessageBox("Cannot save file!", "Save Error", MB_OK); else // Remember the last loaded scene. strcpy(strLoadFile, str_filename); } } //********************************************************************************************* void CGUIAppDlg::OnTextSave() { char str_filename[512]; if (bGetFilename(m_hWnd, str_filename, sizeof(str_filename), "Save Scene", "Text (*.txt)\0*.txt\0All (*.*)\0*.*\0")) { if (!wWorld.bSaveAsText(str_filename)) MessageBox("Cannot save file!", "Save Error", MB_OK); } } //********************************************************************************************* void CGUIAppDlg::OnReset() { const char* str_reset_file = *strLoadFile ? strLoadFile : strLAST_SCENE_FILE; if (*str_reset_file) { if (!wWorld.bLoadWorld(str_reset_file, true)) MessageBox("Cannot load file!", "Reset Error", MB_OK); } pipeMain.UnselectAll(); // Reset wander params as well. randWander.Seed(); fWanderAngleRate = 0; } //********************************************************************************************* void CGUIAppDlg::OnResetSelected() { // Not implemented! Assert(false); } //********************************************************************************************* void CGUIAppDlg::OnReplaySave() { char str_fname[MAX_PATH]; if (crpReplay.bSaveActive()) { // save is active so disable it.... SetMenuItemState(MENU_REPLAYSAVE, FALSE); crpReplay.SetSave(FALSE); } else { // save is inactive so ask for a filename and enable it // get a filename for the replay and enable saving if (::bGetReplayFileName( AfxGetMainWnd()->m_hWnd, str_fname, MAX_PATH, FALSE )==FALSE) { // // if we cannot get a file name ensure that the // option is not selected. // SetMenuItemState(MENU_REPLAYSAVE, FALSE); crpReplay.SetSave(FALSE); return; } // open the replay file now so it cannot be used for loading as well if (crpReplay.bOpenReplay(str_fname)==FALSE) { // // we cannot open the selected file, either it does not exist // or it is not a replay file. // SetMenuItemState(MENU_REPLAYSAVE, FALSE); crpReplay.SetSave(FALSE); return; } // we now have a valid relay filename so enable replay saving // and tick the menu SetMenuItemState(MENU_REPLAYSAVE, TRUE); crpReplay.SetSave(TRUE); } } //********************************************************************************************* void CGUIAppDlg::OnReplayLoad() { char str_fname[MAX_PATH]; if (crpReplay.bLoadActive()) { // load is active so disable it.... SetMenuItemState(MENU_REPLAYLOAD, FALSE); crpReplay.SetLoad(FALSE); } else { // get a filename for the replay and enable loading if (::bGetReplayFileName( AfxGetMainWnd()->m_hWnd, str_fname, MAX_PATH, TRUE )==FALSE) { // // if we cannot get a file name ensure that the // option is not selected. // SetMenuItemState(MENU_REPLAYLOAD, FALSE); crpReplay.SetLoad(FALSE); return; } // open the replay file now so it cannot be used for savinging as well if (crpReplay.bOpenReadReplay(str_fname)==FALSE) { // // we cannot open the selected file, either it does not exist // or it is not a replay file. // SetMenuItemState(MENU_REPLAYLOAD, FALSE); crpReplay.SetLoad(FALSE); return; } // we now have a valid relay filename so enable replays // tick the menu SetMenuItemState(MENU_REPLAYLOAD, TRUE); crpReplay.SetLoad(TRUE); } } //********************************************************************************************* void CGUIAppDlg::OnLoadAnim() { // The maximum number of characters in the anim file name. #define iMAX_ANIMNAME_CHARS (512) char str_filename[iMAX_ANIMNAME_CHARS]; // Open the file dialog. bool b_ok = bGetFilename ( m_hWnd, // Window handle of parent to the dialog. str_filename, // Pointer to string to put filename. iMAX_ANIMNAME_CHARS, // Maximum number of characters for the filename. "Load animation", "Animation (*.asa;*.asb)\0*.asa;*.asb\0All (*.*)\0*.*\0" // Optional extension filter. ); // Abort if the user hits cancel. if (!b_ok) return; // Report if the file is not found. if (!bFileExists(str_filename)) { MessageBox("Animation file not found!", "Animation Error", MB_OK); return; } // Redraw the screen. PaintWindow(); CAnimationScript* pans = new CAnimationScript(str_filename, true); pAnimations->Add(pans); pans->Start(); } //********************************************************************************************* void CGUIAppDlg::OpenTerrainDialog() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pdlgtDialogTerrain == 0) { pdlgtDialogTerrain = new CDialogTerrain(); pdlgtDialogTerrain->Create(IDD_TERRAIN, this); } pdlgtDialogTerrain->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OpenWaterDialog() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pdlgtDialogWater == 0) { pdlgtDialogWater = new CDialogWater(); pdlgtDialogWater->Create(IDD_WATER, this); } pdlgtDialogWater->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OnMenuAddSkeleton() { #if 0 // Hack to test raptor physics/skin // Get an instance of the mesh being loaded. rptr<CMesh> pmesh = rptr_cast(CMesh, rptr_new CSkeletonTestHuman()); rptr<CRenderType> prdt = rptr_cast(CRenderType, pmesh); // We have a biomesh, and ought to create a good physics model for it. CPhysicsInfo* pphi = new CPhysicsInfoHuman(); CAIInfo* paii = new CAIInfo(eaiRAPTOR); // Create a CInstance constructor structure. CInstance::SInit initins ( CPresence3<>(), prdt, pphi, paii, // Null AI. "Skeletal Raptor" ); CAnimal* pani = new CAnimal(initins); wWorld.Add(pani); #endif } //********************************************************************************************* void CGUIAppDlg::Process(const CMessageNewRaster& msgnewr) { // Set the new screen mode. bSetScreenMode(msgnewr.iMode, msgnewr.bSystemMem, msgnewr.bForce); } //********************************************************************************************* void CGUIAppDlg::LoadTerrain() { // This is really the handler for the convert terrain menu item!!! // The maximum number of characters in the terrain file name. #define iMAX_TERRAINNAME_CHARS (512) char str_filename[iMAX_TERRAINNAME_CHARS]; // The terrain file name. // Open the file dialog and get the terrain file name. bool b_ok = bGetFilename ( m_hWnd, // Window handle of parent to the dialog. str_filename, // Pointer to string to put filename. iMAX_TERRAINNAME_CHARS, // Maximum number of characters for the filename. "Convert Terrain", "Terrain (*.trr)\0*.trr\0All (*.*)\0*.*\0" // Optional extension filter. ); // Abort if the user hits cancel. if (!b_ok) return; // Report if the file is not found. if (!bFileExists(str_filename)) { MessageBox("Terrain file not found!", "Terrain Error", MB_OK); return; } bool b_old_active_state = conTerrain.bIsActive(); if (!b_old_active_state) ToggleConTerrain(); // Redraw the screen. PaintWindow(); // Remove extension from filename. str_filename[strlen(str_filename) - 4] = 0; conTerrain.CloseFileSession(); ConvertTerrainData(str_filename, CDialogTerrain::iNumQuantisationBits, conTerrain); conTerrain.CloseFileSession(); MessageBox("Finished terrain conversion!", "Terrain", MB_OK); if (!b_old_active_state) ToggleConTerrain(); // Redraw the screen. PaintWindow(); } //********************************************************************************************* void CGUIAppDlg::ExportTerrainTri(bool b_conform) { // The maximum number of characters in the terrain file name. #define iMAX_TERRAINNAME_CHARS (512) char str_filename[iMAX_TERRAINNAME_CHARS]; // The terrain file name. // Open the file dialog and get the terrain file name. bool b_ok = bGetFilename ( m_hWnd, // Window handle of parent to the dialog. str_filename, // Pointer to string to put filename. iMAX_TERRAINNAME_CHARS, // Maximum number of characters for the filename. "Convert Terrain", "Terrain (*.trr)\0*.wtd\0All (*.*)\0*.*\0" // Optional extension filter. ); // Abort if the user hits cancel. if (!b_ok) return; // Report if the file is not found. if (!bFileExists(str_filename)) { MessageBox("Terrain file not found!", "Terrain Error", MB_OK); return; } bool b_old_active_state = conTerrain.bIsActive(); if (!b_old_active_state) ToggleConTerrain(); // Redraw the screen. PaintWindow(); // Remove extension from filename. str_filename[strlen(str_filename) - 4] = 0; conTerrain.CloseFileSession(); SaveTerrainTriangulation(str_filename, CDialogTerrain::fFreqCutoff, CDialogTerrain::bFreqAsRatio, b_conform, conTerrain); conTerrain.CloseFileSession(); MessageBox("Finished terrain optimisation!", "Terrain", MB_OK); if (!b_old_active_state) ToggleConTerrain(); // Redraw the screen. PaintWindow(); } //***************************************************************************************** void CGUIAppDlg::ToggleTerrainTest() { static CTerrainTest* ptrrt = 0; bTerrainTest = !bTerrainTest; if (bTerrainTest) { if (!ptrrt) ptrrt = new CTerrainTest; wWorld.Add(ptrrt); } else { if (ptrrt) wWorld.Remove(ptrrt); } // Change the menu and redraw. SetMenuState(); } //***************************************************************************************** void CGUIAppDlg::ToggleHeightmap() { // Change the menu and redraw. SetMenuState(); } //***************************************************************************************** void CGUIAppDlg::ToggleTerrainWire() { // Change the menu and redraw. SetMenuState(); } //***************************************************************************************** void CGUIAppDlg::ToggleTextureWire() { // Change the menu and redraw. SetMenuState(); } //***************************************************************************************** // control selection functions.... //***************************************************************************************** // checks if the first joystick connected is the type passed in. // bool CGUIAppDlg::bDetectJoystick(EControlMethod ecm_stick) { // ecm_joystick is ignored at the moment JOYINFOEX ji_stick; ji_stick.dwSize=sizeof(JOYINFOEX); ji_stick.dwFlags=0; if (joyGetPosEx(JOYSTICKID1,&ji_stick)==JOYERR_NOERROR) return(TRUE); return(FALSE); } //**************************************************************************************** void CGUIAppDlg::OnDefaultControls() { gpInputDeemone->SetControlMethod(ecm_DefaultControls); SetMenuState(); } //***************************************************************************************** void CGUIAppDlg::OnStandardJoystick() { if (!bDetectJoystick(ecm_Joystick)) { MessageBox("No joystick found!", "Joystick Error", MB_OK); return; } gpInputDeemone->SetControlMethod(ecm_Joystick); SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnAI() { gaiSystem.bActive = !gaiSystem.bActive; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnPhysics() { pphSystem->bActive = !pphSystem->bActive; SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::EnterGameMode() { // Make the GUIApp emulate an actual game shell as much as possible! // Load a game GROFF file. // Until we have an actual game GROFF file, the user will just have to provide // their own game file command line argument if they want one. // CLoadWorld lw(str_argument); // Fast render mode. if (!bFastMode) { ToggleFastMode(); } // Start a replay recording. char str_fname[MAX_PATH]; sprintf(str_fname, "replay.rpl"); // open the replay file now so it cannot be used for loading as well if (crpReplay.bOpenReplay(str_fname)==FALSE) { // // we cannot open the selected file, either it does not exist // or it is not a replay file. // SetMenuItemState(MENU_REPLAYSAVE, FALSE); crpReplay.SetSave(FALSE); //return; } else { // we now have a valid relay filename so enable replay saving // and tick the menu SetMenuItemState(MENU_REPLAYSAVE, TRUE); crpReplay.SetSave(TRUE); } // Player Physics on. if (!gpPlayer->bPhysics) { OnPlayerPhysics(); } // Now actually start the game loop! SendMessage(WM_COMMAND, MENU_PLAY, 0); } //********************************************************************************************* void CGUIAppDlg::OpenDepthSortProperties() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pdepthdlgProperties == 0) { pdepthdlgProperties = new CDialogDepthSort(); pdepthdlgProperties->Create(IDD_DEPTHSORT_SETTINGS, this); } pdepthdlgProperties->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::SetWindowSize(int i_mode) { // // Select the width and the height for the window. // int i_width = 2 * GetSystemMetrics(SM_CXFRAME); int i_height = 2 * GetSystemMetrics(SM_CYFRAME) + GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYMENU); switch (i_mode) { case 1: i_width += 320; i_height += 240; break; case 2: i_width += 400; i_height += 300; break; case 3: i_width += 512; i_height += 384; break; case 4: i_width += 640; i_height += 480; break; default: Assert(0); } // Set the window size. SetWindowPos(&wndTop, 0, 0, i_width, i_height, SWP_SHOWWINDOW | SWP_NOMOVE); } //********************************************************************************************* void CGUIAppDlg::OpenSoundProperties() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (psounddlgProperties == 0) { psounddlgProperties = new CDialogSoundProp(); psounddlgProperties->Create(IDD_SOUND_PROPERTIES, this); } psounddlgProperties->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OnArtStats() { conArtStats.SetActive(!conArtStats.bIsActive() && !bFullScreen()); if (conArtStats.bIsActive()) { // Reset the max stats. i_max_total_polys = 0; i_max_cache_polys = 0; i_max_terrain_polys = 0; } // Set a new menu state. SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnPredictMovement() { // Open dialog. conPredictMovement.SetActive(!conPredictMovement.bIsActive() && !bFullScreen()); // Set a new menu state. SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OnMipMapSettings() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pdlgMipmap == 0) { pdlgMipmap = new CDialogMipmap(); pdlgMipmap->Create(IDD_MIPMAP, this); } pdlgMipmap->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OnAlphaColourSettings() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Create the background settings dialog box. if (pdlgAlphaColour == 0) { pdlgAlphaColour = new CDialogAlphaColour(); } // Destroy any open background settings dialog to ensure the dialog is sized properly. pdlgAlphaColour->DestroyWindow(); // Create and display the background settings dialog. pdlgAlphaColour->Create(IDD_ALPHA_COLOUR, this); pdlgAlphaColour->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* // Open the texture packing window void CGUIAppDlg::OnTexturePack() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pdlgTexturePack == 0) { pdlgTexturePack = new CDialogTexturePack(); pdlgTexturePack->Create(IDD_TEXTUREPACK, this); } pdlgTexturePack->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* // Open the texture packing window void CGUIAppDlg::OnMemStats() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; CDialogMemLog pdlgMemLog; pdlgMemLog.DoModal(); } //********************************************************************************************* // Grab the first directional light. void CGUIAppDlg::OnGiveMeALight() { // Summon the light to my face, dammit! CWDbQueryLights wqlt; foreach (wqlt) { // Do the first directional light. if (rptr_const_dynamic_cast(CLightDirectional, (*wqlt)->prdtGetRenderInfo())) { CPlacement3<> p3 = (*wqlt)->pr3Presence(); p3.v3Pos = CVector3<>(0, 10.0, 0) * pcamGetCamera()->pr3Presence(); // Position: in front of camera. (*wqlt)->Move(p3); Invalidate(); break; } } } //********************************************************************************************* // Toggle Z Only editing (world space up/down) void CGUIAppDlg::OnZOnlyEdit() { bZOnlyEdit = !bZOnlyEdit; SetMenuState(); } //********************************************************************************************* // Selects based on a user-entered name void CGUIAppDlg::OnNameSelect() { CDialogString ds("Object to select:"); if (ds.DoModal() == IDOK) { CInstance* pins = 0; if (!strcmpi(ds.strText, "Terrain")) { CTerrain* ptrr = CWDbQueryTerrain().tGet(); pins = ptrr; } else { if (ds.strText[0] == '#') { uint32 u4_hash; const char* buf = ds.strText; sscanf(&buf[1], "%x", &u4_hash); pins = wWorld.ppartPartitions->pinsFindInstance(u4_hash); } else pins = wWorld.ppartPartitions->pinsFindNamedInstance(basic_string<char>(ds.strText)); } wWorld.Select(pins, true); PaintWindow(); } } //********************************************************************************************* // Turns smaller debug movement on and off void CGUIAppDlg::OnSmallMoveSteps() { bSmallMoveSteps = !bSmallMoveSteps; SetMenuState(); } //********************************************************************************************* // Turns terrain sounds on and off void CGUIAppDlg::OnTerrainSound() { bTerrainSound = !bTerrainSound; Assert(padAudioDaemon); padAudioDaemon->bTerrainSound = bTerrainSound; SetMenuState(); } //********************************************************************************************** // static bool bFileExtention(char* str_fname, char* str_ext) { while ((*str_fname != 0) && (*str_fname != '.')) { str_fname++; } if (*str_fname == 0) { return false; } if (stricmp(str_fname+1,str_ext) == 0) return true; return false; } //********************************************************************************************* // Do that drag and drop thingy void CGUIAppDlg::OnDropFiles(HDROP hDrop) { uint32 u4_files; uint32 u4_count = 0; CLoadWorld* plw; char str_fname[MAX_PATH]; // Determine how many objects have been dropped u4_files = DragQueryFile(hDrop, 0xFFFFFFFF, (LPSTR) NULL, 0); while (u4_files>0) { // Get the name of the file dropped. DragQueryFile(hDrop, u4_count, str_fname, MAX_PATH); if (bFileExtention(str_fname,"grf")) { //CMemCheck mem_all("CLoadWorld", MEM_DIFF_STATS|MEM_DIFF_DUMP); plw = new CLoadWorld(str_fname); // Save the current positions to a standard file name. wWorld.bSaveWorld(strLAST_SCENE_FILE); // Show what is loaded. ShowLoadedFile(str_fname); delete plw; //dprintf("Allocations: %d\n", ulGetMemoryLogCounter(emlAllocCount)); } else if (bFileExtention(str_fname, "scn")) { if (!wWorld.bLoadScene(str_fname)) MessageBox("Cannot load file!", "Load Error", MB_OK); else // Remember the last loaded scene. strcpy(strLoadFile, str_fname); // Show what is loaded. ShowLoadedFile(str_fname); } else if (bFileExtention(str_fname, "rpl")) { bool b = crpReplay.bOpenReadReplay(str_fname); SetMenuItemState(MENU_REPLAYLOAD, b); crpReplay.SetLoad(b); } else { dprintf("Drop file not a .grf, .scn, .rpl: (%s)\n", str_fname); } u4_files--; u4_count++; } DragFinish(hDrop); // set the focus back to the GUIApp SetFocus(); SetActiveWindow(); return; } //********************************************************************************************* void CGUIAppDlg::ToggleOcclusionConsole() { conOcclusion.SetActive(!conOcclusion.bIsActive() && !bFullScreen()); // Set a new menu state. SetMenuState(); } //********************************************************************************************* void CGUIAppDlg::OcclusionSettings() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Create the occlusion dialog box. if (pdlgOcclusion == 0) { pdlgOcclusion = new CDialogOcclusion(); } // Destroy any open occlusion dialog to ensure the dialog is sized properly. pdlgOcclusion->DestroyWindow(); // Create and display the occlusion dialog. pdlgOcclusion->Create(IDD_OCCLUDE, this); pdlgOcclusion->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* // Toggles the sky rather than disable it! void CGUIAppDlg::OnSkyDisable() { prenMain->pSettings->bDrawSky = !prenMain->pSettings->bDrawSky; SetMenuItemState(MENU_SKY_DISABLE, prenMain->pSettings->bDrawSky); } //********************************************************************************************* // Remove the whole sky and the dialog void CGUIAppDlg::OnSkyRemove() { delete pdlgSky; pdlgSky = NULL; CSkyRender::RemoveSky(); SetMenuItemState(MENU_SKY_TEXTURE, true); } //********************************************************************************************* // Toggles the sky between texture and flat modes, cannot be changed unless there is a sky // loaded. void CGUIAppDlg::OnSkyTexture() { if (gpskyRender == NULL) return; bool b_texture = !gpskyRender->bSkyTextured(); if (b_texture) gpskyRender->SetDrawMode(CSkyRender::sdmTextured); else gpskyRender->SetDrawMode(CSkyRender::sdmGradient); SetMenuItemState(MENU_SKY_TEXTURE, b_texture); } //********************************************************************************************* // Toggles between filling empty space or not, default is not. This cannot be changed unless // there is a sky loaded. void CGUIAppDlg::OnSkyFill() { if (gpskyRender==NULL) return; bool b_fill = !gpskyRender->bSkyFill(); gpskyRender->SetFilled(b_fill); SetMenuItemState(MENU_SKY_FILL, b_fill); } //********************************************************************************************* void CGUIAppDlg::OnSkySettings() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (gpskyRender == NULL) return; // Create the sky dialog box. if (pdlgSky == 0) { pdlgSky = new CDialogSky(); // Create and display the occlusion dialog. pdlgSky->Create(IDD_SKY, this); } pdlgSky->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OpenGunSettings() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Create the occlusion dialog box. if (pdlgGun == 0) { pdlgGun = new CDialogGun(); } // Destroy any open occlusion dialog to ensure the dialog is sized properly. pdlgGun->DestroyWindow(); // Create and display the occlusion dialog. pdlgGun->Create(IDD_GUN, this); pdlgGun->ShowWindow(SW_SHOWNORMAL); } //***************************************************************************************** void CGUIAppDlg::OpenSchedulerSettings() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Create the occlusion dialog box. if (pdlgScheduler == 0) { pdlgScheduler = new CDialogScheduler(); } // Destroy any open occlusion dialog to ensure the dialog is sized properly. pdlgScheduler->DestroyWindow(); // Create and display the occlusion dialog. pdlgScheduler->Create(IDD_SCHEDULER, this); pdlgScheduler->ShowWindow(SW_SHOWNORMAL); } //***************************************************************************************** char *CGUIAppDlg::pcSave(char *pc_buffer) const { return pc_buffer; } //***************************************************************************************** const char*CGUIAppDlg::pcLoad(const char* pc_buffer) { return pc_buffer; } //********************************************************************************************* void CGUIAppDlg::OnEditAI() { static CAIDialogs2Dlg* paidlg = 0; // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; CAnimal* pani = ptCast<CAnimal>(gaiSystem.pinsSelected); if (!pani) return; // Create the AI DIALOG box. if (paidlg == 0) { paidlg = new CAIDialogs2Dlg(); // Create and display the ai dialog paidlg->Create(IDD_AIDIALOGS2_DIALOG, this); } else { paidlg->ShowWindow(SW_SHOWNORMAL); } } //********************************************************************************************* void CGUIAppDlg::OnEditAIEmotions() { static CParameterDlg* pParameterDialog = 0; // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; CAnimal* pani = ptCast<CAnimal>(pipeMain.ppartLastSelected()); if (!pani) return; if (pParameterDialog == 0) { // Lastly, make a parameters dialog. pParameterDialog = new CParameterDlg(); pParameterDialog->Create(IDD_PARAMETER_DIALOG, this); } CBrain* pbr = 0; pbr = pani->pbrBrain; AlwaysAssert(pbr); pParameterDialog->SetFeeling(&pbr->pmsState->feelEmotions, 0.0f, 1.0f); pParameterDialog->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OnVMSettings() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Create the sky dialog box. if (pdlgVM == 0) { pdlgVM = new CDialogVM(); // Create and display the vm dialog pdlgVM->Create(IDD_VIRTUALMEM, this); } pdlgVM->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OnSoundMaterialProp() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; if (pdlgSoundMaterial == 0) { pdlgSoundMaterial = new CDialogSoundMaterial(); // Create and display the vm dialog pdlgSoundMaterial->Create(CDialogSoundMaterial::IDD, this); } // Do nothing if no object is currently selected. CPartition* ppart = pipeMain.ppartLastSelected(); if (ppart == 0) return; CInstance* pins = ptCast<CInstance>(ppart); if (pins == NULL) return; // // If the currently selected object has a light attached, edit the light // properties. // CInstance* pins_light = pipeMain.pinsGetLight(ptCast<CInstance>(ppart)); if (pins_light) return; pdlgSoundMaterial->SetInstance(pins); pdlgSoundMaterial->ShowWindow(SW_SHOWNORMAL); } //********************************************************************************************* void CGUIAppDlg::OnChangeSMat() { // Do nothing if no object is currently selected. CPartition* ppart = pipeMain.ppartLastSelected(); if (ppart == 0) return; CInstance* pins = ptCast<CInstance>(ppart); if (pins == NULL) return; // // If the currently selected object has a light attached, edit the light // properties. // CInstance* pins_light = pipeMain.pinsGetLight(ptCast<CInstance>(ppart)); if (pins_light) return; CDialogString ds("Change Object Sound Material"); if (ds.DoModal() == IDOK) { CString str; char buf[256]; str = "Are you sure you want to change sound material of obejct '"; str += pins->strGetInstanceName(); str += "' to '"; str += ds.strText; str += "' (ID = "; TSoundHandle sndhnd = sndhndHashIdentifier(ds.strText); wsprintf(buf,"%x",(uint32)sndhnd); str += buf; str += ")?"; if (MessageBox(str, "Are you sure", MB_YESNO|MB_ICONQUESTION) == IDYES) { // change the material ID.. CPhysicsInfo* pphi = (CPhysicsInfo*)pins->pphiGetPhysicsInfo(); if (pphi) { pphi->SetMaterialType(sndhnd); } } } } void CGUIAppDlg::OnTeleport() { CDialogTeleport dlg; dlg.DoModal(); } //********************************************************************************************* // Bump packing has to be modal because the renderer must not be going while we change the // bump maps! void CGUIAppDlg::OnBumpPacking() { CDialogBumpPack dlgPacker; dlgPacker.DoModal(); } //********************************************************************************************* // Open the dialog that controls texture packing void CGUIAppDlg::OnDropMarker() { #if VER_TEST extern CInstance* pinsMasterMarker; extern int iMaxMarker; extern char strMarkerName[256]; if (!pinsMasterMarker) return; static int i_last_marker = 0; char buffer[256]; int i_safe; for (i_safe = iMaxMarker; i_safe >= 0; --i_safe) { ++i_last_marker; if (i_last_marker > iMaxMarker) i_last_marker = 1; sprintf(buffer, "%s%02d", strMarkerName, i_last_marker); CInstance* pins = wWorld.pinsFindInstance(u4Hash(buffer)); if (pins) { CInstance* pins_target = pcamGetCamera()->pinsAttached() ? pcamGetCamera()->pinsAttached() : pcamGetCamera(); pins->Move(pins_target->pr3Presence()); return; } } AlwaysAssert(i_safe >= 0); #endif } //********************************************************************************************* // Open the dialog that controls texture packing void CGUIAppDlg::OnPackOptions() { CDialogTexturePackOptions dlg; dlg.DoModal(); } // Porting code. void* hwndGetMainHwnd() { AlwaysAssert(pgui); return pgui->m_hWnd; } // Porting code. HINSTANCE hinstGetMainHInstance() { return AfxGetApp()->m_hInstance; } // Porting code. void ResetAppData() { // Clears all data that needs clearing on a world dbase reset. // Clear the pipeline selected stuff. pipeMain.lsppartSelected.erase(pipeMain.lsppartSelected.begin(), pipeMain.lsppartSelected.end()); } //********************************************************************************************* void CGUIAppDlg::InvokeCullingDialog() { CDialogCulling dlgcull; dlgcull.DoModal(); } //********************************************************************************************* void CGUIAppDlg::OnRenderQualitySettings() { // Don't do anything unless in debug mode. if (!bCanOpenChild()) return; // Create the sky dialog box. if (pdlgQuality == 0) { pdlgQuality = new CDialogQuality(); // Create and display the vm dialog pdlgQuality->Create(IDD_QUALITY, this); } pdlgQuality->ShowWindow(SW_SHOWNORMAL); } void CGUIAppDlg::ExitApp() { if (bExiting) return; bExiting = true; // Go back to startup path. CPushDir pshd(strStartupPath()); void SaveMenuSettings(char *); //SaveMenuSettings("options.txt"); SaveMenuSettings("lastopt.txt"); // Stop the timer. KillTimer(1); // delete the sky class and the associated texture etc CSkyRender::RemoveSky(); // shut the performance system PSClose(); destroy(&prasMainScreen); } BOOL CGUIAppDlg::DestroyWindow() { ExitApp(); return CDialog::DestroyWindow(); } //********************************************************************************************* void CGUIAppDlg::StatsDisplay() { // // Handle stat display, in a prioritised manner. If we are windowed, we show each console // in its own window, and other stats on screen. If we are fullscreen, we show only one // console or stat on screen. // // // Create any stats needed. // CCycleTimer ctmr_text; DisplayCacheStats(); // Set terrain stat averaging to current menu state. CTerrain* ptrr = CWDbQueryTerrain().tGet(); if (ptrr != 0) ptrr->SetStatAveraging(bAvgStats); bool b_showed_on_screen = false; if (bIsFullScreen) { // Show any output needed directly on screen. if (bShowConsole) { prnshMain->ShowConsoleOnScreen(conStd); b_showed_on_screen = true; } else if (bShowHardwareStats) { int i_hw_total_kb = d3dDriver.iGetTotalTextureMem() >> 10; int i_hw_sky_kb = 128; int i_hw_water_kb = CEntityWater::iGetManagedMemSize() >> 10; int i_hw_terrain_kb = NMultiResolution::CTextureNode::ptexmTexturePages->iGetManagedMemSize() >> 10; int i_hw_caches_kb = CRenderCache::iGetHardwareLimit() >> 10; int i_hw_buffer_kb = i_hw_total_kb - (i_hw_sky_kb + i_hw_water_kb + i_hw_terrain_kb + i_hw_caches_kb); conHardware.SetActive(true, false); conHardware.ClearScreen(); conHardware.Print("\n\n\n"); conHardware.Print("Vid Mem Total : %ld\n", i_hw_total_kb); conHardware.Print("Vid Lim Sky : %ld\n", i_hw_sky_kb); conHardware.Print("Vid Lim Water : %ld\n", i_hw_water_kb); conHardware.Print("Vid Lim Terrain : %ld\n", i_hw_terrain_kb); conHardware.Print("Vid Lim Cache : %ld\n", i_hw_caches_kb); conHardware.Print("Vid Buffer : %ld\n", i_hw_buffer_kb); conHardware.Print("\n"); conHardware.Print("Vid Mem Sky : %ld\n", i_hw_sky_kb); conHardware.Print("Vid Mem Water : %ld\n", CEntityWater::iGetManagedMemUsed() >> 10); conHardware.Print("Vid Mem Terrain : %ld\n", NMultiResolution::CTextureNode::ptexmTexturePages->iGetManagedMemUsed() >> 10); conHardware.Print("\n"); conHardware.Print("Vid Mem Cache : %ld\n", CRenderCache::iGetHardwareMem() >> 10); conHardware.Print("All Mem Cache : %ld\n", CRenderCache::iGetTotalMem() >> 10); conHardware.Print("All Lim Cache : %ld\n", CRenderCache::iGetLimitMem() >> 10); conHardware.Print("\n"); proHardware.psHardware.WriteToConsole(conHardware); prnshMain->ShowConsoleOnScreen(conHardware); b_showed_on_screen = true; } else if (bShowStats) { conProfile.SetActive(true, false); conProfile.ClearScreen(); proProfile.psMain.WriteToConsole(conProfile); prnshMain->ShowConsoleOnScreen(conProfile); b_showed_on_screen = true; } if (!bAvgStats) { // If averaging is on, let stats accumulate. Otherwise, reset them. proProfile.psFrame.Reset(); proHardware.psHardware.Reset(); proHardware.psHardware.Add(0, 1); } } // Clear screen if required. if (!b_showed_on_screen && bShowFPS || rcstCacheStats.bKeepStats) { conHardware.ClearScreen(); conProfile.ClearScreen(); b_showed_on_screen = true; } #if VER_TIMING_STATS // Show FPS. if (bShowFPS) { char buf[20]; // Show FPS stats based on the amout of time elapsed since we were last here. sprintf(buf, "FPS: %3.1f", 1.0 / ((double)ctmrFPS() * (double)ctmrFPS.fSecondsPerCycle())); prnshMain->PrintString(buf); } #endif // _asm // { // _emit 0x0f // _emit 0x31 // mov DWORD PTR [i8FrameStop+0],eax // mov DWORD PTR [i8FrameStop+4],edx // } // __int64 i8_elapsed = i8FrameStop-i8FrameStart; // i8FrameStart = i8FrameStop; // char buf[20]; // // Show FPS stats based on the amout of time elapsed since we were last here. // sprintf(buf, "FPS: %3.1f", 1.0 / ((double)i8_elapsed * 0.000000005)); // prnshMain->PrintString(buf); int i_remember_num_caches = iNumCaches(); // Display text. if (b_showed_on_screen) prnshMain->ShowConsoleOnScreen(conProfile); proProfile.psText.Add(ctmr_text()); // // Show specified consoles in their own window. // ctmr_text.Reset(); if (!bIsFullScreen) { // Test camera movement prediction. if (conPredictMovement.bIsActive()) { // Test prediction. TestPrediction(pcamGetCamera()->ppmGetPrediction()); // Display results. conPredictMovement.Show(); conPredictMovement.ClearScreen(); } // Occlusion console. conocOcclusion.Show(); if ((int)proProfile.psFrame.fCountPer() % 5 == 0) { if (bShowConsole) { // Create dialog if needed. conStd.SetActive(true); conStd.Show(); } else if (bShowStats) { // Activate profile dialog. conProfile.SetActive(true); conProfile.ClearScreen(); proProfile.psMain.WriteToConsole(conProfile); conProfile.Show(); } // Update all system consoles, if active. conAI.Show(); conPhysics.Show(); conShadows.Show(); if (conArtStats.bIsActive()) { float f_frames = 5.0f; // Frames over which stats are accumulated. int i_temp = 0; conArtStats.ClearScreen(); // Start with constant data. conArtStats.Print("Screen Mode: \t\t%dx%dx%d\n", prasMainScreen->iWidth, prasMainScreen->iHeight, prasMainScreen->iPixelBits); CCamera* pcam = pcamGetCamera(); CVector3<> v3_cam = pcam->v3Pos(); conArtStats.Print("Camera position: %f\t%f\t%f\n", v3_cam.tX, v3_cam.tY, v3_cam.tZ); #define iMAX_OBJECT_POLYGONS 500 #define iMAX_TOTAL_POLYGONS 1200 extern CProfileStat psTerrain; int i_total_polys = (float(proProfile.psDrawPolygon.iGetCount()) / f_frames) + 0.5f; // int i_cache_polys = i_remember_num_caches; int i_cache_polys = (psCacheSched.iGetCount() / f_frames) + 0.5f; int i_terrain_polys = float(psTerrain.iGetCount()) / f_frames + 0.5f; int i_object_polys = i_total_polys - i_cache_polys - i_terrain_polys; // Make sure our various cache stats match within one polygon. // psCacheUsed doesn't seem to match i_cache_polys. // Assert(psCacheUse.iGetCount() >= (i_cache_polys-1) * 5); // Assert(psCacheUse.iGetCount() <= (i_cache_polys+1) * 5); // psCacheUse.Reset(); if (i_max_total_polys < i_total_polys) i_max_total_polys = i_total_polys; conArtStats.Print("Total polys: \t\t%d of %d allowed, %d%% (M %d)\n", i_total_polys, iMAX_TOTAL_POLYGONS, int((100 * i_total_polys) / (iMAX_TOTAL_POLYGONS)), i_max_total_polys); if (i_max_cache_polys < i_cache_polys) i_max_cache_polys = i_cache_polys; if (i_max_terrain_polys < i_terrain_polys) i_max_terrain_polys = i_terrain_polys; conArtStats.Print("Cache polys: \t\t%d (M %d)\nTerrain polys: \t\t%d (M %d)\n", i_cache_polys, i_max_cache_polys, i_terrain_polys, i_max_terrain_polys); conArtStats.Print("Object Polys: \t\t%d of %d allowed, %d%%\n", i_object_polys, iMAX_OBJECT_POLYGONS, (i_object_polys * 100) / iMAX_OBJECT_POLYGONS); #define iALLOWED_TEXTURE_MEM_KB 4096 #ifdef LOG_MEM conArtStats.Print("Num textures: \t\t%d\n", ulGetMemoryLogCounter(emlTextureCount) + ulGetMemoryLogCounter(emlBumpMapCount) ); int i_num_unpacked = ulGetMemoryLogCounter(emlBumpNoPack) + ulGetMemoryLogCounter(emlTextureNoPack); int i_bumpmap_mem_bytes = ulGetMemoryLogCounter(emlTexturePages32) * (512*1024); int i_texture_mem_bytes = ulGetMemoryLogCounter(emlTexturePages8) * (128*1024); int i_unpacked_mem_bytes = ulGetMemoryLogCounter(emlBumpNoPackMem) + ulGetMemoryLogCounter(emlTextureNoPackMem); int i_total_mem_bytes = i_bumpmap_mem_bytes + i_texture_mem_bytes + i_unpacked_mem_bytes; conArtStats.Print("Total texture mem: \t%1.3f of %1.3f MB, %d%%\n", float(i_total_mem_bytes) / (1024.0f * 1024.0f), float(iALLOWED_TEXTURE_MEM_KB) / 1024.0f, float(i_total_mem_bytes) / (1024.0f * float(iALLOWED_TEXTURE_MEM_KB))); conArtStats.Print("Mem for bumpmaps: \t%1.3f MB\n", (i_bumpmap_mem_bytes + ulGetMemoryLogCounter(emlBumpNoPackMem)) / (1024.0f * 1024.0f)); conArtStats.Print("Unpacked textures: \t%d bytes in %d surfaces\n", i_unpacked_mem_bytes, i_num_unpacked); #else // LOG_MEM conArtStats.Print("No texture data available."); #endif // LOG_MEM extern int iNumClipped; conArtStats.Print("Split polys: \t\t%ld\n", iNumClipped); static int i_worst_cache = 0; conArtStats.Print("Cache update time: \t%dms\n", int(psCacheSched.fSeconds() * 1000)); if (psCacheSched.fSeconds() * 1000 > i_worst_cache) i_worst_cache = psCacheSched.fSeconds() * 1000; conArtStats.Print("Worst Cache update time:%dms\n", i_worst_cache); conArtStats.Print("FPS: \t\t\t%2.1f\n", 1.0 / proProfile.psFrame.fSecondsPerCount()); // Print transparency stats. if (iNumPixelsIterated > 0) { float f_percentage_transparent = float(iNumPixelsIterated - iNumPixelsSolid) / float(iNumPixelsIterated) * 100.0f; conArtStats.Print("Percentage Transparent: %1.1f\n", f_percentage_transparent); } // Clear stats. iNumPixelsIterated = 0; iNumPixelsSolid = 0; // Now show the stats. conArtStats.Show(); psTerrain.Reset(); } if (!bAvgStats) // If averaging is on, let stats accumulate. Otherwise, reset them. proProfile.psFrame.Reset(); } conTerrain.Show(); } // Show stats for depth sorting. DepthSortStatsWriteAndClear(); proProfile.psText.Add(ctmr_text()); } int iSkipFrames = 100; extern CProfileStat psExecuteCaches; extern CProfileStat psExecuteTerrain; class CFrameTime { float fFrameTime; float fOther; int32 i4TickCount; public: CFrameTime() { } ~CFrameTime() { if (fileStats) { fclose(fileStats); fileStats = 0; } } void SetCount() { i4TickCount = GetTickCount(); } void Begin() { fFrameTime = float(int32(GetTickCount()) - i4TickCount) / 1000.0f; if (fFrameTime < 0.0f) fFrameTime = 0.1f; fOther = fFrameTime; fprintf(fileStats, "%1.5f", fFrameTime); } void Print(float f) { fOther -= f; fprintf(fileStats, ",%1.5f", f); } void Print(const CProfileStat& stat) { float f = stat.fSeconds(); fOther -= f; Print(f); } void End() { //fprintf(fileStats, ",%1.5f", fOther); fprintf(fileStats, "\n"); proProfile.psFrame.Reset(); SetCount(); } }; CFrameTime Frame; //********************************************************************************************* void CGUIAppDlg::StatsDump() { if (iSkipFrames > 1) iSkipFrames = 1; if (iSkipFrames > 0) { --iSkipFrames; proProfile.psFrame.Reset(); if (iSkipFrames == 0) { if (!fileStats) fileStats = fopen("Stats.csv", "wt"); fprintf(fileStats, "Total,Physics,AI,Step,Cache Bld,Terr Tex,Special\n"); } Frame.SetCount(); return; } Frame.Begin(); float f_step = proProfile.psStep.fSeconds() - proProfile.psPhysics.fSeconds() - proProfile.psAI.fSeconds(); Frame.Print(proProfile.psPhysics); Frame.Print(proProfile.psAI); Frame.Print(f_step); Frame.Print(psExecuteCaches); Frame.Print(psExecuteTerrain); Frame.Print(psOTHER_STAT); Frame.End(); proProfile.psPhysics.Reset(); proProfile.psAI.Reset(); // proProfile.psStepOther.Reset(); psExecuteCaches.Reset(); psExecuteTerrain.Reset(); psOTHER_STAT.Reset(); } //********************************************************************************************* uint32 u4LookupResourceString(int32 i4_id,char* str_buf,uint32 u4_buf_len) { char buf[1024]; int i_res = LoadString(AfxGetInstanceHandle(), IDS_STR_HINTS + i4_id, buf, 1024); if ((i_res>0) && (i_res<(int)u4_buf_len)) { // copy the string to the destination buffer and process and escape sequences wsprintf(str_buf,buf); Assert(strlen(str_buf)<u4_buf_len); return strlen(str_buf); } return 0; }
87bc5657384eef2299d8aebd0d8c0a891725f5c1
9e4b20e6ba7805df9b377ca5650b249f6d59df24
/week-2/diet/diet.cc
0824979f850412d328549252e1037329d0fc0943
[]
no_license
aakarsh/linear_programming
2e4f99911799eef781d63ac665be0fdc065a61c2
b28b8c15072b392d8f4ac53af83b92ae127d06f9
refs/heads/master
2020-05-22T20:04:28.945409
2017-07-09T08:47:32
2017-07-09T08:47:32
84,720,013
1
0
null
null
null
null
UTF-8
C++
false
false
1,088
cc
#include <algorithm> #include <iostream> #include <vector> #include <cstdio> using namespace std; typedef vector<vector<double>> matrix; pair<int, vector<double>> solve_diet_problem(int n, int m, matrix A,vector<double> b,vector<double> c) { // Write your code here // something goes here but idk w return {0, vector<double>(m, 0)}; } int main() { int n, m; cin >> n >> m; matrix A(n, vector<double>(m)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> A[i][j]; } } vector<double> b(n); for (int i = 0; i < n; i++) { cin >> b[i]; } vector<double> c(m); for (int i = 0; i < m; i++) { cin >> c[i]; } pair<int, vector<double>> ans = solve_diet_problem(n, m, A, b, c); switch (ans.first) { case -1: printf("No solution\n"); break; case 0: printf("Bounded solution\n"); for (int i = 0; i < m; i++) { printf("%.18f%c", ans.second[i], " \n"[i + 1 == m]); } break; case 1: printf("Infinity\n"); break; } return 0; }
a1c42bd4af64531f493290baad4aa01e205fa48b
f3f100d7997a4739bc883dca02e3abbe86e18a33
/AAI/SjoerdOpenGL/Assignment/Steering/Steering.cpp
4d8d43e4d1274b3b8b5db5840dd71d7ed1a9b9cc
[ "MIT" ]
permissive
jjkramok/ICTGP
4ed51d3409ca2163ba28d32b4bd1174d5b8cdeb1
fbe45cc5ebbc5095353512cbe0f0db61e2c95042
refs/heads/master
2021-05-05T01:05:47.894526
2018-06-18T12:48:57
2018-06-18T12:48:57
119,531,472
1
0
null
null
null
null
UTF-8
C++
false
false
948
cpp
#include "Steering.h" Steering::Steering() { } Steering::~Steering() { } SteeringForce Steering::flee(Entity * entity) { entity->location; SteeringForce a = {3.0f}; return a; } SteeringForce Steering::flee(int entityType) { return SteeringForce(); } SteeringForce Steering::seek(Entity * entity) { return SteeringForce(); } SteeringForce Steering::seek(int entityType) { return SteeringForce(); } SteeringForce Steering::wander() { return SteeringForce(); } SteeringForce Steering::arrive(std::vector<float> location) { return SteeringForce(); } SteeringForce Steering::arrive(Entity * entity) { return SteeringForce(); } SteeringForce Steering::follow(Entity * entity) { return SteeringForce(); } SteeringForce Steering::flocking(int entityType) { return SteeringForce(); } SteeringForce Steering::obstacleAvoidence() { return SteeringForce(); } SteeringForce Steering::hide(int entityType) { return SteeringForce(); }
e972a7ae6dacfe11c4653423e583a471f4095bc7
51f6e63555b4fda6a620fb42952c5c1fa6eac706
/content/browser/indexed_db/leveldb/fake_leveldb_factory.cc
bd42a3113218f96ebae602c2e4a1620cfd7aa474
[ "BSD-3-Clause" ]
permissive
heanglightman/chromium
6f74026b428317a28cbb1226d20d1116ed54dd2b
f561f3e0174135fcc555aad31f4adb845977b8bd
refs/heads/master
2023-02-25T08:18:13.731198
2019-03-25T16:19:12
2019-03-25T16:19:12
177,623,917
1
0
NOASSERTION
2019-03-25T16:27:22
2019-03-25T16:27:22
null
UTF-8
C++
false
false
9,042
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/indexed_db/leveldb/fake_leveldb_factory.h" #include <mutex> #include <string> #include <thread> #include <utility> #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/optional.h" #include "base/synchronization/lock.h" #include "base/thread_annotations.h" #include "content/browser/indexed_db/indexed_db_leveldb_operations.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/leveldatabase/src/include/leveldb/slice.h" #include "third_party/leveldatabase/src/include/leveldb/status.h" namespace content { namespace indexed_db { namespace { class BrokenIterator : public leveldb::Iterator { public: BrokenIterator(leveldb::Status returned_status) : returned_status_(returned_status) {} bool Valid() const override { return false; } void SeekToFirst() override {} void SeekToLast() override {} void Seek(const leveldb::Slice& target) override {} void Next() override {} void Prev() override {} leveldb::Slice key() const override { return leveldb::Slice(); } leveldb::Slice value() const override { return leveldb::Slice(); } leveldb::Status status() const override { return returned_status_; } private: leveldb::Status returned_status_; }; // BrokenDB is a fake leveldb::DB that will return a given error status on every // method call, or no-op if there is nothing to return. class BrokenDB : public leveldb::DB { public: BrokenDB(leveldb::Status returned_status) : returned_status_(std::move(returned_status)) {} ~BrokenDB() override = default; // Implementations of the DB interface leveldb::Status Put(const leveldb::WriteOptions&, const leveldb::Slice& key, const leveldb::Slice& value) override { return returned_status_; } leveldb::Status Delete(const leveldb::WriteOptions&, const leveldb::Slice& key) override { return returned_status_; } leveldb::Status Write(const leveldb::WriteOptions& options, leveldb::WriteBatch* updates) override { return returned_status_; } leveldb::Status Get(const leveldb::ReadOptions& options, const leveldb::Slice& key, std::string* value) override { return returned_status_; } leveldb::Iterator* NewIterator(const leveldb::ReadOptions&) override { return new BrokenIterator(returned_status_); } const leveldb::Snapshot* GetSnapshot() override { return nullptr; } void ReleaseSnapshot(const leveldb::Snapshot* snapshot) override {} bool GetProperty(const leveldb::Slice& property, std::string* value) override { return false; } void GetApproximateSizes(const leveldb::Range* range, int n, uint64_t* sizes) override {} void CompactRange(const leveldb::Slice* begin, const leveldb::Slice* end) override {} private: leveldb::Status returned_status_; }; // BreakOnCallbackDB is a leveldb::DB wrapper that will return a given error // status or fail every method call after the |Break| method is called. This is // thread-safe, just like leveldb::DB. class BreakOnCallbackDB : public leveldb::DB { public: BreakOnCallbackDB(std::unique_ptr<leveldb::DB> db) : db_(std::move(db)) {} ~BreakOnCallbackDB() override = default; void Break(leveldb::Status broken_status) { base::AutoLock lock(lock_); broken_status_ = std::move(broken_status); } // Implementations of the DB interface leveldb::Status Put(const leveldb::WriteOptions& options, const leveldb::Slice& key, const leveldb::Slice& value) override { { base::AutoLock lock(lock_); if (broken_status_) return broken_status_.value(); } return db_->Put(options, key, value); } leveldb::Status Delete(const leveldb::WriteOptions& options, const leveldb::Slice& key) override { { base::AutoLock lock(lock_); if (broken_status_) return broken_status_.value(); } return db_->Delete(options, key); } leveldb::Status Write(const leveldb::WriteOptions& options, leveldb::WriteBatch* updates) override { { base::AutoLock lock(lock_); if (broken_status_) return broken_status_.value(); } return db_->Write(options, updates); } leveldb::Status Get(const leveldb::ReadOptions& options, const leveldb::Slice& key, std::string* value) override { { base::AutoLock lock(lock_); if (broken_status_) return broken_status_.value(); } return db_->Get(options, key, value); } leveldb::Iterator* NewIterator(const leveldb::ReadOptions& options) override { { base::AutoLock lock(lock_); if (broken_status_) return new BrokenIterator(broken_status_.value()); } return db_->NewIterator(options); } const leveldb::Snapshot* GetSnapshot() override { { base::AutoLock lock(lock_); if (broken_status_) return nullptr; } return db_->GetSnapshot(); } void ReleaseSnapshot(const leveldb::Snapshot* snapshot) override { { base::AutoLock lock(lock_); if (broken_status_) return; } return db_->ReleaseSnapshot(snapshot); } bool GetProperty(const leveldb::Slice& property, std::string* value) override { { base::AutoLock lock(lock_); if (broken_status_) return false; } return db_->GetProperty(property, value); } void GetApproximateSizes(const leveldb::Range* range, int n, uint64_t* sizes) override { { base::AutoLock lock(lock_); if (broken_status_) return; } db_->GetApproximateSizes(range, n, sizes); } void CompactRange(const leveldb::Slice* begin, const leveldb::Slice* end) override { { base::AutoLock lock(lock_); if (broken_status_) return; } db_->CompactRange(begin, end); } private: base::Lock lock_; const std::unique_ptr<leveldb::DB> db_; base::Optional<leveldb::Status> broken_status_ GUARDED_BY(lock_); }; } // namespace FakeLevelDBFactory::FakeLevelDBFactory() = default; FakeLevelDBFactory::~FakeLevelDBFactory() {} // static scoped_refptr<LevelDBState> FakeLevelDBFactory::GetBrokenLevelDB( leveldb::Status error_to_return, const base::FilePath& reported_file_path) { return LevelDBState::CreateForDiskDB( indexed_db::GetDefaultLevelDBComparator(), indexed_db::GetDefaultIndexedDBComparator(), std::make_unique<BrokenDB>(error_to_return), reported_file_path); } // static std::pair<std::unique_ptr<leveldb::DB>, base::OnceCallback<void(leveldb::Status)>> FakeLevelDBFactory::CreateBreakableDB(std::unique_ptr<leveldb::DB> db) { std::unique_ptr<BreakOnCallbackDB> breakable_db = std::make_unique<BreakOnCallbackDB>(std::move(db)); base::OnceCallback<void(leveldb::Status)> callback = base::BindOnce( &BreakOnCallbackDB::Break, base::Unretained(breakable_db.get())); return std::make_pair(std::move(breakable_db), std::move(callback)); } void FakeLevelDBFactory::EnqueueNextOpenDBResult( std::unique_ptr<leveldb::DB> db, leveldb::Status status) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); next_dbs_.push(std::make_tuple(std::move(db), status)); } std::tuple<std::unique_ptr<leveldb::DB>, leveldb::Status> FakeLevelDBFactory::OpenDB(const leveldb_env::Options& options, const std::string& name) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (next_dbs_.empty()) return DefaultLevelDBFactory::OpenDB(options, name); auto tuple = std::move(next_dbs_.front()); next_dbs_.pop(); return tuple; } void FakeLevelDBFactory::EnqueueNextOpenLevelDBStateResult( scoped_refptr<LevelDBState> state, leveldb::Status status, bool is_disk_full) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); next_leveldb_states_.push( std::make_tuple(std::move(state), status, is_disk_full)); } std::tuple<scoped_refptr<LevelDBState>, leveldb::Status, bool /*disk_full*/> FakeLevelDBFactory::OpenLevelDBState( const base::FilePath& file_name, const LevelDBComparator* idb_comparator, const leveldb::Comparator* ldb_comparator) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (next_leveldb_states_.empty()) { return DefaultLevelDBFactory::OpenLevelDBState(file_name, idb_comparator, ldb_comparator); } auto tuple = std::move(next_leveldb_states_.front()); next_leveldb_states_.pop(); return tuple; } } // namespace indexed_db } // namespace content
65eafdcd9234e2c4b1bf0710412e5e0c8661af56
f959849552c83bcccdfdb3ec7f200348fda2309b
/nRF_First_Success/Transmitter/Transmitter/Transmitter.ino
755319b1911468af4561d872da2bee70065892f4
[]
no_license
sujeet-banerjee/radio
a907b93c50f0929e1e3dd7161d4f1939515fee1b
b63e5ed37c5581c3aab23d8bf8c41f37cc1765a0
refs/heads/master
2020-06-28T11:46:46.297312
2017-01-06T09:00:30
2017-01-06T09:00:30
67,323,791
1
0
null
null
null
null
UTF-8
C++
false
false
4,780
ino
#include <nRF24L01.h> #include <RF24.h> #include <RF24_config.h> /* YourDuinoStarter Example: nRF24L01 Transmit Joystick values - WHAT IT DOES: Reads Analog values on A0, A1 and transmits them over a nRF24L01 Radio Link to another transceiver. - SEE the comments after "//" on each line below - CONNECTIONS: nRF24L01 Modules See: http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo 1 - GND 2 - VCC 3.3V !!! NOT 5V 3 - CE to Arduino pin 9 4 - CSN to Arduino pin 10 5 - SCK to Arduino pin 13 6 - MOSI to Arduino pin 11 7 - MISO to Arduino pin 12 8 - UNUSED - Analog Joystick or two 10K potentiometers: GND to Arduino GND VCC to Arduino +5V X Pot to Arduino A0 Y Pot to Arduino A1 - V1.00 11/26/13 Based on examples at http://www.bajdi.com/ Questions: [email protected] */ /*-----( Import needed libraries )-----*/ #include <SPI.h> /*-----( Declare Constants and Pin Numbers )-----*/ #define CE_PIN 9 #define CSN_PIN 10 //#define JOYSTICK_X A0 //#define JOYSTICK_Y A1 /* * Indicators */ #define LED_INTX 8 #define LED_TX_OK 7 #define LED_TX_FAIL 6 #define LED_LOOP 4 // NOTE: the "LL" at the end of the constant is "LongLong" type const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe /*-----( Declare objects )-----*/ RF24Debug radio(CE_PIN, CSN_PIN); // Create a Radio /*-----( Declare Variables )-----*/ int joystick[2]; // 2 element array holding Joystick readings void print_hex_byte(uint8_t b) { Serial.print(F(" 0x")); if (b < 16) Serial.print('0'); Serial.print(b, HEX); } void print_status(uint8_t status) { Serial.println("\n\n=== STT ==="); print_hex_byte(status); Serial.print(F(" RX_DR=")); Serial.print((status & _BV(RX_DR))? 1: 0); Serial.print(F(" TX_DS=")); Serial.print((status & _BV(TX_DS))? 1: 0); Serial.print(F(" MAX_RT=")); Serial.print((status & _BV(MAX_RT))? 1: 0); Serial.print(F(" RX_P_NO=")); Serial.print((status >> RX_P_NO) & B111); Serial.print(F(" TX_FULL=")); Serial.println((status & _BV(TX_FULL))? 1: 0); } uint8_t write_register(uint8_t reg, uint8_t value) { uint8_t status; digitalWrite(CSN_PIN, LOW); status = SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) ); SPI.transfer(value); digitalWrite(CSN_PIN, HIGH); return status; } void setup() /****** SETUP: RUNS ONCE ******/ { Serial.begin(115200); delay(200); pinMode(CE_PIN, OUTPUT); digitalWrite(CE_PIN, HIGH); pinMode(CSN_PIN, OUTPUT); Serial.println("Nrf24L01 Transmitter Starting..."); radio.begin(); radio.openWritingPipe(pipe); radio.printDetails(); delay(2000); attachInterrupt(0, get_data, FALLING);//kick things off by attachin the IRQ interrupt //Indicators pinMode(LED_INTX, OUTPUT); pinMode(LED_LOOP, OUTPUT); pinMode(LED_TX_OK, OUTPUT); pinMode(LED_TX_FAIL, OUTPUT); }//--(end setup )--- void get_data(){// get data start get data start get data start get data start get data start // this routine is called when the IRQ pin is pulled LOW by the NRF //Serial.println(" <<< INTERRUPT >>> "); digitalWrite(LED_INTX, HIGH); for(int i=0; i<1000 ;i++) delayMicroseconds(100); digitalWrite(LED_INTX, LOW); for(int i=0; i<1000 ;i++) delayMicroseconds(40); digitalWrite(LED_INTX, HIGH); for(int i=0; i<1000 ;i++) delayMicroseconds(100); digitalWrite(LED_INTX, LOW); // Status bool st_ok, st_failed, rx_ready; // The below code snippet expands "whatHappened" uint8_t stt2 = write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); st_ok = stt2 & _BV(TX_DS); st_failed = stt2 & _BV(MAX_RT); rx_ready = stt2 & _BV(RX_DR); if(st_ok) { digitalWrite(LED_TX_OK, HIGH); digitalWrite(LED_TX_FAIL, LOW); } else { digitalWrite(LED_TX_OK, LOW); digitalWrite(LED_TX_FAIL, HIGH); } } int valY = 808; int valX = 333; void loop() /****** LOOP: RUNS CONSTANTLY ******/ { delay(20); Serial.println("................"); joystick[0] = valX; joystick[1] = valY++; valX = valY>3000?++valX:valX; valY = valY>3000?101:valY; Serial.print("=> Sending "); Serial.print("X = "); Serial.print(joystick[0]); Serial.print(" Y = "); Serial.println(joystick[1]); radio.write( joystick, sizeof(joystick) ); delay(200); // Loop indication digitalWrite(LED_LOOP, HIGH); delay(200); digitalWrite(LED_LOOP, LOW); uint8_t stt = write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); print_status(stt); Serial.println(stt & _BV(TX_DS)? F("OOOOOOKKKKKKK ...OK."): F("FZFZFZFZFZFZFZ ...FAIL")); }//--(end main loop )--- /*-----( Declare User-written Functions )-----*/ //NONE //*********( THE END )***********
7ac5f1f6857667a8552fc892e4670798c0249e95
c85fd542bd7c23aed09e044b947c4a8e6074bc25
/src/core/risa/packages/risa/sound/ALSource.h
ad0ced638501f4364c7346601399646c03afde10
[]
no_license
w-dee/kirikiri3-legacy
35742a56cb1e5b5f0252a48c41d1c594ee3a79a6
9a918425c41fc3f64468ded61cdce6c464d2247a
refs/heads/master
2020-06-23T22:18:34.794911
2010-01-04T06:33:50
2010-01-04T06:33:50
198,763,501
19
0
null
null
null
null
UTF-8
C++
false
false
11,414
h
//--------------------------------------------------------------------------- /* Risa [りさ] alias 吉里吉里3 [kirikiri-3] stands for "Risa Is a Stagecraft Architecture" Copyright (C) 2000 W.Dee <[email protected]> and contributors See details of license at "license.txt" */ //--------------------------------------------------------------------------- //! @file //! @brief OpenAL ソース管理 //--------------------------------------------------------------------------- #ifndef ALSourceH #define ALSourceH #include <AL/al.h> #include <AL/alc.h> #include "risa/packages/risa/sound/ALCommon.h" #include "risa/packages/risa/sound/ALBuffer.h" #include "risa/packages/risa/sound/WaveSegmentQueue.h" #include "risa/packages/risa/sound/WaveLoopManager.h" #include "risa/common/RisaThread.h" #include "risa/common/Singleton.h" #include "risa/packages/risa/event/Event.h" #include "risseNativeBinder.h" namespace Risa { //--------------------------------------------------------------------------- class tALSource; //--------------------------------------------------------------------------- /** * 監視用スレッド * @note 監視用スレッドは、約50ms周期のコールバックをすべての * ソースに発生させる。ソースではいくつかポーリングを * 行わなければならない場面でこのコールバックを利用する。 */ class tWaveWatchThread : public singleton_base<tWaveWatchThread>, manual_start<tWaveWatchThread>, public tThread { tThreadEvent Event; //!< スレッドをたたき起こすため/スレッドを眠らせるためのイベント public: /** * コンストラクタ */ tWaveWatchThread(); /** * デストラクタ */ ~tWaveWatchThread(); /** * 眠っているスレッドを叩き起こす */ void Wakeup(); protected: /** * スレッドのエントリーポイント */ void Execute(void); }; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- /** * tALSourceのステータスを含むクラス */ class tALSourceStatus { public: /** * サウンドソースの状態 */ enum tStatus { ssUnload /*!< data is not specified (tALSourceではこの状態は存在しない) */, ssStop /*!< stopping */, ssPlay /*!< playing */, ssPause /*!< pausing */, }; }; //--------------------------------------------------------------------------- } namespace Risse { //--------------------------------------------------------------------------- /** * NativeBinder 用の Variant -> tALSourceStatus::tStatus 変換定義 */ template <> inline Risa::tALSourceStatus::tStatus FromVariant<Risa::tALSourceStatus::tStatus>(const tVariant & v) { return (Risa::tALSourceStatus::tStatus)(int)(risse_int64)v; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- /** * NativeBinder 用の tALSourceStatus::tStatus -> Variant 変換定義 */ template <> inline tVariant ToVariant<Risa::tALSourceStatus::tStatus>(Risa::tALSourceStatus::tStatus s) { return tVariant((risse_int64)(int)s); } //--------------------------------------------------------------------------- } namespace Risa { class tWaveDecodeThread; //--------------------------------------------------------------------------- /** * OpenALソース */ class tALSource : public tCollectee, protected depends_on<tOpenAL>, protected depends_on<tWaveWatchThread>, protected depends_on<tEventSystem>, public tALSourceStatus { friend class tWaveDecodeThread; friend class tWaveWatchThread; public: // 定数など static const risse_uint STREAMING_NUM_BUFFERS = tALBuffer::MAX_NUM_BUFFERS; //!< ストリーミング時のバッファの数(調整可) static const risse_uint STREAMING_PREPARE_BUFFERS = 4; //!< 再生開始前にソースにキューしておくバッファの数 private: struct tInternalSource : public tDestructee { ALuint Source; //!< OpenAL ソース tInternalSource(); //!< コンストラクタ ~tInternalSource(); //!< デストラクタ }; tCriticalSection * CS; //!< このオブジェクトを保護するクリティカルセクション tCriticalSection * BufferCS; //!< バッファへのキューイングを保護するクリティカルセクション risse_uint NumBuffersQueued; //!< キューに入っているバッファの数 tInternalSource * Source; tALBuffer * Buffer; //!< バッファ tWaveLoopManager * LoopManager; //!< ループマネージャ bool NeedRewind; //!< リワインド (巻き戻し) が必要な場合に真 tWaveDecodeThread * DecodeThread; //!< デコードスレッド tStatus Status; //!< サウンドステータス tStatus PrevStatus; //!< 直前のサウンドステータス /** * 一つの OpenAL バッファに対応するセグメントの情報 */ struct tSegmentInfo { tWaveSegmentQueue SegmentQueue; //!< セグメントキュー risse_uint64 DecodePosition; //!< デコードを開始した任意の原点からの相対デコード位置(サンプルグラニュール単位) }; gc_deque<tSegmentInfo> SegmentQueues; //!< セグメントキューの配列 gc_deque<tWaveEvent> SegmentEvents; //!< イベントの配列 risse_uint64 DecodePosition; //!< デコードした総サンプル数 public: /** * コンストラクタ * @param buffer OpenAL バッファを管理する tALBuffer インスタンス */ tALSource(tALBuffer * buffer, tWaveLoopManager * loopmanager = NULL); /** * コンストラクタ(ほかのtALSourceとバッファを共有する場合) * @param ref コピー元ソース */ tALSource(const tALSource * ref); /** * デストラクタ */ virtual ~tALSource() {;} private: /** * オブジェクトを初期化する * @param buffer OpenAL バッファを管理する tALBuffer インスタンス */ void Init(tALBuffer * buffer); /** * Source の存在を確実にする */ void EnsureSource(); /** * Source を強制的に削除する */ void DeleteSource(); public: ALuint GetSource() const { if(Source) return Source->Source; else return 0; } //!< Source を得る private: //---- queue/buffer management /** * レンダリング(デコード)を行う * @note 残り容量が少ないと偽を返す */ bool Render(); /** * バッファのデータを埋める */ void FillBuffer(); /** * すべてのバッファをアンキューする */ void UnqueueAllBuffers(); /** * バッファをソースにキューする * @note キューできない場合は何もしない */ void QueueBuffer(); /** * 状態をチェックする * @note OpenAL による実際の再生状況と、このクラス内の管理情報が * 異なる場合がある(特に再生停止時)ため、その状態を再度チェックするためにある。 * クリティカルセクションによる保護は別の場所で行うこと。 */ void RecheckStatus(); public: /** * 監視用コールバック(tWaveWatchThreadから約50msごとに呼ばれる) */ void WatchCallback(); /** * 現在再生位置までに発生したイベントをすべて発生させる * @return もっとも近い次のラベルイベントまでの時間を ms で返す */ private: /** * 前回とステータスが変わっていたら OnStatusChanged を呼ぶ * @param async 非同期イベントかどうか * @note このメソッド内でロックは行わないので、呼び出し元が * ちゃんとロックを行っているかどうかを確認すること。 */ void CallStatusChanged(bool async); public: /** * 再生の開始 */ void Play(); protected: /** * 再生の停止(内部関数) * @param notify OnStatusChanged で通知をするかどうか * 0=通知しない 1=同期イベントとして通知 2=非同期イベントとして通知 */ void InternalStop(int notify); public: /** * 再生の停止 * @param notify OnStatusChanged で通知をするかどうか * 0=通知しない 1=同期イベントとして通知 2=非同期イベントとして通知 */ void Stop(int notify = 1); /** * 再生の一時停止 */ void Pause(); private: /** * 再生中のバッファ内の位置を得る * @return 再生中のバッファ内の位置 (キューの先頭からのサンプルグラニュール数単位) * @note 現在位置を得られなかった場合は risse_size_max が帰る。このメソッドは * スレッド保護を行わないので注意 */ risse_size GetBufferPlayingPosition(); public: /** * 再生位置を得る * @return 再生位置 (デコーダ出力時におけるサンプルグラニュール数単位) * @note 返される値は、デコーダ上(つまり元のメディア上での)サンプルグラニュール数 * 単位となる。これは、フィルタとして時間の拡縮を行うようなフィルタが * 挟まっていた場合は、実際に再生されたサンプルグラニュール数とは * 異なる場合があるということである。 */ risse_uint64 GetPosition(); /** * 再生位置を設定する * @param pos 再生位置 (デコーダ出力におけるサンプルグラニュール数単位) */ void SetPosition(risse_uint64 pos); public: /** * 現在の再生位置までのラベルイベントを発生させ、次のラベルイベントまでの時間を帰す * @return 次のラベルイベントまでの時間(ms) ラベルイベントが見つからない場合は -1 を帰す */ risse_int32 FireLabelEvents(); public: /** * ステータスの変更を通知する * @param status ステータス * @note OnStatusChangedAsync は非同期イベント用。 * OnStatusChanged 同士や OnStatusChangedAsync 同士、 * あるいはそれぞれ同士の呼び出しが重ならないことは * このクラスが保証している。 * OnStatusChangedAsync は OnStatusChanged を呼んだ * スレッドとは別のスレッドが呼ぶ可能性があるので注意すること。 */ virtual void OnStatusChanged(tStatus status) {;} /** * ステータスの変更を非同期に通知する * @param status ステータス * @note OnStatusChangedAsync は非同期イベント用。 * OnStatusChanged 同士や OnStatusChangedAsync 同士、 * あるいはそれぞれ同士の呼び出しが重ならないことは * このクラスが保証している。 * OnStatusChangedAsync は OnStatusChanged を呼んだ * スレッドとは別のスレッドが呼ぶ可能性があるので注意すること。 */ virtual void OnStatusChangedAsync(tStatus status) {;} /** * ラベルイベントの発生を通知する * @param name ラベル名 * @note このイベントは常に非同期イベントとなるはず。 * スレッドとは別のスレッドが呼ぶ可能性があるので注意すること。 */ virtual void OnLabel(const tString & name) {;} }; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- } // namespace Risa #endif
[ "w.dee@9e463c26-7fdd-0310-8662-bb9cb7c2284e" ]
w.dee@9e463c26-7fdd-0310-8662-bb9cb7c2284e
499c670929ecbe46b4a4910561bd289425ddf714
5cc69797640c8aa3697eb7aba8820dd98055c25a
/SFMLTemplate/Player.hpp
7b2daa30f33e552e18eec60c532c9568b0432399
[]
no_license
Painpillow/SFML-Templaatti
103dd2a18df67cfc3dcd00ae43b6ee432b7499d0
29a2e4be718e354cfffaef1132634b3949597129
refs/heads/master
2021-01-14T14:07:05.169666
2015-10-26T13:54:42
2015-10-26T13:54:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
248
hpp
#pragma once #include <SFML\System.hpp> #include <SFML\Graphics.hpp> class Player { private: sf::Vector2f position; int health; public: Player(); void update(const sf::Time& time); void draw(sf::RenderWindow& renderWindow); ~Player(); };
7753c2c62284e221a795ab0a2e0d6ddd7ce0aaf1
4e131c7fa40381a378488c96fa47a44744b26cc5
/GUI/dialog.h
06cf388541d664ed30d4164c307302e6365697fb
[]
no_license
voidrealms/Qt-24
700c06d5d2c27dae45218e904cd2b045a31e1ff3
7bd0a12387c4738acf481dbc7a72f9774e064c6e
refs/heads/master
2021-07-23T04:20:11.879410
2017-11-02T19:34:56
2017-11-02T19:34:56
109,310,345
0
0
null
null
null
null
UTF-8
C++
false
false
316
h
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include <QtCore> #include <QtGui> namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); private: Ui::Dialog *ui; }; #endif // DIALOG_H
00de4d42e06cea80dc6dfc13611e33100ac11a70
0e3ab186e07482b3c7d8b6bdddcb13e765a3f208
/Sorting/InsertionSort.cpp
26670708e3e92cbba96d57ee2e330982ecec75f2
[]
no_license
201710757/DataS
7fda8a6e68b775530d2903dbd338cac8d40523f1
5d61166dc37f5ab3a037d32f2c254404465a9704
refs/heads/master
2023-02-05T06:48:35.123531
2020-12-28T14:29:52
2020-12-28T14:29:52
293,270,327
1
0
null
2020-12-28T14:29:53
2020-09-06T12:16:49
C++
UTF-8
C++
false
false
611
cpp
#include<iostream> using namespace std; void InsertionSort(int arr[], int n) { int nowData = 0; int j; for(int i = 1;i<n;i++) { nowData = arr[i]; for(j=i-1;j>=0;j--) { if(arr[j] > nowData) { arr[j+1] = arr[j]; } else { break; } } arr[j+1] = nowData; } } int main(void) { int arr[] = {6,5,4,3,2,1}; InsertionSort(arr, 6); for(int i=0;i<6;i++) cout<<arr[i]<<" "; cout<<endl; return 0; }
e73c122552f61c9b3bef68c8435a6c8f05681c0a
fdcab8dbdfa88fb93b17e6e731283e83da5bd123
/src/Bitshifing.cpp
97b1cd480ae6ed0a74567f76c9cebbff5aa837a9
[]
no_license
bako2010/NucleoGitHub
7d38b46adb785e7676b43d8171dee8c064accded
5611fc68d434859fc3c5b90d96267dd470233325
refs/heads/master
2023-03-23T03:02:15.117359
2021-03-11T16:11:48
2021-03-11T16:11:48
346,743,088
0
0
null
null
null
null
UTF-8
C++
false
false
125
cpp
#include <mbed.h> void wait(int x); int main() { while (1) { } } void wait(int x) { wait_us(x * 1000); }
f2d90eda51685626976124aaaef330814612e751
5f77516a28c03021bca3886cb193136ccce870ff
/math/verify_prime.cpp
32b3abaef92c8eaa11228b691b3adf984aca6256
[]
no_license
thelastsupreme/interviewbit
75fc488e3d0a3cdf4471bc35ef2e6c06ba595e0f
c39162e6f6e51d718b9f9b6832bbbd52adf61b9d
refs/heads/master
2022-12-01T02:17:51.147924
2020-08-13T03:59:16
2020-08-13T03:59:16
264,120,353
0
0
null
null
null
null
UTF-8
C++
false
false
190
cpp
int Solution::isPrime(int A) { if(A==1||A==2) return 0; for(int i=2;i<=sqrt(A);i++) { if(A%i==0) { return 0; } } return 1; }
d5c45a3c92b522f0456031e35cfad5f96020d111
0b111b10f185e0148f9ad137a1f6590e79d2cdeb
/kraUtilities/include/kraPlatformTypes.h
6d36ed84e3ab75c03152b9d02e0fcb2128948c63
[]
no_license
GalahadP92/Kraken-Engine
c409497592e3e2c8645484d94b17df7a63d03af9
fe8f27a378c9e85c36d4c0b3a042a549782988e7
refs/heads/master
2023-08-07T14:17:06.601235
2020-07-09T16:44:43
2020-07-09T16:44:43
278,412,919
0
0
null
null
null
null
UTF-8
C++
false
false
3,158
h
#pragma once #include <cstdint> #include <cstddef> #include "kraPlatformDefines.h" #if KRA_PLATFORM == KRA_PLATFORM_PS4 #include <scebase.h> #endif namespace kraEngineSDK { using std::uint8_t; using std::uint16_t; using std::uint32_t; using std::uint64_t; using std::int8_t; using std::int16_t; using std::int32_t; using std::int64_t; /*****************************************************************************/ /** * Basic unsigned types */ /*****************************************************************************/ using uint8 = uint8_t; using uint16 = uint16_t; using uint32 = uint32_t; using uint64 = uint64_t; /*****************************************************************************/ /** * Basic unsigned types */ /*****************************************************************************/ using int8 = int8_t; using int16 = int16_t; using int32 = int32_t; using int64 = int64_t; /*****************************************************************************/ /** * @class Qword * @brief */ /*****************************************************************************/ MS_ALIGN(16) class QWord { /** * Constructor */ public: QWord() : m_lower(0), m_upper(0) {} explicit QWord(bool from) : m_lower(static_cast<uint64>(from)), m_upper(0) {} explicit QWord(uint8 from) : m_lower(static_cast<uint64>(from)), m_upper(0) {} explicit QWord(int8 from) : m_lower(static_cast<uint64>(from)), m_upper(0) {} explicit QWord(uint16 from) : m_lower(static_cast<uint64>(from)), m_upper(0) {} explicit QWord(int16 from) : m_lower(static_cast<uint64>(from)), m_upper(0) {} explicit QWord(uint32 from) : m_lower(static_cast<uint64>(from)), m_upper(0) {} explicit QWord(int32 from) : m_lower(static_cast<uint64>(from)), m_upper(0) {} explicit QWord(uint64 from) : m_lower(from), m_upper(0) {} explicit QWord(int64 from) : m_lower(static_cast<uint64>(from)), m_upper(0) {} explicit QWord(float from) : m_lower(static_cast<uint64>(from)), m_upper(0) {} explicit QWord(double from) : m_lower(static_cast<uint64>(from)), m_upper(0) {} operator int64() const { return static_cast<uint64>(m_lower); } public: uint64 m_lower; int64 m_upper; }GCC_ALIGN(16); /*****************************************************************************/ /** * Character types */ /*****************************************************************************/ #if KRA_COMPILER == KRA_COMPILER_MSVC || KRA_PLATFORM == KRA_PLATFORM_PS4 using WCHAR = wchar_t; #else using WCHAR = unsigned short; #endif using ANSICHAR = char; using UNICHAR = WCHAR; /*****************************************************************************/ /** * NULL data type */ /*****************************************************************************/ using TYPE_OF_NULL = int32; /*****************************************************************************/ /** * SIZE_T is architecture dependant data type */ /*****************************************************************************/ using SIZE_T = size_t; }
21b31b881360eb5afd2e512c8a3d9a7829453554
38c10c01007624cd2056884f25e0d6ab85442194
/components/dom_distiller/core/page_features_unittest.cc
8e259e4382bb39a998cfe82e692d03233792c1c6
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
3,984
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/dom_distiller/core/page_features.h" #include <string> #include <vector> #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "testing/gtest/include/gtest/gtest.h" namespace dom_distiller { // This test uses input data of core features and the output of the training // pipeline's derived feature extraction to ensure that the extraction that is // done in Chromium matches that in the training pipeline. TEST(DomDistillerPageFeaturesTest, TestCalculateDerivedFeatures) { base::FilePath dir_source_root; EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &dir_source_root)); std::string input_data; ASSERT_TRUE(base::ReadFileToString( dir_source_root.AppendASCII( "components/test/data/dom_distiller/core_features.json"), &input_data)); std::string expected_output_data; // This file contains the output from the calculation of derived features in // the training pipeline. ASSERT_TRUE(base::ReadFileToString( dir_source_root.AppendASCII( "components/test/data/dom_distiller/derived_features.json"), &expected_output_data)); scoped_ptr<base::Value> input_json = base::JSONReader::Read(input_data); ASSERT_TRUE(input_json); scoped_ptr<base::Value> expected_output_json = base::JSONReader::Read(expected_output_data); ASSERT_TRUE(expected_output_json); base::ListValue* input_entries; ASSERT_TRUE(input_json->GetAsList(&input_entries)); ASSERT_GT(input_entries->GetSize(), 0u); base::ListValue* expected_output_entries; ASSERT_TRUE(expected_output_json->GetAsList(&expected_output_entries)); ASSERT_EQ(expected_output_entries->GetSize(), input_entries->GetSize()); // In the output, the features list is a sequence of labels followed by values // (so labels at even indices, values at odd indices). base::DictionaryValue* entry; base::ListValue* derived_features; ASSERT_TRUE(expected_output_entries->GetDictionary(0, &entry)); ASSERT_TRUE(entry->GetList("features", &derived_features)); std::vector<std::string> labels; for (size_t i = 0; i < derived_features->GetSize(); i += 2) { std::string label; ASSERT_TRUE(derived_features->GetString(i, &label)); labels.push_back(label); } for (size_t i = 0; i < input_entries->GetSize(); ++i) { base::DictionaryValue* core_features; ASSERT_TRUE(input_entries->GetDictionary(i, &entry)); ASSERT_TRUE(entry->GetDictionary("features", &core_features)); // CalculateDerivedFeaturesFromJSON expects a base::Value of the stringified // JSON (and not a base::Value of the JSON itself) std::string stringified_json; ASSERT_TRUE(base::JSONWriter::Write(*core_features, &stringified_json)); scoped_ptr<base::Value> stringified_value( new base::StringValue(stringified_json)); std::vector<double> derived( CalculateDerivedFeaturesFromJSON(stringified_value.get())); ASSERT_EQ(labels.size(), derived.size()); ASSERT_TRUE(expected_output_entries->GetDictionary(i, &entry)); ASSERT_TRUE(entry->GetList("features", &derived_features)); std::string entry_url; ASSERT_TRUE(entry->GetString("url", &entry_url)); for (size_t j = 0, value_index = 1; j < derived.size(); ++j, value_index += 2) { double expected_value; if (!derived_features->GetDouble(value_index, &expected_value)) { bool bool_value; ASSERT_TRUE(derived_features->GetBoolean(value_index, &bool_value)); expected_value = bool_value ? 1.0 : 0.0; } EXPECT_DOUBLE_EQ(derived[j], expected_value) << "incorrect value for entry with url " << entry_url << " for derived feature " << labels[j]; } } } }
e2f82924566940aabd923a93bf45273db3a12206
b3832793e06ca23210720a992b9be960800295fd
/6. Debugging/Overloading Ostream Operator.cpp
696bfb7f257f1307a1c07ba7a9d0d5f3e48519c4
[]
no_license
laziestcoder/CPP_HackerRank
aa5ed0ff6b869cc741c7a49ed9140215b58ff947
6f4866ab926a3bf99f1f066ccb44d14e9d2abfdd
refs/heads/master
2020-06-19T19:39:52.361095
2019-08-06T17:46:59
2019-08-06T17:46:59
196,845,645
4
0
null
null
null
null
UTF-8
C++
false
false
1,536
cpp
#include <iostream> using namespace std; class Person { public: Person(const string& first_name, const string& last_name) : first_name_(first_name), last_name_(last_name) {} const string& get_first_name() const { return first_name_; } const string& get_last_name() const { return last_name_; } private: string first_name_; string last_name_; }; // Enter your code here. ostream& operator << (ostream& output, const Person& P){ output <<"first_name=" << P.get_first_name() << ",last_name=" << P.get_last_name(); return output; } int main() { string first_name, last_name, event; cin >> first_name >> last_name >> event; auto p = Person(first_name, last_name); cout << p << " " << event << endl; return 0; } /** editorial: The most important thing is to have the correct signature of the operator. Since it's going to be used as follows: cout << p << SOME_OTHER_VALUES which is going to be executed as: (cout << p) << SOME_OTHER_VALUES then << operator for class Person must return a non-const reference to ostream object passes as the argument. Thus, the signature is: ostream& operator<<(ostream& os, const Person& p) and after the operator passes the correctly formatted data to the os, then it has to return the os object. ------------------------------------- Problem Setter's code: ostream& operator<<(ostream& os, const Person& p) { os << "first_name=" << p.get_first_name() << ",last_name=" << p.get_last_name(); return os; } */
55ebddfda239c7a7d1a866a2edde3d03cf72170e
b49c20d320b20182efb6106a65a4c9c73ade7578
/bzoj3038.cpp
854f21f76efd9eb7bc21b024829c96d5b4531d40
[]
no_license
thhyj/bzoj-ACcode
65a674e42d70e00c2f5ee48ce84d650956ddf67f
2072f81fb841bafc0c5f804da3cd35fa595fcd3e
refs/heads/master
2022-11-22T23:15:05.135037
2020-07-17T03:09:16
2020-07-17T03:09:16
280,313,883
0
0
null
null
null
null
UTF-8
C++
false
false
2,194
cpp
#include <bits/stdc++.h> using namespace std; inline void R(int &v) { static char ch; v = 0; bool p = 0; do { ch = getchar(); if (ch == '-') p = 1; } while (!isdigit(ch)); while (isdigit(ch)) { v = (v + (v << 2) << 1) + (ch^'0'); ch = getchar(); } if (p) v = -v; } inline void R(long long &v) { static char ch; v = 0; bool p = 0; do { ch = getchar(); if (ch == '-') p = 1; } while (!isdigit(ch)); while (isdigit(ch)) { v = (v + (v << 2) << 1) + (ch^'0'); ch = getchar(); } if (p) v = -v; } struct tree { long long sum; int son[2]; long long max; } tr[400040]; int tot, root; long long a[100040]; inline void updata(int x) { tr[x].sum = tr[tr[x].son[0]].sum + tr[tr[x].son[1]].sum; tr[x].max = max(tr[tr[x].son[0]].max, tr[tr[x].son[1]].max); } inline void build (int &now, int l, int r) { if (!now) now = ++tot; if (l == r) { tr[now].sum = tr[now].max = a[l]; return ; } int mid = l + r >> 1; build(tr[now].son[0], l, mid); build(tr[now].son[1], mid + 1, r); updata(now); } inline void modify(int x, int al, int ar, int l, int r) { if (tr[x].max <= 1) return; if (l == r) { // cout << "l=" << l << '\n'; // cout << "tr[x].sum=" << tr[x].sum << '\n'; tr[x].sum = tr[x].max = sqrt(tr[x].sum); //cout << "change to " << tr[x].sum << '\n'; return; } int mid = l + r >> 1; if (al <= mid) { modify(tr[x].son[0], al, ar, l, mid); } if (ar > mid) { modify(tr[x].son[1], al, ar, mid + 1, r); } updata(x); } inline long long query(int x, int ql, int qr, int l, int r) { if (l >= ql && r <= qr) { return tr[x].sum; } long long ret = 0; int mid = l + r >> 1; if (ql <= mid) { ret += query(tr[x].son[0], ql, qr, l, mid); } if (qr > mid) { ret += query(tr[x].son[1], ql, qr, mid + 1, r); } return ret; } int main() { //freopen("in.in", "r", stdin); int n; R(n); for (int i = 1; i <= n; ++i) { R(a[i]); } tot = root = 1; build(root, 1, n); int m; R(m); int kind, l, r; for (int i = 1; i <= m; ++i) { R(kind); if (kind == 0) { R(l), R(r); if(l>r) swap(l,r); modify(root, l, r, 1, n); } if (kind == 1) { R(l), R(r); if(l>r) swap(l,r); printf("%lld\n", query(root, l, r, 1, n) ); } } }
e7f90b668dfa3556358fbff0ddf54d7894adf6d3
3ae80dbc18ed3e89bedf846d098b2a98d8e4b776
/header/Media/GDIEngine.h
62c405a419b151ab120292c8d064b5d1f16e67c2
[]
no_license
sswroom/SClass
deee467349ca249a7401f5d3c177cdf763a253ca
9a403ec67c6c4dfd2402f19d44c6573e25d4b347
refs/heads/main
2023-09-01T07:24:58.907606
2023-08-31T11:24:34
2023-08-31T11:24:34
329,970,172
10
7
null
null
null
null
UTF-8
C++
false
false
9,198
h
#ifndef _SM_MEDIA_GDIENGINE #define _SM_MEDIA_GDIENGINE #include "Media/DrawEngine.h" #include "Media/ABlend/AlphaBlend8_C8.h" #include "Sync/Mutex.h" namespace Media { class GDIImage; class GDIEngine : public Media::DrawEngine { public: Media::ABlend::AlphaBlend8_C8 iab; private: void *hdc; void *hdcScreen; void *hpenBlack; void *hbrushWhite; Sync::Mutex gdiMut; #ifndef _WIN32_WCE void *gdiplusStartupInput; UInt32 gdiplusToken; #endif public: GDIEngine(); virtual ~GDIEngine(); virtual DrawImage *CreateImage32(Math::Size2D<UOSInt> size, Media::AlphaType atype); GDIImage *CreateImage24(Math::Size2D<UOSInt> size); DrawImage *CreateImageScn(void *hdc, OSInt left, OSInt top, OSInt right, OSInt bottom); virtual DrawImage *LoadImage(Text::CStringNN fileName); virtual DrawImage *LoadImageStream(NotNullPtr<IO::SeekableStream> stm); virtual DrawImage *ConvImage(Media::Image *img); virtual DrawImage *CloneImage(DrawImage *img); virtual Bool DeleteImage(DrawImage *img); void *GetBlackPen(); void *GetWhiteBrush(); }; class GDIBrush : public DrawBrush { public: void *hbrush; DrawImage *img; UInt32 color; UInt32 oriColor; public: GDIBrush(void *hbrush, UInt32 oriColor, DrawImage *img); virtual ~GDIBrush(); }; class GDIPen : public DrawPen { public: void *hpen; UInt32 *pattern; UOSInt nPattern; DrawImage *img; Double thick; UInt32 oriColor; public: GDIPen(void *hpen, UInt32 *pattern, UOSInt nPattern, DrawImage *img, Double thick, UInt32 oriColor); virtual ~GDIPen(); Double GetThick(); }; class GDIFont : public DrawFont { private: DrawImage *img; void *hdc; const WChar *fontName; Double ptSize; Media::DrawEngine::DrawFontStyle style; Int32 codePage; public: Int32 pxSize; void *hfont; GDIFont(void *hdc, const Char *fontName, Double ptSize, Media::DrawEngine::DrawFontStyle style, DrawImage *img, Int32 codePage); GDIFont(void *hdc, const WChar *fontName, Double ptSize, Media::DrawEngine::DrawFontStyle style, DrawImage *img, Int32 codePage); virtual ~GDIFont(); const WChar *GetNameW(); Double GetPointSize(); Media::DrawEngine::DrawFontStyle GetFontStyle(); Int32 GetCodePage(); }; class GDIImage : public DrawImage, public Image { private: GDIEngine *eng; Math::Size2D<UOSInt> size; UInt32 bitCount; Media::DrawEngine::DrawPos strAlign; DrawBrush *currBrush; DrawFont *currFont; DrawPen *currPen; Math::Coord2D<OSInt> tl; public: void *hBmp; void *bmpBits; void *hdcBmp; GDIImage(GDIEngine *eng, Math::Coord2D<OSInt> tl, Math::Size2D<UOSInt> size, UInt32 bitCount, void *hBmp, void *bmpBits, void *hdcBmp, Media::AlphaType atype); virtual ~GDIImage(); virtual UOSInt GetWidth() const; virtual UOSInt GetHeight() const; virtual Math::Size2D<UOSInt> GetSize() const; virtual UInt32 GetBitCount() const; virtual ColorProfile *GetColorProfile() const; virtual void SetColorProfile(const ColorProfile *color); virtual Media::AlphaType GetAlphaType() const; virtual void SetAlphaType(Media::AlphaType atype); virtual Double GetHDPI() const; virtual Double GetVDPI() const; virtual void SetHDPI(Double dpi); virtual void SetVDPI(Double dpi); virtual UInt8 *GetImgBits(Bool *revOrder); virtual void GetImgBitsEnd(Bool modified); virtual UOSInt GetImgBpl() const; virtual Media::EXIFData *GetEXIF() const; virtual Media::PixelFormat GetPixelFormat() const; virtual Bool DrawLine(Double x1, Double y1, Double x2, Double y2, DrawPen *p); virtual Bool DrawPolylineI(const Int32 *points, UOSInt nPoints, DrawPen *p); virtual Bool DrawPolygonI(const Int32 *points, UOSInt nPoints, DrawPen *p, DrawBrush *b); virtual Bool DrawPolyPolygonI(const Int32 *points, const UInt32 *pointCnt, UOSInt nPointCnt, DrawPen *p, DrawBrush *b); virtual Bool DrawPolyline(const Math::Coord2DDbl *points, UOSInt nPoints, DrawPen *p); virtual Bool DrawPolygon(const Math::Coord2DDbl *points, UOSInt nPoints, DrawPen *p, DrawBrush *b); virtual Bool DrawPolyPolygon(const Math::Coord2DDbl *points, const UInt32 *pointCnt, UOSInt nPointCnt, DrawPen *p, DrawBrush *b); virtual Bool DrawRect(Math::Coord2DDbl tl, Math::Size2DDbl size, DrawPen *p, DrawBrush *b); virtual Bool DrawEllipse(Math::Coord2DDbl tl, Math::Size2DDbl size, DrawPen *p, DrawBrush *b); virtual Bool DrawString(Math::Coord2DDbl tl, NotNullPtr<Text::String> str, DrawFont *f, DrawBrush *b); virtual Bool DrawString(Math::Coord2DDbl tl, Text::CString str, DrawFont *f, DrawBrush *b); Bool DrawStringW(Math::Coord2DDbl tl, const WChar *str, DrawFont *f, DrawBrush *p); virtual Bool DrawStringRot(Math::Coord2DDbl center, NotNullPtr<Text::String> str, DrawFont *f, DrawBrush *p, Double angleDegree); virtual Bool DrawStringRot(Math::Coord2DDbl center, Text::CString str, DrawFont *f, DrawBrush *p, Double angleDegree); Bool DrawStringRotW(Math::Coord2DDbl center, const WChar *str, DrawFont *f, DrawBrush *p, Double angleDegree); virtual Bool DrawStringB(Math::Coord2DDbl tl, NotNullPtr<Text::String> str, DrawFont *f, DrawBrush *p, UOSInt buffSize); virtual Bool DrawStringB(Math::Coord2DDbl tl, Text::CString str, DrawFont *f, DrawBrush *p, UOSInt buffSize); Bool DrawStringBW(Math::Coord2DDbl tl, const WChar *str, DrawFont *f, DrawBrush *p, UOSInt buffSize); virtual Bool DrawStringRotB(Math::Coord2DDbl center, NotNullPtr<Text::String> str, DrawFont *f, DrawBrush *p, Double angleDegree, UOSInt buffSize); virtual Bool DrawStringRotB(Math::Coord2DDbl center, Text::CString str, DrawFont *f, DrawBrush *p, Double angleDegree, UOSInt buffSize); Bool DrawStringRotBW(Math::Coord2DDbl center, const WChar *str, DrawFont *f, DrawBrush *p, Double angleDegree, UOSInt buffSize); virtual Bool DrawImagePt(DrawImage *img, Math::Coord2DDbl tl); virtual Bool DrawImagePt2(Media::StaticImage *img, Math::Coord2DDbl tl); virtual Bool DrawImagePt3(DrawImage *img, Math::Coord2DDbl destTL, Math::Coord2DDbl srcTL, Math::Size2DDbl srcSize); Bool DrawImageRect(DrawImage *img, OSInt tlx, OSInt tly, OSInt brx, OSInt bry); virtual DrawPen *NewPenARGB(UInt32 color, Double thick, UInt8 *pattern, UOSInt nPattern); virtual DrawBrush *NewBrushARGB(UInt32 color); virtual DrawFont *NewFontPt(Text::CString name, Double ptSize, Media::DrawEngine::DrawFontStyle fontStyle, UInt32 codePage); DrawFont *NewFontPtW(const WChar *name, Double ptSize, Media::DrawEngine::DrawFontStyle fontStyle, UInt32 codePage); virtual DrawFont *NewFontPx(Text::CString name, Double pxSize, Media::DrawEngine::DrawFontStyle fontStyle, UInt32 codePage); DrawFont *NewFontPxW(const WChar *name, Double pxSize, Media::DrawEngine::DrawFontStyle fontStyle, UInt32 codePage); virtual DrawFont *CloneFont(Media::DrawFont *f); virtual void DelPen(DrawPen *p); virtual void DelBrush(DrawBrush *b); virtual void DelFont(DrawFont *f); virtual Math::Size2DDbl GetTextSize(DrawFont *fnt, Text::CString txt); Math::Size2DDbl GetTextSize(DrawFont *fnt, const WChar *txt, OSInt txtLen); virtual void SetTextAlign(DrawEngine::DrawPos pos); virtual void GetStringBound(Int32 *pos, OSInt centX, OSInt centY, const UTF8Char *str, DrawFont *f, OSInt *drawX, OSInt *drawY); void GetStringBoundW(Int32 *pos, OSInt centX, OSInt centY, const WChar *str, DrawFont *f, OSInt *drawX, OSInt *drawY); virtual void GetStringBoundRot(Int32 *pos, Double centX, Double centY, const UTF8Char *str, DrawFont *f, Double angleDegree, OSInt *drawX, OSInt *drawY); void GetStringBoundRotW(Int32 *pos, Double centX, Double centY, const WChar *str, DrawFont *f, Double angleDegree, OSInt *drawX, OSInt *drawY); virtual void CopyBits(OSInt x, OSInt y, void *imgPtr, UOSInt bpl, UOSInt width, UOSInt height, Bool upsideDown) const; virtual Media::StaticImage *ToStaticImage() const; virtual UOSInt SavePng(NotNullPtr<IO::SeekableStream> stm); virtual UOSInt SaveGIF(NotNullPtr<IO::SeekableStream> stm); virtual UOSInt SaveJPG(NotNullPtr<IO::SeekableStream> stm); virtual Media::Image *Clone() const; virtual Media::Image::ImageType GetImageType() const; virtual void GetImageData(UInt8 *destBuff, OSInt left, OSInt top, UOSInt width, UOSInt height, UOSInt destBpl, Bool upsideDown, Media::RotateType destRotate) const; static void PolylineAccel(void *hdc, const Int32 *points, UOSInt nPoints, OSInt ofstX, OSInt ofstY, OSInt width, OSInt height); static void PolygonAccel(void *hdc, const Int32 *points, UOSInt nPoints, OSInt ofstX, OSInt ofstY, OSInt width, OSInt height, Int32 penWidth); static void PolyPolygonAccel(void *hdc, const Int32 *points, const UInt32 *pointCnt, UOSInt nPointCnt, OSInt ofstX, OSInt ofstY, OSInt width, OSInt height, Int32 penWidth); Bool IsOffScreen(); Bool DrawRectN(OSInt x, OSInt y, OSInt w, OSInt h, DrawPen *p, DrawBrush *b); void *GetHDC(); void FillAlphaRect(OSInt left, OSInt top, OSInt width, OSInt height, UInt8 alpha); private: void *CreateGDIImage(); }; } #endif
4d433cf64e4ab9ad118e6c4c2e8597361c113617
c289c3aca633d851f7c4d5604aad9d053de17530
/common/geometryIO.h
bffb00090a4ddffe8d63fd5855d2e8986a7dfe77
[ "MIT" ]
permissive
wangyiqiu/closest-pair
f436aaabb6ecc0cbed2b281f1634e269678d6be7
57b777575fa5ea59c445e9b812cbde0e7a85edb3
refs/heads/main
2023-05-26T12:40:35.434054
2021-06-10T04:24:18
2021-06-10T04:24:18
340,196,260
4
0
null
null
null
null
UTF-8
C++
false
false
6,825
h
// This code is part of the Problem Based Benchmark Suite (PBBS) // Copyright (c) 2011 Guy Blelloch and the PBBS team // // 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. #ifndef _BENCH_GEOMETRY_IO #define _BENCH_GEOMETRY_IO #include <string> #include "IO.h" #include "pbbs/parallel.h" #include "geometry.h" using namespace benchIO; inline int xToStringLen(point2d a) { return xToStringLen(a.x) + xToStringLen(a.y) + 1; } inline void xToString(char* s, point2d a) { int l = xToStringLen(a.x); xToString(s, a.x); s[l] = ' '; xToString(s+l+1, a.y); } inline int xToStringLen(point3d a) { return xToStringLen(a.x) + xToStringLen(a.y) + xToStringLen(a.z) + 2; } inline void xToString(char* s, point3d a) { int lx = xToStringLen(a.x); int ly = xToStringLen(a.y); xToString(s, a.x); s[lx] = ' '; xToString(s+lx+1, a.y); s[lx+ly+1] = ' '; xToString(s+lx+ly+2, a.z); } inline int xToStringLen(triangle a) { return xToStringLen(a.C[0]) + xToStringLen(a.C[1]) + xToStringLen(a.C[2]) + 2; } inline void xToString(char* s, triangle a) { int lx = xToStringLen(a.C[0]); int ly = xToStringLen(a.C[1]); xToString(s, a.C[0]); s[lx] = ' '; xToString(s+lx+1, a.C[1]); s[lx+ly+1] = ' '; xToString(s+lx+ly+2, a.C[2]); } namespace benchIO { using namespace std; string HeaderPoint2d = "pbbs_sequencePoint2d"; string HeaderPoint3d = "pbbs_sequencePoint3d"; string HeaderPoint4d = "pbbs_sequencePoint4d"; string HeaderPoint5d = "pbbs_sequencePoint5d"; string HeaderPoint6d = "pbbs_sequencePoint6d"; string HeaderPoint7d = "pbbs_sequencePoint7d"; string HeaderPoint8d = "pbbs_sequencePoint8d"; string HeaderPoint9d = "pbbs_sequencePoint9d"; string HeaderTriangles = "pbbs_triangles"; inline string headerPoint(int dim) { if (dim == 2) return HeaderPoint2d; else if (dim == 3) return HeaderPoint3d; else if (dim == 4) return HeaderPoint4d; else if (dim == 5) return HeaderPoint5d; else if (dim == 6) return HeaderPoint6d; else if (dim == 7) return HeaderPoint7d; else if (dim == 8) return HeaderPoint8d; else if (dim == 9) return HeaderPoint9d; else { cout << "headerPoint unsupported dimension, abort" << dim << endl; abort(); } } template <class pointT> int writePointsToFile(pointT* P, intT n, char* fname) { string Header = (pointT::dim == 2) ? HeaderPoint2d : HeaderPoint3d; int r = writeArrayToFile(Header, P, n, fname); return r; } template <class pointT> void parsePoints(char** Str, pointT* P, intT n) { int d = pointT::dim; double* a = newA(double,n*d); {par_for (long i=0; i<d*n; i++) a[i] = atof(Str[i]);} {par_for (long i=0; i<n; i++) P[i] = pointT(a+(d*i));} free(a); } template <class pointT> void parseCsvPoints(char** Str, pointT* P, intT n, int col, int sCol, int eCol) { int d = pointT::dim; double* a = newA(double,n*d); par_for (long i=0; i<n/col; i++) { for (int j=sCol; j<eCol; j++) { a[i*d+j-sCol] = atof(Str[i*col+j]); } } par_for (long i=0; i<n/col; i++) { P[i] = pointT(a+(d*i)); //cout << P[i] << endl; } free(a); } void parseNdPoints(char** Str, pointNd* P, long n, int dim) { // double* a = newA(double,n*dim); // {parallel_for (long i=0; i < dim*n; i++) { // a[i] = atof(Str[i]); // // cout << a[i] << ' '; // }} {par_for (long i=0; i<n; i++) { // P[i].init(a+(dim*i), dim); P[i].m_dim = dim; for (intT d = 0; d < dim; ++ d) { // P[i].m_data[d] = *(a+(dim*i) + d); P[i].m_data[d] = atof(Str[dim * i + d]); // P[i].m_data[d] = 1; // cout << P[i].m_data[d] << ' '; } // cout << endl; }} // cout << '\n' << "!!!" << endl; // free(a); } inline int readPointsDimensionFromFile(char* fname) { _seq<char> S = readStringFromFile(fname); words W = stringToWords(S.A, S.n); return (int)(W.Strings[0][18])-48; } template <class pointT> _seq<pointT> readPointsFromFile(char* fname) { _seq<char> S = readStringFromFile(fname); words W = stringToWords(S.A, S.n); int d = pointT::dim; if (W.m == 0 || W.Strings[0] != headerPoint(d)) { cout << "readPointsFromFile wrong file type" << endl; abort(); } long n = (W.m-1)/d; pointT *P = newA(pointT, n); parsePoints(W.Strings + 1, P, n); W.del(); return _seq<pointT>(P, n); } template <class pointT> _seq<pointT> readPointsFromFileCSV(char* fname, int col, int sCol, int eCol) { _seq<char> S = readStringFromFile(fname); cout << "S.n = " << S.n << endl; words W = stringToWordsCSV(S.A, S.n); int d = pointT::dim; if (W.m == 0) { cout << "invalid csv" << endl; abort(); } cout << "csv columns: "; for(intT i=sCol; i<eCol; ++i) { cout << W.Strings[i] << " "; } cout << endl; long n = (W.m-col); pointT *P = newA(pointT, n/col); parseCsvPoints(W.Strings+col, P, n, col, sCol, eCol); // W.del(); cout << "verify P[0] = " << P[0] << endl; cout << "verify P[last] = " << P[n/col-1] << endl; cout << "input n = " << n/col-1 << endl; return _seq<pointT>(P, n/col); } inline bool isNumber(char myChar) { if (myChar == '0' || myChar == '1' || myChar == '2' || myChar == '3' || myChar == '4' || myChar == '5' || myChar == '6' || myChar == '7' || myChar == '8' || myChar == '9') { return true; } else { return false; } } inline intT extractDim(words *W) { int d; char *targetString = W->Strings[0]; intT myPt = 18; while (isNumber(targetString[myPt])) myPt ++; targetString[myPt] = '\0'; // TODO Support 10+ d = atoi(&targetString[18]); return d; } }; #endif // _BENCH_GEOMETRY_IO
b10bed3d6a3a8364f203d3e801f0407ffe40fc95
74cf880326c5a606541742a7c6af2873278b90bc
/Core/plugins/TranslateModule/TranslateModule.cpp
cbd2ad13139cf464666861749300c10a626c317e
[]
no_license
CBowlen/CASP
341cfeab8cd2b7ef9c26e715ffd2be8b47c24d58
47ed90eaad05bd36bfcf951692f2f4ca5d1266d3
refs/heads/master
2021-01-19T00:18:55.608145
2017-04-04T02:56:52
2017-04-04T02:56:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
494
cpp
#include "TranslateModule.h" static string _TranslateModule = RegisterPlugin("Translate", new TranslateModule()); TranslateModule::TranslateModule() {} void TranslateModule::Execute(Markup* markup, string* fnArgs, int fnArgCount) { /* This module hasn't implemented any Function Args yet! Use Helpers::ParseArrayArgument() and Helpers::ParseArgument() to scrape out arguments */ cout << "This is the entry point for the " << _TranslateModule << " Module!\n"; }
11a4ce0c31824de8bc3c91642c81d8de3adfc23b
bbfd9580432f897a8c1139450c818da1645077c5
/src/test/test_bitcoin_main.cpp
3d06d26cde06f8fe9f45a098a366a1f41d1fdfb7
[ "MIT" ]
permissive
gripen89/c0ban
a2d4dd8fc05e00c20a3c393fb7f1135e08c0a495
bf77fff2361fc7672f75fc6a25b61ab8bddc292c
refs/heads/master
2020-08-23T18:17:12.549054
2019-01-11T04:12:45
2019-01-11T04:12:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
// Copyright (c) 2011-2016 The Bitcoin Core developers // Copyright (c) 2017-2018 The c0ban Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #define BOOST_TEST_MODULE c0ban Test Suite #include "net.h" #include <boost/test/unit_test.hpp> std::unique_ptr<CConnman> g_connman; void Shutdown(void* parg) { exit(EXIT_SUCCESS); } void StartShutdown() { exit(EXIT_SUCCESS); } bool ShutdownRequested() { return false; }
f4757bb83842583f4ef760f1ffb545b60afec34f
ee5375c57898cc4a86d0384058fa243ba40a1070
/prog3.6.cpp
a6ee5938e65bd5e358b25633ddebbdc3f286b615
[]
no_license
jiegec/parallel-programming-hw3
079646f6271422e50f6d36f3056b27659eecf97b
69c24dd585234d29089f1833159d4ee51f6f1c9f
refs/heads/master
2020-05-09T20:17:50.812284
2019-04-15T08:08:47
2019-04-15T08:08:47
181,402,023
0
0
null
null
null
null
UTF-8
C++
false
false
6,948
cpp
#include <cmath> #include <ctime> #include <iostream> #include <mpi.h> #include <stdio.h> #include <stdlib.h> /* * Modify the "multiply, run" to implement your parallel algorihtm. * Compile: * this is a c++ style code */ using namespace std; void serial(int n, double **matrix, double *vector, double **result); void gen(int n, double ***matrix, double **vector); void print(int n, double **matrix, double *vector); void free(int n, double **matrix, double *vector); void run(int n, double **matrix, double *vector); int main(int argc, char *argv[]) { if (argc < 2) { cout << "Usage: " << argv[0] << " n" << endl; return -1; } double **matrix; double *vector; int n = atoi(argv[1]); run(n, matrix, vector); } void serial(int n, double **matrix, double *vector, double **result) { /* * It is a serial algorithm to * get the true value of matrix-vector multiplication * please calculation the difference between true value and the value you * obtain * */ (*result) = new double[n]; for (int i = 0; i < n; i++) { (*result)[i] = 0.0; } for (int i = 0; i < n; i++) { double temp = 0.0; for (int j = 0; j < n; j++) { temp += matrix[i][j] * vector[j]; } (*result)[i] = temp; } } void gen(int n, double ***matrix, double **vector) { /* * generate random matrix and vector, * In order to debug conveniently, you can define a const matrix and vector * but I will check your answer based on random matrix and vector */ (*matrix) = new double *[n]; srand((unsigned)time(0)); for (int i = 0; i < n; i++) { (*matrix)[i] = new double[n]; for (int j = 0; j < n; j++) { (*matrix)[i][j] = -1 + rand() * 1.0 / RAND_MAX * 2; } } (*vector) = new double[n]; for (int i = 0; i < n; i++) { (*vector)[i] = -1 + rand() * 1.0 / RAND_MAX * 2; } } void print(int n, double **matrix, double *vector) { for (int i = 0; i < n; i++) { cout << vector[i] << endl; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << matrix[i][j] << " "; } cout << endl; } } void free(int n, double **matrix, double *vector) { delete[] vector; for (int i = 0; i < n; i++) delete[] matrix[i]; delete[] matrix; } void run(int n, double **matrix, double *vector) { /* * Description: * data partition, communication, calculation based on MPI programming in this * function. * * 1. call gen() on one process to generate the random matrix and vecotr. * 2. distribute the data to other processes. * 3. Implement matrix-vector mutiply * 4. calculate the diffenence between product vector and the value of * serial(), I'll check this answer. */ double *answer, *expected; int my_rank, comm_sz; MPI_Comm comm; MPI_Init(NULL, NULL); comm = MPI_COMM_WORLD; MPI_Comm_size(comm, &comm_sz); MPI_Comm_rank(comm, &my_rank); int sqrt_comm_sz = sqrt(comm_sz); // every row a comm MPI_Comm row_comm; int my_row_rank; MPI_Comm_split(MPI_COMM_WORLD, my_rank / sqrt_comm_sz, my_rank, &row_comm); // first col a comm MPI_Group world_group; MPI_Comm_group(MPI_COMM_WORLD, &world_group); int *ranks = new int[sqrt_comm_sz]; for (int i = 0; i < sqrt_comm_sz; i++) { ranks[i] = i * sqrt_comm_sz; } MPI_Group col_group; MPI_Group_incl(world_group, sqrt_comm_sz, ranks, &col_group); // Create a new communicator based on the group MPI_Comm col_comm; MPI_Comm_create_group(MPI_COMM_WORLD, col_group, 0, &col_comm); MPI_Datatype block_sub_mpi_t; MPI_Datatype vect_mpi_t; int local_n = n / sqrt_comm_sz; double *local_matrix = new double[local_n * local_n]; double *local_vector = new double[local_n]; double *local_ans = new double[local_n]; double *local_sum = new double[local_n]; if (n % comm_sz || (sqrt_comm_sz * sqrt_comm_sz != comm_sz)) { if (my_rank == 0) { printf("Bad n and comm_sz!\n"); } MPI_Finalize(); return; } /* n blocks each containing local_n elements */ /* The start of each block is n doubles beyond the preceding block */ MPI_Type_vector(local_n, local_n, n, MPI_DOUBLE, &vect_mpi_t); /* Resize the new type so that it has the extent of local_n doubles */ MPI_Type_create_resized(vect_mpi_t, 0, local_n * sizeof(double), &block_sub_mpi_t); MPI_Type_commit(&block_sub_mpi_t); double *flat_matrix = NULL; if (my_rank == 0) { gen(n, &matrix, &vector); flat_matrix = new double[n * n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { flat_matrix[i * n + j] = matrix[i][j]; } } printf("Now begins\n"); } double time_before_scatter = MPI_Wtime(); int *sendcounts = new int[comm_sz]; int *displs = new int[comm_sz]; for (int i = 0; i < sqrt_comm_sz; i++) { for (int j = 0; j < sqrt_comm_sz; j++) { sendcounts[i * sqrt_comm_sz + j] = 1; displs[i * sqrt_comm_sz + j] = i * sqrt_comm_sz * local_n + j; } } MPI_Scatterv(flat_matrix, sendcounts, displs, block_sub_mpi_t, local_matrix, local_n * local_n, MPI_DOUBLE, 0, comm); for (int i = 0; i < sqrt_comm_sz; i++) { for (int j = 0; j < sqrt_comm_sz; j++) { sendcounts[i * sqrt_comm_sz + j] = local_n; displs[i * sqrt_comm_sz + j] = j * local_n; } } MPI_Scatterv(vector, sendcounts, displs, MPI_DOUBLE, local_vector, local_n, MPI_DOUBLE, 0, comm); double time_after_scatter = MPI_Wtime(); MPI_Barrier(comm); double time_before_calc = MPI_Wtime(); for (int i = 0; i < local_n; i++) { local_sum[i] = 0.0; for (int j = 0; j < local_n; j++) { local_sum[i] += local_matrix[i * local_n + j] * local_vector[j]; } } MPI_Reduce(local_sum, local_ans, local_n, MPI_DOUBLE, MPI_SUM, 0, row_comm); MPI_Barrier(comm); double time_after_calc = MPI_Wtime(); if (my_rank == 0) { answer = new double[n]; MPI_Gather(local_ans, local_n, MPI_DOUBLE, answer, local_n, MPI_DOUBLE, 0, col_comm); double time_before_serial = MPI_Wtime(); serial(n, matrix, vector, &expected); double time_after_serial = MPI_Wtime(); double loss = 0; for (int i = 0; i < n; i++) { loss += (answer[i] - expected[i]) * (answer[i] - expected[i]); } printf("loss: %lf\n", loss); printf("time(scatter): %lf\n", time_after_scatter - time_before_scatter); printf("time(calc): %lf\n", time_after_calc - time_before_calc); printf("time(serial): %lf\n", time_after_serial - time_before_serial); } else if (my_rank % sqrt_comm_sz == 0) { MPI_Gather(local_ans, local_n, MPI_DOUBLE, answer, local_n, MPI_DOUBLE, 0, col_comm); } MPI_Finalize(); }
c9637a69f31f7b71dcd3bf5cfa0b51b6f76b48fd
dc182283f6eed3b5aaa45c7da61bdc07b41ee161
/chrome/browser/ash/power/auto_screen_brightness/light_provider_mojo_unittest.cc
3ff3a503e92f5a5ccac9fecf4713cbd48e1be0be
[ "BSD-3-Clause" ]
permissive
KHJcode/chromium
c2bf1c71363e81aaa9e14de582cd139e46877e0a
61f837c7b6768f2e74501dd614624f44e396f363
refs/heads/master
2023-06-19T07:25:15.090544
2021-07-08T12:38:31
2021-07-08T12:38:31
299,554,207
1
0
BSD-3-Clause
2020-09-29T08:33:13
2020-09-29T08:33:12
null
UTF-8
C++
false
false
8,718
cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/power/auto_screen_brightness/light_provider_mojo.h" #include <map> #include <memory> #include <utility> #include "base/run_loop.h" #include "base/test/task_environment.h" #include "chrome/browser/ash/power/auto_screen_brightness/fake_observer.h" #include "chromeos/components/sensors/fake_sensor_device.h" #include "chromeos/components/sensors/fake_sensor_hal_server.h" #include "chromeos/components/sensors/sensor_hal_dispatcher.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash { namespace power { namespace auto_screen_brightness { namespace { constexpr int32_t kFakeAcpiAlsId = 1; constexpr int32_t kFakeBaseLightId = 2; constexpr int32_t kFakeLidLightId = 3; constexpr int64_t kFakeSampleData = 50; const char kWrongLocation[5] = "lidd"; constexpr char kCrosECLightName[] = "cros-ec-light"; constexpr char kAcpiAlsName[] = "acpi-als"; } // namespace class LightProviderMojoTest : public testing::Test { protected: void SetUp() override { chromeos::sensors::SensorHalDispatcher::Initialize(); sensor_hal_server_ = std::make_unique<chromeos::sensors::FakeSensorHalServer>(); als_reader_ = std::make_unique<AlsReader>(); als_reader_->AddObserver(&fake_observer_); } void TearDown() override { chromeos::sensors::SensorHalDispatcher::Shutdown(); } void SetProvider(bool has_several_light_sensors) { provider_ = std::make_unique<LightProviderMojo>(als_reader_.get(), has_several_light_sensors); } void AddDevice(int32_t iio_device_id, const absl::optional<std::string> name, const absl::optional<std::string> location) { std::vector<chromeos::sensors::FakeSensorDevice::ChannelData> channels_data( 1); channels_data[0].id = chromeos::sensors::mojom::kLightChannel; channels_data[0].sample_data = kFakeSampleData; std::unique_ptr<chromeos::sensors::FakeSensorDevice> sensor_device( new chromeos::sensors::FakeSensorDevice(std::move(channels_data))); sensor_devices_[iio_device_id] = sensor_device.get(); if (name.has_value()) { sensor_device->SetAttribute(chromeos::sensors::mojom::kDeviceName, name.value()); } if (location.has_value()) { sensor_device->SetAttribute(chromeos::sensors::mojom::kLocation, location.value()); } sensor_hal_server_->GetSensorService()->SetDevice( iio_device_id, std::set<chromeos::sensors::mojom::DeviceType>{ chromeos::sensors::mojom::DeviceType::LIGHT}, std::move(sensor_device)); } void StartConnection() { chromeos::sensors::SensorHalDispatcher::GetInstance()->RegisterServer( sensor_hal_server_->PassRemote()); } void TriggerNewDevicesTimeout() { provider_->OnNewDevicesTimeout(); } void CheckValues(int32_t iio_device_id) { EXPECT_TRUE(sensor_hal_server_->GetSensorService()->HasReceivers()); EXPECT_TRUE(sensor_devices_.find(iio_device_id) != sensor_devices_.end()); EXPECT_TRUE(sensor_devices_[iio_device_id]->HasReceivers()); EXPECT_EQ(fake_observer_.status(), AlsReader::AlsInitStatus::kSuccess); EXPECT_EQ(fake_observer_.num_received_ambient_lights(), ++num_samples_); EXPECT_EQ(fake_observer_.ambient_light(), kFakeSampleData); } FakeObserver fake_observer_; std::unique_ptr<chromeos::sensors::FakeSensorHalServer> sensor_hal_server_; std::unique_ptr<AlsReader> als_reader_; std::unique_ptr<LightProviderMojo> provider_; std::map<int32_t, chromeos::sensors::FakeSensorDevice*> sensor_devices_; int num_samples_ = 0; base::test::SingleThreadTaskEnvironment task_environment; }; TEST_F(LightProviderMojoTest, GetSamplesWithOneSensor) { SetProvider(/*has_several_light_sensors=*/false); AddDevice(kFakeAcpiAlsId, kAcpiAlsName, absl::nullopt); StartConnection(); // Wait until a sample is received. base::RunLoop().RunUntilIdle(); CheckValues(kFakeAcpiAlsId); } TEST_F(LightProviderMojoTest, AssumingAcpiAlsWithoutDeviceNameWithOneSensor) { SetProvider(/*has_several_light_sensors=*/false); AddDevice(kFakeAcpiAlsId, absl::nullopt, absl::nullopt); StartConnection(); // Wait until a sample is received. base::RunLoop().RunUntilIdle(); CheckValues(kFakeAcpiAlsId); } TEST_F(LightProviderMojoTest, PreferCrosECLightWithOneSensor) { SetProvider(/*has_several_light_sensors=*/false); AddDevice(kFakeAcpiAlsId, kAcpiAlsName, absl::nullopt); AddDevice(kFakeLidLightId, kCrosECLightName, absl::nullopt); StartConnection(); // Wait until a sample is received. base::RunLoop().RunUntilIdle(); CheckValues(kFakeLidLightId); } TEST_F(LightProviderMojoTest, InvalidLocationWithSeveralLightSensors) { SetProvider(/*has_several_light_sensors=*/true); AddDevice(kFakeLidLightId, kCrosECLightName, kWrongLocation); StartConnection(); // Wait until all tasks are done. base::RunLoop().RunUntilIdle(); // Simulate the timeout so that the initialization fails. TriggerNewDevicesTimeout(); // Wait until the mojo connection of SensorService is reset. base::RunLoop().RunUntilIdle(); EXPECT_FALSE(sensor_hal_server_->GetSensorService()->HasReceivers()); EXPECT_EQ(fake_observer_.status(), AlsReader::AlsInitStatus::kIncorrectConfig); } TEST_F(LightProviderMojoTest, GetSamplesFromLidLightsSeveralLightSensors) { SetProvider(/*has_several_light_sensors=*/true); AddDevice(kFakeAcpiAlsId, kAcpiAlsName, absl::nullopt); AddDevice(kFakeBaseLightId, kCrosECLightName, chromeos::sensors::mojom::kLocationBase); AddDevice(kFakeLidLightId, kCrosECLightName, chromeos::sensors::mojom::kLocationLid); StartConnection(); // Wait until a sample is received. base::RunLoop().RunUntilIdle(); CheckValues(kFakeLidLightId); // Simulate a disconnection of the accelerometer's mojo channel in IIO // Service. AddDevice(kFakeLidLightId, kCrosECLightName, chromeos::sensors::mojom::kLocationLid); // Wait until the disconnection is done. base::RunLoop().RunUntilIdle(); EXPECT_FALSE(sensor_hal_server_->GetSensorService()->HasReceivers()); // Simulate a disconnection of IIO Service. sensor_hal_server_->GetSensorService()->ClearReceivers(); sensor_hal_server_->OnServerDisconnect(); // Wait until the disconnect arrives at SensorHalDispatcher. base::RunLoop().RunUntilIdle(); StartConnection(); // Wait until samples are received. base::RunLoop().RunUntilIdle(); CheckValues(kFakeLidLightId); } TEST_F(LightProviderMojoTest, PreferLateCrosECLightWithOneSensor) { provider_ = std::make_unique<LightProviderMojo>(als_reader_.get(), /*has_two_sensors=*/false); StartConnection(); // Wait until all tasks are done. base::RunLoop().RunUntilIdle(); EXPECT_FALSE(fake_observer_.has_status()); AddDevice(kFakeAcpiAlsId, kAcpiAlsName, absl::nullopt); // Wait until all tasks are done. base::RunLoop().RunUntilIdle(); // Acpi-als is used. CheckValues(kFakeAcpiAlsId); AddDevice(kFakeLidLightId, kCrosECLightName, absl::nullopt); // Wait until all tasks are done. base::RunLoop().RunUntilIdle(); // Simulate the timeout. TriggerNewDevicesTimeout(); // Wait until all tasks are done. base::RunLoop().RunUntilIdle(); // Cros-ec-light overwrites the acpi-als. CheckValues(kFakeLidLightId); } TEST_F(LightProviderMojoTest, GetSamplesFromLateLidLightsWithTwoSensors) { provider_ = std::make_unique<LightProviderMojo>(als_reader_.get(), /*has_two_sensors=*/true); StartConnection(); // Wait until all tasks are done. base::RunLoop().RunUntilIdle(); EXPECT_FALSE(fake_observer_.has_status()); AddDevice(kFakeAcpiAlsId, kAcpiAlsName, absl::nullopt); AddDevice(kFakeBaseLightId, kCrosECLightName, chromeos::sensors::mojom::kLocationBase); // Wait until all tasks are done. base::RunLoop().RunUntilIdle(); EXPECT_FALSE(fake_observer_.has_status()); AddDevice(kFakeLidLightId, kCrosECLightName, chromeos::sensors::mojom::kLocationLid); // Wait until all tasks are done. base::RunLoop().RunUntilIdle(); // Simulate the timeout. TriggerNewDevicesTimeout(); // Wait until all tasks are done. base::RunLoop().RunUntilIdle(); CheckValues(kFakeLidLightId); } } // namespace auto_screen_brightness } // namespace power } // namespace ash
c34d74667cc52a2da6ec590137606b18ee501f8c
43fe4d201f86a83f87589b8f519cd066a94fe7a5
/srcs/model/commonlib/MessageSender.cpp
5b1a4a5c9bb01f008bb6b7171c606f1eeb48a034
[]
no_license
Aharobot/SIGServer
b7ddcfe5627efe5b975a2f30a310b2bf5547b21b
7b7657afe21573e4f08baa24ff8e2fac6a60b7e0
refs/heads/master
2021-01-22T00:13:10.628330
2014-10-31T20:22:31
2014-10-31T20:22:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
33
cpp
../../commonlib/MessageSender.cpp
5f11c4135ad1e3259e5be3ece0a281e0a6810cd4
575ccc5e1269b843c7c4759871c90e1f75b3ffd8
/OpenGLPlat/OpenGLPlat.cpp
ae7049bc49ef7cb62dd5b51ef423351adeba0d4c
[]
no_license
kennycaiguo/Computer-Aided-Geometric-Modeling
50523b9cfdec3de67f238d16eca260bf205b58e7
0ee41539ba53804a96be07eb6d4a65a1472a4953
refs/heads/master
2022-02-25T18:52:55.518440
2019-11-02T06:20:51
2019-11-02T06:20:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,762
cpp
 // OpenGLPlat.cpp: 定义应用程序的类行为。 // #include "pch.h" #include "framework.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "OpenGLPlat.h" #include "MainFrm.h" #include "ChildFrm.h" #include "OpenGLPlatDoc.h" #include "OpenGLPlatView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // COpenGLPlatApp BEGIN_MESSAGE_MAP(COpenGLPlatApp, CWinAppEx) ON_COMMAND(ID_APP_ABOUT, &COpenGLPlatApp::OnAppAbout) // 基于文件的标准文档命令 ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen) // 标准打印设置命令 ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinAppEx::OnFilePrintSetup) END_MESSAGE_MAP() // COpenGLPlatApp 构造 COpenGLPlatApp::COpenGLPlatApp() noexcept { m_bHiColorIcons = TRUE; // 支持重新启动管理器 m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; #ifdef _MANAGED // 如果应用程序是利用公共语言运行时支持(/clr)构建的,则: // 1) 必须有此附加设置,“重新启动管理器”支持才能正常工作。 // 2) 在您的项目中,您必须按照生成顺序向 System.Windows.Forms 添加引用。 System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif // TODO: 将以下应用程序 ID 字符串替换为唯一的 ID 字符串;建议的字符串格式 //为 CompanyName.ProductName.SubProduct.VersionInformation SetAppID(_T("OpenGLPlat.AppID.NoVersion")); // TODO: 在此处添加构造代码, // 将所有重要的初始化放置在 InitInstance 中 } // 唯一的 COpenGLPlatApp 对象 COpenGLPlatApp theApp; // COpenGLPlatApp 初始化 BOOL COpenGLPlatApp::InitInstance() { // 如果一个运行在 Windows XP 上的应用程序清单指定要 // 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式, //则需要 InitCommonControlsEx()。 否则,将无法创建窗口。 INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // 将它设置为包括所有要在应用程序中使用的 // 公共控件类。 InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); // 初始化 OLE 库 if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); EnableTaskbarInteraction(FALSE); // 使用 RichEdit 控件需要 AfxInitRichEdit2() // AfxInitRichEdit2(); // 标准初始化 // 如果未使用这些功能并希望减小 // 最终可执行文件的大小,则应移除下列 // 不需要的特定初始化例程 // 更改用于存储设置的注册表项 // TODO: 应适当修改该字符串, // 例如修改为公司或组织名 SetRegistryKey(_T("应用程序向导生成的本地应用程序")); LoadStdProfileSettings(4); // 加载标准 INI 文件选项(包括 MRU) InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // 注册应用程序的文档模板。 文档模板 // 将用作文档、框架窗口和视图之间的连接 CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate(IDR_OpenGLPlatTYPE, RUNTIME_CLASS(COpenGLPlatDoc), RUNTIME_CLASS(CChildFrame), // 自定义 MDI 子框架 RUNTIME_CLASS(COpenGLPlatView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // 创建主 MDI 框架窗口 CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME)) { delete pMainFrame; return FALSE; } m_pMainWnd = pMainFrame; // 仅当具有后缀时才调用 DragAcceptFiles // 在 MDI 应用程序中,这应在设置 m_pMainWnd 之后立即发生 // 启用拖/放 m_pMainWnd->DragAcceptFiles(); // 分析标准 shell 命令、DDE、打开文件操作的命令行 CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // 启用“DDE 执行” EnableShellOpen(); RegisterShellFileTypes(TRUE); // 调度在命令行中指定的命令。 如果 // 用 /RegServer、/Register、/Unregserver 或 /Unregister 启动应用程序,则返回 FALSE。 if (!ProcessShellCommand(cmdInfo)) return FALSE; // 主窗口已初始化,因此显示它并对其进行更新 pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); return TRUE; } int COpenGLPlatApp::ExitInstance() { //TODO: 处理可能已添加的附加资源 AfxOleTerm(FALSE); return CWinAppEx::ExitInstance(); } // COpenGLPlatApp 消息处理程序 // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg() noexcept; // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() noexcept : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // 用于运行对话框的应用程序命令 void COpenGLPlatApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } // COpenGLPlatApp 自定义加载/保存方法 void COpenGLPlatApp::PreLoadState() { BOOL bNameValid; CString strName; bNameValid = strName.LoadString(IDS_EDIT_MENU); ASSERT(bNameValid); GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT); } void COpenGLPlatApp::LoadCustomState() { } void COpenGLPlatApp::SaveCustomState() { } // COpenGLPlatApp 消息处理程序
8139d6ef450b64b7123c1339980e524728982f6f
a06a9ae73af6690fabb1f7ec99298018dd549bb7
/_Library/_Include/boost/type_traits/is_same.hpp
cb7f882a08f27b640aed0548595bac75a68bdc26
[]
no_license
longstl/mus12
f76de65cca55e675392eac162dcc961531980f9f
9e1be111f505ac23695f7675fb9cefbd6fa876e9
refs/heads/master
2021-05-18T08:20:40.821655
2020-03-29T17:38:13
2020-03-29T17:38:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,905
hpp
//////////////////////////////////////////////////////////////////////////////// // is_same.hpp // (C) Copyright Dave Abrahams, Steve Cleary, Beman Dawes, // Howard Hinnant and John Maddock 2000. // (C) Copyright Mat Marcus, Jesse Jones and Adobe Systems Inc 2001 // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). // // See http://www.boost.org/libs/type_traits for most recent version including documentation. // Fixed is_pointer, is_reference, is_const, is_volatile, is_same, // is_member_pointer based on the Simulated Partial Specialization work // of Mat Marcus and Jesse Jones. See http://opensource.adobe.com or // http://groups.yahoo.com/group/boost/message/5441 // Some workarounds in here use ideas suggested from "Generic<Programming>: // Mappings between Types and Values" // by Andrei Alexandrescu (see http://www.cuj.com/experts/1810/alexandr.html). #ifndef BOOST_TT_IS_SAME_HPP_INCLUDED #define BOOST_TT_IS_SAME_HPP_INCLUDED #include <boost/type_traits/config.hpp> // should be the last #include #include <boost/type_traits/detail/bool_trait_def.hpp> namespace boost { BOOST_TT_AUX_BOOL_TRAIT_DEF2(is_same,T,U,false) BOOST_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_1(typename T,is_same,T,T,true) #if BOOST_WORKAROUND(__BORLANDC__, < 0x600) // without this, Borland's compiler gives the wrong answer for // references to arrays: BOOST_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_1(typename T,is_same,T&,T&,true) #endif } // namespace boost #include <boost/type_traits/detail/bool_trait_undef.hpp> #endif // BOOST_TT_IS_SAME_HPP_INCLUDED ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
6ac8b6e730f9e7829dcc150bf1dc764cc55889df
b122925a68dd997c9a9bc208fd0f53e4baa113de
/build/iOS/Preview1/include/Uno.Platform.ClosingEventArgs.h
ddb2fde8612ae60ba2fe5f29e8eadbfe8ae5af8a
[]
no_license
samscislowicz/Lensy
e2ca1e5838176687299236bff23ef1f692a6504e
69270bad64ee7e8884e322f8e9e481e314293d30
refs/heads/master
2021-01-25T01:03:05.456091
2017-06-23T23:29:30
2017-06-23T23:29:30
94,716,371
0
0
null
null
null
null
UTF-8
C++
false
false
937
h
// This file was generated based on '/Users/Sam/Library/Application Support/Fusetools/Packages/UnoCore/1.0.11/source/uno/platform/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.EventArgs.h> namespace g{namespace Uno{namespace Platform{struct ClosingEventArgs;}}} namespace g{ namespace Uno{ namespace Platform{ // public sealed class ClosingEventArgs :326 // { uType* ClosingEventArgs_typeof(); void ClosingEventArgs__ctor_1_fn(ClosingEventArgs* __this); void ClosingEventArgs__get_Cancel_fn(ClosingEventArgs* __this, bool* __retval); void ClosingEventArgs__set_Cancel_fn(ClosingEventArgs* __this, bool* value); void ClosingEventArgs__New2_fn(ClosingEventArgs** __retval); struct ClosingEventArgs : ::g::Uno::EventArgs { bool _Cancel; void ctor_1(); bool Cancel(); void Cancel(bool value); static ClosingEventArgs* New2(); }; // } }}} // ::g::Uno::Platform
f8567b1ba072c0b23aa5eef3970d8858fb334b87
46b1de0d14505e69d3c106526fea1c7271c0b828
/assignment4/main.cpp
ea120704982ee64516560c74cde63129088663c0
[]
no_license
AStadum/C-C-Unix
990a739d3673a65963115954c97f2ae7ed4ff98e
608220423b64066a2067009cd124b2ef3140f0b0
refs/heads/master
2021-01-19T03:22:43.897482
2014-11-11T06:26:34
2014-11-11T06:26:34
26,472,953
1
0
null
null
null
null
UTF-8
C++
false
false
2,024
cpp
/* * main.cpp * * Created on: Jan 27, 2014 * Author: norris */ #include <iostream> // needed #include <fstream> // needed to read from a file #include "mymaze.hpp" #include "utils.hpp" int main(int argc, const char *argv[]) { if( argc != 2 ) //checks for the input file name { std::cerr << "Error: no input file name" << std::endl; std::cerr << "Usage: ./" << argv[0] << " someinput.txt" << std::endl; return 1; } std::ifstream mazeInputFile ( argv[1] ); // open the input file int numberOfMazes = 0; mazeInputFile >> numberOfMazes; // read the number of mazes for (int currentMaze = 0; currentMaze < numberOfMazes; currentMaze++ ) { int mazeSize = 0; mazeInputFile >> mazeSize; // read the maze size from the input file std::cout << "size = " << mazeSize << std::endl; Utils mazeUtils(mazeSize, mazeInputFile); // helper class for testing, output if (mazeSize < 10 || mazeSize > 30) { std::cerr << "Error: invalid maze size " << mazeSize << " read from " << argv[1] << std::endl; std::cerr << " Maze sizes must be between 10 and 30" << std::endl; return 1; } // Create a new maze object of the given size Maze maze(mazeSize); // // Initialize the maze maze.readFromFile(mazeInputFile); int row, col; // Solve the maze do { // Get current location of 'x' in the maze maze.getCurrentPosition(row, col); // Print the current maze string (this is provided, you don't need to implement) mazeUtils.print(row, col); std::cout << "Press ENTER to continue..." << std::endl; std::cin.get(); // wait for a keypress by user before moving on // Advance one step in the maze maze.step(); } while ( ! maze.atExit() ); maze.getCurrentPosition(row, col); mazeUtils.print(row, col); std::cout << "YAY! Maze solved!" << std::endl; std::cout << "Press ENTER to continue..." << std::endl; std::cin.get(); // wait for a keypress by user before moving on mazeUtils.reset(); } // currentMaze }
1758dcd135de76b2fff20206fe5f731591cf894b
574249e7c5864b36b4cf6c26d7f23151f5f766d8
/Iniciante/UOJ_1042 - (1006477) Accepted.cpp
89237de959a9c86a9784c9dfeec3f56c8516a111
[]
no_license
filipeherculano/Quest-esURI
f0de20cf361b7fc172a6c99ec84c5ca9e23b5302
059006838b43a2cd35cdea33ef66f3e95b31c9a8
refs/heads/master
2021-01-23T20:21:43.309839
2015-07-01T04:29:34
2015-07-01T04:29:34
37,881,914
1
0
null
null
null
null
UTF-8
C++
false
false
719
cpp
#include <stdio.h> int main(){ int i, x[3], y[3], aux, j; scanf("%d %d %d", &x[0], &x[1], &x[2]); for (i = 0; i < 3; i++){ y[i] = x[i]; } for (i = 0; i < 3; i++){ for (j = 0; j < 3; j++){ if(x[i] < x[j]){ aux = x[j]; x[j] = x[i]; x[i] = aux; } } } for (i = 0; i < 3; i++){ printf("%d\n", x[i]); } printf("\n"); for (i = 0; i < 3; i++){ printf("%d\n", y[i]); } return 0; }
[ "alunos@Labcomp.(none)" ]
alunos@Labcomp.(none)
e54cbd9167de4992348d91a6d91f72a9c4c84c91
43f9c0d3058f1f8b52231b2d8d06befbe4cfc873
/ServeurWorms/Gestion.cpp
5b15b28ec2f5ae464961af5d4311338836d45114
[]
no_license
Predatorium/Worms
33275d6b742a17f6da1029bbbd0e041999f3793e
c00146ffe94ba24b66e826a90e95b62d54c7fca9
refs/heads/main
2023-04-12T05:31:19.184868
2021-05-06T18:40:12
2021-05-06T18:40:12
364,231,303
0
0
null
null
null
null
ISO-8859-1
C++
false
false
5,595
cpp
#include "Gestion.h" int Gestion::Init(int _port) { // Vérification que le port soit libre si il est libre // on commence à écouter les nouvelles connexions if (listener.listen(_port) == sf::Socket::Done) { std::cout << "Serveur en ligne" << std::endl; } else { // Si le port n'est pas libre on quitte return EXIT_FAILURE; } // Si il est libre on ajoute le listener au selector selector.add(listener); // On crée un container pour stocker tout les sockets DispoId.push_back(4); DispoId.push_back(3); DispoId.push_back(2); DispoId.push_back(1); } void Gestion::Update(const float& dt) { if (selector.wait()) { switch (state) { case Waiting: CheckNewPlayer(); WaitingFullReday(); break; case Game: if (!selector.isReady(listener)) { for (int i = 0; i < client.size(); i++) { if (selector.isReady(*client[i]->socket)) { client[i]->CheckPacket(client); } } } for (int i = 0; i < client.size(); i++) { if (!client[i]->Ready) { DispoId.push_back(client[i]->Id); std::cout << client[i]->username << " s'est deconnecte" << std::endl; client.erase(client.begin() + i); i--; } if (client[i]->Worms.size() == 0) { sf::Packet sendPacket; // Déclaration d'un packet sendPacket << state << Disconnect << client[i]->Id; for (int j = 0; j < client.size(); j++) { client[j]->socket->send(sendPacket); } client.erase(client.begin() + i); i--; } } break; default: break; } for (int i = 0; i < client.size(); i++) { client[i]->timeout += dt; if (client[i]->timeout > 15.f) { sf::Packet sendPacket; // Déclaration d'un packet sendPacket << state << Disconnect << client[i]->Id; DispoId.push_back(client[i]->Id); std::cout << client[i]->username << " TimedOut" << std::endl; client.erase(client.begin() + i); i--; for (int j = 0; j < client.size(); j++) { client[j]->socket->send(sendPacket); } } } if (client.size() < 1) { state = Waiting; } } } void Gestion::CheckNewPlayer() { if (selector.isReady(listener) && client.size() < 4) { int id = DispoId.back(); DispoId.pop_back(); std::string pseudo; if (id == 0) pseudo = Name1; if (id == 1) pseudo = Name2; if (id == 2) pseudo = Name3; if (id == 3) pseudo = Name4; Client* socket = new Client(pseudo); socket->socket = new sf::TcpSocket(); listener.accept(*socket->socket); selector.add(*socket->socket); int type; sf::Packet receivePacket; if (socket->socket->receive(receivePacket) == sf::Socket::Done) { receivePacket >> type; socket->Id = id; socket->timeout = 0; std::cout << socket->username << " vient de se connecter." << id << std::endl; } client.push_back(socket); client.back()->timeout = 0; sf::Packet NsendPacket; // Déclaration d'un packet pour l'envoi NsendPacket << state << ME << id; // Préparation d'un packet client.back()->socket->send(NsendPacket); std::string ip = client.back()->socket->getRemoteAddress().toString(); std::cout << "Recu du client " << socket->username << " ip: " << ip << std::endl; sf::Packet sendPacket; // Déclaration d'un packet pour l'envoi sendPacket << state << New << id << socket->username; // Préparation d'un packet // envoi de ce paquet à tous les clients sauf à celui qui à envoyé for (int j = 0; j < client.size(); j++) { if (client[j] != client.back()) { client[j]->socket->send(sendPacket); sf::Packet sendPacketP; // Déclaration d'un packet pour l'envoi sendPacketP << state << AddOtherPlayer << client[j]->Id << client[j]->username; // Préparation d'un packet client.back()->socket->send(sendPacketP); } } } } void Gestion::WaitingFullReday() { if (!selector.isReady(listener)) { // pour chaque client connecté for (int i = 0; i < client.size(); i++) { // si il reçoit des données if (selector.isReady(*client[i]->socket)) { sf::Packet receivePacket; // Déclaration d'un packet pour la reception // Si les données ont toutes été reçus if (client[i]->socket->receive(receivePacket) == sf::Socket::Done) { client[i]->timeout = 0; int type; receivePacket >> type; if (type == Ready) { if (client[i]->Ready != true) { client[i]->Ready = true; std::cout << client[i]->username << " est pret." << std::endl; } } if (type == NoReady) { if (client[i]->Ready != false) { client[i]->Ready = false; std::cout << client[i]->username << " n est pas pret." << std::endl; } } if (type == Disconnect) { sf::Packet sendPacket; // Déclaration d'un packet sendPacket << state << Disconnect << client[i]->Id; DispoId.push_back(client[i]->Id); std::cout << client[i]->username << " s est deco." << std::endl; client.erase(client.begin() + i); i--; for (int j = 0; j < client.size(); j++) { client[j]->socket->send(sendPacket); } } } } } if (client.size() > 1) { int FullReady = 0; for (int j = 0; j < client.size(); j++) { if (client[j]->Ready) FullReady++; } if (FullReady == client.size()) { state = Game; sf::Packet sendPacket; // Déclaration d'un packet pour l'envoi sendPacket << state; // Préparation d'un packet std::cout << "Tous le monde est pret" << std::endl; for (int j = 0; j < client.size(); j++) { client[j]->socket->send(sendPacket); } } } } }
e29f28952eb88e7ca4ecbec32d9214ca743a8dc0
eea06aa79c774cdb4b91cb9eae48c8be67289a82
/walk-time.cpp
e9afd1e0c38e48160431552d0c702f7a412e4e31
[]
no_license
JamesMCurrier/time-for-a-walk
a8939321285bcdc4dec2c5518094180e0f3c262c
148fc3385789a7085f2c1f3aaa38ae8cd098f71d
refs/heads/master
2022-11-14T21:16:20.890436
2020-07-02T01:35:23
2020-07-02T01:35:23
273,578,217
1
0
null
null
null
null
UTF-8
C++
false
false
222
cpp
#include <iostream> using namespace std; int main() { srand(time(NULL)); int mins = rand() % 60; cout << rand() % 3 + 1 << ":"; if (mins <= 10) { cout << "0"; } cout << mins << "PM\n"; }