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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
82bc0659ece04883cfa7f4b114131d007876e8e4 | c485cb363d29d81212427d3268df1ddcda64d952 | /dependencies/boost/libs/geometry/test/algorithms/test_intersects.hpp | a74cc9b369e764b313f5718b34d672480e0e2cde | [
"BSL-1.0"
] | permissive | peplopez/El-Rayo-de-Zeus | 66e4ed24d7d1d14a036a144d9414ca160f65fb9c | dc6f0a98f65381e8280d837062a28dc5c9b3662a | refs/heads/master | 2021-01-22T04:40:57.358138 | 2013-10-04T01:19:18 | 2013-10-04T01:19:18 | 7,038,026 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,700 | hpp | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test
// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.
// 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.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_TEST_INTERSECTS_HPP
#define BOOST_GEOMETRY_TEST_INTERSECTS_HPP
#include <geometry_test_common.hpp>
#include <boost/geometry/core/ring_type.hpp>
#include <boost/geometry/algorithms/intersects.hpp>
#include <boost/geometry/strategies/strategies.hpp>
#include <boost/geometry/geometries/ring.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/domains/gis/io/wkt/read_wkt.hpp>
template <typename Geometry1, typename Geometry2>
void test_geometry(std::string const& wkt1,
std::string const& wkt2, bool expected)
{
Geometry1 geometry1;
Geometry2 geometry2;
bg::read_wkt(wkt1, geometry1);
bg::read_wkt(wkt2, geometry2);
bool detected = bg::intersects(geometry1, geometry2);
BOOST_CHECK_MESSAGE(detected == expected,
"intersects: " << wkt1
<< " with " << wkt2
<< " -> Expected: " << expected
<< " detected: " << detected);
}
template <typename Geometry>
void test_self_intersects(std::string const& wkt, bool expected)
{
Geometry geometry;
bg::read_wkt(wkt, geometry);
bool detected = bg::intersects(geometry);
BOOST_CHECK_MESSAGE(detected == expected,
"intersects: " << wkt
<< " -> Expected: " << expected
<< " detected: " << detected);
}
#endif
| [
"fibrizo.raziel@gmail.com"
] | fibrizo.raziel@gmail.com |
5df9133d7f82bf1973c23771125474d0ba6a0689 | 6aa69b089b8569ac13cd0084db3e8b5fe8d04c3d | /src/NFParam/ParamImplementation.h | aa3c5b2ac80a39aee1f3e7c335c84313f33f8c06 | [
"Apache-2.0",
"MIT"
] | permissive | maxthielen/yml | 5d0bfb625ec15fe60fd7dfab6abcc0994180df69 | 58f5a1707f1034eb4e24c305e416def1e5cbf50b | refs/heads/development | 2023-08-25T04:59:05.859371 | 2021-10-15T16:59:15 | 2021-10-15T16:59:15 | 416,984,352 | 0 | 0 | MIT | 2021-10-15T10:07:32 | 2021-10-14T04:08:53 | C++ | UTF-8 | C++ | false | false | 4,050 | h | /*
* Copyright (c) 2016 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* Adapted by RoboTeam Twente
*/
#pragma once
#include <list>
#include <map>
#include <mutex>
#include <string>
#include <NFParam/Param.h>
#include "WAAParamEvents.h"
namespace nativeformat {
namespace param {
class ParamImplementation : public Param {
typedef std::unique_ptr<ParamEvent> EVENT_PTR;
public:
ParamImplementation(float default_value,
float max_value,
float min_value,
const std::string &name);
virtual ~ParamImplementation();
float yForX(double x) override;
void yValuesForXRange(float *y_values,
size_t y_values_count,
double start_x,
double end_x) override;
std::string name() override;
float smoothedYForXRange(double start_x, double end_x, size_t samples = 5) override;
float cumulativeYForXRange(double start_x,
double end_x,
double precision = 0.1) override;
// WAAParam
float defaultY() const override;
float maxY() const override;
float minY() const override;
void setY(float y) override;
void setYAtX(float y, double x) override;
void linearRampToYAtX(float end_y, double end_x) override;
void setTargetYAtX(float target_y, double start_x, float x_constant) override;
void exponentialRampToYAtX(float y, double end_x) override;
void setYCurveAtX(std::vector<float> y_values, double start_x, double duration) override;
// Custom
void addCustomEvent(double start_x,
double end_x,
Anchor anchor,
NF_AUDIO_PARAM_FUNCTION function) override;
private:
const float _default_value;
const float _max_value;
const float _min_value;
const std::string _name;
std::list<EVENT_PTR> _events;
std::mutex _events_mutex;
std::vector<float> _smoothed_samples_buffer;
std::map<double, std::map<double, float>> _cumulative_values_cache;
// Find the event (if any) that governs the param curve at the given time
std::list<std::unique_ptr<ParamEvent>>::iterator iteratorForTime(double time);
// Find the last event (if any) whose anchor time is <= time
std::list<std::unique_ptr<ParamEvent>>::iterator prevEvent(double time);
// Populate start and end with the required start and end of an event.
// If the event's anchor is NONE, getRequiredTimeRange will return false.
// If the event's anchor is START or END, start = end.
// If the event's anchor is ALL, end >= start.
bool getRequiredTimeRange(const EVENT_PTR &event, double &start, double &end);
// Throw an exception if an event overlaps with any existing events
void checkOverlap(const EVENT_PTR &event);
// Update events' start and end times according to their anchor.
// Assumes prev's required time range ends before event's.
void updateTimes(EVENT_PTR &prev, EVENT_PTR &event);
// Update adjacent events on insertion of a new event
void addEvent(EVENT_PTR new_event, std::list<EVENT_PTR>::iterator prev_event);
void invalidateCachedCumulativeValuesAfterTime(double time);
};
} // namespace param
} // namespace nativeformat
| [
"noreply@github.com"
] | noreply@github.com |
e28c4056548bf5b37e9f38dedfda2e77bfa8d4cf | a90e851619abffd1ce5702e9eceb4c2f2b010749 | /fantastic-final/test/dino_test.cpp | c438ea90d93847f63b8dec4efc4fa6a97fb38e91 | [] | no_license | smoorjani/Chrome-Dino-Genetic-Algorithm | 6e248833b4a98dfcfa3997e84cbccb17e253b03c | f34020bc4ea837a825485b8cf9893fbf65d54e8e | refs/heads/master | 2020-11-26T13:20:41.166161 | 2019-12-11T23:37:11 | 2019-12-11T23:37:11 | 229,083,685 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,193 | cpp | #include "../catch.hpp"
#include "../src/game/dino.h"
#include "../src/game/obstacle.h"
constexpr int NUMBER_OF_TEST_OBSTACLES = 5;
constexpr float dino_hitbox_shrink_scalar = 0.4;
std::string DINO_IMAGE_FILE = "big_chrome_dino.png";
TEST_CASE("Test Get Nearest Obstacle Functions") {
dino dino_{ DINO_IMAGE_FILE };
std::vector<obstacle> obstacles_;
for (int obstacle_num = 0; obstacle_num < NUMBER_OF_TEST_OBSTACLES; obstacle_num++) {
obstacle temp_ob(obstacle_num * 100, DEFAULT_START_Y);
obstacles_.push_back(temp_ob);
}
SECTION("Nearest Obstacle") {
int nearest = dino_.get_nearest_obstacle(obstacles_);
REQUIRE(nearest == 0);
}
SECTION("Second Nearest Obstacle") {
int second_nearest = dino_.get_second_nearest_obstacle(obstacles_);
REQUIRE(second_nearest == 1);
}
}
TEST_CASE("Test Has Collided") {
dino dino_{ DINO_IMAGE_FILE };
std::vector<obstacle> obstacles_;
for (int obstacle_num = 0; obstacle_num < NUMBER_OF_TEST_OBSTACLES; obstacle_num++) {
obstacle temp_ob((obstacle_num+1) * 200, DEFAULT_START_Y);
obstacles_.push_back(temp_ob);
}
SECTION("No Collisions") {
for (int obstacle_num = 0; obstacle_num < NUMBER_OF_TEST_OBSTACLES; obstacle_num++) {
REQUIRE(!dino_.has_collided(obstacles_[obstacle_num]));
}
}
SECTION("Collision") {
obstacle new_obstacle(dino_.get_dino_x(), dino_.get_dino_y());
REQUIRE(dino_.has_collided(new_obstacle));
}
}
TEST_CASE("Test Setup Dino Image") {
dino dino_{ DINO_IMAGE_FILE };
std::string file_path = "big_chrome_dino.png";
dino_.setup_image(file_path);
double dino_img_width = dino_.get_dino_image().getWidth();
// 0.35 is dino_shrink_scalar. Have to use double to avoid floating pt arithmetic.
REQUIRE(dino_.get_dino_width() == dino_img_width*0.35);
REQUIRE(dino_.get_dino_height() == dino_.get_dino_image().getHeight());
}
TEST_CASE("Test Jump") {
dino dino_{ DINO_IMAGE_FILE };
REQUIRE(!dino_.get_is_jumping());
dino_.jump();
REQUIRE(dino_.get_is_jumping());
}
TEST_CASE("Test Update Dino Position") {
dino dino_{ DINO_IMAGE_FILE };
float new_dino_x = 20.5;
float new_dino_y = 100.812;
dino_.update_dino_position(new_dino_x, new_dino_y);
REQUIRE(dino_.get_dino_x() == float(20.5));
REQUIRE(dino_.get_dino_y() == float(100.812));
}
TEST_CASE("Test Update Dino") {
dino dino_{ DINO_IMAGE_FILE };
float initial_velocity = dino_.get_velocity_y();
dino_.update();
REQUIRE(abs(dino_.get_velocity_y() - initial_velocity) == float(GRAVITY));
}
TEST_CASE("Test Reset Dino") {
dino dino_{ DINO_IMAGE_FILE };
float new_dino_x = 20.5;
float new_dino_y = 100.812;
float new_velocity_y = 5.3;
dino_.update_dino_position(new_dino_x, new_dino_y);
dino_.set_velocity_y(new_velocity_y);
REQUIRE(dino_.get_dino_x() == new_dino_x);
REQUIRE(dino_.get_dino_y() == new_dino_y);
REQUIRE(dino_.get_velocity_y() == new_velocity_y);
dino_.set_is_dead(true);
dino_.set_is_jumping(true);
REQUIRE(dino_.get_is_jumping());
REQUIRE(dino_.get_is_dead());
dino_.reset();
REQUIRE(dino_.get_dino_x() == DEFAULT_START_X);
REQUIRE(dino_.get_dino_y() == DEFAULT_START_Y);
REQUIRE(dino_.get_velocity_y() == 0);
REQUIRE(!dino_.get_is_jumping());
REQUIRE(!dino_.get_is_dead());
} | [
"samrajmoorjani@gmail.com"
] | samrajmoorjani@gmail.com |
3089fb1e7a580ccaf8462066adfa9c77fe5800f7 | bf621ef220b9be5913670bea2ef4eaecab196be6 | /bitcoin-0.12.1/src/bitcoind.cpp | 6021618e3c47c249b734499d490ad5193089872d | [
"MIT"
] | permissive | TickWall/bitcoin-comment | 4d98e435306af74a81713c7014570353a8ef3ce3 | ff56ba1724e09e55361519291fd7fe9637599595 | refs/heads/master | 2020-04-09T20:55:26.253605 | 2018-07-13T16:55:05 | 2018-07-13T16:55:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,025 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "clientversion.h"
#include "rpcserver.h"
#include "init.h"
#include "noui.h"
#include "scheduler.h"
#include "util.h"
#include "httpserver.h"
#include "httprpc.h"
#include "rpcserver.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <stdio.h>
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (https://www.bitcoin.org/),
* which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
static bool fDaemon;
void WaitForShutdown(boost::thread_group* threadGroup)
{
bool fShutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!fShutdown)
{
MilliSleep(200);
fShutdown = ShutdownRequested();
}
if (threadGroup)
{
Interrupt(*threadGroup);
threadGroup->join_all();
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
CScheduler scheduler;
bool fRet = false;
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
//把程序启动的参数放到 mapArgs mapMultiArgs里面
ParseParameters(argc, argv);
//
// Process help and version before taking care about datadir
if (mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version"))
{
std::string strUsage = _("Bitcoin Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n";
if (mapArgs.count("-version"))
{
strUsage += LicenseInfo();
}
else
{
strUsage += "\n" + _("Usage:") + "\n" +
" bitcoind [options] " + _("Start Bitcoin Core Daemon") + "\n";
strUsage += "\n" + HelpMessage(HMM_BITCOIND);
}
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
try
{
//设置数据目录
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
return false;
}
try
{
//配置文件
ReadConfigFile(mapArgs, mapMultiArgs);
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return false;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
//设置网络参数
SelectParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return false;
}
// Command-line RPC
bool fCommandLine = false;
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:"))
fCommandLine = true;
if (fCommandLine)
{
fprintf(stderr, "Error: There is no RPC client functionality in bitcoind anymore. Use the bitcoin-cli utility instead.\n");
exit(1);
}
#ifndef WIN32
//后台运行
fDaemon = GetBoolArg("-daemon", false);
if (fDaemon)
{
fprintf(stdout, "Bitcoin server starting\n");
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
//服务端模式
SoftSetBoolArg("-server", true);
// Set this early so that parameter interactions go to console
InitLogging();
InitParameterInteraction();
//完成参数初始化,进入第二层初始化,否则跳出异常报错
fRet = AppInit2(threadGroup, scheduler);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet)
{
Interrupt(threadGroup);
// threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
// the startup-failure cases to make sure they don't result in a hang due to some
// thread-blocking-waiting-for-another-thread-during-startup case
} else {
WaitForShutdown(&threadGroup);
}
Shutdown();
return fRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
// Connect bitcoind signal handlers
noui_connect();
return (AppInit(argc, argv) ? 0 : 1);
}
| [
"shixingming@outlook.com"
] | shixingming@outlook.com |
ae9fe2be50de31b5876ae636e027a694a064570c | 587e191159ab12e577940251d14558939e602614 | /verwrite/stockIT/app/src/main/include/Uno.Type.h | 3b1cef8b30858e37063b9d7171af09c3eee57b3c | [] | no_license | hazimayesh/stockIT | cefcaa402e61108294f8db178ee807faf6b14d61 | 809381e7e32df270f0b007a6afc7b394453d1668 | refs/heads/master | 2021-04-09T16:10:23.318883 | 2017-07-31T21:28:05 | 2017-07-31T21:28:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,544 | h | // This file was generated based on 'C:\Users\Emenike pc\AppData\Local\Fusetools\Packages\UnoCore\0.43.8\source\uno\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{
namespace Uno{
// public sealed class Type :7775
// {
uType* Type_typeof();
void Type__get_BaseType_fn(uType* __this, uType** __retval);
void Type__Equals_fn(uType* __this, uObject* obj, bool* __retval);
void Type__get_FullName_fn(uType* __this, uString** __retval);
void Type__GetHashCode_fn(uType* __this, int* __retval);
void Type__GetInterfaces_fn(uType* __this, uArray** __retval);
void Type__get_IsClass_fn(uType* __this, bool* __retval);
void Type__get_IsEnum_fn(uType* __this, bool* __retval);
void Type__IsSubclassOf_fn(uType* __this, uType* c, bool* __retval);
void Type__op_Equality_fn(uType* a, uType* b, bool* __retval);
void Type__op_Inequality_fn(uType* a, uType* b, bool* __retval);
void Type__ToString_fn(uType* __this, uString** __retval);
struct Type
{
static uSStrong<uArray*> EmptyTypes_;
static uSStrong<uArray*>& EmptyTypes() { return Type_typeof()->Init(), EmptyTypes_; }
static uType* BaseType(uType* __this);
static uString* FullName(uType* __this);
static uArray* GetInterfaces(uType* __this);
static bool IsClass(uType* __this);
static bool IsEnum(uType* __this);
static bool IsSubclassOf(uType* __this, uType* c);
static bool op_Equality(uType* a, uType* b);
static bool op_Inequality(uType* a, uType* b);
};
// }
}} // ::g::Uno
| [
"egaleme@gmail.com"
] | egaleme@gmail.com |
f99b513825c93c0dbd5f986eb04fd28a9028ec89 | c1f694e166a608209ef321b6b63db12a8784a986 | /louvain-method/silhouette/main_display.cpp | eab4bb2689a6ddecc14f6d7b642485b3fde24015 | [] | no_license | jcnguyen/research-2015 | d23ba3f9f70e0634903faceef9372a406fe3449f | 920ef96131496349d47b39ce1aca6a90fc074288 | refs/heads/master | 2020-12-24T07:08:46.953779 | 2016-05-31T02:00:40 | 2016-05-31T02:00:40 | 38,121,994 | 0 | 1 | null | 2016-05-31T02:00:41 | 2015-06-26T16:39:31 | C++ | UTF-8 | C++ | false | false | 2,236 | cpp | #include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
char *filename = NULL;
// How to use this exe
void usage(char *prog_name, const char *more) {
cerr << more;
cerr << "usage: " << prog_name << " input_file > graph_file" << endl << endl;
cerr << "input_file: read the community tree from this file." << endl;
cerr << "graph_file: store the final community graph in this file." << endl;
exit(0);
}
// Parses arguments
void parse_args(int argc, char **argv) {
if (argc<2)
usage(argv[0], "Bad arguments number\n");
for (int i = 1; i < argc; i++) {
if (filename==NULL)
filename = argv[i];
else
usage(argv[0], "More than one filename\n");
}
if (filename==NULL)
usage(argv[0], "No input file has been provided.\n");
}
// Main sequence
int main(int argc, char **argv) {
parse_args(argc, argv);
// lists the communities in which the node belongs to at that particular levell (iteration),
// where index = level, vector<int>[level] = node id, vector<vector><int>[level][node] = community
// note that vector<int> will be smaller as iterations pass
vector<vector<int> >levels;
ifstream finput;
finput.open(filename,fstream::in);
// construct the levels
int l=-1;
while (!finput.eof()) {
int node, community;
finput >> node >> community;
if (finput) {
if (node==0) {
l++;
levels.resize(l+1);
}
levels[l].push_back(community);
}
}
// prints the info
// note that levels[0] is when each node is its own community,
// so levels[0].size is the total number of nodes
vector<int> n2c(levels[0].size());
// each node (index) is its own community
for (unsigned int node=0 ; node<levels[0].size() ; node++)
n2c[node]=node;
// setting the community in which the node belongs
for (l=0 ; l<(levels.size() - 1) ; l++)
for (unsigned int node=0 ; node<levels[0].size() ; node++)
n2c[node] = levels[l][n2c[node]];
// print "[node] [community]"
for (unsigned int node=0 ; node<levels[0].size() ; node++)
cout << node << " " << n2c[node] << endl;
}
| [
"jnguyen@cs229-14.local"
] | jnguyen@cs229-14.local |
1b24949710e2ee58025d6d447684d082693f55fd | da0b448a60c046e485cddeb29bae025d940659e7 | /lab/lab012218/Throw_2_Dice/main.cpp | 4f1371767b6c7f644390c542d35129709b7e2ea7 | [] | no_license | eligandrade/AndradeElizabeth_CIS_5_Winter_2018 | 9c74d73ba5854008f0632b0d14b015f4bd430593 | 7c9872434694a4eef06a66074f72455d7af6ed49 | refs/heads/master | 2021-05-12T04:06:08.441727 | 2018-01-28T17:42:27 | 2018-01-28T17:42:27 | 117,151,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,023 | cpp | /*
* File: main.cpp
* Author: Elizabeth Andrade
* Created on January 22, 2018, 12:55 PM
* Purpose: Statistics for throwing 2 Dice
*/
//System Libraries
#include <iostream> //IO Library
#include <cstdlib> //random number Library
#include <ctime> //Time Library
using namespace std;
//User Libraries
//Global Constants - Math/ Physics Constants, Conversions,
// 2-D Array Dimensions
//Function Prototypes
//Execution Begins Here
int main(int argc, char** argv) {
//Seed the random number function
srand(static_cast<unsigned int>(time(0)));
//Declare Variables
int f2, f3, f4, f5, f6, f7, f8, f9, f10, f11 ,f12;//Frequency of the sum x->
int nThrows;
//Initialize Variables
f2=f3=f4=f5=f6=f7=f8=f9=f10=f11=f12=0;
nThrows=36000;
//Process/Map inputs to outputs
for(int thrw=1;thrw<=nThrows;thrw++){
char die1=rand()%6+1;//Range [1,6]
char die2=rand()%6+1;//Range [1,6]
switch(die1+die2){
case 2 :f2++;break;
case 3 :f3++;break;
case 4 :f4++;break;
case 5 :f5++;break;
case 6 :f6++;break;
case 7 :f7++;break;
case 8 :f8++;break;
case 9 :f9++;break;
case 10:f10++;break;
case 11:f11++;break;
case 12:f12++;break;
default:cout<<"Error"<<endl;
}
}
//Output data
cout<<"Frequency of 2 = "<<f2<<endl;
cout<<"Frequency of 3 = "<<f3<<endl;
cout<<"Frequency of 4 = "<<f4<<endl;
cout<<"Frequency of 5 = "<<f5<<endl;
cout<<"Frequency of 6 = "<<f6<<endl;
cout<<"Frequency of 7 = "<<f7<<endl;
cout<<"Frequency of 8 = "<<f8<<endl;
cout<<"Frequency of 9 = "<<f9<<endl;
cout<<"Frequency of 10 = "<<f10<<endl;
cout<<"Frequency of 11 = "<<f11<<endl;
cout<<"Frequency of 12 = "<<f12<<endl;
cout<<nThrows<<"="<<f2+f3+f4+f5+f6+f7+f8+f9+f10+f11+f12<<endl;
//Exit stage right!
return 0;
} | [
"eligandrade@yahoo.com"
] | eligandrade@yahoo.com |
4feb02a4a7cff51a27d90a0d4df12500376cccde | bdeeaee330d9721299cf508e0c716c389e96f4b9 | /FinalProject/Ver1/Boss.cpp | 3f73bd983d751e127e707ee0d492fa6eb168e1aa | [] | no_license | ImbaCow/cpp_course | 4e3ac052208ee83bd14b038f036518c91127d9b9 | e5dcc039e8b825c6c12fe0a92ef62dba2559f4e7 | refs/heads/master | 2021-09-08T17:26:51.060139 | 2018-03-11T10:21:21 | 2018-03-11T10:21:21 | 108,839,032 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,553 | cpp | #include "Boss.h"
#include <cmath>
#include <math.h>
#include <algorithm>
void Boss::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
target.draw(body);
target.draw(head);
target.draw(fullHealth);
target.draw(currentHealth);
}
void Boss::initBoss()
{
bodyDirection = sf::Vector2f(0, 0);
BossStage = 1;
rotation = 0;
spawnCD = BOSS_SPAWN_CD;
shotCD = 0;
fireCD = 0;
blastCD = 0;
position = BOSS_INIT_POS;
healthPoints = BOSS_MAX_HEALTH;
texture.loadFromFile("./tank.png");
body.setTexture(&texture);
head.setTexture(&texture);
head.setFillColor(sf::Color(25, 126, 16));
body.setFillColor(sf::Color(10, 64, 5));
head.setPointCount(11);
head.setPoint(0, sf::Vector2f(-20, -16));
head.setPoint(1, sf::Vector2f(-16, -20));
head.setPoint(2, sf::Vector2f(12, -20));
head.setPoint(3, sf::Vector2f(20, -6));
head.setPoint(4, sf::Vector2f(80, -6));
head.setPoint(5, sf::Vector2f(80, 6));
head.setPoint(6, sf::Vector2f(20, 6));
head.setPoint(7, sf::Vector2f(12, 20));
head.setPoint(8, sf::Vector2f(-16, 20));
head.setPoint(9, sf::Vector2f(-20, 16));
head.setPoint(10, sf::Vector2f(-20, -16));
body.setPointCount(7);
body.setPoint(0, sf::Vector2f(-40, -30));
body.setPoint(1, sf::Vector2f(40, -30));
body.setPoint(2, sf::Vector2f(50, -20));
body.setPoint(3, sf::Vector2f(50, 20));
body.setPoint(4, sf::Vector2f(40, 30));
body.setPoint(5, sf::Vector2f(-40, 30));
body.setPoint(6, sf::Vector2f(-40, -30));
head.setPosition(position);
body.setPosition(position);
initHealthBars();
}
void Boss::initHealthBars()
{
fullHealth.setSize(BOSS_HEALTH_BAR_SIZE);
fullHealth.setFillColor(sf::Color(255, 0, 0, 255));
fullHealth.setOutlineThickness(5);
fullHealth.setOutlineColor(sf::Color::Black);
fullHealth.setPosition(BOSS_HEALTH_BAR_POS);
currentHealth.setSize(BOSS_HEALTH_BAR_SIZE);
currentHealth.setFillColor(sf::Color(0, 255, 0, 200));
currentHealth.setPosition(BOSS_HEALTH_BAR_POS);
}
void Boss::update(float dt, sf::Vector2f heroPosition, sf::Vector2f heroDirection, Bullets &bullets, Enemies &enemies)
{
checkStage(enemies);
switch (BossStage)
{
case 0:
endScene(dt);
break;
case 1:
stageOneUpdate(dt, heroPosition, heroDirection, bullets);
break;
case 2:
stageTwoUpdate(dt, heroPosition, heroDirection, bullets, enemies);
break;
case 3:
stageThreeUpdate(dt, heroPosition, heroDirection, bullets);
break;
default:
break;
}
}
void Boss::stageOneUpdate(float dt, sf::Vector2f heroPosition, sf::Vector2f heroDirection, Bullets &bullets)
{
float healthBarLenght = BOSS_HEALTH_BAR_SIZE.x / BOSS_MAX_HEALTH * healthPoints;
currentHealth.setSize({healthBarLenght, BOSS_HEALTH_BAR_SIZE.y});
bodyRotationUpdate(dt, heroPosition);
bodyUpdate(dt, heroPosition, B_CHANGE_MOVE_RADIUS_1);
headUpdate(heroPosition, heroDirection);
checkWallCollision();
bulletShot(bullets);
shotCD += dt;
}
void Boss::stageTwoUpdate(float dt, sf::Vector2f heroPosition, sf::Vector2f heroDirection, Bullets &bullets, Enemies &enemies)
{
float healthBarLenght = BOSS_HEALTH_BAR_SIZE.x / BOSS_MAX_HEALTH * healthPoints;
currentHealth.setSize({healthBarLenght, BOSS_HEALTH_BAR_SIZE.y});
bodyRotationUpdate(dt, heroPosition);
bodyUpdate(dt, heroPosition, B_CHANGE_MOVE_RADIUS_2);
headUpdate(heroPosition, heroDirection);
checkWallCollision();
spawnMinions(enemies, dt);
bulletShot(bullets);
shotCD += dt;
}
void Boss::stageThreeUpdate(float dt, sf::Vector2f heroPosition, sf::Vector2f heroDirection, Bullets &bullets)
{
float healthBarLenght = BOSS_HEALTH_BAR_SIZE.x / BOSS_MAX_HEALTH * healthPoints;
currentHealth.setSize({healthBarLenght, BOSS_HEALTH_BAR_SIZE.y});
bodyRotationUpdate(dt, heroPosition);
bodyUpdate(dt, heroPosition, M_CHANGE_MOVE_RADIUS);
head.setRotation(body.getRotation());
head.setPosition(position);
checkWallCollision();
fireShot(bullets);
blastShot(bullets);
fireCD += dt;
blastCD += dt;
}
void Boss::endScene(float dt)
{
float healthBarLenght = 0;
currentHealth.setSize({healthBarLenght, BOSS_HEALTH_BAR_SIZE.y});
if (spawnCD >= LEVEL_UP_PAUSE)
{
healthPoints = 0;
}
spawnCD += dt;
}
void Boss::checkStage(Enemies &enemies)
{
float percentHealth = healthPoints / BOSS_MAX_HEALTH * 100;
if ((percentHealth <= 100) && (percentHealth > 80))
{
BossStage = 1;
}
else if ((percentHealth <= 80) && (percentHealth > 30))
{
BossStage = 2;
}
else if ((percentHealth <= 30) && (percentHealth > 1))
{
BossStage = 3;
enemies.range.clear();
enemies.melee.clear();
spawnCD = 0;
}
else if (percentHealth <= 1)
{
healthPoints = BOSS_MAX_HEALTH / 100;
BossStage = 0;
}
}
void Boss::spawnMinions(Enemies &enemies, float dt)
{
if (spawnCD >= BOSS_SPAWN_CD)
{
enemies.addRange(position);
enemies.addMelee(position);
spawnCD = 0;
}
else
spawnCD += dt;
}
void Boss::checkWallCollision()
{
if (position.x > WINDOW_WIDTH)
{
position.x -= 1;
}
if (position.x < 0)
{
position.x += 1;
}
if (position.y > WINDOW_HEIGHT)
{
position.y -= 1;
}
if (position.y < 0)
{
position.y += 1;
}
}
void Boss::bulletShot(Bullets &bullets)
{
if (shotCD > BOSS_SHOT_COOLDOWN)
{
bullets.addBullet(3, position, math.toRadians(head.getRotation()));
shotCD = 0;
}
}
void Boss::fireShot(Bullets &bullets)
{
if (fireCD > M_ENEMY_SHOT_COOLDOWN)
{
for (unsigned bi = 0; bi < M_SHOT_COUNT; ++bi)
{
float angleStep = M_ENEMY_SHOT_ANGLE / M_SHOT_COUNT * bi;
float nextAngle = body.getRotation() - M_ENEMY_SHOT_ANGLE / 2 + angleStep;
bullets.addBullet(4, position, math.toRadians(nextAngle));
}
fireCD = 0;
}
}
void Boss::blastShot(Bullets &bullets)
{
if (blastCD > BOSS_SHOT_COOLDOWN)
{
for (unsigned bi = 0; bi < BOSS_BLAST_COUNT; ++bi)
{
float angleStep = 360 / BOSS_BLAST_COUNT * bi;
float nextAngle = body.getRotation() + angleStep;
bullets.addBullet(3, position, math.toRadians(nextAngle));
}
blastCD = 0;
}
}
void Boss::headUpdate(sf::Vector2f heroPosition, sf::Vector2f heroDirection)
{
sf::Vector2f prediction = heroPosition - position;
prediction += heroDirection * TANK_SPEED * math.vectorLenght(prediction) / BULLET_SPEED * 2.f / 3.f;
float angle = atan2(prediction.y, prediction.x);
head.setRotation(math.toDegrees(angle));
head.setPosition(position);
}
void Boss::bodyRotationUpdate(float dt, sf::Vector2f heroPosition)
{
sf::Vector2f delta = heroPosition - position;
float angle = atan2(delta.y, delta.x);
if (angle < 0)
{
angle += 2 * M_PI;
}
rotation = body.getRotation();
float deltaAngle = math.toDegrees(angle) - rotation;
checkRotation(rotateDirection, deltaAngle);
}
void Boss::bodyUpdate(float dt, sf::Vector2f heroPosition, float changeRadius)
{
sf::Vector2f delta = heroPosition - position;
rotation += BOSS_ROTAION_SPEED * dt * rotateDirection;
sf::Vector2f moveDirection = sf::Vector2f(cos(math.toRadians(rotation)), sin(math.toRadians(rotation)));
if (hypot(delta.x, delta.y) < changeRadius)
{
moveDirection = -moveDirection;
}
position += moveDirection * BOSS_TANK_SPEED * dt;
body.setRotation(rotation);
body.setPosition(position);
}
void Boss::checkRotation(float &rotateDirection, float &deltaAngle)
{
if (deltaAngle < 0)
{
if (deltaAngle < -180)
{
rotateDirection = 1;
}
else
{
rotateDirection = -1;
}
}
else
{
if (deltaAngle > 180)
{
rotateDirection = -1;
}
else
{
rotateDirection = 1;
}
}
} | [
"noreply@github.com"
] | noreply@github.com |
f945bed1fcb17a18629e678543141d4504b709ed | c844ff061aa7b6bf5dd6003cf1833700b11fc271 | /deps/steamworks_sdk/glmgr/glmgr.cpp | 5a2c2a03043e74be1f1f9f355c08958f73c1ca43 | [
"MIT"
] | permissive | Ryjek0/greenworks | 03362a1d5cc6c4fac0301d31fa7914a1454cdc60 | 0ab7427d829e0f5e9d47c6c5ad18fdde8aa96225 | refs/heads/master | 2020-12-11T15:04:34.801733 | 2020-01-14T16:26:32 | 2020-01-14T16:26:32 | 233,879,584 | 0 | 0 | MIT | 2020-01-14T16:01:30 | 2020-01-14T16:01:29 | null | UTF-8 | C++ | false | false | 203,096 | cpp | //============ Copyright (c) Valve Corporation, All rights reserved. ============
//
// glmgr.cpp
//
//===============================================================================
#include "glmgr.h"
#include "glmdisplay.h"
#include "dxabstract.h" // need to be able to see D3D enums
#include "../SteamWorksExample/gameengineosx.h"
extern CGameEngineGL *g_engine; // so glmgr (which is C++) can call up to the game engine ObjC object and ask for things..
#ifdef __clang__
#pragma clang diagnostic warning "-Wint-to-pointer-cast"
#endif
//===============================================================================
char g_nullFragmentProgramText [] =
{
"!!ARBfp1.0 \n"
"PARAM black = { 0.0, 0.0, 0.0, 1.0 }; \n" // opaque black
"MOV result.color, black; \n"
"END \n\n\n"
"//GLSLfp\n"
"void main()\n"
"{\n"
"gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n"
"}\n"
};
// make dummy programs for doing texture preload via dummy draw
char g_preloadTexVertexProgramText[] =
{
"//GLSLvp \n"
"#version 120 \n"
"varying vec4 otex; \n"
"void main() \n"
"{ \n"
"vec4 pos = ftransform(); // vec4( 0.1, 0.1, 0.1, 0.1 ); \n"
"vec4 tex = vec4( 0.0, 0.0, 0.0, 0.0 ); \n"
" \n"
"gl_Position = pos; \n"
"otex = tex; \n"
"} \n"
};
char g_preload2DTexFragmentProgramText[] =
{
"//GLSLfp \n"
"#version 120 \n"
"varying vec4 otex; \n"
"//SAMPLERMASK-8000 // may not be needed \n"
"//HIGHWATER-30 // may not be needed \n"
" \n"
"uniform vec4 pc[31]; \n"
"uniform sampler2D sampler15; \n"
" \n"
"void main() \n"
"{ \n"
"vec4 r0; \n"
"r0 = texture2D( sampler15, otex.xy ); \n"
"gl_FragColor = r0; //discard; \n"
"} \n"
};
char g_preload3DTexFragmentProgramText[] =
{
"//GLSLfp \n"
"#version 120 \n"
"varying vec4 otex; \n"
"//SAMPLERMASK-8000 // may not be needed \n"
"//HIGHWATER-30 // may not be needed \n"
" \n"
"uniform vec4 pc[31]; \n"
"uniform sampler3D sampler15; \n"
" \n"
"void main() \n"
"{ \n"
"vec4 r0; \n"
"r0 = texture3D( sampler15, otex.xyz ); \n"
"gl_FragColor = r0; //discard; \n"
"} \n"
};
char g_preloadCubeTexFragmentProgramText[] =
{
"//GLSLfp \n"
"#version 120 \n"
"varying vec4 otex; \n"
"//SAMPLERMASK-8000 // may not be needed \n"
"//HIGHWATER-30 // may not be needed \n"
" \n"
"uniform vec4 pc[31]; \n"
"uniform samplerCube sampler15; \n"
" \n"
"void main() \n"
"{ \n"
"vec4 r0; \n"
"r0 = textureCube( sampler15, otex.xyz ); \n"
"gl_FragColor = r0; //discard; \n"
"} \n"
};
//===============================================================================
// helper routines for debug
static bool hasnonzeros( float *values, int count )
{
for( int i=0; i<count; i++)
{
if (values[i] != 0.0)
{
return true;
}
}
return false;
}
static void printmat( char *label, int baseSlotNumber, int slots, float *m00 )
{
// print label..
// fetch 4 from row, print as a row
// fetch 4 from column, print as a row
float row[4];
float col[4];
if (hasnonzeros( m00, slots*4) )
{
GLMPRINTF(("-D- %s", label ));
for( int islot=0; islot<4; islot++ ) // we always run this loop til 4, but we special case the printing if there are only 3 submitted
{
// extract row and column floats
for( int slotcol=0; slotcol<4; slotcol++)
{
//copy
row[slotcol] = m00[(islot*4)+slotcol];
// transpose
col[slotcol] = m00[(slotcol*4)+islot];
}
if (slots==4)
{
GLMPRINTF(( "-D- %03d: [ %10.5f %10.5f %10.5f %10.5f ] T=> [ %10.5f %10.5f %10.5f %10.5f ]",
baseSlotNumber+islot,
row[0],row[1],row[2],row[3],
col[0],col[1],col[2],col[3]
));
}
else
{
if (islot<3)
{
GLMPRINTF(( "-D- %03d: [ %10.5f %10.5f %10.5f %10.5f ] T=> [ %10.5f %10.5f %10.5f ]",
baseSlotNumber+islot,
row[0],row[1],row[2],row[3],
col[0],col[1],col[2]
));
}
else
{
GLMPRINTF(( "-D- %03d: T=> [ %10.5f %10.5f %10.5f ]",
baseSlotNumber+islot,
col[0],col[1],col[2]
));
}
}
}
GLMPRINTSTR(("-D-"));
}
else
{
GLMPRINTF(("-D- %s - (all 0.0)", label ));
}
}
static void transform_dp4( float *in4, float *m00, int slots, float *out4 )
{
// m00 points to a column.
// each DP is one column of the matrix ( m00[4*n]
// if we are passed a three slot matrix, this is three columns, the source W plays into all three columns, but we must set the final output W to 1 ?
for( int n=0; n<slots; n++)
{
float col4[4];
col4[0] = m00[(4*n)+0];
col4[1] = m00[(4*n)+1];
col4[2] = m00[(4*n)+2];
col4[3] = m00[(4*n)+3];
out4[n] = 0.0;
for( int inner = 0; inner < 4; inner++ )
{
out4[n] += in4[inner] * col4[inner];
}
}
if (slots==3)
{
out4[3] = 1.0;
}
}
//===============================================================================
// GLMgr static methods
GLMgr *g_glmgr = NULL;
void GLMgr::NewGLMgr( void )
{
if (!g_glmgr)
{
GLMSetupExtensions();
#if GLMDEBUG
// check debug mode early in program lifetime
GLMDebugInitialize( true );
#endif
g_glmgr = new GLMgr;
}
}
GLMgr *GLMgr::aGLMgr( void )
{
assert( g_glmgr != NULL);
return g_glmgr;
}
void GLMgr::DelGLMgr( void )
{
if (g_glmgr)
{
delete g_glmgr;
g_glmgr = NULL;
}
}
// GLMgr class methods
GLMgr::GLMgr()
{
}
GLMgr::~GLMgr()
{
}
//===============================================================================
GLMContext *GLMgr::NewContext( GLMDisplayParams *params )
{
// this now becomes really simple. We just pass through the params.
return new GLMContext( params );
}
void GLMgr::DelContext( GLMContext *context )
{
delete context;
}
void GLMgr::SetCurrentContext( GLMContext *context )
{
CGLError cgl_err;
cgl_err = CGLSetCurrentContext( context->m_ctx );
if (cgl_err)
{
// give up
GLMStop();
}
}
GLMContext *GLMgr::GetCurrentContext( void )
{
CGLContextObj ctx = CGLGetCurrentContext();
GLint glm_context_link = 0;
CGLGetParameter( ctx, kCGLCPClientStorage, &glm_context_link );
if ( glm_context_link )
{
return (GLMContext*) glm_context_link;
}
else
{
return NULL;
}
}
//===============================================================================
// GLMContext public methods
void GLMContext::MakeCurrent( void )
{
// GLM_FUNC;
CGLSetCurrentContext( m_ctx );
}
void GLMContext::CheckCurrent( void )
{
#if 1
// GLM_FUNC;
// probably want to make this a no-op for release builds
// but we can't, because someone is messing with current context and not sure where yet
CGLContextObj curr = CGLGetCurrentContext();
if (curr != m_ctx)
{
if (1 /*!CommandLine()->FindParm("-hushasserts") */)
{
Assert( !"Current context mismatch");
#if GLMDEBUG
Debugger();
#endif
}
MakeCurrent(); // you're welcome
}
#endif
}
const GLMRendererInfoFields& GLMContext::Caps( void )
{
return m_caps;
}
void GLMContext::DumpCaps( void )
{
/*
#define dumpfield( fff ) printf( "\n "#fff" : %d", (int) m_caps.fff )
#define dumpfield_hex( fff ) printf( "\n "#fff" : 0x%08x", (int) m_caps.fff )
#define dumpfield_str( fff ) printf( "\n "#fff" : %s", m_caps.fff )
*/
#define dumpfield( fff ) printf( "\n %-30s : %d", #fff, (int) m_caps.fff )
#define dumpfield_hex( fff ) printf( "\n %-30s : 0x%08x", #fff, (int) m_caps.fff )
#define dumpfield_str( fff ) printf( "\n %-30s : %s", #fff, m_caps.fff )
printf("\n-------------------------------- context caps for context %p", this);
dumpfield( m_fullscreen );
dumpfield( m_accelerated );
dumpfield( m_windowed );
dumpfield_hex( m_rendererID );
dumpfield( m_displayMask );
dumpfield( m_bufferModes );
dumpfield( m_colorModes );
dumpfield( m_accumModes );
dumpfield( m_depthModes );
dumpfield( m_stencilModes );
dumpfield( m_maxAuxBuffers );
dumpfield( m_maxSampleBuffers );
dumpfield( m_maxSamples );
dumpfield( m_sampleModes );
dumpfield( m_sampleAlpha );
dumpfield_hex( m_vidMemory );
dumpfield_hex( m_texMemory );
dumpfield_hex( m_pciVendorID );
dumpfield_hex( m_pciDeviceID );
dumpfield_str( m_pciModelString );
dumpfield_str( m_driverInfoString );
printf( "\n m_osComboVersion: 0x%08x (%d.%d.%d)", m_caps.m_osComboVersion, (m_caps.m_osComboVersion>>16)&0xFF, (m_caps.m_osComboVersion>>8)&0xFF, (m_caps.m_osComboVersion)&0xFF );
dumpfield( m_ati );
if (m_caps.m_ati)
{
dumpfield( m_atiR5xx );
dumpfield( m_atiR6xx );
dumpfield( m_atiR7xx );
dumpfield( m_atiR8xx );
dumpfield( m_atiNewer );
}
dumpfield( m_intel );
if (m_caps.m_intel)
{
dumpfield( m_intel95x );
dumpfield( m_intel3100 );
dumpfield( m_intelNewer );
}
dumpfield( m_nv );
if (m_caps.m_nv)
{
//dumpfield( m_nvG7x );
dumpfield( m_nvG8x );
dumpfield( m_nvNewer );
}
dumpfield( m_hasGammaWrites );
dumpfield( m_hasMixedAttachmentSizes );
dumpfield( m_hasBGRA );
dumpfield( m_hasNewFullscreenMode );
dumpfield( m_hasNativeClipVertexMode );
dumpfield( m_maxAniso );
dumpfield( m_hasBindableUniforms );
dumpfield( m_hasUniformBuffers );
dumpfield( m_hasPerfPackage1 );
dumpfield( m_cantBlitReliably );
dumpfield( m_cantAttachSRGB );
dumpfield( m_cantResolveFlipped );
dumpfield( m_cantResolveScaled );
dumpfield( m_costlyGammaFlips );
dumpfield( m_badDriver1064NV );
printf("\n--------------------------------");
#undef dumpfield
#undef dumpfield_hex
#undef dumpfield_str
}
void DefaultSamplingParams( GLMTexSamplingParams *samp, GLMTexLayoutKey *key )
{
memset( samp, 0, sizeof(*samp) );
// Default to black, it may make drivers happier
samp->m_borderColor[0] = 0.0f;
samp->m_borderColor[0] = 0.0f;
samp->m_borderColor[0] = 0.0f;
samp->m_borderColor[0] = 1.0f;
// generally speaking..
// if it's a render target, default it to GL_CLAMP_TO_BORDER, else GL_REPEAT
// if it has mipmaps, default the min filter to GL_LINEAR_MIPMAP_LINEAR, else GL_LINEAR
// ** none of these really matter all that much because the first time we go to render, the d3d sampler state will be consulted
// and applied directly to the tex object without regard to any previous values..
GLenum rtclamp = GL_CLAMP_TO_EDGE; //GL_CLAMP_TO_BORDER
switch( key->m_texFlags & (kGLMTexRenderable|kGLMTexMipped) )
{
case 0:
// -- mipped, -- renderable
samp->m_addressModes[0] = GL_REPEAT;
samp->m_addressModes[1] = GL_REPEAT;
samp->m_addressModes[2] = GL_REPEAT;
samp->m_magFilter = GL_LINEAR;
samp->m_minFilter = GL_LINEAR;
break;
case kGLMTexRenderable:
// -- mipped, ++ renderable
samp->m_addressModes[0] = rtclamp;
samp->m_addressModes[1] = rtclamp;
samp->m_addressModes[2] = rtclamp;
samp->m_magFilter = GL_LINEAR;
samp->m_minFilter = GL_LINEAR;
break;
case kGLMTexMipped:
// ++ mipped, -- renderable
samp->m_addressModes[0] = GL_REPEAT;
samp->m_addressModes[1] = GL_REPEAT;
samp->m_addressModes[2] = GL_REPEAT;
samp->m_magFilter = GL_LINEAR;
samp->m_minFilter = GL_LINEAR_MIPMAP_LINEAR; // was GL_NEAREST_MIPMAP_LINEAR;
break;
case kGLMTexRenderable | kGLMTexMipped:
// ++ mipped, ++ renderable
samp->m_addressModes[0] = rtclamp;
samp->m_addressModes[1] = rtclamp;
samp->m_addressModes[2] = rtclamp;
samp->m_magFilter = GL_LINEAR;
samp->m_minFilter = GL_LINEAR_MIPMAP_LINEAR; // was GL_NEAREST_MIPMAP_LINEAR;
break;
}
samp->m_mipmapBias = 0.0f;
samp->m_minMipLevel = 0; // this drives GL_TEXTURE_MIN_LOD - i.e. lowest MIP selection index clamp (largest size), not "slice defined" boundary
samp->m_maxMipLevel = 16; // this drives GL_TEXTURE_MAX_LOD - i.e. highest MIP selection clamp (smallest size), not "slice defined" boundary
samp->m_maxAniso = 1;
samp->m_compareMode = GL_NONE; // only for depth or stencil tex
samp->m_srgb = false;
}
CGLMTex *GLMContext::NewTex( GLMTexLayoutKey *key, const char *debugLabel )
{
//hushed GLM_FUNC;
MakeCurrent();
// get a layout based on the key
GLMTexLayout *layout = m_texLayoutTable->NewLayoutRef( key );
GLMTexSamplingParams defsamp;
DefaultSamplingParams( &defsamp, key );
CGLMTex *tex = new CGLMTex( this, layout, &defsamp, debugLabel );
return tex;
}
void GLMContext::DelTex( CGLMTex *tex )
{
//hushed GLM_FUNC;
MakeCurrent();
for( int i=0; i<GLM_SAMPLER_COUNT; i++)
{
// clear out any reference in the drawing sampler array
if (m_samplers[i].m_drawTex == tex)
{
m_samplers[i].m_drawTex = NULL;
}
if (m_samplers[i].m_boundTex == tex)
{
this->BindTexToTMU( NULL, i );
m_samplers[i].m_boundTex = NULL; // for clarity
tex->m_bindPoints &= ~(1<<i); // was [i] = 0 with bitvec
}
}
if (tex->m_rtAttachCount !=0)
{
// leak it and complain - we may have to implement a deferred-delete system for tex like these
GLMPRINTF(("-D- ################## Leaking tex %08x [ %s ] - was attached for drawing at time of delete",tex, tex->m_layout->m_layoutSummary ));
#if 0
// can't actually do this yet as the draw calls will tank
FOR_EACH_VEC( m_fboTable, i )
{
CGLMFBO *fbo = m_fboTable[i];
fbo->TexScrub( tex );
}
tex->m_rtAttachCount = 0;
#endif
}
else
{
delete tex;
}
}
// push and pop attrib when blit has mixed srgb source and dest?
//ConVar gl_radar7954721_workaround_mixed ( "gl_radar7954721_workaround_mixed", "1" );
int gl_radar7954721_workaround_mixed = 1;
// push and pop attrib on any blit?
//ConVar gl_radar7954721_workaround_all ( "gl_radar7954721_workaround_all", "0" );
int gl_radar7954721_workaround_all = 0;
// what attrib mask to use ?
//ConVar gl_radar7954721_workaround_maskval ( "gl_radar7954721_workaround_maskval", "0" );
int gl_radar7954721_workaround_maskval = 0;
enum eBlitFormatClass
{
eColor,
eDepth, // may not get used. not sure..
eDepthStencil
};
uint glAttachFromClass[ 3 ] = { GL_COLOR_ATTACHMENT0_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_DEPTH_STENCIL_ATTACHMENT_EXT };
void glScrubFBO ( GLenum target )
{
glFramebufferRenderbufferEXT ( target, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, 0); GLMCheckError();
glFramebufferRenderbufferEXT ( target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0); GLMCheckError();
glFramebufferRenderbufferEXT ( target, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0); GLMCheckError();
glFramebufferTexture2DEXT ( target, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, 0, 0 ); GLMCheckError();
glFramebufferTexture2DEXT ( target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0 ); GLMCheckError();
glFramebufferTexture2DEXT ( target, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0 ); GLMCheckError();
}
void glAttachRBOtoFBO ( GLenum target, eBlitFormatClass formatClass, uint rboName )
{
switch( formatClass )
{
case eColor:
glFramebufferRenderbufferEXT ( target, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, rboName); GLMCheckError();
break;
case eDepth:
glFramebufferRenderbufferEXT ( target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, rboName); GLMCheckError();
break;
case eDepthStencil:
glFramebufferRenderbufferEXT ( target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, rboName); GLMCheckError();
glFramebufferRenderbufferEXT ( target, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, rboName); GLMCheckError();
break;
}
}
void glAttachTex2DtoFBO ( GLenum target, eBlitFormatClass formatClass, uint texName, uint texMip )
{
switch( formatClass )
{
case eColor:
glFramebufferTexture2DEXT ( target, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texName, texMip ); GLMCheckError();
break;
case eDepth:
glFramebufferTexture2DEXT ( target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texName, texMip ); GLMCheckError();
break;
case eDepthStencil:
glFramebufferTexture2DEXT ( target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texName, texMip ); GLMCheckError();
glFramebufferTexture2DEXT ( target, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, texName, texMip ); GLMCheckError();
break;
}
}
//ConVar gl_can_resolve_flipped("gl_can_resolve_flipped", "0" );
int gl_can_resolve_flipped = 0;
//ConVar gl_cannot_resolve_flipped("gl_cannot_resolve_flipped", "0" );
int gl_cannot_resolve_flipped = 0;
// these are only consulted if the m_cant_resolve_scaled cap bool is false.
//ConVar gl_minify_resolve_mode("gl_minify_resolve_mode", "1" ); // if scaled resolve available, for downscaled resolve blits only (i.e. internal blits)
int gl_minify_resolve_mode = 1;
//ConVar gl_magnify_resolve_mode("gl_magnify_resolve_mode", "2" ); // if scaled resolve available, for upscaled resolve blits only
int gl_magnify_resolve_mode = 2;
// 0 == old style, two steps
// 1 == faster, one step blit aka XGL_SCALED_RESOLVE_FASTEST_EXT - if available.
// 2 == faster, one step blit aka XGL_SCALED_RESOLVE_NICEST_EXT - if available.
unsigned short foo[4];
void GLMContext::Blit2( CGLMTex *srcTex, GLMRect *srcRect, int srcFace, int srcMip, CGLMTex *dstTex, GLMRect *dstRect, int dstFace, int dstMip, uint filter )
{
Assert( srcFace == 0 );
Assert( dstFace == 0 );
// glColor4usv( foo );
//----------------------------------------------------------------- format assessment
eBlitFormatClass formatClass;
uint blitMask= 0;
switch( srcTex->m_layout->m_format->m_glDataFormat )
{
case GL_BGRA: case GL_RGB: case GL_RGBA: case GL_ALPHA: case GL_LUMINANCE: case GL_LUMINANCE_ALPHA:
formatClass = eColor;
blitMask = GL_COLOR_BUFFER_BIT;
break;
case GL_DEPTH_COMPONENT:
formatClass = eDepth;
blitMask = GL_DEPTH_BUFFER_BIT;
break;
case GL_DEPTH_STENCIL_EXT:
formatClass = eDepthStencil;
blitMask = GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
break;
default:
Assert(!"Unsupported format for blit" );
GLMStop();
break;
}
//----------------------------------------------------------------- blit assessment
bool blitResolves = srcTex->m_rboName != 0;
bool blitScales = ((srcRect->xmax - srcRect->xmin) != (dstRect->xmax - dstRect->xmin)) || ((srcRect->ymax - srcRect->ymin) != (dstRect->ymax - dstRect->ymin));
bool blitToBack = (dstTex == NULL);
bool blitFlips = blitToBack; // implicit y-flip upon blit to GL_BACK supplied
//should we support blitFromBack ?
bool srcGamma = srcTex && ((srcTex->m_layout->m_key.m_texFlags & kGLMTexSRGB) != 0);
bool dstGamma = dstTex && ((dstTex->m_layout->m_key.m_texFlags & kGLMTexSRGB) != 0);
bool doPushPop = (srcGamma != dstGamma) && gl_radar7954721_workaround_mixed/*.GetInt()*/ && m_caps.m_nv; // workaround for cross gamma blit problems on NV
// ^^ need to re-check this on some post-10.6.3 build on NV to see if it was fixed
if (doPushPop)
{
glPushAttrib( 0 );
}
//----------------------------------------------------------------- figure out the plan
bool blitTwoStep = false; // think positive
// each subsequent segment here can only set blitTwoStep, not clear it.
// the common case where these get hit is resolve out to presentation
// there may be GL extensions or driver revisions which start doing these safely.
// ideally many blits internally resolve without scaling and can thus go direct without using the scratch tex.
if (blitResolves && (blitFlips||blitToBack)) // flips, blit to back, same thing (for now)
{
if( gl_cannot_resolve_flipped/*.GetInt()*/ )
{
blitTwoStep = true;
}
else if (!gl_can_resolve_flipped/*.GetInt()*/)
{
blitTwoStep = blitTwoStep || m_caps.m_cantResolveFlipped; // if neither convar renders an opinion, fall back to the caps to decide if we have to two-step.
}
}
// only consider trying to use the scaling resolve filter,
// if we are confident we are not headed for two step mode already.
if (!blitTwoStep)
{
if (blitResolves && blitScales)
{
if (m_caps.m_cantResolveScaled)
{
// filter is unchanged, two step mode switches on
blitTwoStep = true;
}
else
{
bool blitScalesDown = ((srcRect->xmax - srcRect->xmin) > (dstRect->xmax - dstRect->xmin)) || ((srcRect->ymax - srcRect->ymin) > (dstRect->ymax - dstRect->ymin));
int mode = (blitScalesDown) ? gl_minify_resolve_mode/*.GetInt()*/ : gl_magnify_resolve_mode/*.GetInt()*/;
// roughly speaking, resolve blits that minify represent setup for special effects ("copy framebuffer to me")
// resolve blits that magnify are almost always on the final present in the case where remder size < display size
switch( mode )
{
case 0:
default:
// filter is unchanged, two step mode
blitTwoStep = true;
break;
case 1:
// filter goes to fastest, one step mode
blitTwoStep = false;
filter = XGL_SCALED_RESOLVE_FASTEST_EXT;
break;
case 2:
// filter goes to nicest, one step mode
blitTwoStep = false;
filter = XGL_SCALED_RESOLVE_NICEST_EXT;
break;
}
}
}
}
//----------------------------------------------------------------- save old scissor state and disable scissor
GLScissorEnable_t oldsciss,newsciss;
m_ScissorEnable.Read( &oldsciss, 0 );
// turn off scissor
newsciss.enable = false;
m_ScissorEnable.Write( &newsciss, true, true );
//----------------------------------------------------------------- fork in the road, depending on two-step or not
if (blitTwoStep)
{
// a resolve that can't be done directly due to constraints on scaling or flipping.
// bind scratch FBO0 to read, scrub it, attach RBO
BindFBOToCtx ( m_scratchFBO[0], GL_READ_FRAMEBUFFER_EXT ); GLMCheckError();
glScrubFBO ( GL_READ_FRAMEBUFFER_EXT );
glAttachRBOtoFBO ( GL_READ_FRAMEBUFFER_EXT, formatClass, srcTex->m_rboName );
// bind scratch FBO1 to write, scrub it, attach scratch tex
BindFBOToCtx ( m_scratchFBO[1], GL_DRAW_FRAMEBUFFER_EXT ); GLMCheckError();
glScrubFBO ( GL_DRAW_FRAMEBUFFER_EXT );
glAttachTex2DtoFBO ( GL_DRAW_FRAMEBUFFER_EXT, formatClass, srcTex->m_texName, 0 );
// set read and draw buffers appropriately
glReadBuffer ( glAttachFromClass[formatClass] );
glDrawBuffer ( glAttachFromClass[formatClass] );
// blit#1 - to resolve to scratch
// implicitly means no scaling, thus will be done with NEAREST sampling
GLenum resolveFilter = GL_NEAREST;
glBlitFramebufferEXT( 0, 0, srcTex->m_layout->m_key.m_xSize, srcTex->m_layout->m_key.m_ySize,
0, 0, srcTex->m_layout->m_key.m_xSize, srcTex->m_layout->m_key.m_ySize, // same source and dest rect, whole surface
blitMask, resolveFilter );
GLMCheckError();
// FBO1 now holds the interesting content.
// scrub FBO0, bind FBO1 to READ, fall through to next stage of blit where 1 goes onto 0 (or BACK)
glScrubFBO ( GL_READ_FRAMEBUFFER_EXT ); // zap FBO0
BindFBOToCtx ( m_scratchFBO[1], GL_READ_FRAMEBUFFER_EXT ); GLMCheckError();
}
else
{
// arrange source surface on FBO1 for blit directly to dest (which could be FBO0 or BACK)
BindFBOToCtx ( m_scratchFBO[1], GL_READ_FRAMEBUFFER_EXT ); GLMCheckError();
glScrubFBO ( GL_READ_FRAMEBUFFER_EXT );
if (blitResolves)
{
glAttachRBOtoFBO( GL_READ_FRAMEBUFFER_EXT, formatClass, srcTex->m_rboName );
}
else
{
glAttachTex2DtoFBO( GL_READ_FRAMEBUFFER_EXT, formatClass, srcTex->m_texName, srcMip );
}
glReadBuffer( glAttachFromClass[formatClass] );
}
//----------------------------------------------------------------- zero or one blits may have happened above, whichever took place, FBO1 is now on read
bool yflip = false;
if (blitToBack)
{
// backbuffer is special - FBO0 is left out (either scrubbed already, or not used)
BindFBOToCtx ( NULL, GL_DRAW_FRAMEBUFFER_EXT ); GLMCheckError();
glDrawBuffer ( GL_BACK ); GLMCheckError();
yflip = true;
}
else
{
// not going to GL_BACK - use FBO0. set up dest tex or RBO on it. i.e. it's OK to blit from MSAA to MSAA if needed, though unlikely.
Assert( dstTex != NULL );
BindFBOToCtx ( m_scratchFBO[0], GL_DRAW_FRAMEBUFFER_EXT ); GLMCheckError();
glScrubFBO ( GL_DRAW_FRAMEBUFFER_EXT );
if (dstTex->m_rboName)
{
glAttachRBOtoFBO( GL_DRAW_FRAMEBUFFER_EXT, formatClass, dstTex->m_rboName );
}
else
{
glAttachTex2DtoFBO( GL_DRAW_FRAMEBUFFER_EXT, formatClass, dstTex->m_texName, dstMip );
}
glDrawBuffer ( glAttachFromClass[formatClass] ); GLMCheckError();
}
// final blit
// i think in general, if we are blitting same size, gl_nearest is the right filter to pass.
// this re-steering won't kick in if there is scaling or a special scaled resolve going on.
if (!blitScales)
{
// steer it
filter = GL_NEAREST;
}
// this is blit #1 or #2 depending on what took place above.
if (yflip)
{
glBlitFramebufferEXT( srcRect->xmin, srcRect->ymin, srcRect->xmax, srcRect->ymax,
dstRect->xmin, dstRect->ymax, dstRect->xmax, dstRect->ymin, // note dest Y's are flipped
blitMask, filter );
}
else
{
glBlitFramebufferEXT( srcRect->xmin, srcRect->ymin, srcRect->xmax, srcRect->ymax,
dstRect->xmin, dstRect->ymin, dstRect->xmax, dstRect->ymax,
blitMask, filter );
}
GLMCheckError();
//----------------------------------------------------------------- scrub READ and maybe DRAW FBO, and unbind
glScrubFBO ( GL_READ_FRAMEBUFFER_EXT );
BindFBOToCtx ( NULL, GL_READ_FRAMEBUFFER_EXT ); GLMCheckError();
if (!blitToBack)
{
glScrubFBO ( GL_DRAW_FRAMEBUFFER_EXT );
BindFBOToCtx ( NULL, GL_DRAW_FRAMEBUFFER_EXT ); GLMCheckError();
}
//----------------------------------------------------------------- restore GLM's drawing FBO
// restore GLM drawing FBO
BindFBOToCtx( m_drawingFBO, GL_READ_FRAMEBUFFER_EXT ); GLMCheckError();
BindFBOToCtx( m_drawingFBO, GL_DRAW_FRAMEBUFFER_EXT ); GLMCheckError();
if (doPushPop)
{
glPopAttrib( );
}
//----------------------------------------------------------------- restore old scissor state
m_ScissorEnable.Write( &oldsciss, true, true );
}
void GLMContext::BlitTex( CGLMTex *srcTex, GLMRect *srcRect, int srcFace, int srcMip, CGLMTex *dstTex, GLMRect *dstRect, int dstFace, int dstMip, GLenum filter, bool useBlitFB )
{
switch( srcTex->m_layout->m_format->m_glDataFormat )
{
case GL_BGRA:
case GL_RGB:
case GL_RGBA:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
#if 0
if (GLMKnob("caps-key",NULL) > 0.0)
{
useBlitFB = false;
}
#endif
if ( m_caps.m_cantBlitReliably ) // this is referring to a problem with the x3100..
{
useBlitFB = false;
}
break;
}
if (0)
{
GLMPRINTF(("-D- Blit from %d %d %d %d to %d %d %d %d",
srcRect->xmin, srcRect->ymin, srcRect->xmax, srcRect->ymax,
dstRect->xmin, dstRect->ymin, dstRect->xmax, dstRect->ymax
));
GLMPRINTF(( "-D- src tex layout is %s", srcTex->m_layout->m_layoutSummary ));
GLMPRINTF(( "-D- dst tex layout is %s", dstTex->m_layout->m_layoutSummary ));
}
int pushed = 0;
uint pushmask = gl_radar7954721_workaround_maskval/*.GetInt()*/;
//GL_COLOR_BUFFER_BIT
//| GL_CURRENT_BIT
//| GL_ENABLE_BIT
//| GL_FOG_BIT
//| GL_PIXEL_MODE_BIT
//| GL_SCISSOR_BIT
//| GL_STENCIL_BUFFER_BIT
//| GL_TEXTURE_BIT
//GL_VIEWPORT_BIT
//;
if (gl_radar7954721_workaround_all/*.GetInt()*/!=0)
{
glPushAttrib( pushmask );
pushed++;
}
else
{
bool srcGamma = (srcTex->m_layout->m_key.m_texFlags & kGLMTexSRGB) != 0;
bool dstGamma = (dstTex->m_layout->m_key.m_texFlags & kGLMTexSRGB) != 0;
if (srcGamma != dstGamma)
{
if (gl_radar7954721_workaround_mixed/*.GetInt()*/)
{
glPushAttrib( pushmask );
pushed++;
}
}
}
if (useBlitFB)
{
// state we need to save
// current setting of scissor
// current setting of the drawing fbo (no explicit save, it's in the context)
GLScissorEnable_t oldsciss,newsciss;
m_ScissorEnable.Read( &oldsciss, 0 );
// remember to restore m_drawingFBO at end of effort
// setup
// turn off scissor
newsciss.enable = false;
m_ScissorEnable.Write( &newsciss, true, true );
// select which attachment enum we're going to use for the blit
// default to color0, unless it's a depth or stencil flava
Assert( srcTex->m_layout->m_format->m_glDataFormat == dstTex->m_layout->m_format->m_glDataFormat );
EGLMFBOAttachment attachIndex = (EGLMFBOAttachment)0;
GLenum attachIndexGL = 0;
GLuint blitMask = 0;
switch( srcTex->m_layout->m_format->m_glDataFormat )
{
case GL_BGRA:
case GL_RGB:
case GL_RGBA:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
attachIndex = kAttColor0;
attachIndexGL = GL_COLOR_ATTACHMENT0_EXT;
blitMask = GL_COLOR_BUFFER_BIT;
break;
case GL_DEPTH_COMPONENT:
attachIndex = kAttDepth;
attachIndexGL = GL_DEPTH_ATTACHMENT_EXT;
blitMask = GL_DEPTH_BUFFER_BIT;
break;
case GL_DEPTH_STENCIL_EXT:
attachIndex = kAttDepthStencil;
attachIndexGL = GL_DEPTH_STENCIL_ATTACHMENT_EXT;
blitMask = GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
break;
default:
Assert(0);
break;
}
// set the read fb, attach read tex at appropriate attach point, set read buffer
BindFBOToCtx( m_blitReadFBO, GL_READ_FRAMEBUFFER_EXT );
GLMCheckError();
GLMFBOTexAttachParams attparams;
attparams.m_tex = srcTex;
attparams.m_face = srcFace;
attparams.m_mip = srcMip;
attparams.m_zslice = 0;
m_blitReadFBO->TexAttach( &attparams, attachIndex, GL_READ_FRAMEBUFFER_EXT );
GLMCheckError();
glReadBuffer( attachIndexGL );
GLMCheckError();
// set the write fb and buffer, and attach write tex
BindFBOToCtx( m_blitDrawFBO, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
attparams.m_tex = dstTex;
attparams.m_face = dstFace;
attparams.m_mip = dstMip;
attparams.m_zslice = 0;
m_blitDrawFBO->TexAttach( &attparams, attachIndex, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
glDrawBuffer( attachIndexGL );
GLMCheckError();
// do the blit
glBlitFramebufferEXT( srcRect->xmin, srcRect->ymin, srcRect->xmax, srcRect->ymax,
dstRect->xmin, dstRect->ymin, dstRect->xmax, dstRect->ymax,
blitMask, filter );
GLMCheckError();
// cleanup
// unset the read fb and buffer, detach read tex
// unset the write fb and buffer, detach write tex
m_blitReadFBO->TexDetach( attachIndex, GL_READ_FRAMEBUFFER_EXT );
GLMCheckError();
m_blitDrawFBO->TexDetach( attachIndex, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
// put the original FB back in place (both read and draw)
// this bind will hit both read and draw bindings
BindFBOToCtx( m_drawingFBO, GL_READ_FRAMEBUFFER_EXT );
GLMCheckError();
BindFBOToCtx( m_drawingFBO, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
// set the read and write buffers back to... what ? does it matter for anything but copies ? don't worry about it
// restore the scissor state
m_ScissorEnable.Write( &oldsciss, true, true );
}
else
{
// textured quad style
// we must attach the dest tex as the color buffer on the blit draw FBO
// so that means we need to re-set the drawing FBO on exit
EGLMFBOAttachment attachIndex = (EGLMFBOAttachment)0;
GLenum attachIndexGL = 0;
switch( srcTex->m_layout->m_format->m_glDataFormat )
{
case GL_BGRA:
case GL_RGB:
case GL_RGBA:
case GL_ALPHA:
case GL_LUMINANCE:
case GL_LUMINANCE_ALPHA:
attachIndex = kAttColor0;
attachIndexGL = GL_COLOR_ATTACHMENT0_EXT;
break;
default:
Assert(!"Can't blit that format");
break;
}
BindFBOToCtx( m_blitDrawFBO, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
GLMFBOTexAttachParams attparams;
attparams.m_tex = dstTex;
attparams.m_face = dstFace;
attparams.m_mip = dstMip;
attparams.m_zslice = 0;
m_blitDrawFBO->TexAttach( &attparams, attachIndex, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
glDrawBuffer( attachIndexGL );
GLMCheckError();
// attempt to just set states directly the way we want them, then use the latched states to repair them afterward.
this->NullProgram(); // out of program mode
glDisable ( GL_ALPHA_TEST );
glDisable ( GL_CULL_FACE );
glDisable ( GL_POLYGON_OFFSET_FILL );
glDisable ( GL_SCISSOR_TEST );
glDisable ( GL_CLIP_PLANE0 );
glDisable ( GL_CLIP_PLANE1 );
glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE );
glDisable ( GL_BLEND );
glDepthMask ( GL_FALSE );
glDisable ( GL_DEPTH_TEST );
glDisable ( GL_STENCIL_TEST );
glStencilMask ( GL_FALSE );
GLMCheckError();
// now do the unlit textured quad...
glActiveTexture( GL_TEXTURE0 );
glBindTexture( GL_TEXTURE_2D, srcTex->m_texName );
GLMCheckError();
glEnable(GL_TEXTURE_2D);
GLMCheckError();
// immediate mode is fine
float topv = 1.0;
float botv = 0.0;
glBegin(GL_QUADS);
glTexCoord2f ( 0.0, botv );
glVertex3f ( -1.0, -1.0, 0.0 );
glTexCoord2f ( 1.0, botv );
glVertex3f ( 1.0, -1.0, 0.0 );
glTexCoord2f ( 1.0, topv );
glVertex3f ( 1.0, 1.0, 0.0 );
glTexCoord2f ( 0.0, topv );
glVertex3f ( -1.0, 1.0, 0.0 );
glEnd();
GLMCheckError();
glBindTexture( GL_TEXTURE_2D, 0 );
GLMCheckError();
glDisable(GL_TEXTURE_2D);
GLMCheckError();
// invalidate tex binding 0 so it gets reset
m_samplers[0].m_boundTex = NULL;
// leave active program empty - flush draw states will fix
// then restore states using the scoreboard
m_AlphaTestEnable.Flush( true );
m_AlphaToCoverageEnable.Flush( true );
m_CullFaceEnable.Flush( true );
m_DepthBias.Flush( true );
m_ScissorEnable.Flush( true );
m_ClipPlaneEnable.FlushIndex( 0, true );
m_ClipPlaneEnable.FlushIndex( 1, true );
m_ColorMaskSingle.Flush( true );
m_BlendEnable.Flush( true );
m_DepthMask.Flush( true );
m_DepthTestEnable.Flush( true );
m_StencilWriteMask.Flush( true );
m_StencilTestEnable.Flush( true );
// unset the write fb and buffer, detach write tex
m_blitDrawFBO->TexDetach( attachIndex, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
// put the original FB back in place (both read and draw)
BindFBOToCtx( m_drawingFBO, GL_READ_FRAMEBUFFER_EXT );
GLMCheckError();
BindFBOToCtx( m_drawingFBO, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
}
while(pushed)
{
glPopAttrib();
pushed--;
}
}
void GLMContext::ResolveTex( CGLMTex *tex, bool forceDirty )
{
// only run resolve if it's (a) possible and (b) dirty or force-dirtied
if ( (tex->m_rboName) && ((tex->m_rboDirty)||forceDirty) )
{
// state we need to save
// current setting of scissor
// current setting of the drawing fbo (no explicit save, it's in the context)
GLScissorEnable_t oldsciss,newsciss;
m_ScissorEnable.Read( &oldsciss, 0 );
// remember to restore m_drawingFBO at end of effort
// setup
// turn off scissor
newsciss.enable = false;
m_ScissorEnable.Write( &newsciss, true, true );
// select which attachment enum we're going to use for the blit
// default to color0, unless it's a depth or stencil flava
// for resolve, only handle a modest subset of the possible formats
EGLMFBOAttachment attachIndex = (EGLMFBOAttachment)0;
GLenum attachIndexGL = 0;
GLuint blitMask = 0;
switch( tex->m_layout->m_format->m_glDataFormat )
{
case GL_BGRA:
case GL_RGB:
case GL_RGBA:
// case GL_ALPHA:
// case GL_LUMINANCE:
// case GL_LUMINANCE_ALPHA:
attachIndex = kAttColor0;
attachIndexGL = GL_COLOR_ATTACHMENT0_EXT;
blitMask = GL_COLOR_BUFFER_BIT;
break;
// case GL_DEPTH_COMPONENT:
// attachIndex = kAttDepth;
// attachIndexGL = GL_DEPTH_ATTACHMENT_EXT;
// blitMask = GL_DEPTH_BUFFER_BIT;
// break;
case GL_DEPTH_STENCIL_EXT:
attachIndex = kAttDepthStencil;
attachIndexGL = GL_DEPTH_STENCIL_ATTACHMENT_EXT;
blitMask = GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
break;
default:
Assert(!"Unsupported format for MSAA resolve" );
break;
}
// set the read fb, attach read RBO at appropriate attach point, set read buffer
BindFBOToCtx( m_blitReadFBO, GL_READ_FRAMEBUFFER_EXT );
GLMCheckError();
// going to avoid the TexAttach / TexDetach calls due to potential confusion, implement it directly here
//-----------------------------------------------------------------------------------
// put tex->m_rboName on the read FB's attachment
if (attachIndexGL==GL_DEPTH_STENCIL_ATTACHMENT_EXT)
{
// you have to attach it both places...
// http://www.opengl.org/wiki/GL_EXT_framebuffer_object
// bind the RBO to the GL_RENDERBUFFER_EXT target - is this extraneous ?
//glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, tex->m_rboName );
//GLMCheckError();
// attach the GL_RENDERBUFFER_EXT target to the depth and stencil attach points
glFramebufferRenderbufferEXT( GL_READ_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, tex->m_rboName);
GLMCheckError();
glFramebufferRenderbufferEXT( GL_READ_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, tex->m_rboName);
GLMCheckError();
// no need to leave the RBO hanging on
//glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0 );
//GLMCheckError();
}
else
{
//glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, tex->m_rboName );
//GLMCheckError();
glFramebufferRenderbufferEXT( GL_READ_FRAMEBUFFER_EXT, attachIndexGL, GL_RENDERBUFFER_EXT, tex->m_rboName);
GLMCheckError();
//glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0 );
//GLMCheckError();
}
glReadBuffer( attachIndexGL );
GLMCheckError();
//-----------------------------------------------------------------------------------
// put tex->m_texName on the draw FBO attachment
// set the write fb and buffer, and attach write tex
BindFBOToCtx( m_blitDrawFBO, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
// regular path - attaching a texture2d
if (attachIndexGL==GL_DEPTH_STENCIL_ATTACHMENT_EXT)
{
glFramebufferTexture2DEXT( GL_DRAW_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, tex->m_texName, 0 );
GLMCheckError();
glFramebufferTexture2DEXT( GL_DRAW_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, tex->m_texName, 0 );
GLMCheckError();
}
else
{
glFramebufferTexture2DEXT( GL_DRAW_FRAMEBUFFER_EXT, attachIndexGL, GL_TEXTURE_2D, tex->m_texName, 0 );
GLMCheckError();
}
glDrawBuffer( attachIndexGL );
GLMCheckError();
//-----------------------------------------------------------------------------------
// blit
glBlitFramebufferEXT( 0, 0, tex->m_layout->m_key.m_xSize, tex->m_layout->m_key.m_ySize,
0, 0, tex->m_layout->m_key.m_xSize, tex->m_layout->m_key.m_ySize,
blitMask, GL_NEAREST );
// or should it be GL_LINEAR? does it matter ?
GLMCheckError();
//-----------------------------------------------------------------------------------
// cleanup
//-----------------------------------------------------------------------------------
// unset the read fb and buffer, detach read RBO
//glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0 );
//GLMCheckError();
if (attachIndexGL==GL_DEPTH_STENCIL_ATTACHMENT_EXT)
{
// detach the GL_RENDERBUFFER_EXT target from the depth and stencil attach points
glFramebufferRenderbufferEXT( GL_READ_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
GLMCheckError();
glFramebufferRenderbufferEXT( GL_READ_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
GLMCheckError();
}
else
{
glFramebufferRenderbufferEXT( GL_READ_FRAMEBUFFER_EXT, attachIndexGL, GL_RENDERBUFFER_EXT, 0);
GLMCheckError();
}
//-----------------------------------------------------------------------------------
// unset the write fb and buffer, detach write tex
if (attachIndexGL==GL_DEPTH_STENCIL_ATTACHMENT_EXT)
{
glFramebufferTexture2DEXT( GL_DRAW_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0 );
GLMCheckError();
glFramebufferTexture2DEXT( GL_DRAW_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0 );
GLMCheckError();
}
else
{
glFramebufferTexture2DEXT( GL_DRAW_FRAMEBUFFER_EXT, attachIndexGL, GL_TEXTURE_2D, 0, 0 );
GLMCheckError();
}
// put the original FB back in place (both read and draw)
// this bind will hit both read and draw bindings
BindFBOToCtx( m_drawingFBO, GL_READ_FRAMEBUFFER_EXT );
GLMCheckError();
BindFBOToCtx( m_drawingFBO, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
// set the read and write buffers back to... what ? does it matter for anything but copies ? don't worry about it
// restore the scissor state
m_ScissorEnable.Write( &oldsciss, true, true );
// mark the RBO clean on the resolved tex
tex->m_rboDirty = false;
}
}
void GLMContext::PreloadTex( CGLMTex *tex, bool force )
{
#if 0 // disabled in sample for time being
// if conditions allow (i.e. a drawing surface is active)
// bind the texture on TMU 15
// set up a dummy program to sample it but not write (use 'discard')
// draw a teeny little triangle that won't generate a lot of fragments
if (!m_pairCache)
return;
if (!m_drawingFBO)
return;
if (!m_drawingFBO)
return;
if (tex->m_texPreloaded && !force) // only do one preload unless forced to re-do
{
//printf("\nnot-preloading %s", tex->m_debugLabel ? tex->m_debugLabel : "(unknown)");
return;
}
//printf("\npreloading %s", tex->m_debugLabel ? tex->m_debugLabel : "(unknown)");
CGLMProgram *vp = m_preloadTexVertexProgram;
CGLMProgram *fp = NULL;
switch(tex->m_layout->m_key.m_texGLTarget)
{
case GL_TEXTURE_2D: fp = m_preload2DTexFragmentProgram;
break;
case GL_TEXTURE_3D: fp = m_preload3DTexFragmentProgram;
break;
case GL_TEXTURE_CUBE_MAP: fp = m_preloadCubeTexFragmentProgram;
break;
}
if (!fp)
return;
CGLMShaderPair *preloadPair = m_pairCache->SelectShaderPair( vp, fp, 0 );
if (!preloadPair)
return;
GLhandleARB pairProgram = preloadPair->m_program;
uint pairRevision = preloadPair->m_revision;
m_boundPair = preloadPair;
m_boundPairProgram = pairProgram;
m_boundPairRevision = pairRevision;
glUseProgram( (GLuint)pairProgram );
GLMCheckError();
// note the binding (not really bound.. just sitting in the linked active GLSL program)
m_boundProgram[ kGLMVertexProgram ] = vp;
m_boundProgram[ kGLMFragmentProgram ] = fp;
// almost ready to draw...
int tmuForPreload = 15;
if(!m_boundPair->m_samplersFixed)
{
if (m_boundPair->m_locSamplers[tmuForPreload] >=0)
{
glUniform1iARB( m_boundPair->m_locSamplers[tmuForPreload], tmuForPreload );
GLMCheckError();
}
m_boundPair->m_samplersFixed = true;
}
// shut down all the generic attribute arrays on the detention level - next real draw will activate them again
m_lastKnownVertexAttribMask = 0;
for( int index=0; index < kGLMVertexAttributeIndexMax; index++ )
{
glDisableVertexAttribArray( index );
GLMCheckError();
}
// bind texture
this->BindTexToTMU( tex, 15 );
// unbind vertex/index buffers
this->BindBufferToCtx( kGLMVertexBuffer, NULL );
this->BindBufferToCtx( kGLMIndexBuffer, NULL );
// draw
static float posns[] = { 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f };
static int indices[] = { 0, 1, 2 };
glEnableVertexAttribArray( 0 );
GLMCheckError();
glVertexAttribPointer( 0, 3, GL_FLOAT, 0, 0, posns );
GLMCheckError();
glDrawRangeElements( GL_TRIANGLES, 0, 3, 3, GL_UNSIGNED_INT, indices);
GLMCheckError();
glDisableVertexAttribArray( 0 );
GLMCheckError();
m_lastKnownVertexAttribMask = 0;
m_lastKnownVertexAttribs[0].m_bufferRevision -= 1; // force mismatch so next FlushDrawStates restores the right attrib source
this->BindTexToTMU( NULL, 15 );
tex->m_texPreloaded = true;
#endif
}
void GLMContext::SetSamplerTex( int sampler, CGLMTex *tex )
{
GLM_FUNC;
CheckCurrent();
m_samplers[sampler].m_drawTex = tex;
}
void GLMContext::SetSamplerParams( int sampler, GLMTexSamplingParams *params )
{
GLM_FUNC;
CheckCurrent();
m_samplers[sampler].m_samp = *params;
}
CGLMFBO *GLMContext::NewFBO( void )
{
GLM_FUNC;
MakeCurrent();
CGLMFBO *fbo = new CGLMFBO( this );
m_fboTable.push_back( fbo );
return fbo;
}
void GLMContext::DelFBO( CGLMFBO *fbo )
{
GLM_FUNC;
MakeCurrent();
if (m_drawingFBO == fbo)
{
m_drawingFBO = NULL; //poof!
}
if (m_boundReadFBO == fbo )
{
this->BindFBOToCtx( NULL, GL_READ_FRAMEBUFFER_EXT );
m_boundReadFBO = NULL;
}
if (m_boundDrawFBO == fbo )
{
this->BindFBOToCtx( NULL, GL_DRAW_FRAMEBUFFER_EXT );
m_boundDrawFBO = NULL;
}
std::vector< CGLMFBO * >::iterator p = find( m_fboTable.begin(), m_fboTable.end(), fbo );
if (p != m_fboTable.end() )
{
m_fboTable.erase( p );
}
delete fbo;
}
void GLMContext::SetDrawingFBO( CGLMFBO *fbo )
{
GLM_FUNC;
CheckCurrent();
// might want to validate that fbo object?
m_drawingFBO = fbo;
}
//===============================================================================
CGLMProgram *GLMContext::NewProgram( EGLMProgramType type, char *progString )
{
//hushed GLM_FUNC;
MakeCurrent();
CGLMProgram *prog = new CGLMProgram( this, type );
prog->SetProgramText( progString );
bool compile_ok = prog->CompileActiveSources();
//AssertOnce( compile_ok );
return prog;
}
void GLMContext::DelProgram( CGLMProgram *prog )
{
GLM_FUNC;
this->MakeCurrent();
if (m_drawingProgram[ prog->m_type ] == prog)
{
m_drawingProgram[ prog->m_type ] = NULL;
}
// make sure to eliminate any cached pairs using this shader
bool purgeResult = m_pairCache->PurgePairsWithShader( prog );
Assert( !purgeResult ); // very unlikely to trigger
this->NullProgram();
delete prog;
}
void GLMContext::NullProgram( void )
{
// just unbind everything on a prog delete
glSetEnable( GL_VERTEX_PROGRAM_ARB, false );
glSetEnable( GL_FRAGMENT_PROGRAM_ARB, false );
glBindProgramARB( GL_VERTEX_PROGRAM_ARB, 0 );
glBindProgramARB( GL_FRAGMENT_PROGRAM_ARB, 0 );
glUseProgram( 0 );
m_boundPair = NULL;
m_boundPairRevision = 0xFFFFFFFF;
m_boundPairProgram = (GLhandleARB)0xFFFFFFFF;
m_boundProgram[ kGLMVertexProgram ] = NULL;
m_boundProgram[ kGLMFragmentProgram ] = NULL;
}
void GLMContext::SetDrawingProgram( EGLMProgramType type, CGLMProgram *prog )
{
GLM_FUNC;
this->MakeCurrent();
if (prog) // OK to pass NULL..
{
if (type != prog->m_type)
{
Debugger();
}
}
else
{
// if a null fragment program is passed, we activate our special null program
// thus FP is always always enabled.
if (type==kGLMFragmentProgram)
{
prog = m_nullFragmentProgram;
}
else
{
//Assert(!"Tried to set NULL vertex program");
}
}
m_drawingProgram[type] = prog;
}
void GLMContext::SetDrawingLang( EGLMProgramLang lang, bool immediate )
{
if ( !m_caps.m_hasDualShaders ) return; // ignore attempts to change language when -glmdualshaders is not engaged
m_drawingLangAtFrameStart = lang;
if (immediate)
{
this->NullProgram();
m_drawingLang = m_drawingLangAtFrameStart;
}
}
void GLMContext::LinkShaderPair( CGLMProgram *vp, CGLMProgram *fp )
{
if ( (m_pairCache) && (m_drawingLang==kGLMGLSL) && (vp && vp->m_descs[kGLMGLSL].m_valid) && (fp && fp->m_descs[kGLMGLSL].m_valid) )
{
CGLMShaderPair *pair = m_pairCache->SelectShaderPair( vp, fp, 0 );
Assert( pair != NULL );
this->NullProgram(); // clear out any binds that were done - next draw will set it right
}
}
void GLMContext::ClearShaderPairCache( void )
{
if (m_pairCache)
{
this->NullProgram();
m_pairCache->Purge(); // bye bye all linked pairs
this->NullProgram();
}
}
void GLMContext::QueryShaderPair( int index, GLMShaderPairInfo *infoOut )
{
if (m_pairCache)
{
m_pairCache->QueryShaderPair( index, infoOut );
}
else
{
memset( infoOut, sizeof( *infoOut ), 0 );
infoOut->m_status = -1;
}
}
void GLMContext::SetProgramParametersF( EGLMProgramType type, uint baseSlot, float *slotData, uint slotCount )
{
GLM_FUNC;
Assert( baseSlot < kGLMProgramParamFloat4Limit );
Assert( baseSlot+slotCount <= kGLMProgramParamFloat4Limit );
GLMPRINTF(("-S-GLMContext::SetProgramParametersF %s slots %d - %d: ", (type==kGLMVertexProgram) ? "VS" : "FS", baseSlot, baseSlot + slotCount - 1 ));
for( int i=0; i<slotCount; i++ )
{
GLMPRINTF(( "-S- %03d: [ %7.4f %7.4f %7.4f %7.4f ]",
baseSlot+i,
slotData[i*4], slotData[i*4+1], slotData[i*4+2], slotData[i*4+3]
));
}
// copy to mirror
// actual delivery happens in FlushDrawStates now
memcpy( &m_programParamsF[type].m_values[baseSlot][0], slotData, (4 * sizeof(float)) * slotCount );
// adjust dirty count
if ( (baseSlot+slotCount) > m_programParamsF[type].m_dirtySlotCount)
{
m_programParamsF[type].m_dirtySlotCount = baseSlot+slotCount;
}
}
void GLMContext::SetProgramParametersB( EGLMProgramType type, uint baseSlot, int *slotData, uint boolCount )
{
GLM_FUNC;
Assert( m_drawingLang == kGLMGLSL );
Assert( type==kGLMVertexProgram );
Assert( baseSlot < kGLMProgramParamBoolLimit );
Assert( baseSlot+boolCount <= kGLMProgramParamBoolLimit );
GLMPRINTF(("-S-GLMContext::SetProgramParametersB %s bools %d - %d: ", (type==kGLMVertexProgram) ? "VS" : "FS", baseSlot, baseSlot + boolCount - 1 ));
for( int i=0; i<boolCount; i++ )
{
GLMPRINTF(( "-S- %03d: %d (bool)",
baseSlot+i,
slotData[i]
));
}
// copy to mirror
// actual delivery happens in FlushDrawStates now
memcpy( &m_programParamsB[type].m_values[baseSlot], slotData, sizeof(int) * boolCount );
// adjust dirty count
if ( (baseSlot+boolCount) > m_programParamsB[type].m_dirtySlotCount)
{
m_programParamsB[type].m_dirtySlotCount = baseSlot+boolCount;
}
}
void GLMContext::SetProgramParametersI( EGLMProgramType type, uint baseSlot, int *slotData, uint slotCount ) // groups of 4 ints...
{
GLM_FUNC;
Assert( m_drawingLang == kGLMGLSL );
Assert( type==kGLMVertexProgram );
Assert( baseSlot < kGLMProgramParamInt4Limit );
Assert( baseSlot+slotCount <= kGLMProgramParamInt4Limit );
GLMPRINTF(("-S-GLMContext::SetProgramParametersI %s slots %d - %d: ", (type==kGLMVertexProgram) ? "VS" : "FS", baseSlot, baseSlot + slotCount - 1 ));
for( int i=0; i<slotCount; i++ )
{
GLMPRINTF(( "-S- %03d: %d %d %d %d (int4)",
baseSlot+i,
slotData[i*4],slotData[i*4+1],slotData[i*4+2],slotData[i*4+3]
));
}
// copy to mirror
// actual delivery happens in FlushDrawStates now
memcpy( &m_programParamsI[type].m_values[baseSlot][0], slotData, (4*sizeof(int)) * slotCount );
// adjust dirty count
if ( (baseSlot+slotCount) > m_programParamsI[type].m_dirtySlotCount)
{
m_programParamsI[type].m_dirtySlotCount = baseSlot+slotCount;
}
}
CGLMBuffer *GLMContext::NewBuffer( EGLMBufferType type, uint size, uint options )
{
//hushed GLM_FUNC;
MakeCurrent();
CGLMBuffer *prog = new CGLMBuffer( this, type, size, options );
return prog;
}
void GLMContext::DelBuffer( CGLMBuffer *buff )
{
GLM_FUNC;
this->MakeCurrent();
for( int index=0; index < kGLMVertexAttributeIndexMax; index++ )
{
if (m_drawVertexSetup.m_attrs[index].m_buffer == buff)
{
// just clear the enable mask - this will force all the attrs to get re-sent on next sync
m_drawVertexSetup.m_attrMask = 0;
}
}
if (m_drawIndexBuffer == buff)
{
m_drawIndexBuffer = NULL;
}
if (m_lastKnownBufferBinds[ buff->m_type ] == buff)
{
// shoot it down
this->BindBufferToCtx( buff->m_type, NULL );
m_lastKnownBufferBinds[ buff->m_type ] = NULL;
}
delete buff;
}
void GLMContext::SetIndexBuffer( CGLMBuffer *buff )
{
GLM_FUNC;
CheckCurrent();
m_drawIndexBuffer = buff;
// draw time is welcome to re-check, but we bind it immediately.
this->BindBufferToCtx( kGLMIndexBuffer, buff );
}
GLMVertexSetup g_blank_setup;
void GLMContext::SetVertexAttributes( GLMVertexSetup *setup )
{
GLM_FUNC;
// we now just latch the vert setup and then execute on it at flushdrawstatestime if shaders are enabled.
if (setup)
{
m_drawVertexSetup = *setup;
}
else
{
memset( &m_drawVertexSetup, 0, sizeof(m_drawVertexSetup) );
}
return;
}
void GLMContext::Clear( bool color, unsigned long colorValue, bool depth, float depthValue, bool stencil, unsigned int stencilValue, GLScissorBox_t *box )
{
GLM_FUNC;
m_debugBatchIndex++; // clears are batches too (maybe blits should be also...)
#if GLMDEBUG
GLMDebugHookInfo info;
memset( &info, 0, sizeof(info) );
info.m_caller = eClear;
do
{
#endif
uint mask = 0;
GLClearColor_t clearcol;
GLClearDepth_t cleardep = { depthValue };
GLClearStencil_t clearsten = { (GLint)stencilValue };
// depth write mask must be saved&restored
GLDepthMask_t olddepthmask;
GLDepthMask_t newdepthmask = { true };
// stencil write mask must be saved and restored
GLStencilWriteMask_t oldstenmask;
GLStencilWriteMask_t newstenmask = { ~(GLint)0 };
GLColorMaskSingle_t oldcolormask;
GLColorMaskSingle_t newcolormask = { -1,-1,-1,-1 }; // D3D clears do not honor color mask, so force it
if (color)
{
// #define D3DCOLOR_ARGB(a,r,g,b) ((D3DCOLOR)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff)))
clearcol.r = ((colorValue >> 16) & 0xFF) / 255.0f; //R
clearcol.g = ((colorValue >> 8) & 0xFF) / 255.0f; //G
clearcol.b = ((colorValue ) & 0xFF) / 255.0f; //B
clearcol.a = ((colorValue >> 24) & 0xFF) / 255.0f; //A
m_ClearColor.Write( &clearcol, true, true ); // no check, no wait
mask |= GL_COLOR_BUFFER_BIT;
// save and set color mask
m_ColorMaskSingle.Read( &oldcolormask, 0 );
m_ColorMaskSingle.Write( &newcolormask, true, true );
}
if (depth)
{
// get old depth write mask
m_DepthMask.Read( &olddepthmask, 0 );
m_DepthMask.Write( &newdepthmask, true, true );
m_ClearDepth.Write( &cleardep, true, true ); // no check, no wait
mask |= GL_DEPTH_BUFFER_BIT;
}
if (stencil)
{
m_ClearStencil.Write( &clearsten, true, true ); // no check, no wait
mask |= GL_STENCIL_BUFFER_BIT;
// save and set sten mask
m_StencilWriteMask.Read( &oldstenmask, 0 );
m_StencilWriteMask.Write( &newstenmask, true, true );
}
bool subrect = (box != NULL);
GLScissorEnable_t scissorEnableSave;
GLScissorEnable_t scissorEnableNew = { true };
GLScissorBox_t scissorBoxSave;
GLScissorBox_t scissorBoxNew;
if (subrect)
{
// save current scissorbox and enable
m_ScissorEnable.Read( &scissorEnableSave, 0 );
m_ScissorBox.Read( &scissorBoxSave, 0 );
if(0)
{
// calc new scissorbox as intersection against *box
// max of the mins
scissorBoxNew.x = std::max(scissorBoxSave.x, box->x);
scissorBoxNew.y = std::max(scissorBoxSave.y, box->y);
// min of the maxes
scissorBoxNew.width = ( std::min(scissorBoxSave.x+scissorBoxSave.width, box->x+box->width)) - scissorBoxNew.x;
// height is just min of the max y's, minus the new base Y
scissorBoxNew.height = ( std::min(scissorBoxSave.y+scissorBoxSave.height, box->y+box->height)) - scissorBoxNew.y;
}
else
{
// ignore old scissor box completely.
scissorBoxNew = *box;
}
// set new box and enable
m_ScissorEnable.Write( &scissorEnableNew, true, true );
m_ScissorBox.Write( &scissorBoxNew, true, true );
}
glClear( mask );
if (subrect)
{
// put old scissor box and enable back
m_ScissorEnable.Write( &scissorEnableSave, true, true );
m_ScissorBox.Write( &scissorBoxSave, true, true );
}
if (depth)
{
// put old depth write mask
m_DepthMask.Write( &olddepthmask );
}
if (color)
{
// put old color write mask
m_ColorMaskSingle.Write( &oldcolormask, true, true );
}
if (stencil)
{
// put old sten mask
m_StencilWriteMask.Write( &oldstenmask, true, true );
}
#if GLMDEBUG
this->DebugHook( &info );
} while (info.m_loop);
#endif
}
// stolen from glmgrbasics.cpp
extern "C" uint GetCurrentKeyModifiers( void );
enum ECarbonModKeyIndex
{
EcmdKeyBit = 8, /* command key down?*/
EshiftKeyBit = 9, /* shift key down?*/
EalphaLockBit = 10, /* alpha lock down?*/
EoptionKeyBit = 11, /* option key down?*/
EcontrolKeyBit = 12 /* control key down?*/
};
enum ECarbonModKeyMask
{
EcmdKey = 1 << EcmdKeyBit,
EshiftKey = 1 << EshiftKeyBit,
EalphaLock = 1 << EalphaLockBit,
EoptionKey = 1 << EoptionKeyBit,
EcontrolKey = 1 << EcontrolKeyBit
};
#if 0
static ConVar gl_flushpaircache ("gl_flushpaircache", "0");
static ConVar gl_paircachestats ("gl_paircachestats", "0");
static ConVar gl_mtglflush_at_tof ("gl_mtglflush_at_tof", "0");
static ConVar gl_texlayoutstats ("gl_texlayoutstats", "0" );
#else
int gl_flushpaircache =0;
int gl_paircachestats =0;
int gl_mtglflush_at_tof =0;
int gl_texlayoutstats =0;
#endif
void GLMContext::BeginFrame( void )
{
GLM_FUNC;
MakeCurrent();
m_debugFrameIndex++;
m_debugBatchIndex = -1;
// check for lang change at TOF
if (m_caps.m_hasDualShaders)
{
if (m_drawingLang != m_drawingLangAtFrameStart)
{
// language change. unbind everything..
this->NullProgram();
m_drawingLang = m_drawingLangAtFrameStart;
}
}
// scrub some critical shock absorbers
for( int i=0; i< 16; i++)
{
glDisableVertexAttribArray( i ); // enable GLSL attribute- this is just client state - will be turned back off
GLMCheckError();
}
m_lastKnownVertexAttribMask = 0;
//FIXME should we also zap the m_lastKnownAttribs array ? (worst case it just sets them all again on first batch)
BindBufferToCtx( kGLMVertexBuffer, NULL, true );
BindBufferToCtx( kGLMIndexBuffer, NULL, true );
if (gl_flushpaircache/*.GetInt()*/)
{
// do the flush and then set back to zero
this->ClearShaderPairCache();
printf("\n\n##### shader pair cache cleared\n\n");
gl_flushpaircache = 0; //.SetValue( 0 );
}
if (gl_paircachestats/*.GetInt()*/)
{
// do the flush and then set back to zero
this->m_pairCache->DumpStats();
gl_paircachestats = 0; //.SetValue( 0 );
}
if (gl_texlayoutstats/*.GetInt()*/)
{
this->m_texLayoutTable->DumpStats();
gl_texlayoutstats = 0; //.SetValue( 0 );
}
if (gl_mtglflush_at_tof/*.GetInt()*/)
{
glFlush(); // TOF flush - skip this if benchmarking, enable it if human playing (smoothness)
}
#if GLMDEBUG
// init debug hook information
GLMDebugHookInfo info;
memset( &info, 0, sizeof(info) );
info.m_caller = eBeginFrame;
do
{
this->DebugHook( &info );
} while (info.m_loop);
#endif
}
void GLMContext::EndFrame( void )
{
GLM_FUNC;
#if GLMDEBUG
// init debug hook information
GLMDebugHookInfo info;
memset( &info, 0, sizeof(info) );
info.m_caller = eEndFrame;
do
{
#endif
if (!m_oneCtxEnable) // if using dual contexts, this flush is needed
{
glFlush();
}
#if GLMDEBUG
this->DebugHook( &info );
} while (info.m_loop);
#endif
}
//===============================================================================
CGLMQuery *GLMContext::NewQuery( GLMQueryParams *params )
{
CGLMQuery *query = new CGLMQuery( this, params );
return query;
}
void GLMContext::DelQuery( CGLMQuery *query )
{
// may want to do some finish/
delete query;
}
// static ConVar mat_vsync( "mat_vsync", "0", 0, "Force sync to vertical retrace", true, 0.0, true, 1.0 );
int mat_vsync = 1;
//===============================================================================
// ConVar glm_nullrefresh_capslock( "glm_nullrefresh_capslock", "0" );
// ConVar glm_literefresh_capslock( "glm_literefresh_capslock", "0" );
// extern ConVar gl_blitmode;
extern int gl_blitmode;
void GLMContext::Present( CGLMTex *tex )
{
#if DX9MODE
GLM_FUNC;
MakeCurrent();
// this is the path whether full screen or windowed... we always blit.
CShowPixelsParams showparams;
memset( &showparams, 0, sizeof(showparams) );
showparams.m_srcTexName = tex->m_texName;
showparams.m_width = tex->m_layout->m_key.m_xSize;
showparams.m_height = tex->m_layout->m_key.m_ySize;
// showparams.m_vsyncEnable = m_displayParams.m_vsyncEnable = mat_vsync; //.GetBool();
// showparams.m_fsEnable = m_displayParams.m_fsEnable;
// we call showpixels once with the "only sync view" arg set, so we know what the latest surface size is, before trying to do our own blit !
// showparams.m_onlySyncView = true;
// g_engine->ShowPixels(&showparams); // doesn't actually show anything, just syncs window/fs state (would make a useful separate call)
// showparams.m_onlySyncView = false;
// blit to GL_BACK done here, not in engine, this lets us do resolve directly if conditions are right
GLMRect srcRect, dstRect;
uint dstWidth,dstHeight;
g_engine->DisplayedSize( dstWidth,dstHeight );
srcRect.xmin = 0;
srcRect.ymin = 0;
srcRect.xmax = showparams.m_width;
srcRect.ymax = showparams.m_height;
dstRect.xmin = 0;
dstRect.ymin = 0;
dstRect.xmax = dstWidth;
dstRect.ymax = dstHeight;
// do not ask for LINEAR if blit is unscaled
// NULL means targeting GL_BACK. Blit2 will break it down into two steps if needed, and will handle resolve, scale, flip.
bool blitScales = (showparams.m_width != dstWidth) || (showparams.m_height != dstHeight);
this->Blit2( tex, &srcRect, 0,0,
NULL, &dstRect, 0,0,
blitScales ? GL_LINEAR : GL_NEAREST );
if (m_oneCtxEnable) // if using single context, we need to blast some state so GLM will recover after the FBO fiddlin'
{
BindFBOToCtx( NULL, GL_READ_FRAMEBUFFER_EXT );
GLMCheckError();
BindFBOToCtx( NULL, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
}
g_engine->ShowPixels(&showparams);
if (m_oneCtxEnable)
{
// put the original FB back in place (both read and draw)
// this bind will hit both read and draw bindings
BindFBOToCtx( m_drawingFBO, GL_READ_FRAMEBUFFER_EXT );
GLMCheckError();
BindFBOToCtx( m_drawingFBO, GL_DRAW_FRAMEBUFFER_EXT );
GLMCheckError();
// put em back !!
m_ScissorEnable.Flush( true );
m_ScissorBox.Flush( true );
m_ViewportBox.Flush( true );
}
else
{
MakeCurrent();
}
#endif
}
//===============================================================================
// GLMContext protected methods
// a naive implementation of this would just clear-drawable on the context at entry,
// and then capture and set fullscreen if requested.
// however that would glitch thescreen every time the user changed resolution while staying in full screen.
// but in windowed mode there's really not much to do in here. Yeah, this routine centers around obtaining
// drawables for fullscreen mode, and/or dropping those drawables if we're going back to windowed.
// um, are we expected to re-make the standard surfaces (color, depthstencil) if the res changes? is that now this routine's job ?
// so, kick it off with an assessment of whather we were FS previously or not.
// if there was no prior display params latched, then it wasn't.
// changes in here take place immediately. If you want to defer display changes then that's going to be a different method.
// common assumption is that there will be two places that call this: context create and the implementation of the DX9 Reset method.
// in either case the client code is aware of what it signed up for.
bool GLMContext::SetDisplayParams( GLMDisplayParams *params )
{
m_displayParams = *params; // latch em
m_displayParamsValid = true;
return true;
}
//extern ConVar gl_singlecontext; // single context mode go-ahead if 10.6.3 or higher
extern int gl_singlecontext; // it's in glmgrbasics.cpp
//ConVar gl_can_query_fast("gl_can_query_fast", "0");
int gl_can_query_fast = 1; // assume SLGU
GLMContext::GLMContext( GLMDisplayParams *params )
{
#if DX9MODE
// flag our copy of display params as blank
m_displayParamsValid = false;
// peek at any CLI options
m_slowAssertEnable = false;//CommandLine()->FindParm("-glmassertslow");
m_slowSpewEnable = false; //CommandLine()->FindParm("-glmspewslow");
m_slowCheckEnable = m_slowAssertEnable || m_slowSpewEnable;
m_drawingLangAtFrameStart = m_drawingLang = kGLMGLSL; // default to GLSL
// this affects FlushDrawStates which will route program bindings, uniform delivery, sampler setup, and enables accordingly.
if ( 0 /*CommandLine()->FindParm("-glslmode")*/ )
{
m_drawingLangAtFrameStart = m_drawingLang = kGLMGLSL;
}
if ( 0 /* CommandLine()->FindParm("-arbmode") && !CommandLine()->FindParm("-glslcontrolflow") */ )
{
m_drawingLangAtFrameStart = m_drawingLang = kGLMARB;
}
// proceed with rest of init
m_nsctx = NULL;
m_ctx = NULL;
// call engine, ask for the attrib list (also naming the specific renderer ID) and use that to make our context
CGLPixelFormatAttribute *selAttribs = NULL;
uint selWords = 0;
memset( &m_caps, 0, sizeof( m_caps ) );
//g_engine->GetDesiredPixelFormatAttribsAndRendererInfo( (uint**)&selAttribs, &selWords, &m_caps );
g_engine->GetRendererInfo( &m_caps );
uint selBytes = selWords * sizeof( uint );
// call engine, ask it about the window we're targeting, get the NSGLContext back, share against that
PseudoNSGLContextPtr shareNsCtx = g_engine->GetNSGLContextForWindow( (void*)params->m_focusWindow );
// decide if we're going to try single context mode.
m_oneCtxEnable = true; // 10.6 only... //(m_caps.m_osComboVersion >= 0x000A0603) && (gl_singlecontext/*.GetInt()*/ );
bool success = false;
if(m_oneCtxEnable)
{
// just steal the window's context
m_nsctx = shareNsCtx;
m_ctx = GetCGLContextFromNSGL( shareNsCtx );
success = (m_nsctx != NULL) && (m_ctx != NULL);
}
else
{
// this is the old 10.5.x two-context path.... ugh
success = NewNSGLContext( (unsigned long*)selAttribs, shareNsCtx, &m_nsctx, &m_ctx );
}
if (success)
{
//write a cookie into the CGL context leading back to the GLM context object
GLint glm_context_link = (GLint)((uintptr_t)this);
CGLSetParameter( m_ctx, kCGLCPClientStorage, &glm_context_link );
// save off the pixel format attributes we used
memcpy(m_pixelFormatAttribs, selAttribs, selBytes );
}
else
{
Debugger(); //FIXME #PMB# bad news, maybe exit to shell if this happens
}
if ( 1 /* CommandLine()->FindParm("-glmspewcaps") */) //FIXME change to '0' later
{
DumpCaps();
}
SetDisplayParams( params );
m_texLayoutTable = new CGLMTexLayoutTable;
memset( m_samplers, 0, sizeof( m_samplers ) );
m_activeTexture = -1;
m_texLocks.reserve( 16 );
// FIXME need a texture tracking table so we can reliably delete CGLMTex objects at context teardown
m_boundReadFBO = NULL;
m_boundDrawFBO = NULL;
m_drawingFBO = NULL;
memset( m_boundProgram, 0, sizeof(m_boundProgram) );
memset( m_drawingProgram, 0, sizeof(m_boundProgram) );
memset( m_programParamsF , 0, sizeof (m_programParamsF) );
memset( m_programParamsB , 0, sizeof (m_programParamsB) );
memset( m_programParamsI , 0, sizeof (m_programParamsI) );
m_paramWriteMode = eParamWriteDirtySlotRange; // default to fastest mode
/*
if (CommandLine()->FindParm("-glmwriteallslots")) m_paramWriteMode = eParamWriteAllSlots;
if (CommandLine()->FindParm("-glmwriteshaderslots")) m_paramWriteMode = eParamWriteShaderSlots;
if (CommandLine()->FindParm("-glmwriteshaderslotsoptional")) m_paramWriteMode = eParamWriteShaderSlotsOptional;
if (CommandLine()->FindParm("-glmwritedirtyslotrange")) m_paramWriteMode = eParamWriteDirtySlotRange;
*/
m_attribWriteMode = eAttribWriteDirty;
/*
if (CommandLine()->FindParm("-glmwriteallattribs")) m_attribWriteMode = eAttribWriteAll;
if (CommandLine()->FindParm("-glmwritedirtyattribs")) m_attribWriteMode = eAttribWriteDirty;
*/
m_pairCache = new CGLMShaderPairCache( this );
m_boundPair = NULL;
m_boundPairRevision = 0xFFFFFFFF;
m_boundPairProgram = (GLhandleARB)0xFFFFFFFF; // GLSL only
memset( m_lastKnownBufferBinds, 0, sizeof(m_lastKnownBufferBinds) );
memset( m_lastKnownVertexAttribs, 0, sizeof(m_lastKnownVertexAttribs) );
m_lastKnownVertexAttribMask = 0;
// make a null program for use when client asks for NULL FP
m_nullFragmentProgram = this->NewProgram(kGLMFragmentProgram, g_nullFragmentProgramText );
// make dummy programs for doing texture preload via dummy draw
m_preloadTexVertexProgram = this->NewProgram(kGLMVertexProgram, g_preloadTexVertexProgramText );
m_preload2DTexFragmentProgram = this->NewProgram(kGLMFragmentProgram, g_preload2DTexFragmentProgramText );
m_preload3DTexFragmentProgram = this->NewProgram(kGLMFragmentProgram, g_preload3DTexFragmentProgramText );
m_preloadCubeTexFragmentProgram = this->NewProgram(kGLMFragmentProgram, g_preloadCubeTexFragmentProgramText );
m_drawIndexBuffer = NULL;
//memset( &m_drawVertexSetup, 0, sizeof(m_drawVertexSetup) );
SetVertexAttributes( NULL ); // will set up all the entries in m_drawVertexSetup
m_debugFontTex = NULL;
// debug state
m_debugFrameIndex = -1;
m_debugBatchIndex = -1;
#if GLMDEBUG
// #######################################################################################
// DebugHook state - we could set these to more interesting values in response to a CLI arg like "startpaused" or something if desired
//m_paused = false;
m_holdFrameBegin = -1;
m_holdFrameEnd = -1;
m_holdBatch = m_holdBatchFrame = -1;
m_debugDelayEnable = false;
m_debugDelay = 1<<19; // ~0.5 sec delay
m_autoClearColor = m_autoClearDepth = m_autoClearStencil = false;
m_autoClearColorValues[0] = 0.0; //red
m_autoClearColorValues[1] = 1.0; //green
m_autoClearColorValues[2] = 0.0; //blue
m_autoClearColorValues[3] = 1.0; //alpha
m_selKnobIndex = 0;
m_selKnobMinValue = -10.0f;
m_selKnobMaxValue = 10.0f;
m_selKnobIncrement = 1/256.0f;
// #######################################################################################
#endif
// make two scratch FBO's for blit purposes
m_blitReadFBO = this->NewFBO();
m_blitDrawFBO = this->NewFBO();
for( int i=0; i<kGLMScratchFBOCount; i++)
{
m_scratchFBO[i] = this->NewFBO();
}
bool new_mtgl = m_caps.m_hasPerfPackage1; // i.e. 10.6.4 plus new driver
/*
if ( CommandLine()->FindParm("-glmenablemtgl2") )
{
new_mtgl = true;
}
if ( CommandLine()->FindParm("-glmdisablemtgl2") )
{
new_mtgl = false;
}
*/
bool mtgl_on = params->m_mtgl;
/*
if (CommandLine()->FindParm("-glmenablemtgl"))
{
mtgl_on = true;
}
if (CommandLine()->FindParm("-glmdisablemtgl"))
{
mtgl_on = false;
}
*/
CGLError result = (CGLError)0;
if (mtgl_on)
{
bool ready = false;
if (new_mtgl)
{
// afterburner
CGLContextEnable kCGLCPGCDMPEngine = ((CGLContextEnable)1314);
result = CGLEnable( m_ctx, kCGLCPGCDMPEngine );
if (!result)
{
ready = true; // succeeded - no need to try non-MTGL
printf("\nMTGL detected.\n");
}
else
{
printf("\nMTGL *not* detected, falling back.\n");
}
}
if (!ready)
{
// try old MTGL
result = CGLEnable( m_ctx, kCGLCEMPEngine );
if (!result)
{
printf("\nMTGL has been detected.\n");
ready = true; // succeeded - no need to try non-MTGL
}
}
}
// also, set the remote convar "gl_can_query_fast" to 1 if perf package present, else 0.
gl_can_query_fast = m_caps.m_hasPerfPackage1?1:0; //.SetValue( m_caps.m_hasPerfPackage1?1:0 );
GLMCheckError();
#endif
}
GLMContext::~GLMContext ()
{
// a lot of stuff that needs to be freed / destroyed
if (m_debugFontTex)
{
this->DelTex( m_debugFontTex );
m_debugFontTex = NULL;
}
if ( m_nullFragmentProgram )
{
this->DelProgram( m_nullFragmentProgram );
m_nullFragmentProgram = NULL;
}
// walk m_fboTable and free them up..
for( std::vector< CGLMFBO * >::iterator p = m_fboTable.begin(); p != m_fboTable.end(); p++ )
{
CGLMFBO *fbo = *p;
this->DelFBO( fbo );
}
m_fboTable.clear();
if (m_pairCache)
{
delete m_pairCache;
m_pairCache = NULL;
}
// we need a m_texTable I think..
// m_texLayoutTable can be scrubbed once we know that all the tex are freed
if (m_nsctx && (!m_oneCtxEnable) )
{
DelNSGLContext( m_nsctx );
m_nsctx = NULL;
m_ctx = NULL;
}
}
void GLMContext::SelectTMU( int tmu )
{
//GLM_FUNC;
CheckCurrent();
if (tmu != m_activeTexture)
{
glActiveTexture( GL_TEXTURE0+tmu );
GLMCheckError();
m_activeTexture = tmu;
}
}
int GLMContext::BindTexToTMU( CGLMTex *tex, int tmu, bool noCheck )
{
GLM_FUNC;
GLMPRINTF(("--- GLMContext::BindTexToTMU tex %p GL name %d -> TMU %d ", tex, tex ? tex->m_texName : -1, tmu ));
CheckCurrent();
#if GLMDEBUG
if ( tex && tex->m_debugLabel && (!strcmp( tex->m_debugLabel, "error" ) ) )
{
static char stop_here = 0;
if (stop_here)
{
stop_here = 1;
}
}
#endif
if (tex && (tex->m_layout->m_key.m_texFlags & kGLMTexMultisampled) )
{
if (tex->m_rboDirty)
{
// the texture must be a multisampled render target which has been targeted recently for drawing.
// check that it's not still attached...
Assert( tex->m_rtAttachCount==0 );
// let it resolve the MSAA RBO back to the texture
ResolveTex( tex );
}
}
SelectTMU( tmu );
// if another texture was previously bound there, mark it not bound now
// this should not be skipped
if (m_samplers[tmu].m_boundTex)
{
m_samplers[tmu].m_boundTex->m_bindPoints &= ~(1<<tmu); // was [ tmu ] = false with bitvec
// if new tex is not the same, then bind 0 for old tex's target
//if (m_samplers[tmu].m_boundTex != tex)
//{
// glBindTexture( m_samplers[tmu].m_boundTex->m_layout->m_key.m_texGLTarget, m_samplers[tmu].m_boundTex->m_texName );
//}
// note m_samplers[tmu].m_boundTex is now stale but we will step on it shortly
}
// if texture chosen is different, or if noCheck is set, do the bind
if (tex)
{
// bind new tex and mark it
if ((tex != m_samplers[tmu].m_boundTex) || noCheck)
{
// if not being forced, we should see if the bind point (target) of the departing tex is different.
if (!noCheck)
{
if ( (m_samplers[tmu].m_boundTex) )
{
// there is an outgoing tex.
// same target?
if ( m_samplers[tmu].m_boundTex->m_layout->m_key.m_texGLTarget != tex->m_layout->m_key.m_texGLTarget )
{
// no, different target. inbound tex will be set below. Here, just clear the different target of the outbound tex.
glBindTexture( m_samplers[tmu].m_boundTex->m_layout->m_key.m_texGLTarget, 0 );
}
else
{
// same target, new tex, no work to do.
}
}
}
else
{
// mega scrub
glBindTexture( GL_TEXTURE_1D, 0 );
glBindTexture( GL_TEXTURE_2D, 0 );
glBindTexture( GL_TEXTURE_3D, 0 );
glBindTexture( GL_TEXTURE_CUBE_MAP, 0 );
}
glBindTexture( tex->m_layout->m_key.m_texGLTarget, tex->m_texName );
GLMCheckError();
}
tex->m_bindPoints |= (1<<tmu); // was [ tmu ] = true with bitvec
m_samplers[tmu].m_boundTex = tex;
}
else
{
// this is an unbind request, bind name 0
if (m_samplers[tmu].m_boundTex)
{
// no inbound tex. Just clear the one target that the old tex occupied.
glBindTexture( m_samplers[tmu].m_boundTex->m_layout->m_key.m_texGLTarget, 0 );
GLMCheckError();
}
else
{
// none was bound before, so no action
}
m_samplers[tmu].m_boundTex = NULL;
}
return 0;
}
void GLMContext::BindFBOToCtx( CGLMFBO *fbo, GLenum bindPoint )
{
GLM_FUNC;
GLMPRINTF(( "--- GLMContext::BindFBOToCtx fbo %p, GL name %d", fbo, (fbo) ? fbo->m_name : -1 ));
CheckCurrent();
bool targetRead = (bindPoint==GL_READ_FRAMEBUFFER_EXT) || (bindPoint==GL_FRAMEBUFFER_EXT);
bool targetDraw = (bindPoint==GL_DRAW_FRAMEBUFFER_EXT) || (bindPoint==GL_FRAMEBUFFER_EXT);
if (targetRead)
{
if (fbo) // you can pass NULL to go back to no-FBO
{
glBindFramebufferEXT( GL_READ_FRAMEBUFFER_EXT, fbo->m_name );
GLMCheckError();
m_boundReadFBO = fbo;
//dontcare fbo->m_bound = true;
}
else
{
glBindFramebufferEXT( GL_READ_FRAMEBUFFER_EXT, 0 );
GLMCheckError();
m_boundReadFBO = NULL;
}
}
if (targetDraw)
{
if (fbo) // you can pass NULL to go back to no-FBO
{
glBindFramebufferEXT( GL_DRAW_FRAMEBUFFER_EXT, fbo->m_name );
GLMCheckError();
m_boundDrawFBO = fbo;
//dontcare fbo->m_bound = true;
}
else
{
glBindFramebufferEXT( GL_DRAW_FRAMEBUFFER_EXT, 0 );
GLMCheckError();
m_boundDrawFBO = NULL;
}
}
}
void GLMContext::BindBufferToCtx( EGLMBufferType type, CGLMBuffer *buff, bool force )
{
GLM_FUNC;
GLMPRINTF(( "--- GLMContext::BindBufferToCtx buff %p, GL name %d", buff, (buff) ? buff->m_name : -1 ));
CheckCurrent();
if (!force)
{
// compare desired bind to last known bind, and see if we can bail
if (m_lastKnownBufferBinds[ type ] == buff)
{
return;
}
}
GLenum target=0;
switch( type )
{
case kGLMVertexBuffer: target = GL_ARRAY_BUFFER_ARB; break;
case kGLMIndexBuffer: target = GL_ELEMENT_ARRAY_BUFFER_ARB; break;
case kGLMUniformBuffer: target = GL_UNIFORM_BUFFER_EXT; break;
case kGLMPixelBuffer: target = GL_PIXEL_UNPACK_BUFFER_ARB; break;
default: Assert(!"Unknown buffer type" );
}
bool wasBound = false;
bool isBound = false;
if (m_lastKnownBufferBinds[type])
{
m_lastKnownBufferBinds[type]->m_bound = false;
m_lastKnownBufferBinds[type] = NULL;
wasBound = true;
}
if (buff)
{
if (buff->m_buffGLTarget != target)
Debugger();
glBindBufferARB( buff->m_buffGLTarget, buff->m_name );
GLMCheckError();
m_lastKnownBufferBinds[ type ] = buff;
buff->m_bound = true;
isBound = true;
}
else
{
// isBound stays false
// bind name 0
// note that no buffer is bound in the ctx state
glBindBufferARB( target, 0 );
GLMCheckError();
m_lastKnownBufferBinds[ type ] = NULL;
}
}
//ConVar gl_can_mix_shader_gammas( "gl_can_mix_shader_gammas", 0 );
int gl_can_mix_shader_gammas = 0;
//ConVar gl_cannot_mix_shader_gammas( "gl_cannot_mix_shader_gammas", 0 );
int gl_cannot_mix_shader_gammas = 0;
void GLMContext::FlushDrawStates( bool shadersOn ) // shadersOn = true for draw calls, false for clear calls
{
GLM_FUNC;
CheckCurrent();
// FBO
if ( (m_drawingFBO != m_boundDrawFBO) || (m_drawingFBO != m_boundReadFBO) )
{
//GLMPRINTF(("\nGLMContext::FlushDrawStates, setting FBO to %8x(gl %d), was %8x(gl %d)", m_drawingFBO, (m_drawingFBO? m_drawingFBO->m_name: -1),m_boundFBO, (m_boundFBO ? m_boundFBO->m_name : -1) ));
this->BindFBOToCtx( m_drawingFBO, GL_READ_FRAMEBUFFER_EXT );
this->BindFBOToCtx( m_drawingFBO, GL_DRAW_FRAMEBUFFER_EXT );
}
// if drawing FBO has any MSAA attachments, mark them dirty
{
CGLMTex *tex;
for( int att=kAttColor0; att<kAttCount; att++)
{
if (m_drawingFBO->m_attach[ att ].m_tex)
{
CGLMTex *tex = m_drawingFBO->m_attach[ att ].m_tex;
if (tex->m_rboName) // is it MSAA
{
// mark it dirty
tex->m_rboDirty = true;
}
}
}
}
// renderstates
this->FlushStates(); // latched renderstates..
// if there is no color target - bail out
// OK, this doesn't work in general - you can't leave the color target floating(null) or you will get FBO errors
//if (!m_boundDrawFBO[0].m_attach[0].m_tex)
//{
// GLMPRINTF(("-D- GLMContext::FlushDrawStates -> no color target! exiting.. " ));
// return;
//}
bool tex0_srgb = (m_boundDrawFBO[0].m_attach[0].m_tex->m_layout->m_key.m_texFlags & kGLMTexSRGB) != 0;
// you can only actually use the sRGB FB state on some systems.. check caps
if (m_caps.m_hasGammaWrites)
{
GLBlendEnableSRGB_t writeSRGBState;
m_BlendEnableSRGB.Read( &writeSRGBState, 0 ); // the client set value, not the API-written value yet..
bool draw_srgb = writeSRGBState.enable;
if (draw_srgb)
{
if (tex0_srgb)
{
// good - draw mode and color tex agree
}
else
{
// bad
// Client has asked to write sRGB into a texture that can't do it.
// there is no way to satisfy this unless we change the RT tex and we avoid doing that.
// (although we might consider a ** ONE TIME ** promotion.
// this shouldn't be a big deal if the tex format is one where it doesn't matter like 32F.
GLMPRINTF(("-Z- srgb-enabled FBO conflict: attached tex %08x [%s] is not SRGB", m_boundDrawFBO[0].m_attach[0].m_tex, m_boundDrawFBO[0].m_attach[0].m_tex->m_layout->m_layoutSummary ));
// do we shoot down the srgb-write state for this batch?
// I think the runtime will just ignore it.
}
}
else
{
if (tex0_srgb)
{
// odd - client is not writing sRGB into a texture which *can* do it.
//GLMPRINTF(( "-Z- srgb-disabled FBO conflict: attached tex %08x [%s] is SRGB", m_boundFBO[0].m_attach[0].m_tex, m_boundFBO[0].m_attach[0].m_tex->m_layout->m_layoutSummary ));
//writeSRGBState.enable = true;
//m_BlendEnableSRGB.Write( &writeSRGBState );
}
else
{
// good - draw mode and color tex agree
}
}
// now go ahead and flush the SRGB write state for real
// set the noDefer on it too
m_BlendEnableSRGB.Flush( /*true*/ );
}
// else... FlushDrawStates will work it out via flSRGBWrite in the fragment shader..
// textures and sampling
// note we generate a mask of which samplers are running "decode sRGB" mode, to help out the shader pair cache mechanism below.
uint srgbMask = 0;
for( int i=0; i<GLM_SAMPLER_COUNT; i++)
{
GLMTexSampler *samp = &m_samplers[i];
// push tex binding?
if (samp->m_boundTex != samp->m_drawTex)
{
this->BindTexToTMU( samp->m_drawTex, i );
samp->m_boundTex = samp->m_drawTex;
}
// push sampling params? it will check each one individually.
if (samp->m_boundTex)
{
samp->m_boundTex->ApplySamplingParams( &samp->m_samp );
}
if (samp->m_samp.m_srgb)
{
srgbMask |= (1<<i);
}
}
// index buffer
if (m_drawIndexBuffer != m_lastKnownBufferBinds[ kGLMIndexBuffer ] )
{
BindBufferToCtx( kGLMIndexBuffer, m_drawIndexBuffer ); // note this could be a pseudo buffer..
}
// shader setup
if (shadersOn)
{
switch( m_drawingLang )
{
case kGLMARB:
{
// disable any GLSL program
glUseProgram( 0 );
m_boundPair = NULL;
// bind selected drawing programs in ARB flavor.
// asking for "null" fragment shader is allowed, we offer up the dummy frag shader in response.
// vertex side
bool vpgood = false;
bool fpgood = false;
{
CGLMProgram *vp = m_drawingProgram[ kGLMVertexProgram ];
if (vp)
{
if (vp->m_descs[ kGLMARB ].m_valid)
{
glSetEnable( GL_VERTEX_PROGRAM_ARB, true );
glBindProgramARB(GL_VERTEX_PROGRAM_ARB, vp->m_descs[ kGLMARB ].m_object.arb);
GLMCheckError();
m_boundProgram[ kGLMVertexProgram ] = vp;
vpgood = true;
}
else
{
//Assert( !"Trying to draw with invalid ARB vertex program" );
}
}
else
{
//Assert( !"Trying to draw with NULL ARB vertex program" );
}
}
// fragment side
{
CGLMProgram *fp = m_drawingProgram[ kGLMFragmentProgram ];
if (fp)
{
if (fp->m_descs[ kGLMARB ].m_valid)
{
glSetEnable( GL_FRAGMENT_PROGRAM_ARB, true );
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, fp->m_descs[ kGLMARB ].m_object.arb);
GLMCheckError();
m_boundProgram[ kGLMFragmentProgram ] = fp;
fpgood = true;
}
else
{
//Assert( !"Trying to draw with invalid ARB fragment program" );
m_boundProgram[ kGLMFragmentProgram ] = NULL;
}
}
else
{
// this is actually OK, we substitute a dummy shader
glSetEnable( GL_FRAGMENT_PROGRAM_ARB, true );
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_nullFragmentProgram->m_descs[kGLMARB].m_object.arb );
m_boundProgram[ kGLMFragmentProgram ] = m_nullFragmentProgram;
fpgood = true;
}
}
if (fpgood & vpgood)
{
// flush parameter values to both stages
// FIXME: this can be optimized by dirty range, since ARB supports single-parameter-bank aka .env
// FIXME: magic numbers, yuk
glProgramEnvParameters4fvEXT( GL_VERTEX_PROGRAM_ARB, 0, 256, (const GLfloat*)&m_programParamsF[kGLMVertexProgram].m_values[0][0] );
GLMCheckError();
glProgramEnvParameters4fvEXT( GL_FRAGMENT_PROGRAM_ARB, 0, 32, (const GLfloat*)&m_programParamsF[kGLMFragmentProgram].m_values[0][0] );
GLMCheckError();
}
else
{
// silence all (clears wind up here for example)
glBindProgramARB(GL_VERTEX_PROGRAM_ARB, 0 );
glSetEnable( GL_VERTEX_PROGRAM_ARB, false );
m_boundProgram[ kGLMVertexProgram ] = NULL;
glSetEnable( GL_FRAGMENT_PROGRAM_ARB, false );
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, 0 );
m_boundProgram[ kGLMFragmentProgram ] = NULL;
}
///////////////////////////////////
// ARB vert setup. maybe generalize this to handle both ARB and GLSL after we see what GLSL attrib setup looks like.
//http://www.opengl.org/sdk/docs/man/xhtml/glVertexAttribPointer.xml
//http://www.opengl.org/sdk/docs/man/xhtml/glEnableVertexAttribArray.xml
// for (each attrib)
// if (enable unchanged and off) -> do nothing
// if (enable changed to off) -> disable that array ... set the attrib pointer to nil for clarity
// if (enable changed to on) -> bind the appropriate vertex buffer, set that attrib, log it
// if (enable unchanged and on) -> diff the attrib setup, re-bind if needed, log it
GLMVertexSetup *setup = &m_drawVertexSetup;
uint relevantMask = setup->m_attrMask;
for( int index=0; index < kGLMVertexAttributeIndexMax; index++ )
{
uint mask = 1<<index;
if (relevantMask & mask)
{
GLMVertexAttributeDesc *setdesc = &setup->m_attrs[index]; // ptr to desired setup
CGLMBuffer * buf = setdesc->m_buffer; // bind buffer
Assert( buf );
BindBufferToCtx( kGLMVertexBuffer, buf );
glEnableVertexAttribArray( index ); // enable attribute, set pointer.
GLMCheckError();
glVertexAttribPointer( index, setdesc->m_datasize, setdesc->m_datatype, setdesc->m_normalized, setdesc->m_stride, ( const GLvoid *)setdesc->m_offset );
GLMCheckError();
//GLMPRINTF(("--- GLMContext::SetVertexAttributes attr %d set to offset/stride %d/%d in buffer %d (normalized=%s)", index, setdesc->m_offset, setdesc->m_stride, setdesc->m_buffer->m_name, setdesc->m_normalized?"true":"false" ));
}
else
{
// disable attribute
glDisableVertexAttribArray( index );
GLMCheckError();
//GLMPRINTF((" -- GLMContext::SetVertexAttributes attr %d is disabled", index ));
// tidy up in case there was garbage? necessary ?
memset ( &setup->m_attrs[index], 0, sizeof(setup->m_attrs[index]) );
}
}
///////////////////////////////////
}
break;
case kGLMGLSL:
{
// early out if one of the stages is not set.
// draw code needs to watch for this too.
if ( (m_drawingProgram[ kGLMVertexProgram ]==NULL) || (m_drawingProgram[ kGLMFragmentProgram ]==NULL) )
{
this->NullProgram();
return;
}
// examine selected drawing programs for both stages
// try to find a match in thelinked-pair-cache
// if no match, link one
// examine metadata
// get uniform locations for parameters, attributes, and samplers
// put in cache
// dispatch vertex attribute locations to shader (could be one-time)
// dispatch parameter values to both stages (could be optimized with UBO)
// dispatch sampler locations to shader (need sampler metadata)
// new way - use the pair cache
// cook up some extra bits so that we can track different srgb-usages of the same vp/fp pair.
// note that this is only important on some hardware/OS combos.
// let the pair cache decide if it needs to honor the extra key bits or not.
// decide if we need to mix extra bits into the lookup key.
bool useExtraKeyBits = m_caps.m_costlyGammaFlips;
// the "can" variable is allowed to override the static assessment.
if ( gl_can_mix_shader_gammas/*.GetInt()*/ )
{
useExtraKeyBits = false;
}
// the "cannot" variable is allowed to override the first two
if ( gl_cannot_mix_shader_gammas/*.GetInt()*/ )
{
useExtraKeyBits = true;
}
uint extraKeyBits = 0;
if (useExtraKeyBits)
{
extraKeyBits = (srgbMask & m_drawingProgram[ kGLMFragmentProgram ]->m_samplerMask);
}
CGLMShaderPair *newPair = m_pairCache->SelectShaderPair( m_drawingProgram[ kGLMVertexProgram ], m_drawingProgram[ kGLMFragmentProgram ], extraKeyBits );
GLhandleARB newPairProgram = newPair->m_program;
uint newPairRevision = newPair->m_revision;
// you cannot only key on the pair address, since pairs get evicted and pair records likely get recycled.
// so key on all three - pair address, program name, revision number
// this will also catch cases where a pair is re-linked (batch debugger / live edit)
if ( (newPair != m_boundPair) || (newPairProgram != m_boundPairProgram) || (newPairRevision != m_boundPairRevision) )
{
m_boundPair = newPair;
m_boundPairProgram = newPairProgram;
m_boundPairRevision = newPairRevision;
glUseProgram( (uintptr_t)newPairProgram );
GLMCheckError();
// set the dirty levels appropriately since the program changed and has never seen any of the current values.
m_programParamsF[kGLMVertexProgram].m_dirtySlotCount = m_drawingProgram[ kGLMVertexProgram ]->m_descs[kGLMGLSL].m_highWater+1;
m_programParamsF[kGLMFragmentProgram].m_dirtySlotCount = m_drawingProgram[ kGLMFragmentProgram ]->m_descs[kGLMGLSL].m_highWater+1;
// bool and int dirty levels get set to max, we don't have actual high water marks for them
// code which sends the values must clamp on these types.
m_programParamsB[kGLMVertexProgram].m_dirtySlotCount = kGLMProgramParamBoolLimit;
m_programParamsB[kGLMFragmentProgram].m_dirtySlotCount = 0;
m_programParamsI[kGLMVertexProgram].m_dirtySlotCount = kGLMProgramParamInt4Limit;
m_programParamsI[kGLMFragmentProgram].m_dirtySlotCount = 0;
}
// note the binding (not really bound.. just sitting in the linked active GLSL program)
m_boundProgram[ kGLMVertexProgram ] = m_drawingProgram[ kGLMVertexProgram ];
m_boundProgram[ kGLMFragmentProgram ] = m_drawingProgram[ kGLMFragmentProgram ];
// now pave the way for drawing
// parameters - find and set
// vertex stage --------------------------------------------------------------------
// find "vc" in VS
GLint vconstLoc = m_boundPair->m_locVertexParams;
if (vconstLoc >=0)
{
#if GLMDEBUG
static uint paramsPushed=0,paramsSkipped=0,callsPushed=0; // things that happened on pushed param trips
static uint callsSkipped=0,paramsSkippedByCallSkip=0; // on unpushed param trips (zero dirty)
#endif
int slotCountToPush = 0;
int shaderSlots = m_boundPair->m_vertexProg->m_descs[kGLMGLSL].m_highWater+1;
int dirtySlots = m_programParamsF[kGLMVertexProgram].m_dirtySlotCount;
switch( m_paramWriteMode )
{
case eParamWriteAllSlots: slotCountToPush = kGLMVertexProgramParamFloat4Limit; break;
case eParamWriteShaderSlots: slotCountToPush = shaderSlots; break;
case eParamWriteShaderSlotsOptional:
{
slotCountToPush = shaderSlots;
// ...unless, we're actually unchanged since last draw
if (dirtySlots == 0)
{
// write none
slotCountToPush = 0;
}
}
break;
case eParamWriteDirtySlotRange: slotCountToPush = dirtySlots; break;
}
if (slotCountToPush)
{
glUniform4fv( vconstLoc, slotCountToPush, &m_programParamsF[kGLMVertexProgram].m_values[0][0] );
GLMCheckError();
#if GLMDEBUG
paramsPushed += slotCountToPush;
paramsSkipped += shaderSlots - slotCountToPush;
callsPushed++;
#endif
}
else
{
#if GLMDEBUG
paramsSkippedByCallSkip += shaderSlots;
callsSkipped++;
#endif
}
#if GLMDEBUG && 0
if (GLMKnob("caps-key",NULL) > 0.0)
{
// spew
GLMPRINTF(("VP callsPushed=%d ( paramsPushed=%d paramsSkipped=%d ) callsSkipped=%d (paramsSkippedByCallSkip=%d)",
callsPushed, paramsPushed, paramsSkipped, callsSkipped, paramsSkippedByCallSkip
));
}
#endif
m_programParamsF[kGLMVertexProgram].m_dirtySlotCount = 0; //ack
}
// see if VS uses i0, b0, b1, b2, b3.
// use a glUniform1i to set any one of these if active. skip all of them if no dirties reported.
// my kingdom for the UBO extension!
// ------- bools ---------- //
if ( 1 /*m_programParamsB[kGLMVertexProgram].m_dirtySlotCount*/ ) // optimize this later after the float param pushes are proven out
{
GLint vconstBool0Loc = m_boundPair->m_locVertexBool0; //glGetUniformLocationARB( prog, "b0");
if ( vconstBool0Loc >= 0 )
{
glUniform1i( vconstBool0Loc, m_programParamsB[kGLMVertexProgram].m_values[0] ); //FIXME magic number
GLMCheckError();
}
GLint vconstBool1Loc = m_boundPair->m_locVertexBool1; //glGetUniformLocationARB( prog, "b1");
if ( vconstBool1Loc >= 0 )
{
glUniform1i( vconstBool1Loc, m_programParamsB[kGLMVertexProgram].m_values[1] ); //FIXME magic number
GLMCheckError();
}
GLint vconstBool2Loc = m_boundPair->m_locVertexBool2; //glGetUniformLocationARB( prog, "b2");
if ( vconstBool2Loc >= 0 )
{
glUniform1i( vconstBool2Loc, m_programParamsB[kGLMVertexProgram].m_values[2] ); //FIXME magic number
GLMCheckError();
}
GLint vconstBool3Loc = m_boundPair->m_locVertexBool3; //glGetUniformLocationARB( prog, "b3");
if ( vconstBool3Loc >= 0 )
{
glUniform1i( vconstBool3Loc, m_programParamsB[kGLMVertexProgram].m_values[3] ); //FIXME magic number
GLMCheckError();
}
m_programParamsB[kGLMVertexProgram].m_dirtySlotCount = 0; //ack
}
// ------- int ---------- //
if ( 1 /*m_programParamsI[kGLMVertexProgram].m_dirtySlotCount*/ ) // optimize this later after the float param pushes are proven out
{
GLint vconstInt0Loc = m_boundPair->m_locVertexInteger0; //glGetUniformLocationARB( prog, "i0");
if ( vconstInt0Loc >= 0 )
{
glUniform1i( vconstInt0Loc, m_programParamsI[kGLMVertexProgram].m_values[0][0] ); //FIXME magic number
GLMCheckError();
}
m_programParamsI[kGLMVertexProgram].m_dirtySlotCount = 0; //ack
}
// attribs - find and set
// GLSL vert setup - clone/edit of ARB setup. try to re-unify these later.
GLMVertexSetup *setup = &m_drawVertexSetup;
uint relevantMask = setup->m_attrMask;
//static char *attribnames[] = { "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" };
CGLMBuffer *loopCurrentBuf = NULL; // local shock absorber for this loop
for( int index=0; index < kGLMVertexAttributeIndexMax; index++ )
{
uint mask = 1<<index;
if (relevantMask & mask)
{
GLMVertexAttributeDesc *newDesc = &setup->m_attrs[index]; // ptr to desired setup
bool writeAttrib = false;
switch(m_attribWriteMode)
{
case eAttribWriteAll:
writeAttrib = true;
break;
case eAttribWriteDirty:
static uint hits=0,misses=0;
// first see if we have to do anything at all.
// the equality operator checks buffer name, offset, stride, datatype and normalized.
// we check buffer revision separately, submitter of vertex setup is not expected to provide it (zero is preferred).
// consult the actual buffer directly.
// note also, we're only doing thi compare when attrib #index is active for this batch.
// previously-active attribs which are becoming disabled need not be checked..
GLMVertexAttributeDesc *lastDesc = &m_lastKnownVertexAttribs[index];
if ( (!(*newDesc == *lastDesc)) || (newDesc->m_buffer->m_revision != lastDesc->m_bufferRevision) )
{
*lastDesc = *newDesc; // latch new setup
lastDesc->m_bufferRevision = newDesc->m_buffer->m_revision; // including proper revision of the sourcing buffer
writeAttrib = true;
misses++;
}
else
{
hits++;
}
#if 0
if ( ((hits+misses) % 10000)==0)
{
printf("\n** attrib setup hits %d misses %d",hits,misses);
}
#endif
break;
}
if( writeAttrib )
{
CGLMBuffer * buf = newDesc->m_buffer; // bind buffer
Assert( buf );
if (buf != loopCurrentBuf)
{
BindBufferToCtx( kGLMVertexBuffer, buf ); // (if not already on the bind point of interest)
GLMCheckError();
loopCurrentBuf = buf;
}
glVertexAttribPointer( index, newDesc->m_datasize, newDesc->m_datatype, newDesc->m_normalized, newDesc->m_stride, ( const GLvoid *)newDesc->m_offset );
GLMCheckError();
}
// enable is checked separately from the attrib binding
if (! (m_lastKnownVertexAttribMask & (1<<index)) )
{
glEnableVertexAttribArray( index ); // enable GLSL attribute- this is just client state - will be turned back off
GLMCheckError();
m_lastKnownVertexAttribMask |= (1<<index);
}
}
else
{
// this shader doesnt use that pair.
if ( m_lastKnownVertexAttribMask & (1<<index) )
{
glDisableVertexAttribArray( index ); // enable GLSL attribute- this is just client state - will be turned back off
GLMCheckError();
m_lastKnownVertexAttribMask &= ~(1<<index);
}
}
}
// fragment stage --------------------------------------------------------------------
// find "pc" in FS ("pixel constants")
GLint fconstLoc = m_boundPair->m_locFragmentParams;
if (fconstLoc >=0)
{
#if GLMDEBUG
static uint paramsPushed=0,paramsSkipped=0,callsPushed=0; // things that happened on pushed param trips
static uint callsSkipped=0,paramsSkippedByCallSkip=0; // on unpushed param trips (zero dirty)
#endif
int slotCountToPush = 0;
int shaderSlots = m_boundPair->m_fragmentProg->m_descs[kGLMGLSL].m_highWater+1;
int dirtySlots = m_programParamsF[kGLMFragmentProgram].m_dirtySlotCount;
switch( m_paramWriteMode )
{
case eParamWriteAllSlots: slotCountToPush = kGLMFragmentProgramParamFloat4Limit; break;
case eParamWriteShaderSlots: slotCountToPush = shaderSlots; break;
case eParamWriteShaderSlotsOptional:
{
slotCountToPush = shaderSlots;
// ...unless, we're actually unchanged since last draw
if (dirtySlots == 0)
{
// write none
slotCountToPush = 0;
}
}
break;
case eParamWriteDirtySlotRange: slotCountToPush = dirtySlots; break;
}
if (slotCountToPush)
{
glUniform4fv( fconstLoc, slotCountToPush, &m_programParamsF[kGLMFragmentProgram].m_values[0][0] );
GLMCheckError();
#if GLMDEBUG
paramsPushed += slotCountToPush;
paramsSkipped += shaderSlots - slotCountToPush;
callsPushed++;
#endif
}
else
{
#if GLMDEBUG
paramsSkippedByCallSkip += shaderSlots;
callsSkipped++;
#endif
}
#if GLMDEBUG && 0
if ( 0 && (GLMKnob("caps-key",NULL) > 0.0) ) // turn on as needed
{
// spew
GLMPRINTF(("FP callsPushed=%d ( paramsPushed=%d paramsSkipped=%d ) callsSkipped=%d (paramsSkippedByCallSkip=%d)",
callsPushed, paramsPushed, paramsSkipped, callsSkipped, paramsSkippedByCallSkip
));
}
#endif
m_programParamsF[kGLMFragmentProgram].m_dirtySlotCount = 0; //ack
}
// fake SRGB
if (!m_caps.m_hasGammaWrites) // do we need to think about fake SRGB?
{
if (m_boundPair->m_locFragmentFakeSRGBEnable >= 0) // does the shader have that uniform handy?
{
float desiredValue = m_FakeBlendEnableSRGB ? 1.0 : 0.0; // what should it be set to?
if (desiredValue != m_boundPair->m_fakeSRGBEnableValue) // and is that different from what it is known to be set to ?
{
glUniform1f( m_boundPair->m_locFragmentFakeSRGBEnable, desiredValue ); // if so, write it
GLMCheckError();
m_boundPair->m_fakeSRGBEnableValue = desiredValue; // and recall that we did so
}
}
}
//samplers
if (m_boundPair)
{
if(!m_boundPair->m_samplersFixed)
{
for( int sampler=0; sampler<16; sampler++)
{
if (m_boundPair->m_locSamplers[sampler] >=0)
{
glUniform1iARB( m_boundPair->m_locSamplers[sampler], sampler );
GLMCheckError();
}
}
m_boundPair->m_samplersFixed = true;
}
}
}
break;
}
}
else
{
this->NullProgram();
}
}
#if GLMDEBUG
enum EGLMDebugDumpOptions
{
eDumpBatchInfo,
eDumpSurfaceInfo,
eDumpStackCrawl,
eDumpShaderLinks,
// eDumpShaderText, // we never use this one
eDumpShaderParameters,
eDumpTextureSetup,
eDumpVertexAttribSetup,
eDumpVertexData,
eOpenShadersForEdit
};
enum EGLMVertDumpMode
{
// options that affect eDumpVertexData above
eDumpVertsNoTransformDump,
eDumpVertsTransformedByViewProj,
eDumpVertsTransformedByModelViewProj,
eDumpVertsTransformedByBoneZeroThenViewProj,
eDumpVertsTransformedByBonesThenViewProj,
eLastDumpVertsMode
};
const char *g_vertDumpModeNames[] =
{
"noTransformDump",
"transformedByViewProj",
"transformedByModelViewProj",
"transformedByBoneZeroThenViewProj",
"transformedByBonesThenViewProj"
};
static void CopyTilEOL( char *dst, char *src, int dstSize )
{
dstSize--;
int i=0;
while ( (i<dstSize) && (src[i] != 0) && (src[i] != '\n') && (src[i] != '\r') )
{
dst[i] = src[i];
i++;
}
dst[i] = 0;
}
static uint g_maxVertsToDumpLog2 = 4;
static uint g_maxFramesToCrawl = 20; // usually enough. Not enough? change it..
extern char sg_pPIXName[128];
// min is eDumpVertsNormal, max is the one before eLastDumpVertsMode
static enum EGLMVertDumpMode g_vertDumpMode = eDumpVertsNoTransformDump;
void GLMContext::DebugDump( GLMDebugHookInfo *info, uint options, uint vertDumpMode )
{
int oldIndent = GLMGetIndent();
GLMSetIndent(0);
CGLMProgram *vp = m_boundProgram[kGLMVertexProgram];
CGLMProgram *fp = m_boundProgram[kGLMFragmentProgram];
bool is_draw = ( (info->m_caller==eDrawElements) || (info->m_caller==eDrawArrays) );
const char *batchtype = is_draw ? "draw" : "clear";
if (options & (1<<eDumpBatchInfo))
{
GLMPRINTF(("-D- %s === %s %d ======================================================== %s %d frame %d", sg_pPIXName, batchtype, m_debugBatchIndex, batchtype, m_debugBatchIndex, m_debugFrameIndex ));
}
if (options & (1<<eDumpSurfaceInfo))
{
GLMPRINTF(("-D-" ));
GLMPRINTF(("-D- surface info:"));
GLMPRINTF(("-D- drawing FBO: %8x bound draw-FBO: %8x (%s)", m_drawingFBO, m_boundDrawFBO, (m_drawingFBO==m_boundDrawFBO) ? "in sync" : "desync!" ));
CGLMFBO *fbo = m_boundDrawFBO;
for( int i=0; i<kAttCount; i++)
{
CGLMTex *tex = fbo->m_attach[i].m_tex;
if (tex)
{
GLMPRINTF(("-D- bound FBO (%8x) attachment %d = tex %8x (GL %d) (%s)", fbo, i, tex, tex->m_texName, tex->m_layout->m_layoutSummary ));
}
else
{
// warning if no depthstencil attachment
switch(i)
{
case kAttDepth:
case kAttStencil:
case kAttDepthStencil:
GLMPRINTF(("-D- bound FBO (%8x) attachment %d = NULL, warning!", fbo, i ));
break;
}
}
}
}
#if 0 // disabled in steamworks sample for the time being
if (options & (1<<eDumpStackCrawl))
{
CStackCrawlParams cp;
memset( &cp, 0, sizeof(cp) );
cp.m_frameLimit = g_maxFramesToCrawl;
g_extCocoaMgr->GetStackCrawl(&cp);
GLMPRINTF(("-D-" ));
GLMPRINTF(("-D- stack crawl"));
for( int i=0; i< cp.m_frameCount; i++)
{
GLMPRINTF(("-D-\t%s", cp.m_crawlNames[i] ));
}
}
#endif
if ( (options & (1<<eDumpShaderLinks)) && is_draw)
{
// we want to print out - GL name, pathname to disk copy if editable, extra credit would include the summary translation line
// so grep for "#// trans#"
char attribtemp[1000];
char transtemp[1000];
if (vp)
{
char *attribmap = strstr(vp->m_text, "#//ATTRIBMAP");
if (attribmap)
{
CopyTilEOL( attribtemp, attribmap, sizeof(attribtemp) );
}
else
{
strcpy( attribtemp, "no attrib map" );
}
char *trans = strstr(vp->m_text, "#// trans#");
if (trans)
{
CopyTilEOL( transtemp, trans, sizeof(transtemp) );
}
else
{
strcpy( transtemp, "no translation info" );
}
const char *linkpath = "no file link";
#if GLMDEBUG && 0 // no editable shader support in example code
linkpath = vp->m_editable->m_mirror->m_path;
GLMPRINTF(("-D-"));
GLMPRINTF(("-D- ARBVP || GL %d || Path %s ", vp->m_descs[kGLMARB].m_object.arb, linkpath ));
GLMPRINTF(("-D- Attribs %s", attribtemp ));
GLMPRINTF(("-D- Trans %s", transtemp ));
#endif
/*
if ( (options & (1<<eDumpShaderText)) && is_draw )
{
GLMPRINTF(("-D-"));
GLMPRINTF(("-D- VP text " ));
GLMPRINTTEXT(vp->m_string, eDebugDump ));
}
*/
}
else
{
GLMPRINTF(("-D- VP (none)" ));
}
if (fp)
{
char *trans = strstr(fp->m_text, "#// trans#");
if (trans)
{
CopyTilEOL( transtemp, trans, sizeof(transtemp) );
}
else
{
strcpy( transtemp, "no translation info" );
}
const char *linkpath = "no file link";
#if GLMDEBUG && 0 // no editable shader support in example code
linkpath = fp->m_editable->m_mirror->m_path;
GLMPRINTF(("-D-"));
GLMPRINTF(("-D- FP || GL %d || Path %s ", fp->m_descs[kGLMARB].m_object.arb, linkpath ));
GLMPRINTF(("-D- Trans %s", transtemp ));
#endif
/*
if ( (options & (1<<eDumpShaderText)) && is_draw )
{
GLMPRINTF(("-D-"));
GLMPRINTF(("-D- FP text " ));
GLMPRINTTEXT((fp->m_string, eDebugDump));
}
*/
}
else
{
GLMPRINTF(("-D- FP (none)" ));
}
}
if ( (options & (1<<eDumpShaderParameters)) && is_draw )
{
GLMPRINTF(("-D-"));
GLMPRINTF(("-D- VP parameters" ));
const char *label = "";
int labelcounter = 0;
static int vmaskranges[] = { /*18,47,*/ -1,-1 };
float transposeTemp; // row, column for printing
int slotIndex = 0;
int upperSlotLimit = 4; // reduced from 61 for example code
// take a peek at the vertex attrib setup. If it has an attribute for bone weights, then raise the shader param dump limit to 256.
bool usesSkinning = false;
GLMVertexSetup *setup = &this->m_drawVertexSetup;
for( int index=0; index < kGLMVertexAttributeIndexMax; index++ )
{
usesSkinning |= (setup->m_attrMask & (1<<index)) && ((setup->m_vtxAttribMap[index]>>4)== D3DDECLUSAGE_BLENDWEIGHT);
}
if (usesSkinning)
{
upperSlotLimit = 256;
}
while( slotIndex < upperSlotLimit )
{
// if slot index is in a masked range, skip it
// if slot index is the start of a matrix, label it, print it, skip ahead 4 slots
for( int maski=0; vmaskranges[maski] >=0; maski+=2)
{
if ( (slotIndex >= vmaskranges[maski]) && (slotIndex <= vmaskranges[maski+1]) )
{
// that index is masked. set to one past end of range, print a blank line for clarity
slotIndex = vmaskranges[maski+1]+1;
GLMPrintStr("-D- .....");
}
}
if (slotIndex < upperSlotLimit)
{
float *values = &m_programParamsF[ kGLMVertexProgram ].m_values[slotIndex][0];
#if 0 // Source specific
switch( slotIndex )
{
case 4:
printmat( "MODELVIEWPROJ", slotIndex, 4, values );
slotIndex += 4;
break;
case 8:
printmat( "VIEWPROJ", slotIndex, 4, values );
slotIndex += 4;
break;
default:
if (slotIndex>=58)
{
// bone
char bonelabel[100];
sprintf(bonelabel, "MODEL_BONE%-2d", (slotIndex-58)/3 );
printmat( bonelabel, slotIndex, 3, values );
slotIndex += 3;
}
else
{
// just print the one slot
GLMPRINTF(("-D- %03d: [ %10.5f %10.5f %10.5f %10.5f ] %s", slotIndex, values[0], values[1], values[2], values[3], label ));
slotIndex++;
}
break;
}
#else
// just print the one slot
GLMPRINTF(("-D- %03d: [ %10.5f %10.5f %10.5f %10.5f ] %s", slotIndex, values[0], values[1], values[2], values[3], label ));
slotIndex++;
#endif
}
}
// VP stage still, if in GLSL mode, find the bound pair and see if it has live i0, b0-b3 uniforms
if (m_boundPair) // should only be non-NULL in GLSL mode
{
if (m_boundPair->m_locVertexBool0>=0)
{
GLMPRINTF(("-D- GLSL 'b0': %d", m_programParamsB[kGLMVertexProgram].m_values[0] ));
}
if (m_boundPair->m_locVertexBool1>=0)
{
GLMPRINTF(("-D- GLSL 'b1': %d", m_programParamsB[kGLMVertexProgram].m_values[1] ));
}
if (m_boundPair->m_locVertexBool2>=0)
{
GLMPRINTF(("-D- GLSL 'b2': %d", m_programParamsB[kGLMVertexProgram].m_values[2] ));
}
if (m_boundPair->m_locVertexBool3>=0)
{
GLMPRINTF(("-D- GLSL 'b3': %d", m_programParamsB[kGLMVertexProgram].m_values[3] ));
}
if (m_boundPair->m_locVertexInteger0>=0)
{
GLMPRINTF(("-D- GLSL 'i0': %d", m_programParamsI[kGLMVertexProgram].m_values[0][0] ));
}
}
GLMPRINTF(("-D-"));
GLMPRINTF(("-D- FP parameters " ));
static int fmaskranges[] = { 40,41, -1,-1 };
slotIndex = 0;
label = "";
while(slotIndex < 4) // reduced from 40 for example code
{
// if slot index is in a masked range, skip it
// if slot index is the start of a matrix, label it, print it, skip ahead 4 slots
for( int maski=0; fmaskranges[maski] >=0; maski+=2)
{
if ( (slotIndex >= fmaskranges[maski]) && (slotIndex <= fmaskranges[maski+1]) )
{
// that index is masked. set to one past end of range, print a blank line for clarity
slotIndex = fmaskranges[maski+1]+1;
GLMPrintStr("-D- .....");
}
}
if (slotIndex < 40)
{
float *values = &m_programParamsF[ kGLMFragmentProgram ].m_values[slotIndex][0];
#if 0 //Source specific
switch( slotIndex )
{
case 0: label = "g_EnvmapTint"; break;
case 1: label = "g_DiffuseModulation"; break;
case 2: label = "g_EnvmapContrast_ShadowTweaks"; break;
case 3: label = "g_EnvmapSaturation_SelfIllumMask (xyz, and w)"; break;
case 4: label = "g_SelfIllumTint_and_BlendFactor (xyz, and w)"; break;
case 12: label = "g_ShaderControls"; break;
case 13: label = "g_DepthFeatheringConstants"; break;
case 20: label = "g_EyePos"; break;
case 21: label = "g_FogParams"; break;
case 22: label = "g_FlashlightAttenuationFactors"; break;
case 23: label = "g_FlashlightPos"; break;
case 24: label = "g_FlashlightWorldToTexture"; break;
case 28: label = "cFlashlightColor"; break;
case 29: label = "g_LinearFogColor"; break;
case 30: label = "cLightScale"; break;
case 31: label = "cFlashlightScreenScale"; break;
default:
label = "";
break;
}
#else
label = "";
#endif
GLMPRINTF(("-D- %03d: [ %10.5f %10.5f %10.5f %10.5f ] %s", slotIndex, values[0], values[1], values[2], values[3], label ));
slotIndex ++;
}
}
//if (m_boundPair->m_locFragmentFakeSRGBEnable)
//{
// GLMPRINTF(("-D- GLSL 'flEnableSRGBWrite': %f", m_boundPair->m_fakeSRGBEnableValue ));
//}
}
if ( (options & (1<<eDumpTextureSetup)) && is_draw )
{
GLMPRINTF(( "-D-" ));
GLMPRINTF(( "-D- Texture / Sampler setup" ));
for( int i=0; i<GLM_SAMPLER_COUNT; i++ )
{
if (m_samplers[i].m_boundTex)
{
GLMTexSamplingParams *samp = &m_samplers[i].m_samp;
GLMPRINTF(( "-D-" ));
GLMPRINTF(("-D- Sampler %-2d tex %08x layout %s", i, m_samplers[i].m_boundTex, m_samplers[i].m_boundTex->m_layout->m_layoutSummary ));
GLMPRINTF(("-D- addressMode[ %s %s %s ]",
GLMDecode( eGL_ENUM, samp->m_addressModes[0] ),
GLMDecode( eGL_ENUM, samp->m_addressModes[1] ),
GLMDecode( eGL_ENUM, samp->m_addressModes[2] )
));
GLMPRINTF(("-D- magFilter [ %s ]", GLMDecode( eGL_ENUM, samp->m_magFilter ) ));
GLMPRINTF(("-D- minFilter [ %s ]", GLMDecode( eGL_ENUM, samp->m_minFilter ) ));
GLMPRINTF(("-D- srgb [ %s ]", samp->m_srgb ? "T" : "F" ));
// add more as needed later..
}
}
}
if ( (options & (1<<eDumpVertexAttribSetup)) && is_draw )
{
GLMVertexSetup *setup = &this->m_drawVertexSetup;
uint relevantMask = setup->m_attrMask;
for( int index=0; index < kGLMVertexAttributeIndexMax; index++ )
{
uint mask = 1<<index;
if (relevantMask & mask)
{
GLMVertexAttributeDesc *setdesc = &setup->m_attrs[index];
char sizestr[100];
if (setdesc->m_datasize < 32)
{
sprintf( sizestr, "%d", setdesc->m_datasize);
}
else
{
strcpy( sizestr, GLMDecode( eGL_ENUM, setdesc->m_datasize ) );
}
if (setup->m_vtxAttribMap[index] != 0xBB)
{
GLMPRINTF(("-D- attr=%-2d decl=$%s%1d stride=%-2d offset=%-3d buf=%08x bufbase=%08x size=%s type=%s normalized=%s ",
index,
GLMDecode(eD3D_VTXDECLUSAGE, setup->m_vtxAttribMap[index]>>4 ),
setup->m_vtxAttribMap[index]&0x0F,
setdesc->m_stride,
setdesc->m_offset,
setdesc->m_buffer,
setdesc->m_buffer->m_lastMappedAddress,
sizestr,
GLMDecode( eGL_ENUM, setdesc->m_datatype),
setdesc->m_normalized?"Y":"N"
));
}
else
{
// the attrib map is referencing an attribute that is not wired up in the vertex setup...
Debugger();
}
}
}
}
if ( (options & (1<<eDumpVertexData)) && is_draw )
{
GLMVertexSetup *setup = &this->m_drawVertexSetup;
int start = info->m_drawStart;
int end = info->m_drawEnd;
int endLimit = start + (1<<g_maxVertsToDumpLog2);
int realEnd = std::min( end, endLimit );
// vertex data
GLMPRINTF(("-D-"));
GLMPRINTF(("-D- Vertex Data : %d of %d verts (index %d through %d)", realEnd-start, end-start, start, realEnd-1));
for( int vtxIndex=-1; vtxIndex < realEnd; vtxIndex++ ) // vtxIndex will jump from -1 to start after first spin, not necessarily to 0
{
char buf[64000];
char *mark = buf;
// index -1 is the first run through the loop, we just print a header
// iterate attrs
if (vtxIndex>=0)
{
mark += sprintf(mark, "-D- %04d: ", vtxIndex );
}
// for transform dumping, we latch values as we spot them
float vtxPos[4];
int vtxBoneIndices[4]; // only three get used
float vtxBoneWeights[4]; // only three get used and index 2 is synthesized from 0 and 1
vtxPos[0] = vtxPos[1] = vtxPos[2] = 0.0;
vtxPos[3] = 1.0;
vtxBoneIndices[0] = vtxBoneIndices[1] = vtxBoneIndices[2] = vtxBoneIndices[3] = 0;
vtxBoneWeights[0] = vtxBoneWeights[1] = vtxBoneWeights[2] = vtxBoneWeights[3] = 0.0;
for( int attr = 0; attr < kGLMVertexAttributeIndexMax; attr++ )
{
if (setup->m_attrMask & (1<<attr) )
{
GLMVertexAttributeDesc *desc = &setup->m_attrs[ attr ];
// print that attribute.
// on OSX, VB's never move unless resized. You can peek at them when unmapped. Safe enough for debug..
char *bufferBase = (char*)desc->m_buffer->m_lastMappedAddress;
uint stride = desc->m_stride;
uint fieldoffset = desc->m_offset;
uint baseoffset = vtxIndex * stride;
char *attrBase = bufferBase + baseoffset + fieldoffset;
uint usage = setup->m_vtxAttribMap[attr]>>4;
uint usageindex = setup->m_vtxAttribMap[attr]&0x0F;
if (vtxIndex <0)
{
mark += sprintf(mark, "[%s%1d @ offs=%04d / strd %03d] ", GLMDecode(eD3D_VTXDECLUSAGE, usage ), usageindex, fieldoffset, stride );
}
else
{
mark += sprintf(mark, "[%s%1d ", GLMDecode(eD3D_VTXDECLUSAGE, usage ), usageindex );
if (desc->m_datasize<32)
{
for( int which = 0; which < desc->m_datasize; which++ )
{
static const char *fieldname = "xyzw";
switch( desc->m_datatype )
{
case GL_FLOAT:
{
float *floatbase = (float*)attrBase;
mark += sprintf(mark, (usage != D3DDECLUSAGE_TEXCOORD) ? "%c%7.3f " : "%c%.3f", fieldname[which], floatbase[which] );
if (usage==D3DDECLUSAGE_POSITION)
{
if (which<4)
{
// latch pos
vtxPos[which] = floatbase[which];
}
}
if (usage==D3DDECLUSAGE_BLENDWEIGHT)
{
if (which<4)
{
// latch weight
vtxBoneWeights[which] = floatbase[which];
}
}
}
break;
case GL_UNSIGNED_BYTE:
{
unsigned char *unchbase = (unsigned char*)attrBase;
mark += sprintf(mark, "%c$%02X ", fieldname[which], unchbase[which] );
}
break;
default:
// hold off on other formats for now
mark += sprintf(mark, "%c????? ", fieldname[which] );
break;
}
}
}
else // special path for BGRA bytes which are expressed in GL by setting the *size* to GL_BGRA (gross large enum)
{
switch(desc->m_datasize)
{
case GL_BGRA: // byte reversed color
{
for( int which = 0; which < 4; which++ )
{
static const char *fieldname = "BGRA";
switch( desc->m_datatype )
{
case GL_UNSIGNED_BYTE:
{
unsigned char *unchbase = (unsigned char*)attrBase;
mark += sprintf(mark, "%c$%02X ", fieldname[which], unchbase[which] );
if (usage==D3DDECLUSAGE_BLENDINDICES)
{
if (which<4)
{
// latch index
vtxBoneIndices[which] = unchbase[which]; // ignoring the component reverse which BGRA would inflict, but we also ignore it below so it matches up.
}
}
}
break;
default:
Debugger();
break;
}
}
}
break;
}
}
mark += sprintf(mark, "] " );
}
}
}
GLMPrintStr( buf, eDebugDump );
if (vtxIndex >=0)
{
// if transform dumping requested, and we've reached the actual vert dump phase, do it
float vtxout[4];
const char *translabel = NULL; // NULL means no print...
switch( g_vertDumpMode )
{
case eDumpVertsNoTransformDump: break;
case eDumpVertsTransformedByViewProj: // viewproj is slot 8
{
float *viewproj = &m_programParamsF[ kGLMVertexProgram ].m_values[8][0];
transform_dp4( vtxPos, viewproj, 4, vtxout );
translabel = "post-viewproj";
}
break;
case eDumpVertsTransformedByModelViewProj: // modelviewproj is slot 4
{
float *modelviewproj = &m_programParamsF[ kGLMVertexProgram ].m_values[4][0];
transform_dp4( vtxPos, modelviewproj, 4, vtxout );
translabel = "post-modelviewproj";
}
break;
case eDumpVertsTransformedByBoneZeroThenViewProj:
{
float postbone[4];
postbone[3] = 1.0;
float *bonemat = &m_programParamsF[ kGLMVertexProgram ].m_values[58][0];
transform_dp4( vtxPos, bonemat, 3, postbone );
float *viewproj = &m_programParamsF[ kGLMVertexProgram ].m_values[8][0]; // viewproj is slot 8
transform_dp4( postbone, viewproj, 4, vtxout );
translabel = "post-bone0-viewproj";
}
break;
case eDumpVertsTransformedByBonesThenViewProj:
{
float bone[4][4]; // [bone index][bone member] // members are adjacent
vtxout[0] = vtxout[1] = vtxout[2] = vtxout[3] = 0;
// unpack the third weight
vtxBoneWeights[2] = 1.0 - (vtxBoneWeights[0] + vtxBoneWeights[1]);
for( int ibone=0; ibone<3; ibone++ )
{
int boneindex = vtxBoneIndices[ ibone ];
float *bonemat = &m_programParamsF[ kGLMVertexProgram ].m_values[58+(boneindex*3)][0];
float boneweight = vtxBoneWeights[ibone];
float postbonevtx[4];
transform_dp4( vtxPos, bonemat, 3, postbonevtx );
// add weighted sum into output
for( int which=0; which<4; which++ )
{
vtxout[which] += boneweight * postbonevtx[which];
}
}
// fix W ? do we care ? check shaders to see what they do...
translabel = "post-skin3bone-viewproj";
}
break;
}
if(translabel)
{
// for extra credit, do the perspective divide and viewport
GLMPRINTF(("-D- %-24s: [ %7.4f %7.4f %7.4f %7.4f ]", translabel, vtxout[0],vtxout[1],vtxout[2],vtxout[3] ));
GLMPRINTF(("-D-" ));
}
}
if (vtxIndex<0)
{
vtxIndex = start-1; // for printing of the data (note it will be incremented at bottom of loop, so bias down by 1)
}
else
{ // no more < and > around vert dump lines
//mark += sprintf(mark, "" );
}
}
}
if (options & (1<<eOpenShadersForEdit) )
{
#if GLMDEBUG && 0 // not in example sorry
if (m_drawingProgram[ kGLMVertexProgram ])
{
m_drawingProgram[ kGLMVertexProgram ]->m_editable->OpenInEditor();
}
if (m_drawingProgram[ kGLMFragmentProgram ])
{
m_drawingProgram[ kGLMFragmentProgram ]->m_editable->OpenInEditor();
}
#endif
}
/*
if (options & (1<<))
{
}
*/
// trailer line
GLMPRINTF(("-D- ===================================================================================== end %s %d frame %d", batchtype, m_debugBatchIndex, m_debugFrameIndex ));
GLMSetIndent(oldIndent);
}
// here is the table that binds knob numbers to names. change at will.
const char *g_knobnames[] =
{
/*0*/ "dummy",
/*1*/ "FB-SRGB",
#if 0
/*1*/ "tex-U0-bias", // src left
/*2*/ "tex-V0-bias", // src upper
/*3*/ "tex-U1-bias", // src right
/*4*/ "tex-V1-bias", // src bottom
/*5*/ "pos-X0-bias", // dst left
/*6*/ "pos-Y0-bias", // dst upper
/*7*/ "pos-X1-bias", // dst right
/*8*/ "pos-Y1-bias", // dst bottom
#endif
};
int g_knobcount = sizeof( g_knobnames ) / sizeof( g_knobnames[0] );
void GLMContext::DebugHook( GLMDebugHookInfo *info )
{
#if 0 // disabled in steamworks example for time being
bool debughook = false;
// debug hook is called after an action has taken place.
// that would be the initial action, or a repeat.
// if paused, we stay inside this function until return.
// when returning, we inform the caller if it should repeat its last action or continue.
// there is no global pause state. The rest of the app runs at the best speed it can.
// initial stuff we do unconditionally
// increment iteration
info->m_iteration++; // can be thought of as "number of times the caller's action has now occurred - starting at 1"
// now set initial state guess for the info block (outcome may change below)
info->m_loop = false;
// check prior hold-conditions to see if any of them hit.
// note we disarm each trigger once the hold has occurred (one-shot style)
switch( info->m_caller )
{
case eBeginFrame:
if (debughook) GLMPRINTF(("-D- Caller: BeginFrame" ));
if ( (m_holdFrameBegin>=0) && (m_holdFrameBegin==m_debugFrameIndex) ) // did we hit a frame breakpoint?
{
if (debughook) GLMPRINTF(("-D- BeginFrame trigger match, clearing m_holdFrameBegin, hold=true" ));
m_holdFrameBegin = -1;
info->m_holding = true;
}
break;
case eClear:
if (debughook) GLMPRINTF(("-D- Caller: Clear" ));
if ( (m_holdBatch>=0) && (m_holdBatchFrame>=0) && (m_holdBatch==m_debugBatchIndex) && (m_holdBatchFrame==m_debugFrameIndex) )
{
if (debughook) GLMPRINTF(("-D- Clear trigger match, clearing m_holdBatch&Frame, hold=true" ));
m_holdBatch = m_holdBatchFrame = -1;
info->m_holding = true;
}
break;
case eDrawElements:
if (debughook) GLMPRINTF(( (info->m_caller==eClear) ? "-D- Caller: Clear" : "-D- Caller: Draw" ));
if ( (m_holdBatch>=0) && (m_holdBatchFrame>=0) && (m_holdBatch==m_debugBatchIndex) && (m_holdBatchFrame==m_debugFrameIndex) )
{
if (debughook) GLMPRINTF(("-D- Draw trigger match, clearing m_holdBatch&Frame, hold=true" ));
m_holdBatch = m_holdBatchFrame = -1;
info->m_holding = true;
}
break;
case eEndFrame:
if (debughook) GLMPRINTF(("-D- Caller: EndFrame" ));
// check for any expired batch hold req
if ( (m_holdBatch>=0) && (m_holdBatchFrame>=0) && (m_holdBatchFrame==m_debugFrameIndex) )
{
// you tried to say 'next batch', but there wasn't one in this frame.
// target first batch of next frame instead
if (debughook) GLMPRINTF(("-D- EndFrame noticed an expired draw hold trigger, rolling to next frame, hold=false"));
m_holdBatch = 0;
m_holdBatchFrame++;
info->m_holding = false;
}
// now check for an explicit hold on end of this frame..
if ( (m_holdFrameEnd>=0) && (m_holdFrameEnd==m_debugFrameIndex) )
{
if (debughook) GLMPRINTF(("-D- EndFrame trigger match, clearing m_holdFrameEnd, hold=true" ));
m_holdFrameEnd = -1;
info->m_holding = true;
}
break;
}
// spin until event queue is empty *and* hold is false
int evtcount=0;
bool refresh = info->m_holding || m_debugDelayEnable; // only refresh once per initial visit (if paused!) or follow up event input
int breakToDebugger = 0;
// 1 = break to GDB
// 2 = break to OpenGL Profiler if attached
do
{
if (refresh)
{
if (debughook) GLMPRINTF(("-D- pushing pixels" ));
this->DebugPresent(); // show pixels
uint minidumpOptions = (1<<eDumpBatchInfo) /* | (1<<eDumpSurfaceInfo) */;
this->DebugDump( info, minidumpOptions, g_vertDumpMode );
usleep(10000); // lil sleep
refresh = false;
}
bool eventCheck = true; // event pull will be skipped if we detect a shader edit being done
// keep editable shaders in sync
#if GLMDEBUG
bool redrawBatch = false;
if (m_drawingProgram[ kGLMVertexProgram ])
{
if( m_drawingProgram[ kGLMVertexProgram ]->SyncWithEditable() )
{
redrawBatch = true;
}
}
if (m_drawingProgram[ kGLMFragmentProgram ])
{
if( m_drawingProgram[ kGLMFragmentProgram ]->SyncWithEditable() )
{
redrawBatch = true;
}
}
if (redrawBatch)
{
// act as if user pressed the option-\ key
if (m_drawingLang == kGLMGLSL)
{
// if GLSL mode, force relink - and refresh the pair cache as needed
if (m_boundPair)
{
// fix it in place
m_boundPair->RefreshProgramPair();
}
}
FlushDrawStates( true ); // this is key, because the linked shader pair may have changed (note call to PurgePairsWithShader in cglmprogram.cpp)
GLMPRINTF(("-- Shader changed, re-running batch" ));
m_holdBatch = m_debugBatchIndex;
m_holdBatchFrame = m_debugFrameIndex;
m_debugDelayEnable = false;
info->m_holding = false;
info->m_loop = true;
eventCheck = false;
}
#endif
if(eventCheck)
{
g_extCocoaMgr->PumpWindowsMessageLoop();
CCocoaEvent evt;
evtcount = g_extCocoaMgr->GetEvents( &evt, 1, true ); // asking for debug events only.
if (evtcount)
{
// print it
if (debughook) GLMPRINTF(("-D- Received debug key '%c' with modifiers %x", evt.m_UnicodeKeyUnmodified, evt.m_ModifierKeyMask ));
// flag for refresh if we spin again
refresh = 1;
switch(evt.m_UnicodeKeyUnmodified)
{
case ' ': // toggle pause
// clear all the holds to be sure
m_holdFrameBegin = m_holdFrameEnd = m_holdBatch = m_holdBatchFrame = -1;
info->m_holding = !info->m_holding;
if (!info->m_holding)
{
m_debugDelayEnable = false; // coming out of pause means no slow mo
}
GLMPRINTF((info->m_holding ? "-D- Paused." : "-D- Unpaused." ));
break;
case 'f': // frame advance
GLMPRINTF(("-D- Command: next frame" ));
m_holdFrameBegin = m_debugFrameIndex+1; // stop at top of next numbered frame
m_debugDelayEnable = false; // get there fast
info->m_holding = false;
break;
case ']': // ahead 1 batch
case '}': // ahead ten batches
{
int delta = evt.m_UnicodeKeyUnmodified == ']' ? 1 : 10;
m_holdBatch = m_debugBatchIndex+delta;
m_holdBatchFrame = m_debugFrameIndex;
m_debugDelayEnable = false; // get there fast
info->m_holding = false;
GLMPRINTF(("-D- Command: advance %d batches to %d", delta, m_holdBatch ));
}
break;
case '[': // back one batch
case '{': // back 10 batches
{
int delta = evt.m_UnicodeKeyUnmodified == '[' ? -1 : -10;
m_holdBatch = m_debugBatchIndex + delta;
if (m_holdBatch<0)
{
m_holdBatch = 0;
}
m_holdBatchFrame = m_debugFrameIndex+1; // next frame, but prev batch #
m_debugDelayEnable = false; // get there fast
info->m_holding = false;
GLMPRINTF(("-D- Command: rewind %d batches to %d", delta, m_holdBatch ));
}
break;
case '\\': // batch rerun
m_holdBatch = m_debugBatchIndex;
m_holdBatchFrame = m_debugFrameIndex;
m_debugDelayEnable = false;
info->m_holding = false;
info->m_loop = true;
GLMPRINTF(("-D- Command: re-run batch %d", m_holdBatch ));
break;
case 'c': // toggle auto color clear
m_autoClearColor = !m_autoClearColor;
GLMPRINTF((m_autoClearColor ? "-D- Auto color clear ON" : "-D- Auto color clear OFF" ));
break;
case 's': // toggle auto stencil clear
m_autoClearStencil = !m_autoClearStencil;
GLMPRINTF((m_autoClearStencil ? "-D- Auto stencil clear ON" : "-D- Auto stencil clear OFF" ));
break;
case 'd': // toggle auto depth clear
m_autoClearDepth = !m_autoClearDepth;
GLMPRINTF((m_autoClearDepth ? "-D- Auto depth clear ON" : "-D- Auto depth clear OFF" ));
break;
case '.': // break to debugger or insta-quit
if (evt.m_ModifierKeyMask & (1<<eControlKey))
{
GLMPRINTF(( "-D- INSTA QUIT! (TM) (PAT PEND)" ));
abort();
}
else
{
GLMPRINTF(( "-D- Breaking to debugger" ));
breakToDebugger = 1;
info->m_holding = true;
info->m_loop = true; // so when you come back from debugger, you get another spin (i.e. you enter paused mode)
}
break;
case 'g': // break to OGLP and enable OGLP logging of spew
if (GLMDetectOGLP()) // if this comes back true, there will be a breakpoint set on glColor4sv.
{
uint channelMask = GLMDetectAvailableChannels(); // will re-assert whether spew goes to OGLP log
if (channelMask & (1<<eGLProfiler))
{
GLMDebugChannelMask(&channelMask);
breakToDebugger = 2;
info->m_holding = true;
info->m_loop = true; // so when you come back from debugger, you get another spin (i.e. you enter paused mode)
}
}
break;
case '_': // toggle slow mo
m_debugDelayEnable = !m_debugDelayEnable;
break;
case '-': // go slower
if (m_debugDelayEnable)
{
// already in slow mo, so lower speed
m_debugDelay <<= 1; // double delay
if (m_debugDelay > (1<<24))
{
m_debugDelay = (1<<24);
}
}
else
{
// enter slow mo
m_debugDelayEnable = true;
}
break;
case '=': // go faster
if (m_debugDelayEnable)
{
// already in slow mo, so raise speed
m_debugDelay >>= 1; // halve delay
if (m_debugDelay < (1<<17))
{
m_debugDelay = (1<<17);
}
}
else
{
// enter slow mo
m_debugDelayEnable = true;
}
break;
case 'v':
// open vs in editor (foreground pop)
#if GLMDEBUG
if (m_boundProgram[ kGLMVertexProgram ])
{
m_boundProgram[ kGLMVertexProgram ]->m_editable->OpenInEditor( true );
}
#endif
break;
case 'p':
// open fs/ps in editor (foreground pop)
#if GLMDEBUG
if (m_boundProgram[ kGLMFragmentProgram ])
{
m_boundProgram[ kGLMFragmentProgram ]->m_editable->OpenInEditor( true );
}
#endif
break;
case '<': // dump fewer verts
case '>': // dump more verts
{
int delta = (evt.m_UnicodeKeyUnmodified=='>') ? 1 : -1;
g_maxVertsToDumpLog2 = MIN( MAX( g_maxVertsToDumpLog2+delta, 0 ), 16 );
// just re-dump the verts
DebugDump( info, 1<<eDumpVertexData, g_vertDumpMode );
}
break;
case 'x': // adjust transform dump mode
{
int newmode = g_vertDumpMode+1;
if (newmode >= eLastDumpVertsMode)
{
// wrap
newmode = eDumpVertsNoTransformDump;
}
g_vertDumpMode = (EGLMVertDumpMode)newmode;
GLMPRINTF(("-D- New vert dump mode is %s", g_vertDumpModeNames[g_vertDumpMode] ));
}
break;
case 'u': // more crawl
{
CStackCrawlParams cp;
memset( &cp, 0, sizeof(cp) );
cp.m_frameLimit = kMaxCrawlFrames;
g_extCocoaMgr->GetStackCrawl(&cp);
GLMPRINTF(("-D-" ));
GLMPRINTF(("-D- extended stack crawl:"));
for( int i=0; i< cp.m_frameCount; i++)
{
GLMPRINTF(("-D-\t%s", cp.m_crawlNames[i] ));
}
}
break;
case 'q':
DebugDump( info, 0xFFFFFFFF, g_vertDumpMode );
break;
case 'H':
case 'h':
{
// toggle drawing language. hold down shift key to do it immediately.
if (m_caps.m_hasDualShaders)
{
bool immediate;
immediate = evt.m_UnicodeKeyUnmodified == 'H'; // (evt.m_ModifierKeyMask & (1<<eShiftKey)) != 0;
if (m_drawingLang==kGLMARB)
{
GLMPRINTF(( "-D- Setting GLSL language mode %s.", immediate ? "immediately" : "for next frame start" ));
SetDrawingLang( kGLMGLSL, immediate );
}
else
{
GLMPRINTF(( "-D- Setting ARB language mode %s.", immediate ? "immediately" : "for next frame start" ));
SetDrawingLang( kGLMARB, immediate );
}
refresh = immediate;
}
else
{
GLMPRINTF(("You can't change shader languages unless you launch with -glmdualshaders enabled"));
}
}
break;
// ======================================================== debug knobs. change these as needed to troubleshoot stuff
// keys to select a knob
// or, toggle a debug flavor, if control is being held down
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
{
if (evt.m_ModifierKeyMask & (1<<eControlKey))
{
// '0' toggles the all-channels on or off
int flavorSelect = evt.m_UnicodeKeyUnmodified - '0';
if ( (flavorSelect >=0) && (flavorSelect<eFlavorCount) )
{
uint mask = GLMDebugFlavorMask();
mask ^= (1<<flavorSelect);
GLMDebugFlavorMask(&mask);
}
}
else
{
// knob selection
m_selKnobIndex = evt.m_UnicodeKeyUnmodified - '0';
GLMPRINTF(("-D- Knob # %d (%s) selected.", m_selKnobIndex, g_knobnames[ m_selKnobIndex ] ));
m_selKnobIncrement = (m_selKnobIndex<5) ? (1.0f / 2048.0f) : (1.0 / 256.0f);
usleep( 500000 );
}
refresh = false;
}
break;
// keys to adjust or zero a knob
case 't': // toggle
{
if (m_selKnobIndex < g_knobcount)
{
GLMKnobToggle( g_knobnames[ m_selKnobIndex ] );
}
}
break;
case 'l': // less
case 'm': // more
case 'z': // zero
{
if (m_selKnobIndex < g_knobcount)
{
float val = GLMKnob( g_knobnames[ m_selKnobIndex ], NULL );
if (evt.m_UnicodeKeyUnmodified == 'l')
{
// minus (less)
val -= m_selKnobIncrement;
if (val < m_selKnobMinValue)
{
val = m_selKnobMinValue;
}
// send new value back to the knob
GLMKnob( g_knobnames[ m_selKnobIndex ], &val );
}
if (evt.m_UnicodeKeyUnmodified == 'm')
{
// plus (more)
val += m_selKnobIncrement;
if (val > m_selKnobMaxValue)
{
val = m_selKnobMaxValue;
}
// send new value back to the knob
GLMKnob( g_knobnames[ m_selKnobIndex ], &val );
}
if (evt.m_UnicodeKeyUnmodified == 'z')
{
// zero
val = 0.0f;
// send new value back to the knob
GLMKnob( g_knobnames[ m_selKnobIndex ], &val );
}
GLMPRINTF(("-D- Knob # %d (%s) set to %f (%f/1024.0)", m_selKnobIndex, g_knobnames[ m_selKnobIndex ], val, val * 1024.0 ));
usleep( 500000 );
refresh = false;
}
}
break;
}
}
}
} while( ((evtcount>0) || info->m_holding) && (!breakToDebugger) );
if (m_debugDelayEnable)
{
usleep( m_debugDelay );
}
if (breakToDebugger)
{
switch (breakToDebugger)
{
case 1:
Debugger();
break;
case 2:
short fakecolor[4];
glColor4sv( fakecolor ); // break to OGLP
break;
}
// re-flush all GLM states so you can fiddle with them in the debugger. then run the batch again and spin..
FlushStates( true );
}
#endif
}
void GLMContext::DebugPresent( void )
{
CGLMTex *drawBufferTex = m_drawingFBO->m_attach[kAttColor0].m_tex;
glFinish();
this->Present( drawBufferTex );
}
void GLMContext::DebugClear( void )
{
// get old clear color
GLClearColor_t clearcol_orig;
m_ClearColor.Read( &clearcol_orig,0 );
// new clear color
GLClearColor_t clearcol;
clearcol.r = m_autoClearColorValues[0];
clearcol.g = m_autoClearColorValues[1];
clearcol.b = m_autoClearColorValues[2];
clearcol.a = m_autoClearColorValues[3];
m_ClearColor.Write( &clearcol, true, true ); // don't check, don't defer
uint mask = 0;
if (m_autoClearColor) mask |= GL_COLOR_BUFFER_BIT;
if (m_autoClearDepth) mask |= GL_DEPTH_BUFFER_BIT;
if (m_autoClearStencil) mask |= GL_STENCIL_BUFFER_BIT;
glClear( mask );
glFinish();
// put old color back
m_ClearColor.Write( &clearcol_orig, true, true ); // don't check, don't defer
}
#endif
void GLMContext::DrawRangeElements( GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices )
{
GLM_FUNC;
// CheckCurrent();
m_debugBatchIndex++; // batch index increments unconditionally on entry
bool hasVP = m_boundProgram[ kGLMVertexProgram ] != NULL;
bool hasFP = m_boundProgram[ kGLMFragmentProgram ] != NULL;
void *indicesActual = (void*)indices;
if (m_drawIndexBuffer->m_pseudo)
{
// you have to pass actual address, not offset... shhh... secret
indicesActual = (void*)((uintptr_t)indicesActual + (uintptr_t)m_drawIndexBuffer->m_pseudoBuf);
}
#if GLMDEBUG
// init debug hook information
GLMDebugHookInfo info;
memset( &info, 0, sizeof(info) );
info.m_caller = eDrawElements;
// relay parameters we're operating under
info.m_drawMode = mode;
info.m_drawStart = start;
info.m_drawEnd = end;
info.m_drawCount = count;
info.m_drawType = type;
info.m_drawIndices = indices;
do
{
// obey global options re pre-draw clear
if (m_autoClearColor || m_autoClearDepth || m_autoClearStencil)
{
GLMPRINTF(("-- DrawRangeElements auto clear" ));
this->DebugClear();
}
// always sync with editable shader text prior to draw
#if GLMDEBUG
//FIXME disengage this path if context is in GLSL mode..
// it will need fixes to get the shader pair re-linked etc if edits happen anyway.
if (m_boundProgram[ kGLMVertexProgram ])
{
m_boundProgram[ kGLMVertexProgram ]->SyncWithEditable();
}
else
{
//AssertOnce(!"drawing with no vertex program bound");
}
if (m_boundProgram[ kGLMFragmentProgram ])
{
m_boundProgram[ kGLMFragmentProgram ]->SyncWithEditable();
}
else
{
//AssertOnce(!"drawing with no fragment program bound");
}
#endif
// do the drawing
if (hasVP && hasFP)
{
glDrawRangeElements( mode, start, end, count, type, indicesActual );
GLMCheckError();
if (m_slowCheckEnable)
{
CheckNative();
}
}
this->DebugHook( &info );
} while (info.m_loop);
#else
if (hasVP && hasFP)
{
glDrawRangeElements( mode, start, end, count, type, indicesActual );
GLMCheckError();
if (m_slowCheckEnable)
{
CheckNative();
}
}
#endif
}
void GLMContext::DrawArrays( GLenum mode, GLuint first, GLuint count )
{
GLM_FUNC;
m_debugBatchIndex++; // batch index increments unconditionally on entry
bool hasVP = m_boundProgram[ kGLMVertexProgram ] != NULL;
bool hasFP = m_boundProgram[ kGLMFragmentProgram ] != NULL;
// note that the GLMDEBUG path is not wired up here yet
if (hasVP && hasFP)
{
#if GLMDEBUG && 0
// init debug hook information
GLMDebugHookInfo info;
memset( &info, 0, sizeof(info) );
info.m_caller = eDrawArrays;
// relay parameters we're operating under
info.m_drawMode = mode;
info.m_drawStart = first;
info.m_drawEnd = first+count;
info.m_drawCount = count;
info.m_drawType = 0; // no one was using this anyway..
info.m_drawIndices = NULL;
glDrawArrays(mode, first, count);
GLMCheckError();
DebugDump( &info, 0xFFFFFFFF, g_vertDumpMode );
#else
glDrawArrays(mode, first, count);
GLMCheckError();
#endif
if (m_slowCheckEnable)
{
CheckNative();
}
}
}
void GLMContext::CheckNative( void )
{
// note that this is available in release. We don't use GLMPRINTF for that reason.
// note we do not get called unless either slow-batch asserting or logging is enabled.
bool gpuProcessing;
GLint fragmentGPUProcessing, vertexGPUProcessing;
CGLGetParameter (CGLGetCurrentContext(), kCGLCPGPUFragmentProcessing, &fragmentGPUProcessing);
CGLGetParameter(CGLGetCurrentContext(), kCGLCPGPUVertexProcessing, &vertexGPUProcessing);
// spews then asserts.
// that way you can enable both, get log output on a pair if it's slow, and then the debugger will pop.
if(m_slowSpewEnable)
{
if ( !vertexGPUProcessing )
{
m_boundProgram[ kGLMVertexProgram ]->LogSlow( m_drawingLang );
}
if ( !fragmentGPUProcessing )
{
m_boundProgram[ kGLMFragmentProgram ]->LogSlow( m_drawingLang );
}
}
if(m_slowAssertEnable)
{
if ( !vertexGPUProcessing || !fragmentGPUProcessing)
{
Assert( !"slow batch" );
}
}
}
// debug font
void GLMContext::GenDebugFontTex( void )
{
if(!m_debugFontTex)
{
// make a 128x128 RGBA texture
GLMTexLayoutKey key;
memset( &key, 0, sizeof(key) );
key.m_texGLTarget = GL_TEXTURE_2D;
key.m_xSize = 128;
key.m_ySize = 128;
key.m_zSize = 1;
key.m_texFormat = D3DFMT_A8R8G8B8;
key.m_texFlags = 0;
m_debugFontTex = this->NewTex( &key, "GLM debug font" );
//-----------------------------------------------------
GLMTexLockParams lockreq;
lockreq.m_tex = m_debugFontTex;
lockreq.m_face = 0;
lockreq.m_mip = 0;
GLMTexLayoutSlice *slice = &m_debugFontTex->m_layout->m_slices[ lockreq.m_tex->CalcSliceIndex( lockreq.m_face, lockreq.m_mip ) ];
lockreq.m_region.xmin = lockreq.m_region.ymin = lockreq.m_region.zmin = 0;
lockreq.m_region.xmax = slice->m_xSize;
lockreq.m_region.ymax = slice->m_ySize;
lockreq.m_region.zmax = slice->m_zSize;
char *lockAddress;
int yStride;
int zStride;
m_debugFontTex->Lock( &lockreq, &lockAddress, &yStride, &zStride );
GLMCheckError();
//-----------------------------------------------------
// fetch elements of font data and make texels... we're doing the whole slab so we don't really need the stride info
unsigned long *destTexelPtr = (unsigned long *)lockAddress;
for( int index = 0; index < 16384; index++ )
{
if (g_glmDebugFontMap[index] == ' ')
{
// clear
*destTexelPtr = 0x00000000;
}
else
{
// opaque white (drawing code can modulate if desired)
*destTexelPtr = 0xFFFFFFFF;
}
destTexelPtr++;
}
//-----------------------------------------------------
GLMTexLockParams unlockreq;
unlockreq.m_tex = m_debugFontTex;
unlockreq.m_face = 0;
unlockreq.m_mip = 0;
// region need not matter for unlocks
unlockreq.m_region.xmin = unlockreq.m_region.ymin = unlockreq.m_region.zmin = 0;
unlockreq.m_region.xmax = unlockreq.m_region.ymax = unlockreq.m_region.zmax = 0;
m_debugFontTex->Unlock( &unlockreq );
GLMCheckError();
//-----------------------------------------------------
// change up the tex sampling on this texture to be "nearest" not linear
//-----------------------------------------------------
// don't leave texture bound on the TMU
this->BindTexToTMU(NULL, 0 );
// also make the index and vertex buffers for use - up to 1K indices and 1K verts
uint indexBufferSize = 1024*2;
m_debugFontIndices = this->NewBuffer(kGLMIndexBuffer, indexBufferSize, 0); // two byte indices
// we go ahead and lock it now, and fill it with indices 0-1023.
char *indices = NULL;
GLMBuffLockParams idxLock;
idxLock.m_offset = 0;
idxLock.m_size = indexBufferSize;
idxLock.m_nonblocking = false;
idxLock.m_discard = false;
m_debugFontIndices->Lock( &idxLock, &indices );
for( int i=0; i<1024; i++)
{
unsigned short *idxPtr = &((unsigned short*)indices)[i];
*idxPtr = i;
}
m_debugFontIndices->Unlock();
m_debugFontVertices = this->NewBuffer(kGLMVertexBuffer, 1024 * 128, 0); // up to 128 bytes per vert
}
}
#define MAX_DEBUG_CHARS 256
struct GLMDebugTextVertex
{
float x,y,z;
float u,v;
char rgba[4];
};
void GLMContext::DrawDebugText( float x, float y, float z, float drawCharWidth, float drawCharHeight, char *string )
{
if (!m_debugFontTex)
{
GenDebugFontTex();
}
// setup needed to draw text
// we're assuming that +x goes left to right on screen, no billboarding math in here
// and that +y goes bottom up
// caller knows projection / rectangle so it gets to decide vertex spacing
// debug font must be bound to TMU 0
// texturing enabled
// alpha blending enabled
// generate a quad per character
// characters are 6px wide by 11 px high.
// upper left character in tex is 0x20
// y axis will need to be flipped for display
// for any character in 0x20 - 0x7F - here are the needed UV's
// leftU = ((character % 16) * 6.0f / 128.0f)
// rightU = lowU + (6.0 / 128.0);
// topV = ((character - 0x20) * 11.0f / 128.0f)
// bottomV = lowV + (11.0f / 128.0f)
int stringlen = strlen( string );
if (stringlen > MAX_DEBUG_CHARS)
{
stringlen = MAX_DEBUG_CHARS;
}
// lock
char *vertices = NULL;
GLMBuffLockParams vtxLock;
vtxLock.m_offset = 0;
vtxLock.m_size = 1024 * stringlen;
vtxLock.m_nonblocking = false;
vtxLock.m_discard = false;
m_debugFontVertices->Lock( &vtxLock, &vertices );
GLMDebugTextVertex *vtx = (GLMDebugTextVertex*)vertices;
GLMDebugTextVertex *vtxOutPtr = vtx;
for( int charindex = 0; charindex < stringlen; charindex++ )
{
float leftU,rightU,topV,bottomV;
int character = (int)string[charindex];
character -= 0x20;
if ( (character<0) || (character > 0x7F) )
{
character = '*' - 0x20;
}
leftU = ((character & 0x0F) * 6.0f ) / 128.0f;
rightU = leftU + (6.0f / 128.0f);
topV = ((character >> 4) * 11.0f ) / 128.0f;
bottomV = topV + (11.0f / 128.0f);
float posx,posy,posz;
posx = x + (drawCharWidth * (float)charindex);
posy = y;
posz = z;
// generate four verts
// first vert will be upper left of displayed quad (low X, high Y) then we go clockwise
for( int quadvert = 0; quadvert < 4; quadvert++ )
{
bool isTop = (quadvert <2); // verts 0 and 1
bool isLeft = (quadvert & 1) == (quadvert >> 1); // verts 0 and 3
vtxOutPtr->x = posx + (isLeft ? 0.0f : drawCharWidth);
vtxOutPtr->y = posy + (isTop ? drawCharHeight : 0.0f);
vtxOutPtr->z = posz;
vtxOutPtr->u = isLeft ? leftU : rightU;
vtxOutPtr->v = isTop ? topV : bottomV;
vtxOutPtr++;
}
}
// verts are done.
// unlock...
m_debugFontVertices->Unlock();
// make a vertex setup
GLMVertexSetup vertSetup;
// position, color, tc = 0, 3, 8
vertSetup.m_attrMask = (1<<kGLMGenericAttr00) | (1<<kGLMGenericAttr03) | (1<<kGLMGenericAttr08);
vertSetup.m_attrs[kGLMGenericAttr00].m_buffer = m_debugFontVertices;
vertSetup.m_attrs[kGLMGenericAttr00].m_datasize = 3; // 3 floats
vertSetup.m_attrs[kGLMGenericAttr00].m_datatype = GL_FLOAT;
vertSetup.m_attrs[kGLMGenericAttr00].m_stride = sizeof(GLMDebugTextVertex);
vertSetup.m_attrs[kGLMGenericAttr00].m_offset = offsetof(GLMDebugTextVertex, x);
vertSetup.m_attrs[kGLMGenericAttr00].m_normalized= false;
vertSetup.m_attrs[kGLMGenericAttr03].m_buffer = m_debugFontVertices;
vertSetup.m_attrs[kGLMGenericAttr03].m_datasize = 4; // four bytes
vertSetup.m_attrs[kGLMGenericAttr03].m_datatype = GL_UNSIGNED_BYTE;
vertSetup.m_attrs[kGLMGenericAttr03].m_stride = sizeof(GLMDebugTextVertex);
vertSetup.m_attrs[kGLMGenericAttr03].m_offset = offsetof(GLMDebugTextVertex, rgba);
vertSetup.m_attrs[kGLMGenericAttr03].m_normalized= true;
vertSetup.m_attrs[kGLMGenericAttr08].m_buffer = m_debugFontVertices;
vertSetup.m_attrs[kGLMGenericAttr08].m_datasize = 2; // 2 floats
vertSetup.m_attrs[kGLMGenericAttr08].m_datatype = GL_FLOAT;
vertSetup.m_attrs[kGLMGenericAttr08].m_stride = sizeof(GLMDebugTextVertex);
vertSetup.m_attrs[kGLMGenericAttr08].m_offset = offsetof(GLMDebugTextVertex, u);
vertSetup.m_attrs[kGLMGenericAttr03].m_normalized= false;
// bind texture and draw it..
this->BindTexToTMU( m_debugFontTex, 0 );
SelectTMU(0); // somewhat redundant
glDisable( GL_DEPTH_TEST );
glEnable(GL_TEXTURE_2D);
GLMCheckError();
if (0)
{
glEnableClientState(GL_VERTEX_ARRAY);
GLMCheckError();
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
GLMCheckError();
glVertexPointer( 3, GL_FLOAT, sizeof( vtx[0] ), &vtx[0].x );
GLMCheckError();
glClientActiveTexture(GL_TEXTURE0);
GLMCheckError();
glTexCoordPointer( 2, GL_FLOAT, sizeof( vtx[0] ), &vtx[0].u );
GLMCheckError();
}
else
{
SetVertexAttributes( &vertSetup );
}
glDrawArrays( GL_QUADS, 0, stringlen * 4 );
GLMCheckError();
// disable all the input streams
if (0)
{
glDisableClientState(GL_VERTEX_ARRAY);
GLMCheckError();
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
GLMCheckError();
}
else
{
SetVertexAttributes( NULL );
}
glDisable(GL_TEXTURE_2D);
GLMCheckError();
this->BindTexToTMU( NULL, 0 );
}
//===============================================================================
void GLMgrSelfTests( void )
{
return; // until such time as the tests are revised or axed
// make a new context on renderer 0.
GLMContext *ctx = GLMgr::aGLMgr()->NewContext( 0 ); ////FIXME you can't make contexts this way any more.
if (!ctx)
{
Debugger(); // no go
return;
}
// make a test object based on that context.
int alltests[] = {0,1,2,3, -1};
int newtests[] = {3, -1};
int notests[] = {-1};
int *testlist = notests;
GLMTestParams params;
memset( ¶ms, 0, sizeof(params) );
params.m_ctx = ctx;
params.m_testList = testlist;
params.m_glErrToDebugger = true;
params.m_glErrToConsole = true;
params.m_intlErrToDebugger = true;
params.m_intlErrToConsole = true;
params.m_frameCount = 1000;
GLMTester testobj( ¶ms );
testobj.RunTests( );
GLMgr::aGLMgr()->DelContext( ctx );
}
void GLMContext::SetDefaultStates( void )
{
GLM_FUNC;
CheckCurrent();
m_AlphaTestEnable.Default();
m_AlphaTestFunc.Default();
m_AlphaToCoverageEnable.Default();
m_CullFaceEnable.Default();
m_CullFrontFace.Default();
m_PolygonMode.Default();
m_DepthBias.Default();
m_ClipPlaneEnable.Default();
m_ClipPlaneEquation.Default();
m_ScissorEnable.Default();
m_ScissorBox.Default();
m_ViewportBox.Default();
m_ViewportDepthRange.Default();
m_ColorMaskSingle.Default();
m_ColorMaskMultiple.Default();
m_BlendEnable.Default();
m_BlendFactor.Default();
m_BlendEquation.Default();
m_BlendColor.Default();
//m_BlendEnableSRGB.Default(); // this isn't useful until there is an FBO bound - in fact it will trip a GL error.
m_DepthTestEnable.Default();
m_DepthFunc.Default();
m_DepthMask.Default();
m_StencilTestEnable.Default();
m_StencilFunc.Default();
m_StencilOp.Default();
m_StencilWriteMask.Default();
m_ClearColor.Default();
m_ClearDepth.Default();
m_ClearStencil.Default();
}
void GLMContext::FlushStates( bool noDefer )
{
GLM_FUNC;
CheckCurrent();
m_AlphaTestEnable.Flush( noDefer );
m_AlphaTestFunc.Flush( noDefer );
m_AlphaToCoverageEnable.Flush( noDefer );
m_CullFaceEnable.Flush( noDefer );
m_CullFrontFace.Flush( noDefer );
m_PolygonMode.Flush( noDefer );
m_DepthBias.Flush( noDefer );
#if GLMDEBUG
m_ClipPlaneEnable.Flush( true ); // always push clip state
m_ClipPlaneEquation.Flush( true );
#else
m_ClipPlaneEnable.Flush( noDefer );
m_ClipPlaneEquation.Flush( noDefer );
#endif
m_ScissorEnable.Flush( noDefer );
m_ScissorBox.Flush( noDefer );
m_ViewportBox.Flush( noDefer );
m_ViewportDepthRange.Flush( noDefer );
m_ColorMaskSingle.Flush( noDefer );
m_ColorMaskMultiple.Flush( noDefer );
m_BlendEnable.Flush( noDefer );
m_BlendFactor.Flush( noDefer );
m_BlendEquation.Flush( noDefer );
m_BlendColor.Flush( noDefer );
// the next call should not occur until we're sure the proper SRGB tex format is underneath the FBO.
// So, we're moving it up to FlushDrawStates so it can happen at just the right time.
//m_BlendEnableSRGB.Flush( noDefer );
m_DepthTestEnable.Flush( noDefer );
m_DepthFunc.Flush( noDefer );
m_DepthMask.Flush( noDefer );
m_StencilTestEnable.Flush( noDefer );
m_StencilFunc.Flush( noDefer );
m_StencilOp.Flush( noDefer );
m_StencilWriteMask.Flush( noDefer );
m_ClearColor.Flush( noDefer );
m_ClearDepth.Flush( noDefer );
m_ClearStencil.Flush( noDefer );
GLMCheckError();
}
void GLMContext::VerifyStates ( void )
{
GLM_FUNC;
CheckCurrent();
// bare bones sanity check, head over to the debugger if our sense of the current context state is not correct
// we should only want to call this after a flush or the checks will flunk.
if( m_AlphaTestEnable.Check() ) GLMStop();
if( m_AlphaTestFunc.Check() ) GLMStop();
if( m_AlphaToCoverageEnable.Check() ) GLMStop();
if( m_CullFaceEnable.Check() ) GLMStop();
if( m_CullFrontFace.Check() ) GLMStop();
if( m_PolygonMode.Check() ) GLMStop();
if( m_DepthBias.Check() ) GLMStop();
if( m_ClipPlaneEnable.Check() ) GLMStop();
//if( m_ClipPlaneEquation.Check() ) GLMStop();
if( m_ScissorEnable.Check() ) GLMStop();
if( m_ScissorBox.Check() ) GLMStop();
if( m_ViewportBox.Check() ) GLMStop();
if( m_ViewportDepthRange.Check() ) GLMStop();
if( m_ColorMaskSingle.Check() ) GLMStop();
if( m_ColorMaskMultiple.Check() ) GLMStop();
if( m_BlendEnable.Check() ) GLMStop();
if( m_BlendFactor.Check() ) GLMStop();
if( m_BlendEquation.Check() ) GLMStop();
if( m_BlendColor.Check() ) GLMStop();
// only do this as caps permit
if (m_caps.m_hasGammaWrites)
{
if( m_BlendEnableSRGB.Check() ) GLMStop();
}
if( m_DepthTestEnable.Check() ) GLMStop();
if( m_DepthFunc.Check() ) GLMStop();
if( m_DepthMask.Check() ) GLMStop();
if( m_StencilTestEnable.Check() ) GLMStop();
if( m_StencilFunc.Check() ) GLMStop();
if( m_StencilOp.Check() ) GLMStop();
if( m_StencilWriteMask.Check() ) GLMStop();
if( m_ClearColor.Check() ) GLMStop();
if( m_ClearDepth.Check() ) GLMStop();
if( m_ClearStencil.Check() ) GLMStop();
}
void GLMContext::WriteAlphaTestEnable( GLAlphaTestEnable_t *src )
{
m_AlphaTestEnable.Write( src );
}
void GLMContext::WriteAlphaTestFunc( GLAlphaTestFunc_t *src )
{
m_AlphaTestFunc.Write( src );
}
void GLMContext::WriteAlphaToCoverageEnable( GLAlphaToCoverageEnable_t *src )
{
m_AlphaToCoverageEnable.Write( src );
}
void GLMContext::WriteCullFaceEnable( GLCullFaceEnable_t *src )
{
m_CullFaceEnable.Write( src );
}
void GLMContext::WriteCullFrontFace( GLCullFrontFace_t *src )
{
m_CullFrontFace.Write( src );
}
void GLMContext::WritePolygonMode( GLPolygonMode_t *src )
{
m_PolygonMode.Write( src );
}
void GLMContext::WriteDepthBias( GLDepthBias_t *src )
{
m_DepthBias.Write( src );
}
void GLMContext::WriteClipPlaneEnable( GLClipPlaneEnable_t *src, int which )
{
m_ClipPlaneEnable.WriteIndex( src, which );
}
void GLMContext::WriteClipPlaneEquation( GLClipPlaneEquation_t *src, int which )
{
m_ClipPlaneEquation.WriteIndex( src, which );
}
void GLMContext::WriteScissorEnable( GLScissorEnable_t *src )
{
m_ScissorEnable.Write( src );
}
void GLMContext::WriteScissorBox( GLScissorBox_t *src )
{
m_ScissorBox.Write( src );
}
void GLMContext::WriteViewportBox( GLViewportBox_t *src )
{
m_ViewportBox.Write( src );
}
void GLMContext::WriteViewportDepthRange( GLViewportDepthRange_t *src )
{
m_ViewportDepthRange.Write( src );
}
void GLMContext::WriteColorMaskSingle( GLColorMaskSingle_t *src )
{
m_ColorMaskSingle.Write( src );
}
void GLMContext::WriteColorMaskMultiple( GLColorMaskMultiple_t *src, int which )
{
m_ColorMaskMultiple.WriteIndex( src, which );
}
void GLMContext::WriteBlendEnable( GLBlendEnable_t *src )
{
m_BlendEnable.Write( src );
}
void GLMContext::WriteBlendFactor( GLBlendFactor_t *src )
{
m_BlendFactor.Write( src );
}
void GLMContext::WriteBlendEquation( GLBlendEquation_t *src )
{
m_BlendEquation.Write( src );
}
void GLMContext::WriteBlendColor( GLBlendColor_t *src )
{
m_BlendColor.Write( src );
}
void GLMContext::WriteBlendEnableSRGB( GLBlendEnableSRGB_t *src )
{
if (m_caps.m_hasGammaWrites) // only if caps allow do we actually push it through to the extension
{
m_BlendEnableSRGB.Write( src );
}
else
{
m_FakeBlendEnableSRGB = src->enable;
}
// note however that we're still tracking what this mode should be, so FlushDrawStates can look at it and adjust the pixel shader
// if fake SRGB mode is in place (m_caps.m_hasGammaWrites is false)
}
void GLMContext::WriteDepthTestEnable( GLDepthTestEnable_t *src )
{
m_DepthTestEnable.Write( src );
}
void GLMContext::WriteDepthFunc( GLDepthFunc_t *src )
{
m_DepthFunc.Write( src );
}
void GLMContext::WriteDepthMask( GLDepthMask_t *src )
{
m_DepthMask.Write( src );
}
void GLMContext::WriteStencilTestEnable( GLStencilTestEnable_t *src )
{
m_StencilTestEnable.Write( src );
}
void GLMContext::WriteStencilFunc( GLStencilFunc_t *src )
{
m_StencilFunc.Write( src );
}
void GLMContext::WriteStencilOp( GLStencilOp_t *src, int which )
{
m_StencilOp.WriteIndex( src, which );
}
void GLMContext::WriteStencilWriteMask( GLStencilWriteMask_t *src )
{
m_StencilWriteMask.Write( src );
}
void GLMContext::WriteClearColor( GLClearColor_t *src )
{
m_ClearColor.Write( src );
}
void GLMContext::WriteClearDepth( GLClearDepth_t *src )
{
m_ClearDepth.Write( src );
}
void GLMContext::WriteClearStencil( GLClearStencil_t *src )
{
m_ClearStencil.Write( src );
}
//===============================================================================
// template specializations for each type of state
// --- GLAlphaTestEnable ---
void GLContextSet( GLAlphaTestEnable_t *src )
{
glSetEnable( GL_ALPHA_TEST, src->enable );
}
void GLContextGet( GLAlphaTestEnable_t *dst )
{
dst->enable = glIsEnabled( GL_ALPHA_TEST );
}
void GLContextGetDefault( GLAlphaTestEnable_t *dst )
{
dst->enable = GL_FALSE;
}
// --- GLAlphaTestFunc ---
void GLContextSet( GLAlphaTestFunc_t *src )
{
glAlphaFunc( src->func, src->ref );
}
void GLContextGet( GLAlphaTestFunc_t *dst )
{
glGetEnumv( GL_ALPHA_TEST_FUNC, &dst->func );
glGetFloatv( GL_ALPHA_TEST_REF, &dst->ref );
}
void GLContextGetDefault( GLAlphaTestFunc_t *dst )
{
dst->func = GL_ALWAYS;
dst->ref = 0.0f;
}
// --- GLAlphaToCoverageEnable ---
void GLContextSet( GLAlphaToCoverageEnable_t *src )
{
glSetEnable( GL_SAMPLE_ALPHA_TO_COVERAGE_ARB, src->enable );
}
void GLContextGet( GLAlphaToCoverageEnable_t *dst )
{
dst->enable = glIsEnabled( GL_SAMPLE_ALPHA_TO_COVERAGE_ARB );
}
void GLContextGetDefault( GLAlphaToCoverageEnable_t *dst )
{
dst->enable = GL_FALSE;
}
// --- GLCullFaceEnable ---
void GLContextSet( GLCullFaceEnable_t *src )
{
glSetEnable( GL_CULL_FACE, src->enable );
}
void GLContextGet( GLCullFaceEnable_t *dst )
{
dst->enable = glIsEnabled( GL_CULL_FACE );
}
void GLContextGetDefault( GLCullFaceEnable_t *dst )
{
dst->enable = GL_TRUE;
}
// --- GLCullFrontFace ---
void GLContextSet( GLCullFrontFace_t *src )
{
glFrontFace( src->value ); // legal values are GL_CW or GL_CCW
}
void GLContextGet( GLCullFrontFace_t *dst )
{
glGetEnumv( GL_FRONT_FACE, &dst->value );
}
void GLContextGetDefault( GLCullFrontFace_t *dst )
{
dst->value = GL_CCW;
}
// --- GLPolygonMode ---
void GLContextSet( GLPolygonMode_t *src )
{
glPolygonMode( GL_FRONT, src->values[0] );
glPolygonMode( GL_BACK, src->values[1] );
}
void GLContextGet( GLPolygonMode_t *dst )
{
glGetEnumv( GL_POLYGON_MODE, &dst->values[0] );
}
void GLContextGetDefault( GLPolygonMode_t *dst )
{
dst->values[0] = dst->values[1] = GL_FILL;
}
// --- GLDepthBias ---
// note the implicit enable / disable.
// if you set non zero values, it is enabled, otherwise not.
void GLContextSet( GLDepthBias_t *src )
{
bool enable = (src->factor != 0.0f) || (src->units != 0.0f);
glSetEnable( GL_POLYGON_OFFSET_FILL, enable );
glPolygonOffset( src->factor, src->units );
}
void GLContextGet( GLDepthBias_t *dst )
{
glGetFloatv ( GL_POLYGON_OFFSET_FACTOR, &dst->factor );
glGetFloatv ( GL_POLYGON_OFFSET_UNITS, &dst->units );
}
void GLContextGetDefault( GLDepthBias_t *dst )
{
dst->factor = 0.0;
dst->units = 0.0;
}
// --- GLScissorEnable ---
void GLContextSet( GLScissorEnable_t *src )
{
glSetEnable( GL_SCISSOR_TEST, src->enable );
}
void GLContextGet( GLScissorEnable_t *dst )
{
dst->enable = glIsEnabled( GL_SCISSOR_TEST );
}
void GLContextGetDefault( GLScissorEnable_t *dst )
{
dst->enable = GL_FALSE;
}
// --- GLScissorBox ---
void GLContextSet( GLScissorBox_t *src )
{
glScissor ( src->x, src->y, src->width, src->height );
}
void GLContextGet( GLScissorBox_t *dst )
{
glGetIntegerv ( GL_SCISSOR_BOX, &dst->x );
}
void GLContextGetDefault( GLScissorBox_t *dst )
{
// hmmmm, good question? we can't really know a good answer so we pick a silly one
// and the client better come back with a better answer later.
dst->x = dst->y = 0;
dst->width = dst->height = 16;
}
// --- GLViewportBox ---
void GLContextSet( GLViewportBox_t *src )
{
glViewport (src->x, src->y, src->width, src->height );
}
void GLContextGet( GLViewportBox_t *dst )
{
glGetIntegerv ( GL_VIEWPORT, &dst->x );
}
void GLContextGetDefault( GLViewportBox_t *dst )
{
// as with the scissor box, we don't know yet, so pick a silly one and change it later
dst->x = dst->y = 0;
dst->width = dst->height = 16;
}
// --- GLViewportDepthRange ---
void GLContextSet( GLViewportDepthRange_t *src )
{
glDepthRange ( src->near, src->far );
}
void GLContextGet( GLViewportDepthRange_t *dst )
{
glGetDoublev ( GL_DEPTH_RANGE, &dst->near );
}
void GLContextGetDefault( GLViewportDepthRange_t *dst )
{
dst->near = 0.0;
dst->far = 1.0;
}
// --- GLClipPlaneEnable ---
void GLContextSetIndexed( GLClipPlaneEnable_t *src, int index )
{
#if 0 // disabled for sample GLMDEBUG
if (0 /*CommandLine()->FindParm("-caps_noclipplanes")*/)
{
if (GLMKnob("caps-key",NULL) > 0.0)
{
// caps ON means NO clipping
src->enable = false;
}
}
#endif
glSetEnable( GL_CLIP_PLANE0 + index, src->enable );
GLMCheckError();
}
void GLContextGetIndexed( GLClipPlaneEnable_t *dst, int index )
{
dst->enable = glIsEnabled( GL_CLIP_PLANE0 + index );
}
void GLContextGetDefaultIndexed( GLClipPlaneEnable_t *dst, int index )
{
dst->enable = 0;
}
// --- GLClipPlaneEquation ---
void GLContextSetIndexed( GLClipPlaneEquation_t *src, int index )
{
// shove into glGlipPlane
GLdouble coeffs[4] = { src->x, src->y, src->z, src->w };
glClipPlane( GL_CLIP_PLANE0 + index, coeffs );
GLMCheckError();
}
void GLContextGetIndexed( GLClipPlaneEquation_t *dst, int index )
{
Debugger(); // do this later
// glClipPlane( GL_CLIP_PLANE0 + index, coeffs );
// GLdouble coeffs[4] = { src->x, src->y, src->z, src->w };
}
void GLContextGetDefaultIndexed( GLClipPlaneEquation_t *dst, int index )
{
dst->x = 1.0;
dst->y = 0.0;
dst->z = 0.0;
dst->w = 0.0;
}
// --- GLColorMaskSingle ---
void GLContextSet( GLColorMaskSingle_t *src )
{
glColorMask( src->r, src->g, src->b, src->a );
}
void GLContextGet( GLColorMaskSingle_t *dst )
{
glGetBooleanv( GL_COLOR_WRITEMASK, (GLboolean*)&dst->r);
}
void GLContextGetDefault( GLColorMaskSingle_t *dst )
{
dst->r = dst->g = dst->b = dst->a = 1;
}
// --- GLColorMaskMultiple ---
void GLContextSetIndexed( GLColorMaskMultiple_t *src, int index )
{
// FIXME: this call is not in the Leopard headers. A runtime-lookup will be needed.
pfnglColorMaskIndexedEXT ( index, src->r, src->g, src->b, src->a );
}
void GLContextGetIndexed( GLColorMaskMultiple_t *dst, int index )
{
// FIXME: this call is not in the Leopard headers. A runtime-lookup will be needed.
glGetBooleanIndexedvEXT ( GL_COLOR_WRITEMASK, index, (GLboolean*)&dst->r );
}
void GLContextGetDefaultIndexed( GLColorMaskMultiple_t *dst, int index )
{
dst->r = dst->g = dst->b = dst->a = 1;
}
// --- GLBlendEnable ---
void GLContextSet( GLBlendEnable_t *src )
{
glSetEnable( GL_BLEND, src->enable );
}
void GLContextGet( GLBlendEnable_t *dst )
{
dst->enable = glIsEnabled( GL_BLEND );
}
void GLContextGetDefault( GLBlendEnable_t *dst )
{
dst->enable = GL_FALSE;
}
// --- GLBlendFactor ---
void GLContextSet( GLBlendFactor_t *src )
{
glBlendFunc ( src->srcfactor, src->dstfactor );
}
void GLContextGet( GLBlendFactor_t *dst )
{
glGetEnumv ( GL_BLEND_SRC, &dst->srcfactor );
glGetEnumv ( GL_BLEND_DST, &dst->dstfactor );
}
void GLContextGetDefault( GLBlendFactor_t *dst )
{
dst->srcfactor = GL_ONE;
dst->dstfactor = GL_ZERO;
}
// --- GLBlendEquation ---
void GLContextSet( GLBlendEquation_t *src )
{
glBlendEquation ( src->equation );
}
void GLContextGet( GLBlendEquation_t *dst )
{
glGetEnumv ( GL_BLEND_EQUATION, &dst->equation );
}
void GLContextGetDefault( GLBlendEquation_t *dst )
{
dst->equation = GL_FUNC_ADD;
}
// --- GLBlendColor ---
void GLContextSet( GLBlendColor_t *src )
{
glBlendColor ( src->r, src->g, src->b, src->a );
}
void GLContextGet( GLBlendColor_t *dst )
{
glGetFloatv ( GL_BLEND_COLOR, &dst->r );
}
void GLContextGetDefault( GLBlendColor_t *dst )
{
//solid white
dst->r = dst->g = dst->b = dst->a = 1.0;
}
// --- GLBlendEnableSRGB ---
#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210
#define GL_COLOR_ATTACHMENT0 0x8CE0
void GLContextSet( GLBlendEnableSRGB_t *src )
{
#if GLMDEBUG
// just check in debug... this is too expensive to look at on MTGL
if (src->enable)
{
GLboolean srgb_capable = false;
glGetBooleanv( GL_FRAMEBUFFER_SRGB_CAPABLE_EXT, &srgb_capable);
if (src->enable && !srgb_capable)
{
GLMPRINTF(("-Z- srgb-state-set FBO conflict: attempt to enable SRGB on non SRGB capable FBO config"));
}
}
#endif
// this query is not useful unless you have the ARB_framebuffer_srgb ext.
//GLint encoding = 0;
//pfnglGetFramebufferAttachmentParameteriv( GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &encoding );
//GLMCheckError();
glSetEnable( GL_FRAMEBUFFER_SRGB_EXT, src->enable );
GLMCheckError();
}
void GLContextGet( GLBlendEnableSRGB_t *dst )
{
//dst->enable = glIsEnabled( GL_FRAMEBUFFER_SRGB_EXT );
dst->enable = true; // wtf ?
}
void GLContextGetDefault( GLBlendEnableSRGB_t *dst )
{
dst->enable = GL_FALSE;
}
// --- GLDepthTestEnable ---
void GLContextSet( GLDepthTestEnable_t *src )
{
glSetEnable( GL_DEPTH_TEST, src->enable );
}
void GLContextGet( GLDepthTestEnable_t *dst )
{
dst->enable = glIsEnabled( GL_DEPTH_TEST );
}
void GLContextGetDefault( GLDepthTestEnable_t *dst )
{
dst->enable = GL_FALSE;
}
// --- GLDepthFunc ---
void GLContextSet( GLDepthFunc_t *src )
{
glDepthFunc ( src->func );
}
void GLContextGet( GLDepthFunc_t *dst )
{
glGetEnumv ( GL_DEPTH_FUNC, &dst->func );
}
void GLContextGetDefault( GLDepthFunc_t *dst )
{
dst->func = GL_GEQUAL;
}
// --- GLDepthMask ---
void GLContextSet( GLDepthMask_t *src )
{
glDepthMask ( src->mask );
}
void GLContextGet( GLDepthMask_t *dst )
{
glGetBooleanv ( GL_DEPTH_WRITEMASK, (GLboolean*)&dst->mask );
}
void GLContextGetDefault( GLDepthMask_t *dst )
{
dst->mask = GL_TRUE;
}
// --- GLStencilTestEnable ---
void GLContextSet( GLStencilTestEnable_t *src )
{
glSetEnable( GL_STENCIL_TEST, src->enable );
}
void GLContextGet( GLStencilTestEnable_t *dst )
{
dst->enable = glIsEnabled( GL_STENCIL_TEST );
}
void GLContextGetDefault( GLStencilTestEnable_t *dst )
{
dst->enable = GL_FALSE;
}
// --- GLStencilFunc ---
void GLContextSet( GLStencilFunc_t *src )
{
glStencilFuncSeparateATI( src->frontfunc, src->backfunc, src->ref, src->mask);
}
void GLContextGet( GLStencilFunc_t *dst )
{
glGetEnumv ( GL_STENCIL_FUNC, &dst->frontfunc );
glGetEnumv ( GL_STENCIL_BACK_FUNC_ATI, &dst->backfunc );
glGetIntegerv ( GL_STENCIL_REF, &dst->ref );
glGetIntegerv ( GL_STENCIL_VALUE_MASK, (GLint*)&dst->mask );
}
void GLContextGetDefault( GLStencilFunc_t *dst )
{
dst->frontfunc = GL_ALWAYS;
dst->backfunc = GL_ALWAYS;
dst->ref = 0;
dst->mask = 0xFFFFFFFF;
}
// --- GLStencilOp --- indexed 0=front, 1=back
void GLContextSetIndexed( GLStencilOp_t *src, int index )
{
GLenum face = (index==0) ? GL_FRONT : GL_BACK;
glStencilOpSeparateATI( face, src->sfail, src->dpfail, src->dppass );
}
void GLContextGetIndexed( GLStencilOp_t *dst, int index )
{
GLenum face = (index==0) ? GL_FRONT : GL_BACK;
glGetEnumv ( (index==0) ? GL_STENCIL_FAIL : GL_STENCIL_BACK_FAIL_ATI, &dst->sfail );
glGetEnumv ( (index==0) ? GL_STENCIL_PASS_DEPTH_FAIL : GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI, &dst->dpfail );
glGetEnumv ( (index==0) ? GL_STENCIL_PASS_DEPTH_PASS : GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI, &dst->dppass );
}
void GLContextGetDefaultIndexed( GLStencilOp_t *dst, int index )
{
dst->sfail = dst->dpfail = dst->dppass = GL_KEEP;
}
// --- GLStencilWriteMask ---
void GLContextSet( GLStencilWriteMask_t *src )
{
glStencilMask( src->mask );
}
void GLContextGet( GLStencilWriteMask_t *dst )
{
glGetIntegerv ( GL_STENCIL_WRITEMASK, &dst->mask );
}
void GLContextGetDefault( GLStencilWriteMask_t *dst )
{
dst->mask = 0xFFFFFFFF;
}
// --- GLClearColor ---
void GLContextSet( GLClearColor_t *src )
{
glClearColor( src->r, src->g, src->b, src->a );
}
void GLContextGet( GLClearColor_t *dst )
{
glGetFloatv ( GL_COLOR_CLEAR_VALUE, &dst->r );
}
void GLContextGetDefault( GLClearColor_t *dst )
{
dst->r = dst->g = dst->b = 0.5;
dst->a = 1.0;
}
// --- GLClearDepth ---
void GLContextSet( GLClearDepth_t *src )
{
glClearDepth ( src->d );
}
void GLContextGet( GLClearDepth_t *dst )
{
glGetDoublev ( GL_DEPTH_CLEAR_VALUE, &dst->d );
}
void GLContextGetDefault( GLClearDepth_t *dst )
{
dst->d = 1.0;
}
// --- GLClearStencil ---
void GLContextSet( GLClearStencil_t *src )
{
glClearStencil( src->s );
}
void GLContextGet( GLClearStencil_t *dst )
{
glGetIntegerv ( GL_STENCIL_CLEAR_VALUE, &dst->s );
}
void GLContextGetDefault( GLClearStencil_t *dst )
{
dst->s = 0;
}
//===============================================================================
GLMTester::GLMTester(GLMTestParams *params)
{
m_params = *params;
m_drawFBO = NULL;
m_drawColorTex = NULL;
m_drawDepthTex = NULL;
}
GLMTester::~GLMTester()
{
}
void GLMTester::StdSetup( void )
{
GLMContext *ctx = m_params.m_ctx;
m_drawWidth = 1024;
m_drawHeight = 768;
// make an FBO to draw into and activate it. no depth buffer yet
m_drawFBO = ctx->NewFBO();
// make color buffer texture
GLMTexLayoutKey colorkey;
CGLMTex *colortex;
memset( &colorkey, 0, sizeof(colorkey) );
colorkey.m_texGLTarget = GL_TEXTURE_2D;
colorkey.m_xSize = m_drawWidth;
colorkey.m_ySize = m_drawHeight;
colorkey.m_zSize = 1;
colorkey.m_texFormat = D3DFMT_A8R8G8B8;
colorkey.m_texFlags = kGLMTexRenderable;
m_drawColorTex = ctx->NewTex( &colorkey );
// do not leave that texture bound on the TMU
ctx->BindTexToTMU(NULL, 0 );
// attach color to FBO
GLMFBOTexAttachParams colorParams;
memset( &colorParams, 0, sizeof(colorParams) );
colorParams.m_tex = m_drawColorTex;
colorParams.m_face = 0;
colorParams.m_mip = 0;
colorParams.m_zslice= 0; // for clarity..
m_drawFBO->TexAttach( &colorParams, kAttColor0 );
// check it.
bool ready = m_drawFBO->IsReady();
InternalError( !ready, "drawing FBO no go");
// bind it
ctx->BindFBOToCtx( m_drawFBO, GL_READ_FRAMEBUFFER_EXT );
ctx->BindFBOToCtx( m_drawFBO, GL_DRAW_FRAMEBUFFER_EXT );
glViewport(0, 0, (GLsizei) m_drawWidth, (GLsizei) m_drawHeight );
CheckGLError("stdsetup viewport");
glScissor( 0,0, (GLsizei) m_drawWidth, (GLsizei) m_drawHeight );
CheckGLError("stdsetup scissor");
glOrtho( -1,1, -1,1, -1,1 );
CheckGLError("stdsetup ortho");
// activate debug font
ctx->GenDebugFontTex();
}
void GLMTester::StdCleanup( void )
{
GLMContext *ctx = m_params.m_ctx;
// unbind
ctx->BindFBOToCtx( NULL, GL_READ_FRAMEBUFFER_EXT );
ctx->BindFBOToCtx( NULL, GL_DRAW_FRAMEBUFFER_EXT );
// del FBO
if (m_drawFBO)
{
ctx->DelFBO( m_drawFBO );
m_drawFBO = NULL;
}
// del tex
if (m_drawColorTex)
{
ctx->DelTex( m_drawColorTex );
m_drawColorTex = NULL;
}
if (m_drawDepthTex)
{
ctx->DelTex( m_drawDepthTex );
m_drawDepthTex = NULL;
}
}
void GLMTester::Clear( void )
{
GLMContext *ctx = m_params.m_ctx;
ctx->MakeCurrent();
glViewport(0, 0, (GLsizei) m_drawWidth, (GLsizei) m_drawHeight );
glScissor( 0,0, (GLsizei) m_drawWidth, (GLsizei) m_drawHeight );
glOrtho( -1,1, -1,1, -1,1 );
CheckGLError("clearing viewport");
// clear to black
GLfloat clear_color[4] = { 0.0f, 0.0f, 0.0, 1.0f };
glClearColor(clear_color[0], clear_color[1], clear_color[2], clear_color[3]);
CheckGLError("clearing color");
glClear(GL_COLOR_BUFFER_BIT+GL_DEPTH_BUFFER_BIT+GL_STENCIL_BUFFER_BIT);
CheckGLError("clearing");
//glFinish();
//CheckGLError("clear finish");
}
void GLMTester::Present( int seed )
{
GLMContext *ctx = m_params.m_ctx;
ctx->Present( m_drawColorTex );
}
void GLMTester::CheckGLError( const char *comment )
{
char errbuf[1024];
//borrowed from GLMCheckError.. slightly different
if (!comment)
{
comment = "";
}
GLenum errorcode = (GLenum)glGetError();
GLenum errorcode2 = 0;
if ( errorcode != GL_NO_ERROR )
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
const char *decodedStr2 = "";
if ( errorcode == GL_INVALID_FRAMEBUFFER_OPERATION_EXT )
{
// dig up the more detailed FBO status
errorcode2 = glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT );
decodedStr2 = GLMDecode( eGL_ERROR, errorcode2 );
sprintf( errbuf, "\n%s - GL Error %08x/%08x = '%s / %s'", comment, errorcode, errorcode2, decodedStr, decodedStr2 );
}
else
{
sprintf( errbuf, "\n%s - GL Error %08x = '%s'", comment, errorcode, decodedStr );
}
if ( m_params.m_glErrToConsole )
{
printf("%s", errbuf );
}
if ( m_params.m_glErrToDebugger )
{
Debugger();
}
}
}
void GLMTester::InternalError( int errcode, const char *comment )
{
if (errcode)
{
if (m_params.m_intlErrToConsole)
{
printf("\%s - error %d", comment, errcode );
}
if (m_params.m_intlErrToDebugger)
{
Debugger();
}
}
}
void GLMTester::RunTests( void )
{
int *testList = m_params.m_testList;
while( (*testList >=0) && (*testList < 20) )
{
RunOneTest( *testList++ );
}
}
void GLMTester::RunOneTest( int testindex )
{
// this might be better with 'ptmf' style
switch(testindex)
{
case 0: Test0(); break;
case 1: Test1(); break;
case 2: Test2(); break;
case 3: Test3(); break;
default:
Debugger(); // unrecognized
}
}
// #####################################################################################################################
// some fixed lists which may be useful to all tests
D3DFORMAT g_drawTexFormatsGLMT[] = // -1 terminated
{
D3DFMT_A8R8G8B8,
D3DFMT_A4R4G4B4,
D3DFMT_X8R8G8B8,
D3DFMT_X1R5G5B5,
D3DFMT_A1R5G5B5,
D3DFMT_L8,
D3DFMT_A8L8,
D3DFMT_R8G8B8,
D3DFMT_A8,
D3DFMT_R5G6B5,
D3DFMT_DXT1,
D3DFMT_DXT3,
D3DFMT_DXT5,
D3DFMT_A32B32G32R32F,
D3DFMT_A16B16G16R16,
(D3DFORMAT)-1
};
D3DFORMAT g_fboColorTexFormatsGLMT[] = // -1 terminated
{
D3DFMT_A8R8G8B8,
//D3DFMT_A4R4G4B4, //unsupported
D3DFMT_X8R8G8B8,
D3DFMT_X1R5G5B5,
//D3DFMT_A1R5G5B5, //unsupported
D3DFMT_A16B16G16R16F,
D3DFMT_A32B32G32R32F,
D3DFMT_R5G6B5,
(D3DFORMAT)-1
};
D3DFORMAT g_fboDepthTexFormatsGLMT[] = // -1 terminated, but note 0 for "no depth" mode
{
(D3DFORMAT)0,
D3DFMT_D16,
D3DFMT_D24X8,
D3DFMT_D24S8,
(D3DFORMAT)-1
};
// #####################################################################################################################
void GLMTester::Test0( void )
{
// make and delete a bunch of textures.
// lock and unlock them.
// use various combos of -
// √texel format
// √2D | 3D | cube map
// √mipped / not
// √POT / NPOT
// large / small / square / rect
// square / rect
GLMContext *ctx = m_params.m_ctx;
ctx->MakeCurrent();
std::vector< CGLMTex* > testTextures; // will hold all the built textures
// test stage loop
// 0 is creation
// 1 is lock/unlock
// 2 is deletion
for( int teststage = 0; teststage < 3; teststage++)
{
int innerindex = 0; // increment at stage switch
// format loop
for( D3DFORMAT *fmtPtr = g_drawTexFormatsGLMT; *fmtPtr != ((D3DFORMAT)-1); fmtPtr++ )
{
// form loop
GLenum forms[] = { GL_TEXTURE_2D, GL_TEXTURE_3D, GL_TEXTURE_CUBE_MAP, (GLenum)-1 };
for( GLenum *formPtr = forms; *formPtr != ((GLenum)-1); formPtr++ )
{
// mip loop
for( int mipped = 0; mipped < 2; mipped++ )
{
// large / square / pot loop
// &4 == large &2 == square &1 == POT
// NOTE you *have to be square* for cube maps.
for( int aspect = 0; aspect < 8; aspect++ )
{
switch( teststage )
{
case 0:
{
GLMTexLayoutKey key;
memset( &key, 0, sizeof(key) );
key.m_texGLTarget = *formPtr;
key.m_texFormat = *fmtPtr;
if (mipped)
key.m_texFlags |= kGLMTexMipped;
// assume big, square, POT, and 3D, then adjust as needed
key.m_xSize = key.m_ySize = key.m_zSize = 256;
if ( !(aspect&4) ) // big or little ?
{
// little
key.m_xSize >>= 2;
key.m_ySize >>= 2;
key.m_zSize >>= 2;
}
if ( key.m_texGLTarget != GL_TEXTURE_CUBE_MAP )
{
if ( !(aspect & 2) ) // square or rect?
{
// rect
key.m_ySize >>= 1;
key.m_zSize >>= 2;
}
}
if ( !(aspect&1) ) // POT or NPOT?
{
// NPOT
key.m_xSize += 56;
key.m_ySize += 56;
key.m_zSize += 56;
}
// 2D, 3D, cube map ?
if (key.m_texGLTarget!=GL_TEXTURE_3D)
{
// 2D or cube map: flatten Z extent to one texel
key.m_zSize = 1;
}
else
{
// 3D: knock down Z quite a bit so our test case does not run out of RAM
key.m_zSize >>= 3;
if (!key.m_zSize)
{
key.m_zSize = 1;
}
}
CGLMTex *newtex = ctx->NewTex( &key );
CheckGLError( "tex create test");
InternalError( newtex==NULL, "tex create test" );
testTextures.push_back( newtex );
printf("\n[%5d] created tex %s",innerindex,newtex->m_layout->m_layoutSummary );
}
break;
case 1:
{
CGLMTex *ptex = testTextures[innerindex];
for( int face=0; face <ptex->m_layout->m_faceCount; face++)
{
for( int mip=0; mip <ptex->m_layout->m_mipCount; mip++)
{
GLMTexLockParams lockreq;
lockreq.m_tex = ptex;
lockreq.m_face = face;
lockreq.m_mip = mip;
GLMTexLayoutSlice *slice = &ptex->m_layout->m_slices[ ptex->CalcSliceIndex( face, mip ) ];
lockreq.m_region.xmin = lockreq.m_region.ymin = lockreq.m_region.zmin = 0;
lockreq.m_region.xmax = slice->m_xSize;
lockreq.m_region.ymax = slice->m_ySize;
lockreq.m_region.zmax = slice->m_zSize;
char *lockAddress;
int yStride;
int zStride;
ptex->Lock( &lockreq, &lockAddress, &yStride, &zStride );
CheckGLError( "tex lock test");
InternalError( lockAddress==NULL, "null lock address");
// write some texels of this flavor:
// red 75% green 40% blue 15% alpha 80%
GLMGenTexelParams gtp;
gtp.m_format = ptex->m_layout->m_format->m_d3dFormat;
gtp.m_dest = lockAddress;
gtp.m_chunkCount = (slice->m_xSize * slice->m_ySize * slice->m_zSize) / (ptex->m_layout->m_format->m_chunkSize * ptex->m_layout->m_format->m_chunkSize);
gtp.m_byteCountLimit = slice->m_storageSize;
gtp.r = 0.75;
gtp.g = 0.40;
gtp.b = 0.15;
gtp.a = 0.80;
GLMGenTexels( >p );
InternalError( gtp.m_bytesWritten != gtp.m_byteCountLimit, "byte count mismatch from GLMGenTexels" );
}
}
for( int face=0; face <ptex->m_layout->m_faceCount; face++)
{
for( int mip=0; mip <ptex->m_layout->m_mipCount; mip++)
{
GLMTexLockParams unlockreq;
unlockreq.m_tex = ptex;
unlockreq.m_face = face;
unlockreq.m_mip = mip;
// region need not matter for unlocks
unlockreq.m_region.xmin = unlockreq.m_region.ymin = unlockreq.m_region.zmin = 0;
unlockreq.m_region.xmax = unlockreq.m_region.ymax = unlockreq.m_region.zmax = 0;
char *lockAddress;
int yStride;
int zStride;
ptex->Unlock( &unlockreq );
CheckGLError( "tex unlock test");
}
}
printf("\n[%5d] locked/wrote/unlocked tex %s",innerindex, ptex->m_layout->m_layoutSummary );
}
break;
case 2:
{
CGLMTex *dtex = testTextures[innerindex];
printf("\n[%5d] deleting tex %s",innerindex, dtex->m_layout->m_layoutSummary );
ctx->DelTex( dtex );
CheckGLError( "tex delete test");
}
break;
} // end stage switch
innerindex++;
} // end aspect loop
} // end mip loop
} // end form loop
} // end format loop
} // end stage loop
}
// #####################################################################################################################
void GLMTester::Test1( void )
{
// FBO exercises
GLMContext *ctx = m_params.m_ctx;
ctx->MakeCurrent();
// FBO color format loop
for( D3DFORMAT *colorFmtPtr = g_fboColorTexFormatsGLMT; *colorFmtPtr != ((D3DFORMAT)-1); colorFmtPtr++ )
{
// FBO depth format loop
for( D3DFORMAT *depthFmtPtr = g_fboDepthTexFormatsGLMT; *depthFmtPtr != ((D3DFORMAT)-1); depthFmtPtr++ )
{
// mip loop
for( int mipped = 0; mipped < 2; mipped++ )
{
GLenum forms[] = { GL_TEXTURE_2D, GL_TEXTURE_3D, GL_TEXTURE_CUBE_MAP, (GLenum)-1 };
// form loop
for( GLenum *formPtr = forms; *formPtr != ((GLenum)-1); formPtr++ )
{
//=============================================== make an FBO
CGLMFBO *fbo = ctx->NewFBO();
//=============================================== make a color texture
GLMTexLayoutKey colorkey;
memset( &colorkey, 0, sizeof(colorkey) );
switch(*formPtr)
{
case GL_TEXTURE_2D:
colorkey.m_texGLTarget = GL_TEXTURE_2D;
colorkey.m_xSize = 800;
colorkey.m_ySize = 600;
colorkey.m_zSize = 1;
break;
case GL_TEXTURE_3D:
colorkey.m_texGLTarget = GL_TEXTURE_3D;
colorkey.m_xSize = 800;
colorkey.m_ySize = 600;
colorkey.m_zSize = 32;
break;
case GL_TEXTURE_CUBE_MAP:
colorkey.m_texGLTarget = GL_TEXTURE_CUBE_MAP;
colorkey.m_xSize = 800;
colorkey.m_ySize = 800; // heh, cube maps have to have square sides...
colorkey.m_zSize = 1;
break;
}
colorkey.m_texFormat = *colorFmtPtr;
colorkey.m_texFlags = kGLMTexRenderable;
// decide if we want mips
if (mipped)
{
colorkey.m_texFlags |= kGLMTexMipped;
}
CGLMTex *colorTex = ctx->NewTex( &colorkey );
// Note that GLM will notice the renderable flag, and force texels to be written
// so the FBO will be complete
//=============================================== attach color
GLMFBOTexAttachParams colorParams;
memset( &colorParams, 0, sizeof(colorParams) );
colorParams.m_tex = colorTex;
colorParams.m_face = (colorkey.m_texGLTarget == GL_TEXTURE_CUBE_MAP) ? 2 : 0; // just steer to an alternate face as a test
colorParams.m_mip = (colorkey.m_texFlags & kGLMTexMipped) ? 2 : 0; // pick non-base mip slice
colorParams.m_zslice= (colorkey.m_texGLTarget == GL_TEXTURE_3D) ? 3 : 0; // just steer to an alternate slice as a test;
fbo->TexAttach( &colorParams, kAttColor0 );
//=============================================== optional depth tex
CGLMTex *depthTex = NULL;
if (*depthFmtPtr > 0 )
{
GLMTexLayoutKey depthkey;
memset( &depthkey, 0, sizeof(depthkey) );
depthkey.m_texGLTarget = GL_TEXTURE_2D;
depthkey.m_xSize = colorkey.m_xSize >> colorParams.m_mip; // scale depth tex to match color tex
depthkey.m_ySize = colorkey.m_ySize >> colorParams.m_mip;
depthkey.m_zSize = 1;
depthkey.m_texFormat = *depthFmtPtr;
depthkey.m_texFlags = kGLMTexRenderable | kGLMTexIsDepth; // no mips.
if (depthkey.m_texFormat==D3DFMT_D24S8)
{
depthkey.m_texFlags |= kGLMTexIsStencil;
}
depthTex = ctx->NewTex( &depthkey );
//=============================================== attach depth
GLMFBOTexAttachParams depthParams;
memset( &depthParams, 0, sizeof(depthParams) );
depthParams.m_tex = depthTex;
depthParams.m_face = 0;
depthParams.m_mip = 0;
depthParams.m_zslice= 0;
EGLMFBOAttachment depthAttachIndex = (depthkey.m_texFlags & kGLMTexIsStencil) ? kAttDepthStencil : kAttDepth;
fbo->TexAttach( &depthParams, depthAttachIndex );
}
printf("\n FBO:\n color tex %s\n depth tex %s",
colorTex->m_layout->m_layoutSummary,
depthTex ? depthTex->m_layout->m_layoutSummary : "none"
);
// see if FBO is happy
bool ready = fbo->IsReady();
printf("\n -> %s\n", ready ? "pass" : "fail" );
// unbind
ctx->BindFBOToCtx( NULL, GL_READ_FRAMEBUFFER_EXT );
ctx->BindFBOToCtx( NULL, GL_DRAW_FRAMEBUFFER_EXT );
// del FBO
ctx->DelFBO(fbo);
// del texes
ctx->DelTex( colorTex );
if (depthTex) ctx->DelTex( depthTex );
} // end form loop
} // end mip loop
} // end depth loop
} // end color loop
}
// #####################################################################################################################
static int selftest2_seed = 0; // inc this every run to force main thread to teardown/reset display view
void GLMTester::Test2( void )
{
GLMContext *ctx = m_params.m_ctx;
ctx->MakeCurrent();
this->StdSetup(); // default test case drawing setup
// draw stuff (loop...)
for( int i=0; i<m_params.m_frameCount; i++)
{
// ramping shades of blue...
GLfloat clear_color[4] = { 0.50f, 0.05f, ((float)(i%100)) / 100.0f, 1.0f };
glClearColor(clear_color[0], clear_color[1], clear_color[2], clear_color[3]);
CheckGLError("test2 clear color");
glClear(GL_COLOR_BUFFER_BIT+GL_DEPTH_BUFFER_BIT+GL_STENCIL_BUFFER_BIT);
CheckGLError("test2 clearing");
// try out debug text
for( int j=0; j<16; j++)
{
char text[256];
sprintf(text, "The quick brown fox jumped over the lazy dog %d times", i );
float theta = ( (i*0.10f) + (j * 6.28f) ) / 16.0f;
float posx = cos(theta) * 0.5;
float posy = sin(theta) * 0.5;
float charwidth = 6.0 * (2.0 / 1024.0);
float charheight = 11.0 * (2.0 / 768.0);
ctx->DrawDebugText( posx, posy, 0.0f, charwidth, charheight, text );
}
glFinish();
CheckGLError("test2 finish");
this->Present( selftest2_seed );
}
this->StdCleanup();
selftest2_seed++;
}
// #####################################################################################################################
static char g_testVertexProgram01 [] =
{
"!!ARBvp1.0 \n"
"TEMP vertexClip; \n"
"DP4 vertexClip.x, state.matrix.mvp.row[0], vertex.position; \n"
"DP4 vertexClip.y, state.matrix.mvp.row[1], vertex.position; \n"
"DP4 vertexClip.z, state.matrix.mvp.row[2], vertex.position; \n"
"DP4 vertexClip.w, state.matrix.mvp.row[3], vertex.position; \n"
"ADD vertexClip.y, vertexClip.x, vertexClip.y; \n"
"MOV result.position, vertexClip; \n"
"MOV result.color, vertex.color; \n"
"MOV result.texcoord[0], vertex.texcoord; \n"
"END \n"
};
static char g_testFragmentProgram01 [] =
{
"!!ARBfp1.0 \n"
"TEMP color; \n"
"MUL color, fragment.texcoord[0].y, 2.0; \n"
"ADD color, 1.0, -color; \n"
"ABS color, color; \n"
"ADD result.color, 1.0, -color; \n"
"MOV result.color.a, 1.0; \n"
"END \n"
};
// generic attrib versions..
static char g_testVertexProgram01_GA [] =
{
"!!ARBvp1.0 \n"
"TEMP vertexClip; \n"
"DP4 vertexClip.x, state.matrix.mvp.row[0], vertex.attrib[0]; \n"
"DP4 vertexClip.y, state.matrix.mvp.row[1], vertex.attrib[0]; \n"
"DP4 vertexClip.z, state.matrix.mvp.row[2], vertex.attrib[0]; \n"
"DP4 vertexClip.w, state.matrix.mvp.row[3], vertex.attrib[0]; \n"
"ADD vertexClip.y, vertexClip.x, vertexClip.y; \n"
"MOV result.position, vertexClip; \n"
"MOV result.color, vertex.attrib[3]; \n"
"MOV result.texcoord[0], vertex.attrib[8]; \n"
"END \n"
};
static char g_testFragmentProgram01_GA [] =
{
"!!ARBfp1.0 \n"
"TEMP color; \n"
"TEX color, fragment.texcoord[0], texture[0], 2D;"
//"MUL color, fragment.texcoord[0].y, 2.0; \n"
//"ADD color, 1.0, -color; \n"
//"ABS color, color; \n"
//"ADD result.color, 1.0, -color; \n"
//"MOV result.color.a, 1.0; \n"
"MOV result.color, color; \n"
"END \n"
};
void GLMTester::Test3( void )
{
/**************************
XXXXXXXXXXXXXXXXXXXXXX stale test code until we revise the program interface
GLMContext *ctx = m_params.m_ctx;
ctx->MakeCurrent();
this->StdSetup(); // default test case drawing setup
// make vertex&pixel shader
CGLMProgram *vprog = ctx->NewProgram( kGLMVertexProgram, g_testVertexProgram01_GA );
ctx->BindProgramToCtx( kGLMVertexProgram, vprog );
CGLMProgram *fprog = ctx->NewProgram( kGLMFragmentProgram, g_testFragmentProgram01_GA );
ctx->BindProgramToCtx( kGLMFragmentProgram, fprog );
// draw stuff (loop...)
for( int i=0; i<m_params.m_frameCount; i++)
{
// ramping shades of blue...
GLfloat clear_color[4] = { 0.50f, 0.05f, ((float)(i%100)) / 100.0, 1.0f };
glClearColor(clear_color[0], clear_color[1], clear_color[2], clear_color[3]);
CheckGLError("test3 clear color");
glClear(GL_COLOR_BUFFER_BIT+GL_DEPTH_BUFFER_BIT+GL_STENCIL_BUFFER_BIT);
CheckGLError("test3 clearing");
// try out debug text
for( int j=0; j<16; j++)
{
char text[256];
sprintf(text, "This here is running through a trivial vertex shader");
float theta = ( (i*0.10f) + (j * 6.28f) ) / 16.0f;
float posx = cos(theta) * 0.5;
float posy = sin(theta) * 0.5;
float charwidth = 6.0 * (2.0 / 800.0);
float charheight = 11.0 * (2.0 / 640.0);
ctx->DrawDebugText( posx, posy, 0.0f, charwidth, charheight, text );
}
glFinish();
CheckGLError("test3 finish");
this->Present( 3333 );
}
this->StdCleanup();
*****************************/
}
| [
"szymon.gawlik@gmail.com"
] | szymon.gawlik@gmail.com |
c9ef9b59fe82b389ef8583549decf05127e428d8 | c591b56220405b715c1aaa08692023fca61f22d4 | /Piyush/Milestone 3/Milestone 3/palindrome.cpp | 4dc1ebdcd8e5d86cf9d5efffe131bec955258235 | [] | no_license | Girl-Code-It/Beginner-CPP-Submissions | ea99a2bcf8377beecba811d813dafc2593ea0ad9 | f6c80a2e08e2fe46b2af1164189272019759935b | refs/heads/master | 2022-07-24T22:37:18.878256 | 2021-11-16T04:43:08 | 2021-11-16T04:43:08 | 263,825,293 | 37 | 105 | null | 2023-06-05T09:16:10 | 2020-05-14T05:39:40 | C++ | UTF-8 | C++ | false | false | 937 | cpp | #include<bits/stdc++.h>
#include<stdlib.h>
using namespace std;
#define ll long long
#define pb push_back
#define mod 1000000007
#define inf 1e18
#define ps(x,y) fixed<<setprecision(y)<<x
#define mk(arr,n) int *arr=new int[n];
#define t(x) int t; cin>>t; while(t--)
#define fa(n) for(int i=0; i<n; i++)
#define fr(n) for(int j=n-1; j>=0; j--)fc
#define f(x,y) for(int i=x; i<=y; i++)b
void r_r_2() {
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
void solve() {
int n, m, rev = 0;
cin >> n;
m = n;
while (n > 0)
{
int r = n % 10;
n = n / 10;
rev = rev * 10 + r;
}
if (m == rev)
cout << "Palindrome";
else
cout << "Not a Palindrome";
}
int main() {
r_r_2();
solve();
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
e73422676e21a9396b724e45b3a5b5ceb9e5e58e | 5896196444178fac5a21b709956c871aeffc4077 | /src/robot_control_system/src/dwa.cpp | 0327b98aa039589bc3f9bebcd0cc359104bbe2ad | [] | no_license | EnnSou/Test_robot_control_system | 9332ba4ad9d6105f2d846bd2ff5f60c741380736 | 321d0067374903efd66adb206c76d7f560b10808 | refs/heads/master | 2022-09-05T09:45:44.354745 | 2020-06-03T01:02:45 | 2020-06-03T01:02:45 | 268,937,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,309 | cpp | #include <math.h>
#include "dwa.h"
#include <vector>
Dwa::Dwa() :target(0.0,0.0,0.0) {}
void Dwa::initdwa(vector<double> _limits,State _target)
{
Dwa::limits = _limits;
Dwa::target = _target;
}
void Dwa::calc_dynamic_window(State curr_state,vector<double>limits,vector<double> &dw)
{
double v_min,v_max,w_min,w_max;
v_min = curr_state.linear-limits[6]*dt;
v_max = curr_state.linear+limits[6]*dt;
w_min = curr_state.angular-limits[7]*dt;
w_max = curr_state.angular+limits[7]*dt;
dw[0] = max(v_min,limits[0]);
dw[1] = min(v_max,limits[1]);
dw[2] = max(w_min,limits[3]);
dw[3] = min(w_max,limits[4]);
}
State Dwa::calc_trajectory(State curr_state,double v,double w,vector<double>limits)
{
double time=0;
State new_state(0.0,0.0,0.0);
while(time < pre_time){
new_state.yaw = curr_state.yaw+w*dt;
new_state.x = curr_state.x+v*cos(new_state.yaw)*dt;
new_state.y = curr_state.y+v*sin(new_state.yaw)*dt;
new_state.linear = v;
new_state.angular = w;
time += dt;
}
return new_state;
}
double Dwa::calc_goal_cost(State traj,State goal,vector<double>limits)
{
double goal_mag = sqrt(goal.x * goal.x + goal.y * goal.y);
double traj_mag = sqrt(traj.x * traj.x + traj.y * traj.y);
double dot_product = goal.x * traj.x + goal.y * traj.y;
double dis = dot_product / (goal_mag * traj_mag);
double angel = acos(dis);
return angel;
}
double Dwa::calc_obj_cost(){
return 1.0;
}
State Dwa::FindBestTrajectory(State curr_state,State goal,vector<double>limits)
{
double v = curr_state.linear;
double w = curr_state.angular;
double v_reso = limits[2];
double w_reso = limits[5];
double min_cost = 10000.0;
State best_traj = curr_state;
//generate sample space
vector<double>dw(4,0);
calc_dynamic_window(curr_state,limits,dw);
//evalucate all trajectory
for(v += v_reso;v < dw[1];)
{
for(w += w_reso;w < dw[3];)
{
State traj = calc_trajectory(curr_state,v,w,limits);
//calculate cost
double goal_cost = calc_goal_cost(traj,goal,limits);
double speed_cost = 1/(limits[1]-traj.linear);
double obj_cost = calc_obj_cost();
double final_cost = a*goal_cost+b*obj_cost+c*speed_cost;
//search best trajectory
if(final_cost <= min_cost)
{
min_cost = final_cost;
best_traj = traj;
}
w += w_reso;
}
v += v_reso;
}
return best_traj;
}
| [
"yzbismar@gmail.com"
] | yzbismar@gmail.com |
6776d12ba96fbd6982bbdea7d68cd7a93a23a57d | dfa92a6355707dfa444f97ee3b2a9b4d6be48b96 | /test/legacy/test_5d_newtons_method_v3.cpp | 32e2d216af90a7cfbdcdfd8866c39b6ae888c60b | [] | no_license | smrfeld/ggm-inversion | 744193aadf97d92ff0d5cf8b816dfd0b3c221e21 | 0942c22aace9d818bd75df09e9962501fdb5dcb0 | refs/heads/main | 2023-02-03T13:38:18.534767 | 2020-12-22T04:10:00 | 2020-12-22T04:10:00 | 318,600,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,013 | cpp | #include <iostream>
#include <vector>
#include <map>
#include <ggm_inversion>
#include "spdlog/spdlog.h"
#include <exception>
#include <armadillo>
#include "common.hpp"
using namespace std;
using namespace ggm;
int main() {
std::vector<std::pair<int,int>> idx_pairs_free;
idx_pairs_free.push_back(std::make_pair(0, 0));
idx_pairs_free.push_back(std::make_pair(1, 1));
idx_pairs_free.push_back(std::make_pair(2, 2));
idx_pairs_free.push_back(std::make_pair(3, 3));
idx_pairs_free.push_back(std::make_pair(4, 4));
idx_pairs_free.push_back(std::make_pair(0, 3));
idx_pairs_free.push_back(std::make_pair(1, 2));
idx_pairs_free.push_back(std::make_pair(2, 4));
idx_pairs_free.push_back(std::make_pair(3, 4));
std::vector<std::pair<int,int>> idx_pairs_non_free;
idx_pairs_non_free.push_back(std::make_pair(0, 1));
idx_pairs_non_free.push_back(std::make_pair(0, 2));
idx_pairs_non_free.push_back(std::make_pair(0, 4));
idx_pairs_non_free.push_back(std::make_pair(1, 3));
idx_pairs_non_free.push_back(std::make_pair(1, 4));
idx_pairs_non_free.push_back(std::make_pair(2, 3));
arma::mat cov_mat_true = {
{100, 0, 0, 20, 0},
{0, 80, 30, 0, 0},
{0, 30, 6, 0, 8},
{20, 0, 0, 40, 10},
{0, 0, 8, 10, 60}
};
NewtonsMethodv3 nm(5, idx_pairs_free, idx_pairs_non_free);
arma::mat prec_mat_init = 0.03 * arma::eye(5,5);
nm.no_opt_steps = 5e3;
nm.options.log_progress = true;
nm.options.log_interval = 1;
nm.options.log_mats = true;
nm.options.write_interval = nm.no_opt_steps / 100;
nm.options.write_progress = true;
nm.options.write_dir = "../output/test_5d_newtons_method_v3/data/";
ensure_dir_exists(nm.options.write_dir);
auto pr = nm.solve(cov_mat_true, prec_mat_init);
arma::mat prec_mat_solved = pr.first;
arma::mat cov_mat_solved = pr.second;
// report_results(prec_mat_solved, cov_mat_true, idx_pairs_free, nm);
return 0;
}
| [
"oernst@ucsd.edu"
] | oernst@ucsd.edu |
ac118e1aee8c74d7cb628fa82a389cf1d69b3b36 | 3e931c4d045e086b37b21511f3eda526f8053eca | /nginxbuild/EXTRA/ngx_pagespeed-release-1.5.27.3-beta/src/ngx_fetch.h | b4599643f7a886f9792e540753bf62b6538c3f2b | [
"Apache-2.0"
] | permissive | cryptic-io/rpmbuild | b0ad7ae0f4560fd92ed771685413586cab59a5f5 | 5e8c335e64fcc8815e14ef1520f772bbe72d1cd9 | refs/heads/master | 2016-09-06T10:35:08.716867 | 2013-09-12T15:03:07 | 2013-09-12T15:03:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,731 | h | /*
* Copyright 2012 Google Inc.
*
* 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.
*/
// Author: x.dinic@gmail.com (Junmin Xiong)
//
// The fetch is started by the main thread. It will fetch the remote resource
// from the specific url asynchronously.
#ifndef NET_INSTAWEB_NGX_FETCHER_H_
#define NET_INSTAWEB_NGX_FETCHER_H_
extern "C" {
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
typedef bool (*response_handler_pt)(ngx_connection_t* c);
}
#include "ngx_url_async_fetcher.h"
#include <vector>
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/pool.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/http/public/url_pollable_async_fetcher.h"
#include "net/instaweb/http/public/response_headers.h"
#include "net/instaweb/http/public/response_headers_parser.h"
namespace net_instaweb {
class NgxUrlAsyncFetcher;
class NgxFetch : public PoolElement<NgxFetch> {
public:
NgxFetch(const GoogleString& url,
AsyncFetch* async_fetch,
MessageHandler* message_handler,
ngx_msec_t timeout_ms,
ngx_log_t* log);
~NgxFetch();
// Start the fetch
bool Start(NgxUrlAsyncFetcher* fetcher);
// Show the completed url, for logging purpose
const char* str_url();
// This fetch task is done. Call the done of async_fetch.
// It will copy the buffer to cache.
void CallbackDone(bool success);
// Show the bytes received
size_t bytes_received();
void bytes_received_add(int64 x);
int64 fetch_start_ms();
void set_fetch_start_ms(int64 start_ms);
int64 fetch_end_ms();
void set_fetch_end_ms(int64 end_ms);
MessageHandler* message_handler();
int get_major_version() {
return static_cast<int>(status_->http_version / 1000);
}
int get_minor_version() {
return static_cast<int>(status_->http_version % 1000);
}
int get_status_code() {
return static_cast<int>(status_->code);
}
ngx_event_t* timeout_event() {
return timeout_event_;
};
void set_timeout_event(ngx_event_t* x) {
timeout_event_ = x;
};
private:
response_handler_pt response_handler;
// Do the initialized work and start the resolver work.
bool Init();
bool ParseUrl();
// Prepare the request and write it to remote server.
int InitRequest();
// Create the connection with remote server.
int Connect();
void set_response_handler(response_handler_pt handler) {
response_handler = handler;
}
// Only the Static functions could be used in callbacks.
static void NgxFetchResolveDone(ngx_resolver_ctx_t* ctx);
// Write the request
static void NgxFetchWrite(ngx_event_t* wev);
// Wait for the response
static void NgxFetchRead(ngx_event_t* rev);
// Read and parse the first status line
static bool NgxFetchHandleStatusLine(ngx_connection_t* c);
// Read and parse the HTTP headers
static bool NgxFetchHandleHeader(ngx_connection_t* c);
// Read the response body
static bool NgxFetchHandleBody(ngx_connection_t* c);
// Cancel the fetch when it's timeout
static void NgxFetchTimeout(ngx_event_t* tev);
// Add the pagespeed User-Agent
void FixUserAgent();
void FixHost();
const GoogleString str_url_;
ngx_url_t url_;
NgxUrlAsyncFetcher* fetcher_;
AsyncFetch* async_fetch_;
ResponseHeadersParser parser_;
MessageHandler* message_handler_;
size_t bytes_received_;
int64 fetch_start_ms_;
int64 fetch_end_ms_;
int64 timeout_ms_;
bool done_;
int64 content_length_;
struct sockaddr_in sin_;
ngx_log_t* log_;
ngx_buf_t* out_;
ngx_buf_t* in_;
ngx_pool_t* pool_;
ngx_http_request_t* r_;
ngx_http_status_t* status_;
ngx_event_t* timeout_event_;
ngx_connection_t* connection_;
ngx_resolver_ctx_t* resolver_ctx_;
DISALLOW_COPY_AND_ASSIGN(NgxFetch);
};
} // namespace net_instaweb
#endif // NET_INSTAWEB_NGX_FETCHER_H_
| [
"bgp2396@bellsouth.net"
] | bgp2396@bellsouth.net |
3e8e55cbb55c638ba09735b2f9a395f7acddc5f2 | 443fd6ad57a3a998f916e707bd4b47c3193deb3d | /chilkat/include/CkSshKey.h | 1a1dedfc76a69486dcdb7a00c0aa3a77a89a2818 | [] | no_license | michrasulis/BitsensingApp | a68fb72e8c72ed1bb4a428b78c438e441a3a6fa5 | b60043b50fd65b7c65526de1941dc2e43fce92fb | refs/heads/main | 2023-08-22T08:59:07.289800 | 2021-11-02T14:28:43 | 2021-11-02T14:28:43 | 423,867,447 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 61,177 | h | // CkSshKey.h: interface for the CkSshKey class.
//
//////////////////////////////////////////////////////////////////////
// This header is generated for Chilkat 9.5.0.88
#ifndef _CkSshKey_H
#define _CkSshKey_H
#include "chilkatDefs.h"
#include "CkString.h"
#include "CkMultiByteBase.h"
#if !defined(__sun__) && !defined(__sun)
#pragma pack (push, 8)
#endif
#undef Copy
// CLASS: CkSshKey
class CK_VISIBLE_PUBLIC CkSshKey : public CkMultiByteBase
{
private:
// Don't allow assignment or copying these objects.
CkSshKey(const CkSshKey &);
CkSshKey &operator=(const CkSshKey &);
public:
CkSshKey(void);
virtual ~CkSshKey(void);
static CkSshKey *createNew(void);
void CK_VISIBLE_PRIVATE inject(void *impl);
// May be called when finished with the object to free/dispose of any
// internal resources held by the object.
void dispose(void);
// BEGIN PUBLIC INTERFACE
// ----------------------
// Properties
// ----------------------
// Some key file formats allow a comment to be included. This is the comment if
// present.
void get_Comment(CkString &str);
// Some key file formats allow a comment to be included. This is the comment if
// present.
const char *comment(void);
// Some key file formats allow a comment to be included. This is the comment if
// present.
void put_Comment(const char *newVal);
// true if the object contains a DSA key. false if the object contains an RSA
// key.
bool get_IsDsaKey(void);
// true if the object contains a private key. false if it contains a public
// key.
bool get_IsPrivateKey(void);
// true if the object contains an RSA key. false if the object contains a DSA
// key.
bool get_IsRsaKey(void);
// Indicates the type of key held in this object instance. Can be "rsa", "dsa",
// "ecdsa", "ed25519", or "none".
void get_KeyType(CkString &str);
// Indicates the type of key held in this object instance. Can be "rsa", "dsa",
// "ecdsa", "ed25519", or "none".
const char *keyType(void);
// The password to be used when importing or exporting encrypted private keys.
void get_Password(CkString &str);
// The password to be used when importing or exporting encrypted private keys.
const char *password(void);
// The password to be used when importing or exporting encrypted private keys.
void put_Password(const char *newVal);
// This is a catch-all property to be used for uncommon needs. This property
// defaults to the empty string, and should typically remain empty.
//
// Can be set to a list of the following comma separated keywords:
// "DES-EDE3-CBC" - Use older Triple-DES encryption (instead of the default
// AES-128-CBC) when creating encrypted OpenSSH private keys.
//
void get_UncommonOptions(CkString &str);
// This is a catch-all property to be used for uncommon needs. This property
// defaults to the empty string, and should typically remain empty.
//
// Can be set to a list of the following comma separated keywords:
// "DES-EDE3-CBC" - Use older Triple-DES encryption (instead of the default
// AES-128-CBC) when creating encrypted OpenSSH private keys.
//
const char *uncommonOptions(void);
// This is a catch-all property to be used for uncommon needs. This property
// defaults to the empty string, and should typically remain empty.
//
// Can be set to a list of the following comma separated keywords:
// "DES-EDE3-CBC" - Use older Triple-DES encryption (instead of the default
// AES-128-CBC) when creating encrypted OpenSSH private keys.
//
void put_UncommonOptions(const char *newVal);
// ----------------------
// Methods
// ----------------------
// Loads an SSH key from an OpenSSH private-key file format. If the key is
// encrypted, set the Password property prior to calling this method.
//
// Note: keyStr is not a filename -- it should contain the contents of the OpenSSH
// formatted private key. To load from a file, you may first call LoadText to load
// the complete contents of a text file into a string.
//
// Here are are samples of RSA and DSA private keys in OpenSSH format, both
// encrypted and unencrypted:
//
// Encrypted OpenSSH DSA Key
//
// -----BEGIN DSA PRIVATE KEY-----
// Proc-Type: 4,ENCRYPTED
// DEK-Info: DES-EDE3-CBC,934E999D91EFE8F8
//
// j1sslF86hdpzaBdVeLZ9akXux+CEaa6HyZgou3BkRkWpMn7gFqX3lfRIjrlhY41w
// +snC2HNYF5ae+WymP6fQ7TOhOsQD3KFBNbohn4dJE4fB0El6OKCbR2MGJlUkwMY4
// q3VCu3yAeiMmLwocoHxbfXYXgjqPBqbLXPSsHzpirGyC8FD8+P0QWW/W4rJGGWru
// 866fkIPH+PCJXml4Io/YPUQYYFhRd4XTJvXqU0tLOpFfsLhetGziKNZuLGzpiVCt
// v8Vt0VXKSD6M27gE788mEhJjtqVVpymRDReZhrt1MlGVofhuC34kA4L7+BLHARHq
// bvM0SRSvqwNYxLNDWtV33RlOEvy/Kg7rRLnmSgZ7pPgUB4lbpC23Adp4djpdO5S2
// LERDEV+cTmKGCpLOCGOEGlPOiEnROP8xjmqpGHNMaLh6Jd/zGdgdAN7/6Wk/TeaP
// p/Ma4UQUnZEjkIpfxYtsMJ0Pb5JBZf41vJMVqFlDKeOngFIlWzv9G34Ip2GbZVUJ
// 0CfbD3VrZb8t6ethcSQ7NKkMpB0s4Qu+nSIHZngb6Z/uzTVX/ElbxVu7/kca627n
// LtXBcDZtkYey7ANePw0Q2Ju3rOcWJQK691K3M/qZkPO5TKtybmdMHV6EuVPGlPXV
// d2fUUBCZpTs8udN9bE8lZIGC//RX4hPfCV1eL0cZehByJeJG6EK1UvrCPnsfymFi
// bWJvjM4SWxFaMUNQRPuNywE1c9K0BqR/NQa6scADReXU66pho/ttb1Furnmm68rB
// SQq+CA5DjBOMYIbD6s0zMLKICwrk4DYTZlhRGb/fP9BAWZN+scz3ot4RUaURasXj
// Fb9b0arwqL5b84pDoA+gdxnDcB60RjegLTPqC/EuVepHTRRZN3w5eZvW5ZjHwmzw
// TYPYoraj7NBRaTx81ZVkKViDZnqSY2xjUnuiUbWrgKWC+asZzQDGGebLFQmFr0V3
// rkI7MR7JHrl5VrIKro9ewVFhqugdMASzC3e0GjKQowec5ELjVAGLz+zvHrAcrxkh
// m8Q2lHl1efS/rnCyk9DDKqHBkcIYkyxmtQMtbg4MruEIBQhTx4bUzQdq5VLYYlqY
// YrrEcZveySg0ILT9x0swM22ji3w0S7Xv
// -----END DSA PRIVATE KEY-----
//
// Unencrypted OpenSSH DSA Key
//
// -----BEGIN DSA PRIVATE KEY-----
// MIIDPgIBAAKCAQEAqj/5FQjdsvxasIvxdEKbIe0SuHfJxlLSdCqvKsknpn26UBSd
// W5wXqiUSmLrU7mLIRAVxdQ7umcp3N8w/dIiVkiJvm+tUQqlPYrd6n2JK+eQ0lGtP
// emsn6fQzHhUmG0jCFgot3nNodspb5euUxVrU0BCq2PpKRuGKt6cyq5oEAvlg1K6p
// vpze8tZ+etZGToN2uBQ/3ysGjgiDs3Zgh/k3o+8UteuBdjd8awEHcIzFml8w3+XW
// EjuOslWrda8KiPCRZEQIbNfiZrcTzAefNRzJhKJL6EkuCU+3oZo8DL6Xc+0Obkk6
// 46kYV5oDYbPBDmNIQBCr6odNHnWnBBnSs3TbLQIVANkiO001oz4lzhsO/tDx9rpO
// yH/5AoIBAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJvaHyHi/v
// /eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8ShNPJIByK
// m7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3DtX220CIrE
// BaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+tl4gFR0r
// 4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7xQbYtqHBR
// +oBgRFbPPouNMIUexC4DKxyNeuN2zIcCggEAXh/Akb90+cojwtyjzXTxA9h4CzfT
// E1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwoq2SPW1u9
// qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo3IoKzpEK
// B1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5SaIWYaCiTZ
// WNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuyH/wk2oXd
// lNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqizgIVAKI4
// pSbllzsgU0NB+IQTQU7C/TKv
// -----END DSA PRIVATE KEY-----
//
// Encrypted OpenSSH RSA Key
//
// -----BEGIN RSA PRIVATE KEY-----
// Proc-Type: 4,ENCRYPTED
// DEK-Info: DES-EDE3-CBC,DC983431B352E226
//
// HtBgp1FMd8abEzUiZPbrgImaCh8f5p+IzikphBnWwAfl7ANqhsFaATs+4BoFnals
// sdYlyYnan5I1steUqvI+J/k8j+j+6YOl93uF2nF0oBUp8RBlMprYXEALAAsuaXma
// RAmJKQF1vmg43d4DdZTlsmogK8nzdY1E36qzSTcq/PBP+rYXDNIRIaKn35sESAIy
// shaTOs2n8TfoxiVq0oAC5H3QkPlK3ujd77oIk7JQKEZFvE1kaPaY3a6cgGpVjP7s
// 8eWtFQrTvLT1iqGPOiK2018Nua2rsXfxR6JBMgmkPvfgTtc31EIdfurFK1AOZfac
// 5YXokIEVeXxChIkMFXsbgeZBK87Fa3HnSq5q8VCvuku7NPbqdSI0spGoyRrOuaO8
// 0HXjizWg9QbH+kK5lD1ks/yR3Hj7dxoXsV0Bo8iK0NB/pGfCxwtIJYt8iC1w07Pl
// Io59mH/e+BiHbXI8bp8mozsSvvxMQlEF/iuwaqZozhWhdsn+Q2jd4fh4qEOV49pA
// L6utYnb64/JOqZZZe1HfKfpbNQ8ZaOjciP0+Oe+ktCtySddIYYsac/LbKHdNil78
// EsRIzms/OpYYEt3GQBbaphZa7X2M97+qbPPO6+hosVXwUEo2Tw80gS5LMFF+8W21
// RoK4+VqarMTqB+pHJGWpe7v5MbmKl8HG/dpBM/ufRFdLt2uGYo/dgcE9Y2trWrOP
// DQEB9BpbQ/Od/wnhM9SsUOp3mJHgwW3waGgPoIaQdquB6ipkWen0h42XHT1EqiSZ
// 1S5pXjZvEyXPvYP3mjXBoD0YxNftKCrFHzlWz4EtI74LSgilTLmVD2TauutDdjFc
// zjfTtrwxnS/ZFbijZBSthhG3aVhZAmIguWhZUFJcttAZY4S/AJ46HN7qI/WmGSiQ
// 3SJN7OCZEhJ8xidXT4giMY/xaNWaRPDpUF+aKE1vlCwtVJxV8VlqGkSyvk7/0pcg
// CmPCH9+p4IXmGq16UNrJh6Mp+GwtTbp62mFeyzh6zo1BKPQGzvohHxLs9/qW5I9L
// sbx34VavTbityYDj/r+UqiAJ1srn9kadpDf/Ai5emjWb/f+U5KIrrPvI+iOv/N/p
// g3vOsDYa8x3v7bDjXpQtXxH2T2qbxqFUfI8Ckk18eE0I845TwLsAaoieFmZrYMrV
// nsrgkALuEobUFg+3GFTTPipXhSGn5pRJb249t3pUxcrYYmq5quIBRlK2f2UsxBnX
// 95Mv2H2Ab7ZEiN++CABoCmz3Mim8elWQxQFmW4jgseeOUCINNPxQc+sPL99HAj6s
// C5sSkZMDKTjWYMc3UKN9XOQ1G0RbkA59jg0VwP/DDViCju/UsIllmnPTd5OpjLHf
// AW5xq7i68AQXSXlVfy21T23GiiXKfN1b0wXRL1qvQCBYVXP9UP5zxbKLQM29aIGP
// Sf6ccO/y+pvaxw3ujBhyDdKKMbWcKhWfteEiR2h7Nsf6aSsWha5TDr8T9GavxsyH
// cK88J2Rp3B9Cr4I5le3rbJmi6R1gZkK89kK8UllAnaqjJJXV4EBcVs2eKxMuEsjq
// nxCy9shNjgEOr/6VgPRrimvdhDDt4ZJynhskGoOiWFEK4Ud/1sC+NTrpwtRqjXj9
// -----END RSA PRIVATE KEY-----
//
// Unencrypted OpenSSH RSA Key
//
// -----BEGIN RSA PRIVATE KEY-----
// MIIEpQIBAAKCAQEAvTjHMg1+nAogY3o8V8zXKwf+VuTMtIZggCiUQ9NU884PeHnb
// tezsx5KRuAtNqhWtgEsNg0/aHv6o/7E4HJE9PCqVpUXnTV1mZE14BvmusCnuz1HL
// nV3CtSW3BOh98sHixwu0I4y2RZy0sfaTBn1zDXvCv2mrVL5D1QnOZ8B/Vi5fceQd
// eaLe6Uzj6vTi5MBWjzvVog/xDr0tEo4FPRmu6SUkmTzhwEiETScm5qOm9VnTr2O9
// sCibFPmqrODGAzpj/OWIH2RMMT1B9Nl6P6JvHWZc92rqrUVZHBkSoakNWkytLN5j
// WyxwIdCFxQvCnAKic7uOodMSiqDUPJHHlPIghwIDAQABAoIBAAK9V4JPz9beH3dk
// cqzyfW33VTH6nFX/cr0ISE7c9F+45D4vCTfsfYHvix/mCXbTsJapIagWc9FqZdF2
// +Xd4ayB7riguwz+x1o9YR4cRywwoLBFP9tzvjMnvkaepAQHTG+HHFUTNskfDVngC
// wOtlvGHXZPIbU+QLvoGtMFZSOHBrs1cOfoUO1BToN1cGfgp/DuJY6WWVoNs93C8J
// wgnH2DdosRcMDYOQsASH60hEE2JJuF7Ox+BwlcsV5AUDwIeAChQI0Aend7NL9cee
// U8o3UXAVjABowGI9EQJYUmysir5mFs/BETlPambyvEWWNCtJsT2qrCi2Xme5BRzD
// p5MMJ+ECgYEAzfbbQagHiP48yGiZS2j7i1UcV/0pgeamtjaxJf1njyMrkyxMFOFW
// PfLOVLcRnx4HcqYYv9Opo8mbYlxjUUFxhMBYdyNICx8OjM7eijSjGisvAh0S20Vo
// LvhQ0zzv1/QUdnj4jO4FWNgHYUF+mre8nX8k/s8AcudBR7n5w+MhP7cCgYEA6zCw
// DGB8ipBQMryEWVNc0eYFFXojxlFRKjp4BRc43F0s0gyRLWGCUHTN0Z1DPKQRilo6
// D8nGANN8BYVFDEcuFk8SCks5Xk76YfL+9uAETKv7y//AE8dyrCRk8/7kyOdMhHtq
// 1bHsAutfxeiYrdRWyK0ZApAKdSEy+BvdVRv9hbECgYEAzcNdvlUg2gKsNMcSxpym
// GMe5nknj6svEJ2uyRLLJf91yDgEGLSIFp7Pn4AhYiW9Vn3tCZHoQEvo5yuVjr2zC
// /Q2wE63iroGjZpbRCp+VhnI371OeYAMSF0KqdK5/Km7E9qraHOk53E1N6iKlWepP
// e8Tm781btG9F72NjnAhQUjcCgYEA1XB2FIVsAQQ/BAx5v+cbkZHCg185ID2j/0LY
// sSYGAFa+2lF1X03iycl3EAg8gMgU8w43KyTegNls8EWmCCKA/NX9dUIXajMan9G6
// +akLvdlGxjfvxQN4WikdRSHJ11mx43lt10mE+pFJdX5FMVxG9g/BZsX595qNewUu
// tJKWXcECgYEAqHYYHyZI9dah6JVpm5UQ6kJbDPZad7uus/lmJfTgY+ZCH1sEVySL
// UYk4TyswyUqzLfazhhQ9yZsDBmdm6jRJLYtQBo9fybpOzeyK20aFIGQTSaVFbAGG
// YIsv2DOWk9HHr0TSG7yu/1hiMf3ol0ofpTEQpXyM8qjVuqCeqsMeJ9I=
// -----END RSA PRIVATE KEY-----
bool FromOpenSshPrivateKey(const char *keyStr);
// Loads an OpenSSH public-key from an OpenSSH formatted public-key.
//
// Note: keyStr is not a filename -- it should contain the contents of the OpenSSH
// formatted public key. To load from a file, you may first call LoadText to load
// the complete contents of a text file into a string.
//
// Sample OpenSSH-formatted DSA and RSA public keys are below:
//
// OpenSSH RSA Public Key (Line-breaks are added for readability. An
// OpenSSH-formatted public key would typically be a single line, not multiple
// lines.)
//
// ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCAKJRD01Tzzg94edu17O
// zHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZkTXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjL
// ZFnLSx9pMGfXMNe8K/aatUvkPVCc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZP
// OHASIRNJybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkcGRKhqQ1aTK0
// s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
//
// OpenSSH DSA Public Key (Line-breaks are added for readability.)
//
// ssh-dss AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9ulAUnVucF6olEpi61O5iyEQF
// cXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnkNJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6Skb
// hirenMquaBAL5YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpfMN/l1hI7jrJVq3
// WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3PtDm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQ
// Z0rN02y0AAAAVANkiO001oz4lzhsO/tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWB
// KpaJvaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8ShNPJIByKm7XVGvLFhDqhiN
// KIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3DtX220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0
// zmKsQ2gjdjRphm+tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7xQbYtqHBR+oBgR
// FbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTxA9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWR
// WtTDidZWRxWXxP+8J7PrMwA4Pwoq2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7E
// Qljo3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5SaIWYaCiTZWNTS4vLeNBuJB
// VJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuyH/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nB
// IZDEUQYvVA71Fawp4cqizg==
bool FromOpenSshPublicKey(const char *keyStr);
// Loads an SSH key from a PuTTY private-key file format. If the key is encrypted,
// set the Password property prior to calling this method.
//
// Note: keyStr is not a filename -- it should contain the contents of the PuTTY
// formatted private key. To load from a file, you may first call LoadText to load
// the complete contents of a text file into a string.
//
// Below are samples of RSA and DSA private keys in PuTTY format, both encrypted
// and unencrypted:
//
// Encrypted PuTTY DSA Key
//
// PuTTY-User-Key-File-2: ssh-dss
// Encryption: aes256-cbc
// Comment: dss-key-20080914
// Public-Lines: 18
// AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9
// ulAUnVucF6olEpi61O5iyEQFcXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnk
// NJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6SkbhirenMquaBAL5
// YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpf
// MN/l1hI7jrJVq3WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3Pt
// Dm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQZ0rN02y0AAAAVANkiO001oz4lzhsO
// /tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJ
// vaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8S
// hNPJIByKm7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3Dt
// X220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+
// tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7x
// QbYtqHBR+oBgRFbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTx
// A9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwo
// q2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo
// 3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5Sa
// IWYaCiTZWNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuy
// H/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqi
// zg==
// Private-Lines: 1
// L2iyk4xEmQi4IK8ZCm35/UDan0VVUdd9whyljTo6SoA=
// Private-MAC: 5633A6762B5D9016A5B1D7753713C4A13CD734EC
//
// Unencrypted PuTTY DSA Key
//
// PuTTY-User-Key-File-2: ssh-dss
// Encryption: none
// Comment: dss-key-20080914
// Public-Lines: 18
// AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9
// ulAUnVucF6olEpi61O5iyEQFcXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnk
// NJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6SkbhirenMquaBAL5
// YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpf
// MN/l1hI7jrJVq3WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3Pt
// Dm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQZ0rN02y0AAAAVANkiO001oz4lzhsO
// /tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJ
// vaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8S
// hNPJIByKm7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3Dt
// X220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+
// tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7x
// QbYtqHBR+oBgRFbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTx
// A9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwo
// q2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo
// 3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5Sa
// IWYaCiTZWNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuy
// H/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqi
// zg==
// Private-Lines: 1
// AAAAFQCiOKUm5Zc7IFNDQfiEE0FOwv0yrw==
// Private-MAC: 7A13473EBD5C8E1ADD57D8AE5A5EF3F1789DDD8B
//
// Encrypted PuTTY RSA Key
//
// PuTTY-User-Key-File-2: ssh-rsa
// Encryption: aes256-cbc
// Comment: rsa-key-20080914
// Public-Lines: 6
// AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCA
// KJRD01Tzzg94edu17OzHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZk
// TXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjLZFnLSx9pMGfXMNe8K/aatUvkPV
// Cc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZPOHASIRN
// Jybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkc
// GRKhqQ1aTK0s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
// Private-Lines: 14
// SC03/1Szexogtlxrde1JbuWD0z9cNRLGlroT9Vf7uAJLRLF4bM7ovlcKPVrtsymG
// lJitt6bhK9bmFIGj3Ko+RImpwFNHlL56UYtnJqx2ihSTbU8JJ34VyLy7ADjUlg3S
// wL4YY2Uxwo24p0oLTyl3UYBVZ9z+e9fqTiZJI+jl1mFSJz2FbuA2iuiGZQcOKKHx
// cLye5GgoXgSrMjNcm6evVmHrAi+RjakhBjzFm/aCKmiJr9bf12WI+Sp06oOvnShP
// WcrrqVsr1+4Ju85z2wFevHYfFLjqW13AAMMdJnr/4x0g/AjTjxiuADlXBC5d+V1p
// 7Kwi9ZDd2NMeSeTeM9ZIsKpuR2ndURYsgbTe/Hhl1nU2VwzZJuNU58ROZzjb3HOv
// kjk+2GZhAqVQSfhm8ma9SBW9YIfIRawKSQZh1v9Sa7jh68WjeCzndvyzUCbl0tiW
// irSTLScKcyfxRkZ952CMgGsqKX6kDdb2Yz4YLxSdltD9qs/aPyweln+uf7m+5hIV
// SpFXw7gjZjMq+US5fstdhTAZjkzkKyV4ejlfekneIDmq5oXR5kf+3y4oqkP4nWS8
// xP6aURBK7GdKxREmnj2E5He7nQNf5d5fGLMGtvULbY18k6aMVqRLbCt1rwF7lVsz
// dRrp8fX94pdu0ZFLb8QwKnDI7hXzrK0lYnpfIECwPlA9SdhChVRXsvUFi5scTdB0
// /2lV+IVcz0e1GtbsvV5EaFCcXy9k5Rq8zjhfbbTWtur7dJbwKPPQyByioNeGwzvT
// LN0X5hn0AaDjbSH6KNPFY0YPxx4rfqsVqI8jH4CJJhoByEtb5cBJFpLhl9o6t27d
// 3oafNIL7UjVL0j5df+4JPjSbwm+44ccrp2FBRnIJw5MKtKz58lBarpwKHRecw6Yk
// Private-MAC: 743AFA7F93ABE10BF61C21B9BDEFDCBF52F04980
//
// Unencrypted PuTTY RSA Key
//
// PuTTY-User-Key-File-2: ssh-rsa
// Encryption: none
// Comment: rsa-key-20080914
// Public-Lines: 6
// AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCA
// KJRD01Tzzg94edu17OzHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZk
// TXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjLZFnLSx9pMGfXMNe8K/aatUvkPV
// Cc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZPOHASIRN
// Jybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkc
// GRKhqQ1aTK0s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
// Private-Lines: 14
// AAABAAK9V4JPz9beH3dkcqzyfW33VTH6nFX/cr0ISE7c9F+45D4vCTfsfYHvix/m
// CXbTsJapIagWc9FqZdF2+Xd4ayB7riguwz+x1o9YR4cRywwoLBFP9tzvjMnvkaep
// AQHTG+HHFUTNskfDVngCwOtlvGHXZPIbU+QLvoGtMFZSOHBrs1cOfoUO1BToN1cG
// fgp/DuJY6WWVoNs93C8JwgnH2DdosRcMDYOQsASH60hEE2JJuF7Ox+BwlcsV5AUD
// wIeAChQI0Aend7NL9ceeU8o3UXAVjABowGI9EQJYUmysir5mFs/BETlPambyvEWW
// NCtJsT2qrCi2Xme5BRzDp5MMJ+EAAACBAM3220GoB4j+PMhomUto+4tVHFf9KYHm
// prY2sSX9Z48jK5MsTBThVj3yzlS3EZ8eB3KmGL/TqaPJm2JcY1FBcYTAWHcjSAsf
// DozO3oo0oxorLwIdEttFaC74UNM879f0FHZ4+IzuBVjYB2FBfpq3vJ1/JP7PAHLn
// QUe5+cPjIT+3AAAAgQDrMLAMYHyKkFAyvIRZU1zR5gUVeiPGUVEqOngFFzjcXSzS
// DJEtYYJQdM3RnUM8pBGKWjoPycYA03wFhUUMRy4WTxIKSzleTvph8v724ARMq/vL
// /8ATx3KsJGTz/uTI50yEe2rVsewC61/F6Jit1FbIrRkCkAp1ITL4G91VG/2FsQAA
// AIEAqHYYHyZI9dah6JVpm5UQ6kJbDPZad7uus/lmJfTgY+ZCH1sEVySLUYk4Tysw
// yUqzLfazhhQ9yZsDBmdm6jRJLYtQBo9fybpOzeyK20aFIGQTSaVFbAGGYIsv2DOW
// k9HHr0TSG7yu/1hiMf3ol0ofpTEQpXyM8qjVuqCeqsMeJ9I=
// Private-MAC: 3BE4CAA1B2AE19C3E6841639BD7275019CF961F1
bool FromPuttyPrivateKey(const char *keyStr);
// Loads an SSH public key from an RFC 4716 format.
//
// Note: keyStr is not a filename -- it should contain the contents of the PuTTY
// formatted public key. To load from a file, you may first call LoadText to load
// the complete contents of a text file into a string. Sample RFC 4716 DSA and RSA
// public keys are below:
//
// RSA Public Key
//
// ---- BEGIN SSH2 PUBLIC KEY ----
// Comment: "This is an optional comment"
// AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCA
// KJRD01Tzzg94edu17OzHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZk
// TXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjLZFnLSx9pMGfXMNe8K/aatUvkPV
// Cc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZPOHASIRN
// Jybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkc
// GRKhqQ1aTK0s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
// ---- END SSH2 PUBLIC KEY ----
//
// DSA Public Key
//
// ---- BEGIN SSH2 PUBLIC KEY ----
// Comment: "This is an optional comment"
// AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9
// ulAUnVucF6olEpi61O5iyEQFcXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnk
// NJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6SkbhirenMquaBAL5
// YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpf
// MN/l1hI7jrJVq3WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3Pt
// Dm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQZ0rN02y0AAAAVANkiO001oz4lzhsO
// /tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJ
// vaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8S
// hNPJIByKm7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3Dt
// X220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+
// tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7x
// QbYtqHBR+oBgRFbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTx
// A9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwo
// q2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo
// 3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5Sa
// IWYaCiTZWNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuy
// H/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqi
// zg==
// ---- END SSH2 PUBLIC KEY ----
bool FromRfc4716PublicKey(const char *keyStr);
// Loads an SSH key from XML.
//
// Note: xmlKey is not a filename -- it should contain the contents of the XML SSH
// key. To load from a file, you may first call LoadText to load the complete
// contents of a text file into a string.
//
// Here are RSA public/private keys in XML format:
// _LT_RSAPublicKey>
// _LT_Modulus>x+52s7vvaZ8rT2UdFZWlSUVDHD ... D/m73pYaEJB3Nd7w==_LT_/Modulus>
// _LT_Exponent>JQ==_LT_/Exponent>
// _LT_/RSAPublicKey>
//
// _LT_RSAKeyValue>
// _LT_Modulus>vTjHMg1+n.....JHHlPIghw==_LT_/Modulus>
// _LT_Exponent>AQAB_LT_/Exponent>
// _LT_P>zfbbQagHiP48y.....udBR7n5w+MhP7c=_LT_/P>
// _LT_Q>6zCwDGB8ipB....dSEy+BvdVRv9hbE=_LT_/Q>
// _LT_DP>zcNdvlUg2g......9F72NjnAhQUjc=_LT_/DP>
// _LT_DQ>1XB2FIVsA.....qNewUutJKWXcE=_LT_/DQ>
// _LT_InverseQ>qHYYHyZI9d....VuqCeqsMeJ9I=_LT_/InverseQ>
// _LT_D>Ar1Xgk/P1t4fd2Ryr........Onkwwn4Q==_LT_/D>
// _LT_/RSAKeyValue>
//
bool FromXml(const char *xmlKey);
// Generates a new SSH DSA key that is numBits bits in length. The numBits should be at
// least 1024 bits and a multiple of 64. Typical values are 1024 and 2048.
bool GenerateDsaKey(int numBits);
// Generates an ECDSA (ECC) private key. The curveName specifies the curve name which
// determines the key size.
//
// The following curve names are accepted:
// secp256r1 (also known as P-256 and prime256v1)
// secp384r1 (also known as P-384)
// secp521r1 (also known as P-521)
//
bool GenerateEcdsaKey(const char *curveName);
// Generates a new ED25519 public/private key pair.
bool GenerateEd25519Key(void);
// Generates a new RSA public/private key pair. The numBits can range from 384 to
// 4096. Typical key lengths are 1024 or 2048 bits. After successful generation,
// the public/private keys can be exported in OpenSSH or PuTTY format.
//
// (excerpt from Wikipedia's article on RSA) 65537 is a commonly used value for
// exponent. This value can be regarded as a compromise between avoiding potential
// small exponent attacks and still allowing efficient encryptions (or signature
// verification). The NIST Special Publication on Computer Security (SP 800-78 Rev
// 1 of August 2007) does not allow public exponents e smaller than 65537, but does
// not state a reason for this restriction.
//
bool GenerateRsaKey(int numBits, int exponent);
// Generates a fingerpring for an SSH key. A sample fingerprint looks like this:
// ssh-dss 2048 d0:5f:f7:d6:49:60:7b:50:19:f4:41:59:d4:1f:61:7a
bool GenFingerprint(CkString &outStr);
// Generates a fingerpring for an SSH key. A sample fingerprint looks like this:
// ssh-dss 2048 d0:5f:f7:d6:49:60:7b:50:19:f4:41:59:d4:1f:61:7a
const char *genFingerprint(void);
// Convenience method for loading an entire text file into an in-memory string.
bool LoadText(const char *filename, CkString &outStr);
// Convenience method for loading an entire text file into an in-memory string.
const char *loadText(const char *filename);
// Convenience method for saving the contents of a string variable to a file.
bool SaveText(const char *strToSave, const char *filename);
// Exports the private key to a string in OpenSSH format. If bEncrypt is true, the
// key is encrypted using the value of the Password property. Below are samples of
// RSA and DSA private keys in OpenSSH format, both encrypted and unencrypted:
//
// Encrypted OpenSSH DSA Key
//
// -----BEGIN DSA PRIVATE KEY-----
// Proc-Type: 4,ENCRYPTED
// DEK-Info: DES-EDE3-CBC,934E999D91EFE8F8
//
// j1sslF86hdpzaBdVeLZ9akXux+CEaa6HyZgou3BkRkWpMn7gFqX3lfRIjrlhY41w
// +snC2HNYF5ae+WymP6fQ7TOhOsQD3KFBNbohn4dJE4fB0El6OKCbR2MGJlUkwMY4
// q3VCu3yAeiMmLwocoHxbfXYXgjqPBqbLXPSsHzpirGyC8FD8+P0QWW/W4rJGGWru
// 866fkIPH+PCJXml4Io/YPUQYYFhRd4XTJvXqU0tLOpFfsLhetGziKNZuLGzpiVCt
// v8Vt0VXKSD6M27gE788mEhJjtqVVpymRDReZhrt1MlGVofhuC34kA4L7+BLHARHq
// bvM0SRSvqwNYxLNDWtV33RlOEvy/Kg7rRLnmSgZ7pPgUB4lbpC23Adp4djpdO5S2
// LERDEV+cTmKGCpLOCGOEGlPOiEnROP8xjmqpGHNMaLh6Jd/zGdgdAN7/6Wk/TeaP
// p/Ma4UQUnZEjkIpfxYtsMJ0Pb5JBZf41vJMVqFlDKeOngFIlWzv9G34Ip2GbZVUJ
// 0CfbD3VrZb8t6ethcSQ7NKkMpB0s4Qu+nSIHZngb6Z/uzTVX/ElbxVu7/kca627n
// LtXBcDZtkYey7ANePw0Q2Ju3rOcWJQK691K3M/qZkPO5TKtybmdMHV6EuVPGlPXV
// d2fUUBCZpTs8udN9bE8lZIGC//RX4hPfCV1eL0cZehByJeJG6EK1UvrCPnsfymFi
// bWJvjM4SWxFaMUNQRPuNywE1c9K0BqR/NQa6scADReXU66pho/ttb1Furnmm68rB
// SQq+CA5DjBOMYIbD6s0zMLKICwrk4DYTZlhRGb/fP9BAWZN+scz3ot4RUaURasXj
// Fb9b0arwqL5b84pDoA+gdxnDcB60RjegLTPqC/EuVepHTRRZN3w5eZvW5ZjHwmzw
// TYPYoraj7NBRaTx81ZVkKViDZnqSY2xjUnuiUbWrgKWC+asZzQDGGebLFQmFr0V3
// rkI7MR7JHrl5VrIKro9ewVFhqugdMASzC3e0GjKQowec5ELjVAGLz+zvHrAcrxkh
// m8Q2lHl1efS/rnCyk9DDKqHBkcIYkyxmtQMtbg4MruEIBQhTx4bUzQdq5VLYYlqY
// YrrEcZveySg0ILT9x0swM22ji3w0S7Xv
// -----END DSA PRIVATE KEY-----
//
// Unencrypted OpenSSH DSA Key
//
// -----BEGIN DSA PRIVATE KEY-----
// MIIDPgIBAAKCAQEAqj/5FQjdsvxasIvxdEKbIe0SuHfJxlLSdCqvKsknpn26UBSd
// W5wXqiUSmLrU7mLIRAVxdQ7umcp3N8w/dIiVkiJvm+tUQqlPYrd6n2JK+eQ0lGtP
// emsn6fQzHhUmG0jCFgot3nNodspb5euUxVrU0BCq2PpKRuGKt6cyq5oEAvlg1K6p
// vpze8tZ+etZGToN2uBQ/3ysGjgiDs3Zgh/k3o+8UteuBdjd8awEHcIzFml8w3+XW
// EjuOslWrda8KiPCRZEQIbNfiZrcTzAefNRzJhKJL6EkuCU+3oZo8DL6Xc+0Obkk6
// 46kYV5oDYbPBDmNIQBCr6odNHnWnBBnSs3TbLQIVANkiO001oz4lzhsO/tDx9rpO
// yH/5AoIBAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJvaHyHi/v
// /eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8ShNPJIByK
// m7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3DtX220CIrE
// BaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+tl4gFR0r
// 4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7xQbYtqHBR
// +oBgRFbPPouNMIUexC4DKxyNeuN2zIcCggEAXh/Akb90+cojwtyjzXTxA9h4CzfT
// E1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwoq2SPW1u9
// qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo3IoKzpEK
// B1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5SaIWYaCiTZ
// WNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuyH/wk2oXd
// lNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqizgIVAKI4
// pSbllzsgU0NB+IQTQU7C/TKv
// -----END DSA PRIVATE KEY-----
//
// Encrypted OpenSSH RSA Key
//
// -----BEGIN RSA PRIVATE KEY-----
// Proc-Type: 4,ENCRYPTED
// DEK-Info: DES-EDE3-CBC,DC983431B352E226
//
// HtBgp1FMd8abEzUiZPbrgImaCh8f5p+IzikphBnWwAfl7ANqhsFaATs+4BoFnals
// sdYlyYnan5I1steUqvI+J/k8j+j+6YOl93uF2nF0oBUp8RBlMprYXEALAAsuaXma
// RAmJKQF1vmg43d4DdZTlsmogK8nzdY1E36qzSTcq/PBP+rYXDNIRIaKn35sESAIy
// shaTOs2n8TfoxiVq0oAC5H3QkPlK3ujd77oIk7JQKEZFvE1kaPaY3a6cgGpVjP7s
// 8eWtFQrTvLT1iqGPOiK2018Nua2rsXfxR6JBMgmkPvfgTtc31EIdfurFK1AOZfac
// 5YXokIEVeXxChIkMFXsbgeZBK87Fa3HnSq5q8VCvuku7NPbqdSI0spGoyRrOuaO8
// 0HXjizWg9QbH+kK5lD1ks/yR3Hj7dxoXsV0Bo8iK0NB/pGfCxwtIJYt8iC1w07Pl
// Io59mH/e+BiHbXI8bp8mozsSvvxMQlEF/iuwaqZozhWhdsn+Q2jd4fh4qEOV49pA
// L6utYnb64/JOqZZZe1HfKfpbNQ8ZaOjciP0+Oe+ktCtySddIYYsac/LbKHdNil78
// EsRIzms/OpYYEt3GQBbaphZa7X2M97+qbPPO6+hosVXwUEo2Tw80gS5LMFF+8W21
// RoK4+VqarMTqB+pHJGWpe7v5MbmKl8HG/dpBM/ufRFdLt2uGYo/dgcE9Y2trWrOP
// DQEB9BpbQ/Od/wnhM9SsUOp3mJHgwW3waGgPoIaQdquB6ipkWen0h42XHT1EqiSZ
// 1S5pXjZvEyXPvYP3mjXBoD0YxNftKCrFHzlWz4EtI74LSgilTLmVD2TauutDdjFc
// zjfTtrwxnS/ZFbijZBSthhG3aVhZAmIguWhZUFJcttAZY4S/AJ46HN7qI/WmGSiQ
// 3SJN7OCZEhJ8xidXT4giMY/xaNWaRPDpUF+aKE1vlCwtVJxV8VlqGkSyvk7/0pcg
// CmPCH9+p4IXmGq16UNrJh6Mp+GwtTbp62mFeyzh6zo1BKPQGzvohHxLs9/qW5I9L
// sbx34VavTbityYDj/r+UqiAJ1srn9kadpDf/Ai5emjWb/f+U5KIrrPvI+iOv/N/p
// g3vOsDYa8x3v7bDjXpQtXxH2T2qbxqFUfI8Ckk18eE0I845TwLsAaoieFmZrYMrV
// nsrgkALuEobUFg+3GFTTPipXhSGn5pRJb249t3pUxcrYYmq5quIBRlK2f2UsxBnX
// 95Mv2H2Ab7ZEiN++CABoCmz3Mim8elWQxQFmW4jgseeOUCINNPxQc+sPL99HAj6s
// C5sSkZMDKTjWYMc3UKN9XOQ1G0RbkA59jg0VwP/DDViCju/UsIllmnPTd5OpjLHf
// AW5xq7i68AQXSXlVfy21T23GiiXKfN1b0wXRL1qvQCBYVXP9UP5zxbKLQM29aIGP
// Sf6ccO/y+pvaxw3ujBhyDdKKMbWcKhWfteEiR2h7Nsf6aSsWha5TDr8T9GavxsyH
// cK88J2Rp3B9Cr4I5le3rbJmi6R1gZkK89kK8UllAnaqjJJXV4EBcVs2eKxMuEsjq
// nxCy9shNjgEOr/6VgPRrimvdhDDt4ZJynhskGoOiWFEK4Ud/1sC+NTrpwtRqjXj9
// -----END RSA PRIVATE KEY-----
//
// Unencrypted OpenSSH RSA Key
//
// -----BEGIN RSA PRIVATE KEY-----
// MIIEpQIBAAKCAQEAvTjHMg1+nAogY3o8V8zXKwf+VuTMtIZggCiUQ9NU884PeHnb
// tezsx5KRuAtNqhWtgEsNg0/aHv6o/7E4HJE9PCqVpUXnTV1mZE14BvmusCnuz1HL
// nV3CtSW3BOh98sHixwu0I4y2RZy0sfaTBn1zDXvCv2mrVL5D1QnOZ8B/Vi5fceQd
// eaLe6Uzj6vTi5MBWjzvVog/xDr0tEo4FPRmu6SUkmTzhwEiETScm5qOm9VnTr2O9
// sCibFPmqrODGAzpj/OWIH2RMMT1B9Nl6P6JvHWZc92rqrUVZHBkSoakNWkytLN5j
// WyxwIdCFxQvCnAKic7uOodMSiqDUPJHHlPIghwIDAQABAoIBAAK9V4JPz9beH3dk
// cqzyfW33VTH6nFX/cr0ISE7c9F+45D4vCTfsfYHvix/mCXbTsJapIagWc9FqZdF2
// +Xd4ayB7riguwz+x1o9YR4cRywwoLBFP9tzvjMnvkaepAQHTG+HHFUTNskfDVngC
// wOtlvGHXZPIbU+QLvoGtMFZSOHBrs1cOfoUO1BToN1cGfgp/DuJY6WWVoNs93C8J
// wgnH2DdosRcMDYOQsASH60hEE2JJuF7Ox+BwlcsV5AUDwIeAChQI0Aend7NL9cee
// U8o3UXAVjABowGI9EQJYUmysir5mFs/BETlPambyvEWWNCtJsT2qrCi2Xme5BRzD
// p5MMJ+ECgYEAzfbbQagHiP48yGiZS2j7i1UcV/0pgeamtjaxJf1njyMrkyxMFOFW
// PfLOVLcRnx4HcqYYv9Opo8mbYlxjUUFxhMBYdyNICx8OjM7eijSjGisvAh0S20Vo
// LvhQ0zzv1/QUdnj4jO4FWNgHYUF+mre8nX8k/s8AcudBR7n5w+MhP7cCgYEA6zCw
// DGB8ipBQMryEWVNc0eYFFXojxlFRKjp4BRc43F0s0gyRLWGCUHTN0Z1DPKQRilo6
// D8nGANN8BYVFDEcuFk8SCks5Xk76YfL+9uAETKv7y//AE8dyrCRk8/7kyOdMhHtq
// 1bHsAutfxeiYrdRWyK0ZApAKdSEy+BvdVRv9hbECgYEAzcNdvlUg2gKsNMcSxpym
// GMe5nknj6svEJ2uyRLLJf91yDgEGLSIFp7Pn4AhYiW9Vn3tCZHoQEvo5yuVjr2zC
// /Q2wE63iroGjZpbRCp+VhnI371OeYAMSF0KqdK5/Km7E9qraHOk53E1N6iKlWepP
// e8Tm781btG9F72NjnAhQUjcCgYEA1XB2FIVsAQQ/BAx5v+cbkZHCg185ID2j/0LY
// sSYGAFa+2lF1X03iycl3EAg8gMgU8w43KyTegNls8EWmCCKA/NX9dUIXajMan9G6
// +akLvdlGxjfvxQN4WikdRSHJ11mx43lt10mE+pFJdX5FMVxG9g/BZsX595qNewUu
// tJKWXcECgYEAqHYYHyZI9dah6JVpm5UQ6kJbDPZad7uus/lmJfTgY+ZCH1sEVySL
// UYk4TyswyUqzLfazhhQ9yZsDBmdm6jRJLYtQBo9fybpOzeyK20aFIGQTSaVFbAGG
// YIsv2DOWk9HHr0TSG7yu/1hiMf3ol0ofpTEQpXyM8qjVuqCeqsMeJ9I=
// -----END RSA PRIVATE KEY-----
bool ToOpenSshPrivateKey(bool bEncrypt, CkString &outStr);
// Exports the private key to a string in OpenSSH format. If bEncrypt is true, the
// key is encrypted using the value of the Password property. Below are samples of
// RSA and DSA private keys in OpenSSH format, both encrypted and unencrypted:
//
// Encrypted OpenSSH DSA Key
//
// -----BEGIN DSA PRIVATE KEY-----
// Proc-Type: 4,ENCRYPTED
// DEK-Info: DES-EDE3-CBC,934E999D91EFE8F8
//
// j1sslF86hdpzaBdVeLZ9akXux+CEaa6HyZgou3BkRkWpMn7gFqX3lfRIjrlhY41w
// +snC2HNYF5ae+WymP6fQ7TOhOsQD3KFBNbohn4dJE4fB0El6OKCbR2MGJlUkwMY4
// q3VCu3yAeiMmLwocoHxbfXYXgjqPBqbLXPSsHzpirGyC8FD8+P0QWW/W4rJGGWru
// 866fkIPH+PCJXml4Io/YPUQYYFhRd4XTJvXqU0tLOpFfsLhetGziKNZuLGzpiVCt
// v8Vt0VXKSD6M27gE788mEhJjtqVVpymRDReZhrt1MlGVofhuC34kA4L7+BLHARHq
// bvM0SRSvqwNYxLNDWtV33RlOEvy/Kg7rRLnmSgZ7pPgUB4lbpC23Adp4djpdO5S2
// LERDEV+cTmKGCpLOCGOEGlPOiEnROP8xjmqpGHNMaLh6Jd/zGdgdAN7/6Wk/TeaP
// p/Ma4UQUnZEjkIpfxYtsMJ0Pb5JBZf41vJMVqFlDKeOngFIlWzv9G34Ip2GbZVUJ
// 0CfbD3VrZb8t6ethcSQ7NKkMpB0s4Qu+nSIHZngb6Z/uzTVX/ElbxVu7/kca627n
// LtXBcDZtkYey7ANePw0Q2Ju3rOcWJQK691K3M/qZkPO5TKtybmdMHV6EuVPGlPXV
// d2fUUBCZpTs8udN9bE8lZIGC//RX4hPfCV1eL0cZehByJeJG6EK1UvrCPnsfymFi
// bWJvjM4SWxFaMUNQRPuNywE1c9K0BqR/NQa6scADReXU66pho/ttb1Furnmm68rB
// SQq+CA5DjBOMYIbD6s0zMLKICwrk4DYTZlhRGb/fP9BAWZN+scz3ot4RUaURasXj
// Fb9b0arwqL5b84pDoA+gdxnDcB60RjegLTPqC/EuVepHTRRZN3w5eZvW5ZjHwmzw
// TYPYoraj7NBRaTx81ZVkKViDZnqSY2xjUnuiUbWrgKWC+asZzQDGGebLFQmFr0V3
// rkI7MR7JHrl5VrIKro9ewVFhqugdMASzC3e0GjKQowec5ELjVAGLz+zvHrAcrxkh
// m8Q2lHl1efS/rnCyk9DDKqHBkcIYkyxmtQMtbg4MruEIBQhTx4bUzQdq5VLYYlqY
// YrrEcZveySg0ILT9x0swM22ji3w0S7Xv
// -----END DSA PRIVATE KEY-----
//
// Unencrypted OpenSSH DSA Key
//
// -----BEGIN DSA PRIVATE KEY-----
// MIIDPgIBAAKCAQEAqj/5FQjdsvxasIvxdEKbIe0SuHfJxlLSdCqvKsknpn26UBSd
// W5wXqiUSmLrU7mLIRAVxdQ7umcp3N8w/dIiVkiJvm+tUQqlPYrd6n2JK+eQ0lGtP
// emsn6fQzHhUmG0jCFgot3nNodspb5euUxVrU0BCq2PpKRuGKt6cyq5oEAvlg1K6p
// vpze8tZ+etZGToN2uBQ/3ysGjgiDs3Zgh/k3o+8UteuBdjd8awEHcIzFml8w3+XW
// EjuOslWrda8KiPCRZEQIbNfiZrcTzAefNRzJhKJL6EkuCU+3oZo8DL6Xc+0Obkk6
// 46kYV5oDYbPBDmNIQBCr6odNHnWnBBnSs3TbLQIVANkiO001oz4lzhsO/tDx9rpO
// yH/5AoIBAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJvaHyHi/v
// /eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8ShNPJIByK
// m7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3DtX220CIrE
// BaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+tl4gFR0r
// 4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7xQbYtqHBR
// +oBgRFbPPouNMIUexC4DKxyNeuN2zIcCggEAXh/Akb90+cojwtyjzXTxA9h4CzfT
// E1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwoq2SPW1u9
// qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo3IoKzpEK
// B1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5SaIWYaCiTZ
// WNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuyH/wk2oXd
// lNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqizgIVAKI4
// pSbllzsgU0NB+IQTQU7C/TKv
// -----END DSA PRIVATE KEY-----
//
// Encrypted OpenSSH RSA Key
//
// -----BEGIN RSA PRIVATE KEY-----
// Proc-Type: 4,ENCRYPTED
// DEK-Info: DES-EDE3-CBC,DC983431B352E226
//
// HtBgp1FMd8abEzUiZPbrgImaCh8f5p+IzikphBnWwAfl7ANqhsFaATs+4BoFnals
// sdYlyYnan5I1steUqvI+J/k8j+j+6YOl93uF2nF0oBUp8RBlMprYXEALAAsuaXma
// RAmJKQF1vmg43d4DdZTlsmogK8nzdY1E36qzSTcq/PBP+rYXDNIRIaKn35sESAIy
// shaTOs2n8TfoxiVq0oAC5H3QkPlK3ujd77oIk7JQKEZFvE1kaPaY3a6cgGpVjP7s
// 8eWtFQrTvLT1iqGPOiK2018Nua2rsXfxR6JBMgmkPvfgTtc31EIdfurFK1AOZfac
// 5YXokIEVeXxChIkMFXsbgeZBK87Fa3HnSq5q8VCvuku7NPbqdSI0spGoyRrOuaO8
// 0HXjizWg9QbH+kK5lD1ks/yR3Hj7dxoXsV0Bo8iK0NB/pGfCxwtIJYt8iC1w07Pl
// Io59mH/e+BiHbXI8bp8mozsSvvxMQlEF/iuwaqZozhWhdsn+Q2jd4fh4qEOV49pA
// L6utYnb64/JOqZZZe1HfKfpbNQ8ZaOjciP0+Oe+ktCtySddIYYsac/LbKHdNil78
// EsRIzms/OpYYEt3GQBbaphZa7X2M97+qbPPO6+hosVXwUEo2Tw80gS5LMFF+8W21
// RoK4+VqarMTqB+pHJGWpe7v5MbmKl8HG/dpBM/ufRFdLt2uGYo/dgcE9Y2trWrOP
// DQEB9BpbQ/Od/wnhM9SsUOp3mJHgwW3waGgPoIaQdquB6ipkWen0h42XHT1EqiSZ
// 1S5pXjZvEyXPvYP3mjXBoD0YxNftKCrFHzlWz4EtI74LSgilTLmVD2TauutDdjFc
// zjfTtrwxnS/ZFbijZBSthhG3aVhZAmIguWhZUFJcttAZY4S/AJ46HN7qI/WmGSiQ
// 3SJN7OCZEhJ8xidXT4giMY/xaNWaRPDpUF+aKE1vlCwtVJxV8VlqGkSyvk7/0pcg
// CmPCH9+p4IXmGq16UNrJh6Mp+GwtTbp62mFeyzh6zo1BKPQGzvohHxLs9/qW5I9L
// sbx34VavTbityYDj/r+UqiAJ1srn9kadpDf/Ai5emjWb/f+U5KIrrPvI+iOv/N/p
// g3vOsDYa8x3v7bDjXpQtXxH2T2qbxqFUfI8Ckk18eE0I845TwLsAaoieFmZrYMrV
// nsrgkALuEobUFg+3GFTTPipXhSGn5pRJb249t3pUxcrYYmq5quIBRlK2f2UsxBnX
// 95Mv2H2Ab7ZEiN++CABoCmz3Mim8elWQxQFmW4jgseeOUCINNPxQc+sPL99HAj6s
// C5sSkZMDKTjWYMc3UKN9XOQ1G0RbkA59jg0VwP/DDViCju/UsIllmnPTd5OpjLHf
// AW5xq7i68AQXSXlVfy21T23GiiXKfN1b0wXRL1qvQCBYVXP9UP5zxbKLQM29aIGP
// Sf6ccO/y+pvaxw3ujBhyDdKKMbWcKhWfteEiR2h7Nsf6aSsWha5TDr8T9GavxsyH
// cK88J2Rp3B9Cr4I5le3rbJmi6R1gZkK89kK8UllAnaqjJJXV4EBcVs2eKxMuEsjq
// nxCy9shNjgEOr/6VgPRrimvdhDDt4ZJynhskGoOiWFEK4Ud/1sC+NTrpwtRqjXj9
// -----END RSA PRIVATE KEY-----
//
// Unencrypted OpenSSH RSA Key
//
// -----BEGIN RSA PRIVATE KEY-----
// MIIEpQIBAAKCAQEAvTjHMg1+nAogY3o8V8zXKwf+VuTMtIZggCiUQ9NU884PeHnb
// tezsx5KRuAtNqhWtgEsNg0/aHv6o/7E4HJE9PCqVpUXnTV1mZE14BvmusCnuz1HL
// nV3CtSW3BOh98sHixwu0I4y2RZy0sfaTBn1zDXvCv2mrVL5D1QnOZ8B/Vi5fceQd
// eaLe6Uzj6vTi5MBWjzvVog/xDr0tEo4FPRmu6SUkmTzhwEiETScm5qOm9VnTr2O9
// sCibFPmqrODGAzpj/OWIH2RMMT1B9Nl6P6JvHWZc92rqrUVZHBkSoakNWkytLN5j
// WyxwIdCFxQvCnAKic7uOodMSiqDUPJHHlPIghwIDAQABAoIBAAK9V4JPz9beH3dk
// cqzyfW33VTH6nFX/cr0ISE7c9F+45D4vCTfsfYHvix/mCXbTsJapIagWc9FqZdF2
// +Xd4ayB7riguwz+x1o9YR4cRywwoLBFP9tzvjMnvkaepAQHTG+HHFUTNskfDVngC
// wOtlvGHXZPIbU+QLvoGtMFZSOHBrs1cOfoUO1BToN1cGfgp/DuJY6WWVoNs93C8J
// wgnH2DdosRcMDYOQsASH60hEE2JJuF7Ox+BwlcsV5AUDwIeAChQI0Aend7NL9cee
// U8o3UXAVjABowGI9EQJYUmysir5mFs/BETlPambyvEWWNCtJsT2qrCi2Xme5BRzD
// p5MMJ+ECgYEAzfbbQagHiP48yGiZS2j7i1UcV/0pgeamtjaxJf1njyMrkyxMFOFW
// PfLOVLcRnx4HcqYYv9Opo8mbYlxjUUFxhMBYdyNICx8OjM7eijSjGisvAh0S20Vo
// LvhQ0zzv1/QUdnj4jO4FWNgHYUF+mre8nX8k/s8AcudBR7n5w+MhP7cCgYEA6zCw
// DGB8ipBQMryEWVNc0eYFFXojxlFRKjp4BRc43F0s0gyRLWGCUHTN0Z1DPKQRilo6
// D8nGANN8BYVFDEcuFk8SCks5Xk76YfL+9uAETKv7y//AE8dyrCRk8/7kyOdMhHtq
// 1bHsAutfxeiYrdRWyK0ZApAKdSEy+BvdVRv9hbECgYEAzcNdvlUg2gKsNMcSxpym
// GMe5nknj6svEJ2uyRLLJf91yDgEGLSIFp7Pn4AhYiW9Vn3tCZHoQEvo5yuVjr2zC
// /Q2wE63iroGjZpbRCp+VhnI371OeYAMSF0KqdK5/Km7E9qraHOk53E1N6iKlWepP
// e8Tm781btG9F72NjnAhQUjcCgYEA1XB2FIVsAQQ/BAx5v+cbkZHCg185ID2j/0LY
// sSYGAFa+2lF1X03iycl3EAg8gMgU8w43KyTegNls8EWmCCKA/NX9dUIXajMan9G6
// +akLvdlGxjfvxQN4WikdRSHJ11mx43lt10mE+pFJdX5FMVxG9g/BZsX595qNewUu
// tJKWXcECgYEAqHYYHyZI9dah6JVpm5UQ6kJbDPZad7uus/lmJfTgY+ZCH1sEVySL
// UYk4TyswyUqzLfazhhQ9yZsDBmdm6jRJLYtQBo9fybpOzeyK20aFIGQTSaVFbAGG
// YIsv2DOWk9HHr0TSG7yu/1hiMf3ol0ofpTEQpXyM8qjVuqCeqsMeJ9I=
// -----END RSA PRIVATE KEY-----
const char *toOpenSshPrivateKey(bool bEncrypt);
// Exports the public key to a string in OpenSSH format. Sample OpenSSH-formatted
// DSA and RSA public keys are below:
//
// OpenSSH RSA Public Key (Line-breaks are added for readability. An
// OpenSSH-formatted public key would typically be a single line, not multiple
// lines.)
//
// ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCAKJRD01Tzzg94edu17O
// zHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZkTXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjL
// ZFnLSx9pMGfXMNe8K/aatUvkPVCc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZP
// OHASIRNJybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkcGRKhqQ1aTK0
// s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
//
// OpenSSH DSA Public Key (Line-breaks are added for readability.)
//
// ssh-dss AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9ulAUnVucF6olEpi61O5iyEQF
// cXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnkNJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6Skb
// hirenMquaBAL5YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpfMN/l1hI7jrJVq3
// WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3PtDm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQ
// Z0rN02y0AAAAVANkiO001oz4lzhsO/tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWB
// KpaJvaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8ShNPJIByKm7XVGvLFhDqhiN
// KIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3DtX220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0
// zmKsQ2gjdjRphm+tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7xQbYtqHBR+oBgR
// FbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTxA9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWR
// WtTDidZWRxWXxP+8J7PrMwA4Pwoq2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7E
// Qljo3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5SaIWYaCiTZWNTS4vLeNBuJB
// VJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuyH/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nB
// IZDEUQYvVA71Fawp4cqizg==
bool ToOpenSshPublicKey(CkString &outStr);
// Exports the public key to a string in OpenSSH format. Sample OpenSSH-formatted
// DSA and RSA public keys are below:
//
// OpenSSH RSA Public Key (Line-breaks are added for readability. An
// OpenSSH-formatted public key would typically be a single line, not multiple
// lines.)
//
// ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCAKJRD01Tzzg94edu17O
// zHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZkTXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjL
// ZFnLSx9pMGfXMNe8K/aatUvkPVCc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZP
// OHASIRNJybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkcGRKhqQ1aTK0
// s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
//
// OpenSSH DSA Public Key (Line-breaks are added for readability.)
//
// ssh-dss AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9ulAUnVucF6olEpi61O5iyEQF
// cXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnkNJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6Skb
// hirenMquaBAL5YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpfMN/l1hI7jrJVq3
// WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3PtDm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQ
// Z0rN02y0AAAAVANkiO001oz4lzhsO/tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWB
// KpaJvaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8ShNPJIByKm7XVGvLFhDqhiN
// KIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3DtX220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0
// zmKsQ2gjdjRphm+tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7xQbYtqHBR+oBgR
// FbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTxA9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWR
// WtTDidZWRxWXxP+8J7PrMwA4Pwoq2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7E
// Qljo3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5SaIWYaCiTZWNTS4vLeNBuJB
// VJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuyH/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nB
// IZDEUQYvVA71Fawp4cqizg==
const char *toOpenSshPublicKey(void);
// Exports the private key to PuTTY format. If bEncrypt is true, the key is encrypted
// using the value of the Password property. Below are samples of RSA and DSA
// private keys in PuTTY format, both encrypted and unencrypted:
//
// Encrypted PuTTY DSA Key
//
// PuTTY-User-Key-File-2: ssh-dss
// Encryption: aes256-cbc
// Comment: dss-key-20080914
// Public-Lines: 18
// AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9
// ulAUnVucF6olEpi61O5iyEQFcXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnk
// NJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6SkbhirenMquaBAL5
// YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpf
// MN/l1hI7jrJVq3WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3Pt
// Dm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQZ0rN02y0AAAAVANkiO001oz4lzhsO
// /tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJ
// vaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8S
// hNPJIByKm7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3Dt
// X220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+
// tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7x
// QbYtqHBR+oBgRFbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTx
// A9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwo
// q2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo
// 3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5Sa
// IWYaCiTZWNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuy
// H/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqi
// zg==
// Private-Lines: 1
// L2iyk4xEmQi4IK8ZCm35/UDan0VVUdd9whyljTo6SoA=
// Private-MAC: 5633A6762B5D9016A5B1D7753713C4A13CD734EC
//
// Unencrypted PuTTY DSA Key
//
// PuTTY-User-Key-File-2: ssh-dss
// Encryption: none
// Comment: dss-key-20080914
// Public-Lines: 18
// AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9
// ulAUnVucF6olEpi61O5iyEQFcXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnk
// NJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6SkbhirenMquaBAL5
// YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpf
// MN/l1hI7jrJVq3WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3Pt
// Dm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQZ0rN02y0AAAAVANkiO001oz4lzhsO
// /tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJ
// vaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8S
// hNPJIByKm7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3Dt
// X220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+
// tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7x
// QbYtqHBR+oBgRFbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTx
// A9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwo
// q2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo
// 3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5Sa
// IWYaCiTZWNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuy
// H/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqi
// zg==
// Private-Lines: 1
// AAAAFQCiOKUm5Zc7IFNDQfiEE0FOwv0yrw==
// Private-MAC: 7A13473EBD5C8E1ADD57D8AE5A5EF3F1789DDD8B
//
// Encrypted PuTTY RSA Key
//
// PuTTY-User-Key-File-2: ssh-rsa
// Encryption: aes256-cbc
// Comment: rsa-key-20080914
// Public-Lines: 6
// AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCA
// KJRD01Tzzg94edu17OzHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZk
// TXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjLZFnLSx9pMGfXMNe8K/aatUvkPV
// Cc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZPOHASIRN
// Jybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkc
// GRKhqQ1aTK0s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
// Private-Lines: 14
// SC03/1Szexogtlxrde1JbuWD0z9cNRLGlroT9Vf7uAJLRLF4bM7ovlcKPVrtsymG
// lJitt6bhK9bmFIGj3Ko+RImpwFNHlL56UYtnJqx2ihSTbU8JJ34VyLy7ADjUlg3S
// wL4YY2Uxwo24p0oLTyl3UYBVZ9z+e9fqTiZJI+jl1mFSJz2FbuA2iuiGZQcOKKHx
// cLye5GgoXgSrMjNcm6evVmHrAi+RjakhBjzFm/aCKmiJr9bf12WI+Sp06oOvnShP
// WcrrqVsr1+4Ju85z2wFevHYfFLjqW13AAMMdJnr/4x0g/AjTjxiuADlXBC5d+V1p
// 7Kwi9ZDd2NMeSeTeM9ZIsKpuR2ndURYsgbTe/Hhl1nU2VwzZJuNU58ROZzjb3HOv
// kjk+2GZhAqVQSfhm8ma9SBW9YIfIRawKSQZh1v9Sa7jh68WjeCzndvyzUCbl0tiW
// irSTLScKcyfxRkZ952CMgGsqKX6kDdb2Yz4YLxSdltD9qs/aPyweln+uf7m+5hIV
// SpFXw7gjZjMq+US5fstdhTAZjkzkKyV4ejlfekneIDmq5oXR5kf+3y4oqkP4nWS8
// xP6aURBK7GdKxREmnj2E5He7nQNf5d5fGLMGtvULbY18k6aMVqRLbCt1rwF7lVsz
// dRrp8fX94pdu0ZFLb8QwKnDI7hXzrK0lYnpfIECwPlA9SdhChVRXsvUFi5scTdB0
// /2lV+IVcz0e1GtbsvV5EaFCcXy9k5Rq8zjhfbbTWtur7dJbwKPPQyByioNeGwzvT
// LN0X5hn0AaDjbSH6KNPFY0YPxx4rfqsVqI8jH4CJJhoByEtb5cBJFpLhl9o6t27d
// 3oafNIL7UjVL0j5df+4JPjSbwm+44ccrp2FBRnIJw5MKtKz58lBarpwKHRecw6Yk
// Private-MAC: 743AFA7F93ABE10BF61C21B9BDEFDCBF52F04980
//
// Unencrypted PuTTY RSA Key
//
// PuTTY-User-Key-File-2: ssh-rsa
// Encryption: none
// Comment: rsa-key-20080914
// Public-Lines: 6
// AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCA
// KJRD01Tzzg94edu17OzHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZk
// TXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjLZFnLSx9pMGfXMNe8K/aatUvkPV
// Cc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZPOHASIRN
// Jybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkc
// GRKhqQ1aTK0s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
// Private-Lines: 14
// AAABAAK9V4JPz9beH3dkcqzyfW33VTH6nFX/cr0ISE7c9F+45D4vCTfsfYHvix/m
// CXbTsJapIagWc9FqZdF2+Xd4ayB7riguwz+x1o9YR4cRywwoLBFP9tzvjMnvkaep
// AQHTG+HHFUTNskfDVngCwOtlvGHXZPIbU+QLvoGtMFZSOHBrs1cOfoUO1BToN1cG
// fgp/DuJY6WWVoNs93C8JwgnH2DdosRcMDYOQsASH60hEE2JJuF7Ox+BwlcsV5AUD
// wIeAChQI0Aend7NL9ceeU8o3UXAVjABowGI9EQJYUmysir5mFs/BETlPambyvEWW
// NCtJsT2qrCi2Xme5BRzDp5MMJ+EAAACBAM3220GoB4j+PMhomUto+4tVHFf9KYHm
// prY2sSX9Z48jK5MsTBThVj3yzlS3EZ8eB3KmGL/TqaPJm2JcY1FBcYTAWHcjSAsf
// DozO3oo0oxorLwIdEttFaC74UNM879f0FHZ4+IzuBVjYB2FBfpq3vJ1/JP7PAHLn
// QUe5+cPjIT+3AAAAgQDrMLAMYHyKkFAyvIRZU1zR5gUVeiPGUVEqOngFFzjcXSzS
// DJEtYYJQdM3RnUM8pBGKWjoPycYA03wFhUUMRy4WTxIKSzleTvph8v724ARMq/vL
// /8ATx3KsJGTz/uTI50yEe2rVsewC61/F6Jit1FbIrRkCkAp1ITL4G91VG/2FsQAA
// AIEAqHYYHyZI9dah6JVpm5UQ6kJbDPZad7uus/lmJfTgY+ZCH1sEVySLUYk4Tysw
// yUqzLfazhhQ9yZsDBmdm6jRJLYtQBo9fybpOzeyK20aFIGQTSaVFbAGGYIsv2DOW
// k9HHr0TSG7yu/1hiMf3ol0ofpTEQpXyM8qjVuqCeqsMeJ9I=
// Private-MAC: 3BE4CAA1B2AE19C3E6841639BD7275019CF961F1
bool ToPuttyPrivateKey(bool bEncrypt, CkString &outStr);
// Exports the private key to PuTTY format. If bEncrypt is true, the key is encrypted
// using the value of the Password property. Below are samples of RSA and DSA
// private keys in PuTTY format, both encrypted and unencrypted:
//
// Encrypted PuTTY DSA Key
//
// PuTTY-User-Key-File-2: ssh-dss
// Encryption: aes256-cbc
// Comment: dss-key-20080914
// Public-Lines: 18
// AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9
// ulAUnVucF6olEpi61O5iyEQFcXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnk
// NJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6SkbhirenMquaBAL5
// YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpf
// MN/l1hI7jrJVq3WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3Pt
// Dm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQZ0rN02y0AAAAVANkiO001oz4lzhsO
// /tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJ
// vaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8S
// hNPJIByKm7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3Dt
// X220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+
// tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7x
// QbYtqHBR+oBgRFbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTx
// A9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwo
// q2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo
// 3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5Sa
// IWYaCiTZWNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuy
// H/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqi
// zg==
// Private-Lines: 1
// L2iyk4xEmQi4IK8ZCm35/UDan0VVUdd9whyljTo6SoA=
// Private-MAC: 5633A6762B5D9016A5B1D7753713C4A13CD734EC
//
// Unencrypted PuTTY DSA Key
//
// PuTTY-User-Key-File-2: ssh-dss
// Encryption: none
// Comment: dss-key-20080914
// Public-Lines: 18
// AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9
// ulAUnVucF6olEpi61O5iyEQFcXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnk
// NJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6SkbhirenMquaBAL5
// YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpf
// MN/l1hI7jrJVq3WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3Pt
// Dm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQZ0rN02y0AAAAVANkiO001oz4lzhsO
// /tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJ
// vaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8S
// hNPJIByKm7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3Dt
// X220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+
// tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7x
// QbYtqHBR+oBgRFbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTx
// A9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwo
// q2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo
// 3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5Sa
// IWYaCiTZWNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuy
// H/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqi
// zg==
// Private-Lines: 1
// AAAAFQCiOKUm5Zc7IFNDQfiEE0FOwv0yrw==
// Private-MAC: 7A13473EBD5C8E1ADD57D8AE5A5EF3F1789DDD8B
//
// Encrypted PuTTY RSA Key
//
// PuTTY-User-Key-File-2: ssh-rsa
// Encryption: aes256-cbc
// Comment: rsa-key-20080914
// Public-Lines: 6
// AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCA
// KJRD01Tzzg94edu17OzHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZk
// TXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjLZFnLSx9pMGfXMNe8K/aatUvkPV
// Cc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZPOHASIRN
// Jybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkc
// GRKhqQ1aTK0s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
// Private-Lines: 14
// SC03/1Szexogtlxrde1JbuWD0z9cNRLGlroT9Vf7uAJLRLF4bM7ovlcKPVrtsymG
// lJitt6bhK9bmFIGj3Ko+RImpwFNHlL56UYtnJqx2ihSTbU8JJ34VyLy7ADjUlg3S
// wL4YY2Uxwo24p0oLTyl3UYBVZ9z+e9fqTiZJI+jl1mFSJz2FbuA2iuiGZQcOKKHx
// cLye5GgoXgSrMjNcm6evVmHrAi+RjakhBjzFm/aCKmiJr9bf12WI+Sp06oOvnShP
// WcrrqVsr1+4Ju85z2wFevHYfFLjqW13AAMMdJnr/4x0g/AjTjxiuADlXBC5d+V1p
// 7Kwi9ZDd2NMeSeTeM9ZIsKpuR2ndURYsgbTe/Hhl1nU2VwzZJuNU58ROZzjb3HOv
// kjk+2GZhAqVQSfhm8ma9SBW9YIfIRawKSQZh1v9Sa7jh68WjeCzndvyzUCbl0tiW
// irSTLScKcyfxRkZ952CMgGsqKX6kDdb2Yz4YLxSdltD9qs/aPyweln+uf7m+5hIV
// SpFXw7gjZjMq+US5fstdhTAZjkzkKyV4ejlfekneIDmq5oXR5kf+3y4oqkP4nWS8
// xP6aURBK7GdKxREmnj2E5He7nQNf5d5fGLMGtvULbY18k6aMVqRLbCt1rwF7lVsz
// dRrp8fX94pdu0ZFLb8QwKnDI7hXzrK0lYnpfIECwPlA9SdhChVRXsvUFi5scTdB0
// /2lV+IVcz0e1GtbsvV5EaFCcXy9k5Rq8zjhfbbTWtur7dJbwKPPQyByioNeGwzvT
// LN0X5hn0AaDjbSH6KNPFY0YPxx4rfqsVqI8jH4CJJhoByEtb5cBJFpLhl9o6t27d
// 3oafNIL7UjVL0j5df+4JPjSbwm+44ccrp2FBRnIJw5MKtKz58lBarpwKHRecw6Yk
// Private-MAC: 743AFA7F93ABE10BF61C21B9BDEFDCBF52F04980
//
// Unencrypted PuTTY RSA Key
//
// PuTTY-User-Key-File-2: ssh-rsa
// Encryption: none
// Comment: rsa-key-20080914
// Public-Lines: 6
// AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCA
// KJRD01Tzzg94edu17OzHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZk
// TXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjLZFnLSx9pMGfXMNe8K/aatUvkPV
// Cc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZPOHASIRN
// Jybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkc
// GRKhqQ1aTK0s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
// Private-Lines: 14
// AAABAAK9V4JPz9beH3dkcqzyfW33VTH6nFX/cr0ISE7c9F+45D4vCTfsfYHvix/m
// CXbTsJapIagWc9FqZdF2+Xd4ayB7riguwz+x1o9YR4cRywwoLBFP9tzvjMnvkaep
// AQHTG+HHFUTNskfDVngCwOtlvGHXZPIbU+QLvoGtMFZSOHBrs1cOfoUO1BToN1cG
// fgp/DuJY6WWVoNs93C8JwgnH2DdosRcMDYOQsASH60hEE2JJuF7Ox+BwlcsV5AUD
// wIeAChQI0Aend7NL9ceeU8o3UXAVjABowGI9EQJYUmysir5mFs/BETlPambyvEWW
// NCtJsT2qrCi2Xme5BRzDp5MMJ+EAAACBAM3220GoB4j+PMhomUto+4tVHFf9KYHm
// prY2sSX9Z48jK5MsTBThVj3yzlS3EZ8eB3KmGL/TqaPJm2JcY1FBcYTAWHcjSAsf
// DozO3oo0oxorLwIdEttFaC74UNM879f0FHZ4+IzuBVjYB2FBfpq3vJ1/JP7PAHLn
// QUe5+cPjIT+3AAAAgQDrMLAMYHyKkFAyvIRZU1zR5gUVeiPGUVEqOngFFzjcXSzS
// DJEtYYJQdM3RnUM8pBGKWjoPycYA03wFhUUMRy4WTxIKSzleTvph8v724ARMq/vL
// /8ATx3KsJGTz/uTI50yEe2rVsewC61/F6Jit1FbIrRkCkAp1ITL4G91VG/2FsQAA
// AIEAqHYYHyZI9dah6JVpm5UQ6kJbDPZad7uus/lmJfTgY+ZCH1sEVySLUYk4Tysw
// yUqzLfazhhQ9yZsDBmdm6jRJLYtQBo9fybpOzeyK20aFIGQTSaVFbAGGYIsv2DOW
// k9HHr0TSG7yu/1hiMf3ol0ofpTEQpXyM8qjVuqCeqsMeJ9I=
// Private-MAC: 3BE4CAA1B2AE19C3E6841639BD7275019CF961F1
const char *toPuttyPrivateKey(bool bEncrypt);
// Exports the public key to a string in RFC 4716 format. Sample RFC 4716 DSA and
// RSA public keys are below:
//
// RSA Public Key
//
// ---- BEGIN SSH2 PUBLIC KEY ----
// Comment: "This is an optional comment"
// AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCA
// KJRD01Tzzg94edu17OzHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZk
// TXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjLZFnLSx9pMGfXMNe8K/aatUvkPV
// Cc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZPOHASIRN
// Jybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkc
// GRKhqQ1aTK0s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
// ---- END SSH2 PUBLIC KEY ----
//
// DSA Public Key
//
// ---- BEGIN SSH2 PUBLIC KEY ----
// Comment: "This is an optional comment"
// AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9
// ulAUnVucF6olEpi61O5iyEQFcXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnk
// NJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6SkbhirenMquaBAL5
// YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpf
// MN/l1hI7jrJVq3WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3Pt
// Dm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQZ0rN02y0AAAAVANkiO001oz4lzhsO
// /tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJ
// vaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8S
// hNPJIByKm7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3Dt
// X220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+
// tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7x
// QbYtqHBR+oBgRFbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTx
// A9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwo
// q2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo
// 3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5Sa
// IWYaCiTZWNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuy
// H/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqi
// zg==
// ---- END SSH2 PUBLIC KEY ----
bool ToRfc4716PublicKey(CkString &outStr);
// Exports the public key to a string in RFC 4716 format. Sample RFC 4716 DSA and
// RSA public keys are below:
//
// RSA Public Key
//
// ---- BEGIN SSH2 PUBLIC KEY ----
// Comment: "This is an optional comment"
// AAAAB3NzaC1yc2EAAAADAQABAAABAQC9OMcyDX6cCiBjejxXzNcrB/5W5My0hmCA
// KJRD01Tzzg94edu17OzHkpG4C02qFa2ASw2DT9oe/qj/sTgckT08KpWlRedNXWZk
// TXgG+a6wKe7PUcudXcK1JbcE6H3yweLHC7QjjLZFnLSx9pMGfXMNe8K/aatUvkPV
// Cc5nwH9WLl9x5B15ot7pTOPq9OLkwFaPO9WiD/EOvS0SjgU9Ga7pJSSZPOHASIRN
// Jybmo6b1WdOvY72wKJsU+aqs4MYDOmP85YgfZEwxPUH02Xo/om8dZlz3auqtRVkc
// GRKhqQ1aTK0s3mNbLHAh0IXFC8KcAqJzu46h0xKKoNQ8kceU8iCH
// ---- END SSH2 PUBLIC KEY ----
//
// DSA Public Key
//
// ---- BEGIN SSH2 PUBLIC KEY ----
// Comment: "This is an optional comment"
// AAAAB3NzaC1kc3MAAAEBAKo/+RUI3bL8WrCL8XRCmyHtErh3ycZS0nQqryrJJ6Z9
// ulAUnVucF6olEpi61O5iyEQFcXUO7pnKdzfMP3SIlZIib5vrVEKpT2K3ep9iSvnk
// NJRrT3prJ+n0Mx4VJhtIwhYKLd5zaHbKW+XrlMVa1NAQqtj6SkbhirenMquaBAL5
// YNSuqb6c3vLWfnrWRk6DdrgUP98rBo4Ig7N2YIf5N6PvFLXrgXY3fGsBB3CMxZpf
// MN/l1hI7jrJVq3WvCojwkWRECGzX4ma3E8wHnzUcyYSiS+hJLglPt6GaPAy+l3Pt
// Dm5JOuOpGFeaA2GzwQ5jSEAQq+qHTR51pwQZ0rN02y0AAAAVANkiO001oz4lzhsO
// /tDx9rpOyH/5AAABAA8UN/pP7CYBI1KJ5KvBM7SSd5S5ItjA2ALboHF5uAWBKpaJ
// vaHyHi/v/eCd1BahglmdTsWoP2W5p4HmHjr6fLseuPGyLTHkGFgKd/zC5eTBid8S
// hNPJIByKm7XVGvLFhDqhiNKIIsOqYKYkNXmQjms5VInwT4GfE2orVr5MPSg3k3Dt
// X220CIrEBaPXK4JRdrq2Jezxh7Pp76w+ZEfaQhgf9uEPWtBe0zmKsQ2gjdjRphm+
// tl4gFR0r4JuJeOTs9UZ4rZlMojK2Ew64rHhaAROHHjOJiQdvBEBYxXNru71sqt7x
// QbYtqHBR+oBgRFbPPouNMIUexC4DKxyNeuN2zIcAAAEAXh/Akb90+cojwtyjzXTx
// A9h4CzfTE1G0cWziwToFYPVt/xWZM1/kDEAWRWtTDidZWRxWXxP+8J7PrMwA4Pwo
// q2SPW1u9qQh1mGpPaPDluPiRbMKL2uV9oLfVEY7naVrqH05EPgtbiNjDin7EQljo
// 3IoKzpEKB1lFHT/Vd4CMTdl7o+QhZ5ftMGv9sbmf2eZ6y9fQpebO7o4w7/LgQ5Sa
// IWYaCiTZWNTS4vLeNBuJBVJL/pL3tMQrQFqHAg4o94q6M5Y6NvnsSoyZ3gs5bnuy
// H/wk2oXdlNhRVx1DMYBSdeWRlgjLYUBEKDABs+1N/9nBIZDEUQYvVA71Fawp4cqi
// zg==
// ---- END SSH2 PUBLIC KEY ----
const char *toRfc4716PublicKey(void);
// Exports an SSH key to XML. Samples of RSA and DSA private keys are shown below:
//
// DSA Key
// _LT_DSAKeyValue>
// _LT_P>qj/5FQjdsvxasIvxd......Ss3TbLQ==_LT_/P>
// _LT_Q>2SI7TTWjPiXOGw7+0PH2uk7If/k=_LT_/Q>
// _LT_G>DxQ3+k/sJgEjUon......643bMhw==_LT_/G>
// _LT_Y>Xh/Akb90+cojwty.....VA71p4cqizg==_LT_/Y>
// _LT_X>ojilJuWXOyBTQ0H4hBNBTsL9Mq8=_LT_/X>
// _LT_/DSAKeyValue>
//
// RSA Key
// _LT_RSAKeyValue>
// _LT_Modulus>vTjHMg1+n.....JHHlPIghw==_LT_/Modulus>
// _LT_Exponent>AQAB_LT_/Exponent>
// _LT_P>zfbbQagHiP48y.....udBR7n5w+MhP7c=_LT_/P>
// _LT_Q>6zCwDGB8ipB....dSEy+BvdVRv9hbE=_LT_/Q>
// _LT_DP>zcNdvlUg2g......9F72NjnAhQUjc=_LT_/DP>
// _LT_DQ>1XB2FIVsA.....qNewUutJKWXcE=_LT_/DQ>
// _LT_InverseQ>qHYYHyZI9d....VuqCeqsMeJ9I=_LT_/InverseQ>
// _LT_D>Ar1Xgk/P1t4fd2Ryr........Onkwwn4Q==_LT_/D>
// _LT_/RSAKeyValue>
//
bool ToXml(CkString &outStr);
// Exports an SSH key to XML. Samples of RSA and DSA private keys are shown below:
//
// DSA Key
// _LT_DSAKeyValue>
// _LT_P>qj/5FQjdsvxasIvxd......Ss3TbLQ==_LT_/P>
// _LT_Q>2SI7TTWjPiXOGw7+0PH2uk7If/k=_LT_/Q>
// _LT_G>DxQ3+k/sJgEjUon......643bMhw==_LT_/G>
// _LT_Y>Xh/Akb90+cojwty.....VA71p4cqizg==_LT_/Y>
// _LT_X>ojilJuWXOyBTQ0H4hBNBTsL9Mq8=_LT_/X>
// _LT_/DSAKeyValue>
//
// RSA Key
// _LT_RSAKeyValue>
// _LT_Modulus>vTjHMg1+n.....JHHlPIghw==_LT_/Modulus>
// _LT_Exponent>AQAB_LT_/Exponent>
// _LT_P>zfbbQagHiP48y.....udBR7n5w+MhP7c=_LT_/P>
// _LT_Q>6zCwDGB8ipB....dSEy+BvdVRv9hbE=_LT_/Q>
// _LT_DP>zcNdvlUg2g......9F72NjnAhQUjc=_LT_/DP>
// _LT_DQ>1XB2FIVsA.....qNewUutJKWXcE=_LT_/DQ>
// _LT_InverseQ>qHYYHyZI9d....VuqCeqsMeJ9I=_LT_/InverseQ>
// _LT_D>Ar1Xgk/P1t4fd2Ryr........Onkwwn4Q==_LT_/D>
// _LT_/RSAKeyValue>
//
const char *toXml(void);
// END PUBLIC INTERFACE
};
#if !defined(__sun__) && !defined(__sun)
#pragma pack (pop)
#endif
#endif
| [
"mich@umich.edu"
] | mich@umich.edu |
5a6a347505a5087ad34deb826d8b62f8ab761d30 | 1880ae99db197e976c87ba26eb23a20248e8ee51 | /apigateway/include/tencentcloud/apigateway/v20180808/model/DescribeUsagePlanEnvironmentsResponse.h | 61ca51ea1318668e63d5f3496adee08ecc663d85 | [
"Apache-2.0"
] | permissive | caogenwang/tencentcloud-sdk-cpp | 84869793b5eb9811bb1eb46ed03d4dfa7ce6d94d | 6e18ee6622697a1c60a20a509415b0ddb8bdeb75 | refs/heads/master | 2023-08-23T12:37:30.305972 | 2021-11-08T01:18:30 | 2021-11-08T01:18:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,666 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_APIGATEWAY_V20180808_MODEL_DESCRIBEUSAGEPLANENVIRONMENTSRESPONSE_H_
#define TENCENTCLOUD_APIGATEWAY_V20180808_MODEL_DESCRIBEUSAGEPLANENVIRONMENTSRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/apigateway/v20180808/model/UsagePlanEnvironmentStatus.h>
namespace TencentCloud
{
namespace Apigateway
{
namespace V20180808
{
namespace Model
{
/**
* DescribeUsagePlanEnvironments返回参数结构体
*/
class DescribeUsagePlanEnvironmentsResponse : public AbstractModel
{
public:
DescribeUsagePlanEnvironmentsResponse();
~DescribeUsagePlanEnvironmentsResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
std::string ToJsonString() const;
/**
* 获取使用计划绑定详情。
注意:此字段可能返回 null,表示取不到有效值。
* @return Result 使用计划绑定详情。
注意:此字段可能返回 null,表示取不到有效值。
*/
UsagePlanEnvironmentStatus GetResult() const;
/**
* 判断参数 Result 是否已赋值
* @return Result 是否已赋值
*/
bool ResultHasBeenSet() const;
private:
/**
* 使用计划绑定详情。
注意:此字段可能返回 null,表示取不到有效值。
*/
UsagePlanEnvironmentStatus m_result;
bool m_resultHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_APIGATEWAY_V20180808_MODEL_DESCRIBEUSAGEPLANENVIRONMENTSRESPONSE_H_
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
e44e987ce4db9b0a8040d1c2ab76964d3080c9ee | 12de865aa45e77e1944482986fd2871f54922e5b | /test/mocks/namespace_mock.h | b835e02846a6be7fcea5e4f04a26b8cc98026f14 | [
"LicenseRef-scancode-mulanpsl-2.0-en"
] | permissive | HumbleHunger/isulad | f51c3e94942e62f3d526f36dbadf4f85e932d025 | f985403f87c82e85852ef472507d55a6c1399065 | refs/heads/main | 2023-06-27T20:43:24.290999 | 2021-08-05T09:51:11 | 2021-08-05T09:51:11 | 392,988,278 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,364 | h | /******************************************************************************
* Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved.
* iSulad licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
* PURPOSE.
* See the Mulan PSL v2 for more details.
* Author: wujing
* Create: 2020-02-14
* Description: provide namespace mock
******************************************************************************/
#ifndef _ISULAD_TEST_MOCKS_NAMESPACE_MOCK_H
#define _ISULAD_TEST_MOCKS_NAMESPACE_MOCK_H
#include <gmock/gmock.h>
#include "namespace.h"
#include "specs_namespace.h"
class MockNamespace {
public:
virtual ~MockNamespace() = default;
MOCK_METHOD1(ConnectedContainer, char *(const char *mode));
MOCK_METHOD3(GetShareNamespacePath, int(const char *type, const char *src_path, char **dest_path));
MOCK_METHOD1(GetContainerProcessLabel, char *(const char *path));
};
void MockNamespace_SetMock(MockNamespace *mock);
#endif // _ISULAD_TEST_MOCKS_NAMESPACE_MOCK_H
| [
"2495970924@qq.com"
] | 2495970924@qq.com |
daa3386a25b414e810ac190a3c3545c8770c54ad | 204532dbfde3c7db2635066fd04a66498dd0182c | /bbbTest2/src/mpu6050/I2Cdev.cpp | 273ff6eab2a47c1fd18d91644fb81aadb95fc55d | [] | no_license | anderss90/prosjektoppgave | d7ed655a1b9c69b39bda29bdebeaf571cabbd3f6 | 36640f1fe3bf12c46fd9bd5c07ee704f6b0c54d9 | refs/heads/master | 2021-01-22T05:10:02.030790 | 2014-12-08T12:53:24 | 2014-12-08T12:53:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,217 | 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 <jeff@rowberg.net>
//
// 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
Modified by Nagavenkat Adurthi for Beaglebone Black
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 <stdint.h>
//#include <glib.h>
//#include <glib/gprintf.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BBB_I2C_file "/dev/i2c-1" //change yout i2c 0 or 1 for BBB
/** 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) {
uint8_t b;
uint8_t count = readByte(devAddr, regAddr, &b);
*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 b;
uint8_t count = readWord(devAddr, regAddr, &b);
*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) {
// 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)) != 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) {
// 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)) != 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) {
return readBytes(devAddr, regAddr, 1, data);
}
/** 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) {
return readWords(devAddr, regAddr, 1, data);
}
/** 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) {
int8_t count = 0;
int file;
char filename[40];
// const gchar *buffer;
//int addr = 0b00101001; // The I2C address of the ADC
sprintf(filename,BBB_I2C_file);
if ((file = open(filename,O_RDWR)) < 0) {
printf("Failed to open the bus.");
close(file);
return -1;
/* ERROR HANDLING; you can check errno to see what went wrong */
// exit(1);
}
if (ioctl(file,I2C_SLAVE,devAddr) < 0) {
printf("Failed to acquire bus access and/or talk to slave.\n");
/* ERROR HANDLING; you can check errno to see what went wrong */
close(file);
return -1;
// exit(1);
}
char buf[20] = {0};
buf[0]=regAddr;
//go the register address by first writing to it
if (write(file,buf,1) != 1) {
/* ERROR HANDLING: i2c transaction failed */
if (write(file,buf,1) != 1) {
printf("Failed to write(go to) the required register on the device.\n");
}
// buffer = g_strerror(errno);
// printf(buffer);
// printf("\n\n");
close(file);
return -1;
}
if (read(file,buf,length) != length) {
/* ERROR HANDLING: i2c transaction failed */
printf("Failed to read the required no. of bytes from the i2c bus.\n");
// buffer = g_strerror(errno);
// printf(buffer);
// printf("\n\n");
close(file);
return -1;
} else {
for(;count<length;count++)
{data[count] = (int)buf[count];}
}
close(file);
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) {
int8_t count = 0;
int file;
char filename[40];
// const gchar *buffer;
//int addr = 0b00101001; // The I2C address of the ADC
sprintf(filename,BBB_I2C_file);
if ((file = open(filename,O_RDWR)) < 0) {
printf("Failed to open the bus.");
close(file);
return -1;
/* ERROR HANDLING; you can check errno to see what went wrong */
// exit(1);
}
if (ioctl(file,I2C_SLAVE,devAddr) < 0) {
printf("Failed to acquire bus access and/or talk to slave.\n");
/* ERROR HANDLING; you can check errno to see what went wrong */
close(file);
return -1;
// exit(1);
}
char buf[20] = {0};
buf[0]=regAddr;
//go the register address by first writing to it
if (write(file,buf,1) != 1) {
/* ERROR HANDLING: i2c transaction failed */
printf("Failed to write(go to) the required register on the device.\n");
//buffer = g_strerror(errno);
// printf(buffer);
//printf("\n\n");
close(file);
return -1;
}
if (read(file,buf,2*length) != 2*length) {
/* ERROR HANDLING: i2c transaction failed */
printf("Failed to read the required no. of bytes/words from the i2c bus.\n");
// buffer = g_strerror(errno);
// printf(buffer);
// printf("\n\n");
close(file);
return -1;
} else {
for(;count<length;count++)
{data[count] = (int)((buf[2*count]<< 8)|buf[2*count+1]);} //msb first and then lsb
}
close(file);
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) {
int file;
char filename[40];
// const gchar *buffer;
//int addr = 0b00101001; // The I2C address of the ADC
sprintf(filename,BBB_I2C_file);
if ((file = open(filename,O_RDWR)) < 0) {
printf("Failed to open the bus.");
close(file);
return false;
/* ERROR HANDLING; you can check errno to see what went wrong */
//exit(1);
}
if (ioctl(file,I2C_SLAVE,devAddr) < 0) {
printf("Failed to acquire bus access and/or talk to slave.\n");
/* ERROR HANDLING; you can check errno to see what went wrong */
close(file);
return false;
// exit(1);
}
char buf[20] = {0};
buf[0]=regAddr;
int i;
for(i=0;i<length;i++)
{
buf[1+i]=data[i];
}
//float data;
//char channel;
//unsigned char reg = 0x10; // Device register to access
//buf[0] = reg;
//buf[0] = 0b11110000;
if (write(file,buf,length+1) != (length+1)) {
/* ERROR HANDLING: i2c transaction failed */
printf("Failed to write the required no. of bytes to the i2c bus.\n");
// buffer = g_strerror(errno);
// printf(buffer);
// printf("\n\n");
close(file);
return false;
}
close(file);
return true;
}
/** 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) {
int file;
char filename[40];
// const gchar *buffer;
//int addr = 0b00101001; // The I2C address of the ADC
sprintf(filename,BBB_I2C_file);
if ((file = open(filename,O_RDWR)) < 0) {
printf("Failed to open the bus.");
close(file);
return false;
/* ERROR HANDLING; you can check errno to see what went wrong */
//exit(1);
}
if (ioctl(file,I2C_SLAVE,devAddr) < 0) {
printf("Failed to acquire bus access and/or talk to slave.\n");
/* ERROR HANDLING; you can check errno to see what went wrong */
close(file);
return false;
// exit(1);
}
char buf[20] = {0};
buf[0]=regAddr;
int i;
for(i=0;i<2*length;i=i+1)
{
buf[1+2*i]=(uint8_t)(data[2*i] >> 8); //first msb
buf[2+2*i]=(uint8_t)(data[2*i+1]); // then lsb
}
if (write(file,buf,2*length+1) != (2*length+1)) {
/* ERROR HANDLING: i2c transaction failed */
printf("Failed to write the required no. of words to the i2c bus.\n");
// buffer = g_strerror(errno);
// printf(buffer);
// printf("\n\n");
close(file);
return false;
}
close(file);
return true;
}
| [
"anderss90@gmail.com"
] | anderss90@gmail.com |
f1a542ee00137e7f037b65318a0e4c9125a2e845 | e95b712738ca940a9bda31e7a31c1e36421ba3ef | /Survival/Source/Survival/Items/Interfaces/Item.h | bca09d8e4857e3bbb1c7a742fad9ce211d1e58b8 | [] | no_license | JosaiProduction/Survival | ee75d6038c7fcef2490f0af7451016db0044a9b2 | 872b592ee627a69bf6016b81a3f0eda7c6ba31be | refs/heads/master | 2020-03-28T18:31:34.827511 | 2018-09-20T22:00:45 | 2018-09-20T22:00:45 | 148,888,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Items/Globals/Helpers.h"
#include "Item.generated.h"
class ASurvivalCharacter;
static unsigned int s_itemID;
/**
*
*/
UCLASS(abstract)
class SURVIVAL_API AItem : public AActor
{
GENERATED_BODY()
public:
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
private:
UPROPERTY(EditAnywhere, Category = Item)
UTexture2D* m_image;
UPROPERTY(EditAnywhere, Category = Item)
UStaticMeshComponent* m_mesh;
UPROPERTY(EditAnywhere, Category = Item)
UShapeComponent* m_trigger;
UPROPERTY(EditAnywhere, Category = Item)
FItemProperties m_itemProps;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
public:
bool m_canBeUsed;
void Use(ASurvivalCharacter* character);
FItemProperties GetProps() const;
AItem();
~AItem();
};
| [
"K.schaefer92@gmx.de"
] | K.schaefer92@gmx.de |
15ac082cc6df37e962616628547f4d4a3d8a96af | b4823dcec24cf086674b30022897af807e76edc6 | /Piscine_CPP/day04/ex01/Enemy.cpp | 0d04c973b6355a15a3e36f7cacfaaafa157fe162 | [] | no_license | Salibert/42 | 9e5c36355fff8111f6688e1fa7cf7a144f4193ef | 9f6f091f235fa35bfd05e46cfb4d72ce112d4a4c | refs/heads/master | 2023-01-14T13:28:01.911255 | 2019-06-02T12:35:03 | 2019-06-02T12:35:03 | 189,842,531 | 0 | 0 | null | 2023-01-12T23:58:02 | 2019-06-02T12:16:16 | C | UTF-8 | C++ | false | false | 852 | cpp | #include "Enemy.hpp"
Enemy::~Enemy(void) { return; }
Enemy::Enemy(void) { return; }
Enemy::Enemy(int hp, std::string const & type) : _type(type), _HitPoint(hp) { return; }
Enemy::Enemy(Enemy const & rhs) { *this = rhs; return; }
std::string Enemy::getType(void) const { return this->_type; }
int Enemy::getHitPoint(void) const { return this->_HitPoint; }
void Enemy::deathDisplay(void) const { return; }
void Enemy::takeDamage(int amount) {
if (this->getHitPoint() && (this->getHitPoint() - amount) <= 0)
this->deathDisplay();
if (amount <= this->getHitPoint())
this->_HitPoint -= amount;
else
this->_HitPoint = 0;
return;
}
Enemy & Enemy::operator=(Enemy const & rhs) {
if (this != &rhs) {
this->_HitPoint = rhs.getHitPoint();
this->_type = rhs.getType();
}
return *this;
}
| [
"salibert@e3r2p3.42.fr"
] | salibert@e3r2p3.42.fr |
f149cbbcd2544e4450bf9b3b3a3f5e256baef096 | 3df0244ec7d21acb7c78e187d0549e4641605a59 | /10305.cpp | 76c1db8cb777bb6924fbf8d60c33069c55844f46 | [] | no_license | jfrbr/UVa_online_judge | ff18c98e72515789bf1a911de33b4acc8f3b70b2 | 47572ce26f93d15503d3c47037de7be86ec2a084 | refs/heads/master | 2022-11-30T03:40:46.400223 | 2020-08-04T23:53:02 | 2020-08-04T23:53:02 | 7,121,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | #include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
int n,m,g[100][100],vis[100],a,b;
vector<int> v;
void visit(int u){
vis[u] = 1;
for (int i=0; i<n;i++){
if (g[u][i] && !vis[i]) {
visit(i);
}
}
v.push_back(u);
}
int main(){
while ( scanf("%d %d\n",&n,&m) == 2 && (n || m) ){
memset(g,0,sizeof(g));
memset(vis,0,sizeof(vis));
v.clear();
for (int i=0;i<m;i++){
scanf("%d %d\n",&a,&b);
g[--a][--b] = 1;
}
for (int i=0;i<n;i++){
if ( !vis[i] ) {
visit(i);
}
}
for (int i= v.size()-1 ; i >= 0 ; i--){
if (i) printf("%d ",v[i]+1);
else printf("%d\n",v[i]+1);
}
}
return 0;
}
| [
"juan.franca@gmail.com"
] | juan.franca@gmail.com |
4f03c142723ee885743305ed12de96204810c71a | 9a6199faf18acb92766ba2d5368c3b12d68f5ac7 | /ObjectManager.h | e0610474c868c19616914397a687ca70953d2b1c | [] | no_license | carl0967/Densan | ec60eecc814565ace29a545c0a787f85dbb87e2f | 1006bde0476de6ed2b8b2fcd9132cd3c4ffc9f1f | refs/heads/master | 2021-01-10T00:59:58.665614 | 2014-09-01T03:47:26 | 2014-09-01T03:47:26 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 850 | h | /*
どのセル座標のオブジェクトがどのIDかを管理するクラス
*/
#pragma once
#include "AObject.h"
#include "Map.h"
class ObjectManager{
public:
ObjectManager();
ObjectManager(int map_width,int map_height); //コンストラクタ。引数はセルの座標
int RegisterObject(int cell_x,int cell_y,MapChip map_chip); //オブジェクトを登録する。 (登録したときのIDを返すけど別に使わないかも)
int GetId(int cell_x,int cell_y); //テスト用関数
TwoDimension GetCellPosFromId(int id); //idを引数にとって、セルの座標を返す
~ObjectManager(); //デストラクタ
private:
int** ids; //idを保持しておくための2次元配列(のポインタ)。
int id_counter; //idを割り振るためのカウンター
int width; //横の配列数
int height; //縦の配列数
}; | [
"yblueycarlo1967@gmail.com"
] | yblueycarlo1967@gmail.com |
7af1b303805b0c75bee60707db69409e11b610fc | 98c5af87939de50890e639f26ed15b5341d2168a | /Complex.cpp | daa9859f5366db5c7cb7a71cb9aee3782e1b743b | [] | no_license | whirledsol/CSC415_Assignment4 | 94b82993a97fd23da716d412d832520d7ebc3aa4 | 72c975a96b03a610005e52954689fbc050001da8 | refs/heads/master | 2021-01-18T14:16:02.526313 | 2014-04-01T22:51:16 | 2014-04-01T22:51:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,804 | cpp | // Name: Frankie Nwafili & Will Rhodes
// Course: CSC 415
// Semester: Spring 2014
// Instructor: Dr. Pulimood
// Exercise : Overloading Exercise
// Description: Member function definition file for complex numbers
// Filename: Complex.cpp : complex numbers
// Last modified on: 3/17/2014
// Created by: Dr. Monisha Pulimood
#include "Complex.h"
#include <iostream>
#include <iomanip>
using namespace std;
//CONSTRUCTOR with default params
Complex::Complex (float r, float i)
{
real = r;
imag = i;
}
//operator+: overwrites the addition operator between a float and complex obj
Complex operator+(const float lhs, const Complex &rhs){
Complex res;
res.real = lhs + rhs.real;
res.imag = rhs.imag;
return res;
}
//operator+: overwrites the addition operator for two Complex objs
Complex Complex::operator+ (const Complex &rhs) const{
Complex res;
res.real = real + rhs.real;
res.imag = imag + rhs.imag;
return res;
}
//operator>>: overwrites the extraction operator for the Complex obj
istream& operator>>(istream& lhs, Complex& rhs){
lhs>>rhs.real>>rhs.imag;
return lhs;
}
//operator<<: overwrites the insertion operator for the Complex obj
ostream& operator<<(ostream& lhs, Complex& rhs){
if(!(rhs.real==0.0 && rhs.imag != 0.0)){
lhs << setprecision(1)<<fixed<<rhs.real;
}
//determines the sign for the imaginary component
if(rhs.imag == 0){
return lhs;
}
else if (rhs.imag < 0){
lhs << "-";
}
else{
lhs << "+";
}
lhs << abs(rhs.imag) << "i";
return lhs;
}
//operator==: checks to see if two complex objects are equal
bool Complex::operator== (const Complex& rhs){
if(real == rhs.real && imag == rhs.imag){
return true;
}
else{
return false;
}
}
| [
"astro491@gmail.com"
] | astro491@gmail.com |
3e11d6b3044dd2bde31336e1822b3b991dc5a12f | 8b7b586f5dc645636d7ee70c1e2ef39f682ff865 | /BioImageLib/src/blFiltering/blBinomialBlurFilter.cpp | 3df278246d6bb3e8a2328c2082177bcbb682cf57 | [
"Apache-2.0"
] | permissive | sylvainprigent/BioImageLib | eb83354075f4d9ceeacaef3ddf7b386b20994052 | bf69230b404b969df3faf19c16e3b4a7c3996363 | refs/heads/master | 2021-01-21T21:54:43.937797 | 2020-03-11T16:34:18 | 2020-03-11T16:34:18 | 28,745,649 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,608 | cpp | /// \file blBinomialBlurFilter.cpp
/// \brief blBinomialBlurFilter class
/// \author Sylvain Prigent
/// \version 0.1
/// \date 2014
#include "blBinomialBlurFilter.h"
#include <blCastStacks>
blBinomialBlurFilter::blBinomialBlurFilter() : blFilter(){
m_repetitions = 1;
}
blBinomialBlurFilter::~blBinomialBlurFilter(){
}
std::string blBinomialBlurFilter::name(){
return "blBinomialBlurFilter";
}
void blBinomialBlurFilter::setRepetitions(int repetitions){
m_repetitions = repetitions;
}
void blBinomialBlurFilter::run(){
if (m_inputImage->imageType() == blImage::TypeInt2D){
m_outputImage = binomialBlur<Int2DImage>(m_inputImage->itkInt2DImagePointer());
}
else if ( m_inputImage->imageType() == blImage::TypeInt3D){
m_outputImage = binomialBlur<Int3DImage>(m_inputImage->itkInt3DImagePointer());
}
else if(m_inputImage->imageType() == blImage::TypeFloat2D){
m_outputImage = binomialBlur<Float2DImage>(m_inputImage->itkFloat2DImagePointer());
}
else if(m_inputImage->imageType() == blImage::TypeFloat3D){
m_outputImage = binomialBlur<Float3DImage>(m_inputImage->itkFloat3DImagePointer());
}
else if(m_inputImage->imageType() == blImage::TypeIntColor2D || m_inputImage->imageType() == blImage::TypeFloatColor2D
|| m_inputImage->imageType() == blImage::TypeIntColor3D || m_inputImage->imageType() == blImage::TypeFloatColor3D){
// Calculate gradient
blImage* compRed = binomialBlurOnOneComponent(m_inputImage, 0);
blImage* compGreen =binomialBlurOnOneComponent(m_inputImage, 1);
blImage* compBlue = binomialBlurOnOneComponent(m_inputImage, 2);
// compose images
blComposeColorImage composer;
composer.setComposant1(compRed);
composer.setComposant2(compGreen);
composer.setComposant3(compBlue);
composer.run();
m_outputImage = composer.output();
}
else{
std::string message = "The image format " + m_inputImage->imageType() + " is not suported by blBinomialBlurFilter filter";
throw blException(message.c_str());
}
}
blImage* blBinomialBlurFilter::binomialBlurOnOneComponent(blImage* input, unsigned int index){
// extract component
blExtractComponentColorImage extractor;
extractor.setInput(input);
extractor.setComponentIndex(index);
extractor.run();
blImage* comp = extractor.output();
// Calculate gradient
blBinomialBlurFilter filter;
filter.setInput(comp);
filter.setRepetitions(m_repetitions);
filter.run();
return filter.output();
}
| [
"sylvain.prigent@inria.fr"
] | sylvain.prigent@inria.fr |
e9e684c63b0d99ebf1383ff7159bbf869c104cd5 | 75452de12ec9eea346e3b9c7789ac0abf3eb1d73 | /src/ui/lib/escher/renderer/batch_gpu_downloader.h | af8a3d31cabccc31c518df5501d0fd9b601e65dc | [
"BSD-3-Clause"
] | permissive | oshunter/fuchsia | c9285cc8c14be067b80246e701434bbef4d606d1 | 2196fc8c176d01969466b97bba3f31ec55f7767b | refs/heads/master | 2022-12-22T11:30:15.486382 | 2020-08-16T03:41:23 | 2020-08-16T03:41:23 | 287,920,017 | 2 | 2 | BSD-3-Clause | 2022-12-16T03:30:27 | 2020-08-16T10:18:30 | C++ | UTF-8 | C++ | false | false | 7,460 | h | // Copyrisnapshotter.ccght 2019 The Fuchsia 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 SRC_UI_LIB_ESCHER_RENDERER_BATCH_GPU_DOWNLOADER_H_
#define SRC_UI_LIB_ESCHER_RENDERER_BATCH_GPU_DOWNLOADER_H_
#include <lib/fit/function.h>
#include <variant>
#include "src/ui/lib/escher/escher.h"
#include "src/ui/lib/escher/renderer/buffer_cache.h"
#include "src/ui/lib/escher/renderer/frame.h"
#include "src/ui/lib/escher/third_party/granite/vk/command_buffer.h"
#include "src/ui/lib/escher/vk/buffer.h"
#include "src/ui/lib/escher/vk/command_buffer.h"
#include <vulkan/vulkan.hpp>
namespace escher {
// Provides host-accessible GPU memory for clients to download Images and
// Buffers from the GPU to host memory. Offers the ability to batch downloads
// into consolidated submissions to the GPU driver.
//
// About synchronization:
// We use semaphore (usually generated by ChainedSemaphoreGenerator) for
// synchronization between BatchGpuDownloader/Uploader and other gfx components,
// so we only need the barrier to synchronize all transfer-related commands.
//
// Currently users of BatchGpuDownloader should manually enforce that
// the BatchGpuDownloader waits on other BatchGpuUploader or gfx::Engine if they
// write to the images / buffers the BatchGpuDownloader reads from, by using
// AddWaitSemaphore() function. Also, Submit() function will return a semaphore
// being signaled when command buffer finishes execution, which can be used for
// synchronization.
//
// TODO(SCN-1197) Add memory barriers so the BatchGpuUploader and
// BatchGpuDownloader can handle synchronzation of reads and writes on the same
// Resource.
//
class BatchGpuDownloader {
public:
// Called after download is complete, with a pointer into the downloaded data.
using Callback = fit::function<void(const void* host_ptr, size_t size)>;
public:
static std::unique_ptr<BatchGpuDownloader> New(
EscherWeakPtr weak_escher,
CommandBuffer::Type command_buffer_type = CommandBuffer::Type::kTransfer,
uint64_t frame_trace_number = 0);
BatchGpuDownloader(EscherWeakPtr weak_escher,
CommandBuffer::Type command_buffer_type = CommandBuffer::Type::kTransfer,
uint64_t frame_trace_number = 0);
~BatchGpuDownloader();
// Returns true if the BatchGpuDownloader has work to do on the GPU.
bool HasContentToDownload() const { return !copy_info_records_.empty(); }
// Returns true if BatchGpuDownloader needs a command buffer, i.e. it needs to
// downloading images/buffers, or it needs to wait on/signal semaphores.
bool NeedsCommandBuffer() const {
return HasContentToDownload() || !wait_semaphores_.empty() || !signal_semaphores_.empty();
}
// Schedule a buffer-to-buffer copy that will be submitted when Submit()
// is called. Retains a reference to the source until the submission's
// CommandBuffer is retired.
//
// |source_offset| is the starting offset in bytes from the start of the
// source buffer.
// |copy_size| is the size to be copied to the buffer.
//
// These arguments are used to build VkBufferCopy struct. See the Vulkan
// specs of VkBufferCopy for more details. If copy_size is set to 0 by
// default, it copies all the contents from source.
void ScheduleReadBuffer(const BufferPtr& source, Callback callback,
vk::DeviceSize source_offset = 0U, vk::DeviceSize copy_size = 0U);
// Schedule a image-to-buffer copy that will be submitted when Submit()
// is called. Retains a reference to the source until the submission's
// CommandBuffer is retired.
//
// |region| specifies the buffer region which will be copied to the target
// image.
// |region.bufferOffset| should be set to zero since target buffer is
// managed internally by the uploader; currently |imageOffset| requires to
// be zero and |imageExtent| requires to be the whole image.
// The default value of |region| is vk::BufferImageCopy(), in which case we
// create a default copy region which reads the color data from the whole
// image with only one mipmap layer.
//
// |write_function| is a callback function which will be called at
// GenerateCommands(), where we copy our data to the host-visible buffer.
void ScheduleReadImage(const ImagePtr& source, Callback callback,
vk::BufferImageCopy region = vk::BufferImageCopy());
// Submits all pending work to the given CommandBuffer. Users need to call
// cmds->Submit() after calling this function. Returns a lambda function
// which calls all the callback functions we passed in to ScheduleReadBuffer
// and ScheduleReadImage functions; this function should be called after the
// command buffer has finished execution, typically by passing it to
// cmds->Submit().
//
// After this function is called, all the contents in |copy_info_records|,
// staged |resources_| and semaphores will be moved to the lambda function
// and the downloader will be cleaned and ready for reuse.
//
// The argument |cmds| cannot be nullptr if there is any pending work,
// including writing to buffer/images and waiting on/signaling semaphores.
CommandBufferFinishedCallback GenerateCommands(CommandBuffer* cmds);
// Submits all pending work to the GPU.
// The function |callback|, and all callback functions the user passed to
// ScheduleReadBuffer and ScheduleReadImage, will be called after all work
// is done.
//
// After this function is called, all the contents in |copy_info_records|,
// staged |resources_| and semaphores will be moved to the lambda function
// and the downloader will be cleaned and ready for reuse.
void Submit(CommandBufferFinishedCallback client_callback = nullptr);
// Submit() and GenerateCommands() will wait on all semaphores added by
// AddWaitSemaphore().
void AddWaitSemaphore(SemaphorePtr sema, vk::PipelineStageFlags flags) {
wait_semaphores_.push_back({std::move(sema), flags});
}
// Submit() and GenerateCommands() will signals all semaphores added by
// AddSignalSemaphore().
void AddSignalSemaphore(SemaphorePtr sema) { signal_semaphores_.push_back(std::move(sema)); }
private:
enum class CopyType { COPY_IMAGE = 0, COPY_BUFFER = 1 };
struct ImageCopyInfo {
ImagePtr source;
vk::BufferImageCopy region;
};
struct BufferCopyInfo {
BufferPtr source;
vk::BufferCopy region;
};
using CopyInfoVariant = std::variant<ImageCopyInfo, BufferCopyInfo>;
struct CopyInfo {
CopyType type;
vk::DeviceSize offset;
vk::DeviceSize size;
Callback callback;
// copy_info can either be a ImageCopyInfo or a BufferCopyInfo.
CopyInfoVariant copy_info;
};
EscherWeakPtr escher_;
CommandBuffer::Type command_buffer_type_ = CommandBuffer::Type::kTransfer;
// The trace number for the frame. Cached to support lazy frame creation.
const uint64_t frame_trace_number_;
BufferCacheWeakPtr buffer_cache_;
vk::DeviceSize current_offset_ = 0U;
std::vector<CopyInfo> copy_info_records_;
std::vector<ResourcePtr> resources_;
std::vector<std::pair<SemaphorePtr, vk::PipelineStageFlags>> wait_semaphores_;
std::vector<SemaphorePtr> signal_semaphores_;
FXL_DISALLOW_COPY_AND_ASSIGN(BatchGpuDownloader);
};
} // namespace escher
#endif // SRC_UI_LIB_ESCHER_RENDERER_BATCH_GPU_DOWNLOADER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
12b261ba5347a96ad1307ebb337b82e7a6b66378 | 374ee2f65a9747eefdfef75e59afaacd2b2c02c6 | /main.cpp | 9817d10c79808d0f04634bc190a3ea2df6704538 | [] | no_license | teslaistra/ListArray | 5b443e892ee4b77215317c98834acdb419eaebf6 | 8c09cac94e5857795664661068b0ee03e1ee7f97 | refs/heads/master | 2021-05-19T11:16:45.158175 | 2020-03-31T16:55:25 | 2020-03-31T16:55:25 | 251,669,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,806 | cpp | #include "main.h"
#include <iostream>
using namespace std;
StackL::StackL(const StackL& a)
{
if (!is_empty()) {
//*this->~StackL;
delete(head);
head = nullptr;
}
*this = operator=(a);
}
StackL::~StackL()
{
Node* t = head;
while (t != nullptr)
{
t = head->next;
delete(head);
head = t;
}
}
StackL& StackL::operator=(const StackL&a)
{
if (a.head == nullptr) { delete head; head = nullptr; return *this; }
if (a.head == head) return *this;
head = new Node{ a.head->value,nullptr };
Node* curHere = head;
Node* curThere = a.head->next;
while (curThere != nullptr) {
curHere->next = new Node{ curThere->value,nullptr };
curHere = curHere->next;
curThere = curThere->next;
}
return *this;
}
void StackL::pop()
{
if (!is_empty()) {
Node* t = head;
head = head->next;
delete(t);
current--;
}
}
StackL::StackL() {
head = nullptr;
}
void StackL::push(const float v) {
current++;
head = new Node {v, head};
}
bool StackL::is_empty() const {
return nullptr == head;
}
float& StackL::top() {
if (is_empty()) {
throw new std::exception("stack is empty");
}
return head->value;
}
const float& StackL::top() const {
if (is_empty()) {
throw new std::exception("stack is empty");
}
return head->value;
}
float &StackL::at(int at) {
Node* curHere = head;
for (int i = 0; i < current-at-1; ++i) {
if(nullptr == curHere) break;
curHere = curHere->next;
}
return curHere->value;
}
void StackL::insertAt(int at,float value) {
Node* curHere = head;
Node* prev;
for (int i = 0; i < current-at; ++i) {
if(nullptr == curHere) break;
prev = curHere;
curHere = curHere->next;
}
Node* new_Node = new Node{value, curHere};
prev->next =new_Node;
current++;
}
void StackL::deleteAt(int at) {
Node* curHere = head;
Node* prev = head;
for (int i = 0; i < current-at-1; ++i) {
if(nullptr == curHere) break;
prev = curHere;
curHere = curHere->next;
}
current--;
prev->next = curHere->next;
}
int main(){
system("chcp 65001");
StackL a;
a.push(4);
a.push(6);
a.push(2);
cout << "Тестирую доступ по номеру. В стеке сейчас лежит(в порядке добавления туда) 4, 6, 2.\n";
cout << "Получим доступ к нулевому элементу, то есть первому добавленному\n";
cout << "stack.at(0) = " << a.at(0) << endl << endl;
cout << "Вставим на место первого элемента 1. Сейчас там a.at(1) = "<<a.at(1)<<"\n";
a.insertAt(1,1);
cout << "a.insertAt(1,1);\n";
cout<<"Теперь посмотрим что на месте первого a.at(1) = " << a.at(1) <<"\n" ;
cout << "Выведем все элементы стека с нулевого: " << a.at(0) << " " << a.at(1) << " " << a.at(2) << " "<< a.at(3) << "\n";
cout << "Теперь протестируем удаление элемента. Удалим элемент на первой позиции, то есть который недавно добавили туда.\n";
cout << "a.deleteAt(1);\n";
a.deleteAt(1);
cout << "Выведем все элементы стека с нулевого: " << a.at(0) << " " << a.at(1) << " " << a.at(2) << "\n";
cout << "Стек, в который можно добавить, удалить или получать элемент по конкретному номеру реализован. Ефимов Д. БПМ-18-2";
return 0;
}
| [
"danyefimoff@gmail.com"
] | danyefimoff@gmail.com |
c34a5389414dc07ae6a37e00f0d6073c8b6ff666 | f5a1dd134cc83478e64243ade0aab3bbeba529e8 | /iteration1/src/entity_factory.cc | 1d0ca4f258923e496c43230076a614c5b405b5b7 | [] | no_license | DawoodKhan1/BraitenbergVehicle | be08dcea85288d7fc3d28cede3bdbd9d79daf735 | 03538e9a230a551439262268c65e282d275c4bc9 | refs/heads/master | 2020-03-28T00:27:45.759924 | 2018-09-04T20:56:17 | 2018-09-04T20:56:17 | 147,415,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,549 | cc | /**
* @file entity_factory.cc
*
* @copyright 2017 3081 Staff, All rights reserved.
*/
/*******************************************************************************
* Includes
******************************************************************************/
#include <string>
#include <ctime>
#include <iostream>
#include "src/common.h"
#include "src/entity_factory.h"
#include "src/entity_type.h"
#include "src/params.h"
#include "src/pose.h"
#include "src/rgb_color.h"
/*******************************************************************************
* Namespaces
******************************************************************************/
NAMESPACE_BEGIN(csci3081);
/*******************************************************************************
* Class Definitions
******************************************************************************/
EntityFactory::EntityFactory() {
srand(time(nullptr));
}
ArenaEntity* EntityFactory::CreateEntity(EntityType etype) {
switch (etype) {
case (kRobot):
return CreateRobot();
break;
case (kObstacle):
return CreateObstacle();
break;
case (kBase):
return CreateBase();
break;
default:
std::cout << "FATAL: Bad entity type on creation\n";
assert(false);
}
return nullptr;
}
Robot* EntityFactory::CreateRobot() {
auto* robot = new Robot;
robot->set_type(kRobot);
robot->set_color(ROBOT_COLOR);
robot->set_pose(ROBOT_INIT_POS);
robot->set_radius(ROBOT_RADIUS);
++entity_count_;
++robot_count_;
robot->set_id(robot_count_);
return robot;
}
Obstacle* EntityFactory::CreateObstacle() {
auto* obstacle = new Obstacle;
obstacle->set_type(kObstacle);
obstacle->set_color(OBSTACLE_COLOR);
obstacle->set_pose(SetPoseRandomly());
double rand_radius = random() %
(OBSTACLE_MAX_RADIUS - OBSTACLE_MIN_RADIUS + 1) + OBSTACLE_MIN_RADIUS;
obstacle->set_radius(rand_radius);
++entity_count_;
++obstacle_count_;
obstacle->set_id(obstacle_count_);
return obstacle;
}
Base* EntityFactory::CreateBase() {
auto* base = new Base;
base->set_type(kBase);
base->set_color(BASE_COLOR);
base->set_pose(SetPoseRandomly());
base->set_radius(BASE_RADIUS);
++entity_count_;
++base_count_;
base->set_id(base_count_);
return base;
}
Pose EntityFactory::SetPoseRandomly() {
// Dividing arena into 19x14 grid. Each grid square is 50x50
return {static_cast<double>((30 + (random() % 19) * 50)),
static_cast<double>((30 + (random() % 14) * 50))};
}
NAMESPACE_END(csci3081);
| [
"khanx263@umn.edu"
] | khanx263@umn.edu |
801e5a7d69145b2944f9d132948899d010ba6600 | 6f0c08e1eb271452be2b21b813d19c88a0cbb9e1 | /BattleTank/Source/BattleTank/Private/TankPlayerController.cpp | 44587795417fdd1f37b0fcb417fbcc7a08a72d28 | [] | no_license | Boostedblue24/04_BattleTank | de87ce422566362c7a4b4643d7d88d82c715518a | 5290c1f6a9ed0192732095acf6b138a6d48f3c66 | refs/heads/master | 2021-10-16T06:41:13.467901 | 2019-02-08T17:05:36 | 2019-02-08T17:05:36 | 166,423,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,446 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "TankPlayerController.h"
#include "BattleTank.h"
#include "Tank.h"
#include "TankAimingComponent.h"
#include "GameFramework/PlayerController.h"
#include "Engine/World.h"
class UTankAimingComponent;
void ATankPlayerController::BeginPlay()
{
Super::BeginPlay();
if (!GetPawn()) { return; }
auto AimingComponent = GetPawn()->FindComponentByClass<UTankAimingComponent>();
if (!ensure(AimingComponent)) { return; }
FoundAimingComponent(AimingComponent);
}
void ATankPlayerController::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
AimTowardsCrosshair();
}
void ATankPlayerController::AimTowardsCrosshair()
{
if (!GetPawn()) { return; } /// if not possessing
auto AimingComponent = GetPawn()->FindComponentByClass<UTankAimingComponent>();
if (!ensure(AimingComponent)) { return; }
FVector HitLocation; /// OUT Parameter
bool bGotHitLocation = GetSightRayHitLocation(HitLocation);
if (bGotHitLocation)
{
AimingComponent->AimAt(HitLocation);
}
}
// Get world location of linetrace through crosshair, true if hits landscape
bool ATankPlayerController::GetSightRayHitLocation(FVector & HitLocation) const
{
// Find crosshair position
/// Calculate Viewport Size
int32 ViewportSizeX, ViewportSizeY;
GetViewportSize(ViewportSizeX, ViewportSizeY);
/// Calculate crosshair position (ScreenLocation) by using Viewport size X/Y divided by crosshair position
auto ScreenLocation = FVector2D(ViewportSizeX * CrossHairXLocation, ViewportSizeY * CrossHairYLocation);
// Deproject the screen position of the crosshair to a world direction
/// Variable for the vector that the camera is looking along
FVector LookDirection;
/// Deprojecting using crosshair location and Look vector
/// and logging out the Look direction vector if the Deproject method succeeds
if (GetLookDirection(ScreenLocation, LookDirection))
{
/// Line trace along that look direction and see what we hit (up to a max range)
return GetLookVectorHitLocation(LookDirection, HitLocation);
}
return false;
}
bool ATankPlayerController::GetLookDirection(FVector2D ScreenLocation, FVector& LookDirection) const
{
FVector CameraWorldLocation; /// To be discarded
return DeprojectScreenPositionToWorld(
ScreenLocation.X,
ScreenLocation.Y,
CameraWorldLocation,
LookDirection);
}
bool ATankPlayerController::GetLookVectorHitLocation(FVector LookDirection, FVector & HitLocation) const
{
///Setting up variables
FHitResult HitResult;
auto StartLocation = PlayerCameraManager->GetCameraLocation();
auto EndLocation = StartLocation + (LookDirection * LineTraceRange);
/// Checking to see if line trace succeeds (within specified range)
if (GetWorld()->LineTraceSingleByChannel(HitResult, StartLocation, EndLocation, ECollisionChannel::ECC_Camera))
{
HitLocation = HitResult.Location;
return true;
}
HitLocation = FVector(0);
return false;
}
void ATankPlayerController::OnPossessedTankDeath()
{
UE_LOG(LogTemp, Warning, TEXT("Player Tank Died"));
StartSpectatingOnly();
}
void ATankPlayerController::SetPawn(APawn * InPawn)
{
Super::SetPawn(InPawn);
if (InPawn)
{
auto PossessedTank = Cast<ATank>(InPawn);
if (!ensure(PossessedTank)) { return; }
/// Subscribe our local method to the Tank's death event
PossessedTank->OnDeath.AddUniqueDynamic(this, &ATankPlayerController::OnPossessedTankDeath);
}
}
| [
"evan.oliver87@gmail.com"
] | evan.oliver87@gmail.com |
a6352ba5a3afda3b1e152aee0a2812ee269e6d9c | 24fa4fcc8f4f59081c12ca5dd646a9974b81e85b | /HLS_Set_4/src/m_color_graph.h | 301ee452e4b52b0cf2baa78e1f3ad42398cc5e1f | [] | no_license | Dm1998/HLS_Set_5 | b78805c3858dd7b9ea604d33688b07082bb5517f | 21f66345e38d29aef84c52dae1f20d97aae5cb85 | refs/heads/master | 2023-01-29T09:53:34.061034 | 2020-11-26T19:04:25 | 2020-11-26T19:04:25 | 316,315,670 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 854 | h | #ifndef M_COLOR_GRAPH_H
#define M_COLOR_GRAPH_H
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "ac_int.h"
//#include "mc_scverify.h"
static const int N=6;
//#pragma hls_design top
class ColorGraph{
private:
public:
ColorGraph(){};
//#pragma hls_design interface
void graph_color( bool adj_G[N][N] , ac_int<N,false> V_color[N] , short unsigned int &min_colors)
{
short unsigned int min_color=1;
ac_int<N,false> colors[N];
for (int i=0;i<N;i++)
{
colors[i]=1;
for(int j=0;j<N;j++)
{
if( adj_G[i][j]==1 && colors[i]==colors[j] ) colors[i]+=1;
}
if(colors[i]>min_color) min_color=colors[i];
//std::cout<<min_color;
V_color[i]=colors[i];
}
}//function
};
#endif
| [
"dimitris_mylonidis@hotmail.com"
] | dimitris_mylonidis@hotmail.com |
ec036b98ea6ab79d561bc77c3329c608bd70294b | 7fb359972ed7de0201d83ebc05ff32331b352030 | /src/RcppExports.cpp | 33e238ffd58a4d35237d99693a1ec653506cf5bc | [] | no_license | TasCL/tnorm | 0e159d9d845815a4b0589f0075feb4ed7fc62ae9 | e774291e54178bfd4683b8ac7d14c851322258ab | refs/heads/master | 2020-07-27T09:01:06.571691 | 2017-04-09T02:25:10 | 2017-04-09T02:25:10 | 73,434,271 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,547 | cpp | // Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;
// dtn
arma::vec dtn(arma::vec x, double mean, double sd, double lower, double upper, int lp);
RcppExport SEXP tnorm_dtn(SEXP xSEXP, SEXP meanSEXP, SEXP sdSEXP, SEXP lowerSEXP, SEXP upperSEXP, SEXP lpSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec >::type x(xSEXP);
Rcpp::traits::input_parameter< double >::type mean(meanSEXP);
Rcpp::traits::input_parameter< double >::type sd(sdSEXP);
Rcpp::traits::input_parameter< double >::type lower(lowerSEXP);
Rcpp::traits::input_parameter< double >::type upper(upperSEXP);
Rcpp::traits::input_parameter< int >::type lp(lpSEXP);
rcpp_result_gen = Rcpp::wrap(dtn(x, mean, sd, lower, upper, lp));
return rcpp_result_gen;
END_RCPP
}
// rtn
arma::vec rtn(int n, double mean, double sd, double lower, double upper);
RcppExport SEXP tnorm_rtn(SEXP nSEXP, SEXP meanSEXP, SEXP sdSEXP, SEXP lowerSEXP, SEXP upperSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< int >::type n(nSEXP);
Rcpp::traits::input_parameter< double >::type mean(meanSEXP);
Rcpp::traits::input_parameter< double >::type sd(sdSEXP);
Rcpp::traits::input_parameter< double >::type lower(lowerSEXP);
Rcpp::traits::input_parameter< double >::type upper(upperSEXP);
rcpp_result_gen = Rcpp::wrap(rtn(n, mean, sd, lower, upper));
return rcpp_result_gen;
END_RCPP
}
// ptn
arma::vec ptn(arma::vec q, double mean, double sd, double lower, double upper, int lt, int lp);
RcppExport SEXP tnorm_ptn(SEXP qSEXP, SEXP meanSEXP, SEXP sdSEXP, SEXP lowerSEXP, SEXP upperSEXP, SEXP ltSEXP, SEXP lpSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::vec >::type q(qSEXP);
Rcpp::traits::input_parameter< double >::type mean(meanSEXP);
Rcpp::traits::input_parameter< double >::type sd(sdSEXP);
Rcpp::traits::input_parameter< double >::type lower(lowerSEXP);
Rcpp::traits::input_parameter< double >::type upper(upperSEXP);
Rcpp::traits::input_parameter< int >::type lt(ltSEXP);
Rcpp::traits::input_parameter< int >::type lp(lpSEXP);
rcpp_result_gen = Rcpp::wrap(ptn(q, mean, sd, lower, upper, lt, lp));
return rcpp_result_gen;
END_RCPP
}
| [
"yishin.lin@utas.edu.au"
] | yishin.lin@utas.edu.au |
d9de6703c93594bc3cd458b06af2ea739e506bf0 | 70c2645aab2d095e71ad7b891361566cfe0cb6da | /VulnDB/FileSamples/firefox/CVE-2017-7779/CVE-2017-7779_CWE-119_1373220_bugzilla0_nsWindow.cpp_4.0_NEW.cpp | 4d2d76170546ad3dd1409f71c0f7f9a1435af2af | [] | no_license | Raymiii/SCVDT | ee43c39720780e52d3de252c211fa5a7b4bd6dc2 | 0a30f2e59f45168407cb520e16479d53d7a8845b | refs/heads/main | 2023-05-30T20:00:52.723562 | 2021-06-21T05:24:20 | 2021-06-21T05:24:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270,579 | cpp | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sts=2 sw=2 et cin: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* nsWindow - Native window management and event handling.
*
* nsWindow is organized into a set of major blocks and
* block subsections. The layout is as follows:
*
* Includes
* Variables
* nsIWidget impl.
* nsIWidget methods and utilities
* nsSwitchToUIThread impl.
* nsSwitchToUIThread methods and utilities
* Moz events
* Event initialization
* Event dispatching
* Native events
* Wndproc(s)
* Event processing
* OnEvent event handlers
* IME management and accessibility
* Transparency
* Popup hook handling
* Misc. utilities
* Child window impl.
*
* Search for "BLOCK:" to find major blocks.
* Search for "SECTION:" to find specific sections.
*
* Blocks should be split out into separate files if they
* become unmanageable.
*
* Related source:
*
* nsWindowDefs.h - Definitions, macros, structs, enums
* and general setup.
* nsWindowDbg.h/.cpp - Debug related code and directives.
* nsWindowGfx.h/.cpp - Graphics and painting.
*
*/
/**************************************************************
**************************************************************
**
** BLOCK: Includes
**
** Include headers.
**
**************************************************************
**************************************************************/
#include "gfx2DGlue.h"
#include "gfxEnv.h"
#include "gfxPlatform.h"
#include "gfxPrefs.h"
#include "mozilla/Logging.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/MiscEvents.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/TouchEvents.h"
#include "mozilla/ipc/MessageChannel.h"
#include <algorithm>
#include <limits>
#include "nsWindow.h"
#include <shellapi.h>
#include <windows.h>
#include <wtsapi32.h>
#include <process.h>
#include <commctrl.h>
#include <unknwn.h>
#include <psapi.h>
#include "mozilla/Logging.h"
#include "prtime.h"
#include "prmem.h"
#include "prenv.h"
#include "mozilla/WidgetTraceEvent.h"
#include "nsIAppShell.h"
#include "nsISupportsPrimitives.h"
#include "nsIDOMMouseEvent.h"
#include "nsIKeyEventInPluginCallback.h"
#include "nsITheme.h"
#include "nsIObserverService.h"
#include "nsIScreenManager.h"
#include "imgIContainer.h"
#include "nsIFile.h"
#include "nsIRollupListener.h"
#include "nsIServiceManager.h"
#include "nsIClipboard.h"
#include "WinMouseScrollHandler.h"
#include "nsFontMetrics.h"
#include "nsIFontEnumerator.h"
#include "nsFont.h"
#include "nsRect.h"
#include "nsThreadUtils.h"
#include "nsNativeCharsetUtils.h"
#include "nsGkAtoms.h"
#include "nsCRT.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsXPIDLString.h"
#include "nsWidgetsCID.h"
#include "nsTHashtable.h"
#include "nsHashKeys.h"
#include "nsString.h"
#include "mozilla/Services.h"
#include "nsNativeThemeWin.h"
#include "nsWindowsDllInterceptor.h"
#include "nsLayoutUtils.h"
#include "nsView.h"
#include "nsIWindowMediator.h"
#include "nsIServiceManager.h"
#include "nsWindowGfx.h"
#include "gfxWindowsPlatform.h"
#include "Layers.h"
#include "nsPrintfCString.h"
#include "mozilla/Preferences.h"
#include "nsISound.h"
#include "SystemTimeConverter.h"
#include "WinTaskbar.h"
#include "WidgetUtils.h"
#include "nsIWidgetListener.h"
#include "mozilla/dom/Touch.h"
#include "mozilla/gfx/2D.h"
#include "nsToolkitCompsCID.h"
#include "nsIAppStartup.h"
#include "mozilla/WindowsVersion.h"
#include "mozilla/TextEvents.h" // For WidgetKeyboardEvent
#include "mozilla/TextEventDispatcherListener.h"
#include "mozilla/widget/nsAutoRollup.h"
#include "mozilla/widget/WinNativeEventData.h"
#include "mozilla/widget/PlatformWidgetTypes.h"
#include "nsThemeConstants.h"
#include "nsBidiKeyboard.h"
#include "nsThemeConstants.h"
#include "gfxConfig.h"
#include "InProcessWinCompositorWidget.h"
#include "ScreenHelperWin.h"
#include "nsIGfxInfo.h"
#include "nsUXThemeConstants.h"
#include "KeyboardLayout.h"
#include "nsNativeDragTarget.h"
#include <mmsystem.h> // needed for WIN32_LEAN_AND_MEAN
#include <zmouse.h>
#include <richedit.h>
#if defined(ACCESSIBILITY)
#ifdef DEBUG
#include "mozilla/a11y/Logging.h"
#endif
#include "oleidl.h"
#include <winuser.h>
#include "nsAccessibilityService.h"
#include "mozilla/a11y/DocAccessible.h"
#include "mozilla/a11y/Platform.h"
#if !defined(WINABLEAPI)
#include <winable.h>
#endif // !defined(WINABLEAPI)
#endif // defined(ACCESSIBILITY)
#include "nsIWinTaskbar.h"
#define NS_TASKBAR_CONTRACTID "@mozilla.org/windows-taskbar;1"
#include "nsIWindowsUIUtils.h"
#include "nsWindowDefs.h"
#include "nsCrashOnException.h"
#include "nsIXULRuntime.h"
#include "nsIContent.h"
#include "mozilla/HangMonitor.h"
#include "WinIMEHandler.h"
#include "npapi.h"
#include <d3d11.h>
#include "InkCollector.h"
// ERROR from wingdi.h (below) gets undefined by some code.
// #define ERROR 0
// #define RGN_ERROR ERROR
#define ERROR 0
#if !defined(SM_CONVERTIBLESLATEMODE)
#define SM_CONVERTIBLESLATEMODE 0x2003
#endif
#if !defined(WM_DPICHANGED)
#define WM_DPICHANGED 0x02E0
#endif
#include "mozilla/gfx/DeviceManagerDx.h"
#include "mozilla/layers/APZCTreeManager.h"
#include "mozilla/layers/InputAPZContext.h"
#include "mozilla/layers/KnowsCompositor.h"
#include "mozilla/layers/ScrollInputMethods.h"
#include "InputData.h"
#include "mozilla/Telemetry.h"
#include "mozilla/plugins/PluginProcessParent.h"
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::gfx;
using namespace mozilla::layers;
using namespace mozilla::widget;
using namespace mozilla::plugins;
/**************************************************************
**************************************************************
**
** BLOCK: Variables
**
** nsWindow Class static initializations and global variables.
**
**************************************************************
**************************************************************/
/**************************************************************
*
* SECTION: nsWindow statics
*
**************************************************************/
bool nsWindow::sDropShadowEnabled = true;
uint32_t nsWindow::sInstanceCount = 0;
bool nsWindow::sSwitchKeyboardLayout = false;
BOOL nsWindow::sIsOleInitialized = FALSE;
HCURSOR nsWindow::sHCursor = nullptr;
imgIContainer* nsWindow::sCursorImgContainer = nullptr;
nsWindow* nsWindow::sCurrentWindow = nullptr;
bool nsWindow::sJustGotDeactivate = false;
bool nsWindow::sJustGotActivate = false;
bool nsWindow::sIsInMouseCapture = false;
// imported in nsWidgetFactory.cpp
TriStateBool nsWindow::sCanQuit = TRI_UNKNOWN;
// Hook Data Memebers for Dropdowns. sProcessHook Tells the
// hook methods whether they should be processing the hook
// messages.
HHOOK nsWindow::sMsgFilterHook = nullptr;
HHOOK nsWindow::sCallProcHook = nullptr;
HHOOK nsWindow::sCallMouseHook = nullptr;
bool nsWindow::sProcessHook = false;
UINT nsWindow::sRollupMsgId = 0;
HWND nsWindow::sRollupMsgWnd = nullptr;
UINT nsWindow::sHookTimerId = 0;
// Mouse Clicks - static variable definitions for figuring
// out 1 - 3 Clicks.
POINT nsWindow::sLastMousePoint = {0};
POINT nsWindow::sLastMouseMovePoint = {0};
LONG nsWindow::sLastMouseDownTime = 0L;
LONG nsWindow::sLastClickCount = 0L;
BYTE nsWindow::sLastMouseButton = 0;
bool nsWindow::sHaveInitializedPrefs = false;
TriStateBool nsWindow::sHasBogusPopupsDropShadowOnMultiMonitor = TRI_UNKNOWN;
WPARAM nsWindow::sMouseExitwParam = 0;
LPARAM nsWindow::sMouseExitlParamScreen = 0;
static SystemTimeConverter<DWORD>&
TimeConverter() {
static SystemTimeConverter<DWORD> timeConverterSingleton;
return timeConverterSingleton;
}
namespace mozilla {
class CurrentWindowsTimeGetter {
public:
explicit CurrentWindowsTimeGetter(HWND aWnd)
: mWnd(aWnd)
{
}
DWORD GetCurrentTime() const
{
return ::GetTickCount();
}
void GetTimeAsyncForPossibleBackwardsSkew(const TimeStamp& aNow)
{
DWORD currentTime = GetCurrentTime();
if (sBackwardsSkewStamp && currentTime == sLastPostTime) {
// There's already one inflight with this timestamp. Don't
// send a duplicate.
return;
}
sBackwardsSkewStamp = Some(aNow);
sLastPostTime = currentTime;
static_assert(sizeof(WPARAM) >= sizeof(DWORD), "Can't fit a DWORD in a WPARAM");
::PostMessage(mWnd, MOZ_WM_SKEWFIX, sLastPostTime, 0);
}
static bool GetAndClearBackwardsSkewStamp(DWORD aPostTime, TimeStamp* aOutSkewStamp)
{
if (aPostTime != sLastPostTime) {
// The SKEWFIX message is stale; we've sent a new one since then.
// Ignore this one.
return false;
}
MOZ_ASSERT(sBackwardsSkewStamp);
*aOutSkewStamp = sBackwardsSkewStamp.value();
sBackwardsSkewStamp = Nothing();
return true;
}
private:
static Maybe<TimeStamp> sBackwardsSkewStamp;
static DWORD sLastPostTime;
HWND mWnd;
};
Maybe<TimeStamp> CurrentWindowsTimeGetter::sBackwardsSkewStamp;
DWORD CurrentWindowsTimeGetter::sLastPostTime = 0;
} // namespace mozilla
/**************************************************************
*
* SECTION: globals variables
*
**************************************************************/
static const char *sScreenManagerContractID = "@mozilla.org/gfx/screenmanager;1";
extern mozilla::LazyLogModule gWindowsLog;
// Global used in Show window enumerations.
static bool gWindowsVisible = false;
// True if we have sent a notification that we are suspending/sleeping.
static bool gIsSleepMode = false;
static NS_DEFINE_CID(kCClipboardCID, NS_CLIPBOARD_CID);
// General purpose user32.dll hook object
static WindowsDllInterceptor sUser32Intercept;
// 2 pixel offset for eTransparencyBorderlessGlass which equals the size of
// the default window border Windows paints. Glass will be extended inward
// this distance to remove the border.
static const int32_t kGlassMarginAdjustment = 2;
// When the client area is extended out into the default window frame area,
// this is the minimum amount of space along the edge of resizable windows
// we will always display a resize cursor in, regardless of the underlying
// content.
static const int32_t kResizableBorderMinSize = 3;
// Cached pointer events enabler value, True if pointer events are enabled.
static bool gIsPointerEventsEnabled = false;
// True if we should use compositing for popup widgets.
static bool gIsPopupCompositingEnabled = false;
// We should never really try to accelerate windows bigger than this. In some
// cases this might lead to no D3D9 acceleration where we could have had it
// but D3D9 does not reliably report when it supports bigger windows. 8192
// is as safe as we can get, we know at least D3D10 hardware always supports
// this, other hardware we expect to report correctly in D3D9.
#define MAX_ACCELERATED_DIMENSION 8192
// On window open (as well as after), Windows has an unfortunate habit of
// sending rather a lot of WM_NCHITTEST messages. Because we have to do point
// to DOM target conversions for these, we cache responses for a given
// coordinate this many milliseconds:
#define HITTEST_CACHE_LIFETIME_MS 50
#if defined(ACCESSIBILITY)
namespace mozilla {
/**
* Windows touchscreen code works by setting a global WH_GETMESSAGE hook and
* injecting tiptsf.dll. The touchscreen process then posts registered messages
* to our main thread. The tiptsf hook picks up those registered messages and
* uses them as commands, some of which call into UIA, which then calls into
* MSAA, which then sends WM_GETOBJECT to us.
*
* We can get ahead of this by installing our own thread-local WH_GETMESSAGE
* hook. Since thread-local hooks are called ahead of global hooks, we will
* see these registered messages before tiptsf does. At this point we can then
* raise a flag that blocks a11y before invoking CallNextHookEx which will then
* invoke the global tiptsf hook. Then when we see WM_GETOBJECT, we check the
* flag by calling TIPMessageHandler::IsA11yBlocked().
*
* For Windows 8, we also hook tiptsf!ProcessCaretEvents, which is an a11y hook
* function that also calls into UIA.
*/
class TIPMessageHandler
{
public:
~TIPMessageHandler()
{
if (mHook) {
::UnhookWindowsHookEx(mHook);
}
}
static void Initialize()
{
if (!IsWin8OrLater()) {
return;
}
if (sInstance) {
return;
}
sInstance = new TIPMessageHandler();
ClearOnShutdown(&sInstance);
}
static bool IsA11yBlocked()
{
if (!sInstance) {
return false;
}
return sInstance->mA11yBlockCount > 0;
}
private:
TIPMessageHandler()
: mHook(nullptr)
, mA11yBlockCount(0)
{
MOZ_ASSERT(NS_IsMainThread());
// Registered messages used by tiptsf
mMessages[0] = ::RegisterWindowMessage(L"ImmersiveFocusNotification");
mMessages[1] = ::RegisterWindowMessage(L"TipCloseMenus");
mMessages[2] = ::RegisterWindowMessage(L"TabletInputPanelOpening");
mMessages[3] = ::RegisterWindowMessage(L"IHM Pen or Touch Event noticed");
mMessages[4] = ::RegisterWindowMessage(L"ProgrammabilityCaretVisibility");
mMessages[5] = ::RegisterWindowMessage(L"CaretTrackingUpdateIPHidden");
mMessages[6] = ::RegisterWindowMessage(L"CaretTrackingUpdateIPInfo");
mHook = ::SetWindowsHookEx(WH_GETMESSAGE, &TIPHook, nullptr,
::GetCurrentThreadId());
MOZ_ASSERT(mHook);
// On touchscreen devices, tiptsf.dll will have been loaded when STA COM was
// first initialized.
if (!IsWin10OrLater() && GetModuleHandle(L"tiptsf.dll") &&
!sProcessCaretEventsStub) {
sTipTsfInterceptor.Init("tiptsf.dll");
DebugOnly<bool> ok = sTipTsfInterceptor.AddHook("ProcessCaretEvents",
reinterpret_cast<intptr_t>(&ProcessCaretEventsHook),
(void**) &sProcessCaretEventsStub);
MOZ_ASSERT(ok);
}
if (!sSendMessageTimeoutWStub) {
sUser32Intercept.Init("user32.dll");
DebugOnly<bool> hooked = sUser32Intercept.AddHook("SendMessageTimeoutW",
reinterpret_cast<intptr_t>(&SendMessageTimeoutWHook),
(void**) &sSendMessageTimeoutWStub);
MOZ_ASSERT(hooked);
}
}
class MOZ_RAII A11yInstantiationBlocker
{
public:
A11yInstantiationBlocker()
{
if (!TIPMessageHandler::sInstance) {
return;
}
++TIPMessageHandler::sInstance->mA11yBlockCount;
}
~A11yInstantiationBlocker()
{
if (!TIPMessageHandler::sInstance) {
return;
}
MOZ_ASSERT(TIPMessageHandler::sInstance->mA11yBlockCount > 0);
--TIPMessageHandler::sInstance->mA11yBlockCount;
}
};
friend class A11yInstantiationBlocker;
static LRESULT CALLBACK TIPHook(int aCode, WPARAM aWParam, LPARAM aLParam)
{
if (aCode < 0 || !sInstance) {
return ::CallNextHookEx(nullptr, aCode, aWParam, aLParam);
}
MSG* msg = reinterpret_cast<MSG*>(aLParam);
UINT& msgCode = msg->message;
for (uint32_t i = 0; i < ArrayLength(sInstance->mMessages); ++i) {
if (msgCode == sInstance->mMessages[i]) {
A11yInstantiationBlocker block;
return ::CallNextHookEx(nullptr, aCode, aWParam, aLParam);
}
}
return ::CallNextHookEx(nullptr, aCode, aWParam, aLParam);
}
static void CALLBACK ProcessCaretEventsHook(HWINEVENTHOOK aWinEventHook,
DWORD aEvent, HWND aHwnd,
LONG aObjectId, LONG aChildId,
DWORD aGeneratingTid,
DWORD aEventTime)
{
A11yInstantiationBlocker block;
sProcessCaretEventsStub(aWinEventHook, aEvent, aHwnd, aObjectId, aChildId,
aGeneratingTid, aEventTime);
}
static LRESULT WINAPI SendMessageTimeoutWHook(HWND aHwnd, UINT aMsgCode,
WPARAM aWParam, LPARAM aLParam,
UINT aFlags, UINT aTimeout,
PDWORD_PTR aMsgResult)
{
// We don't want to handle this unless the message is a WM_GETOBJECT that we
// want to block, and the aHwnd is a nsWindow that belongs to the current
// thread.
if (!aMsgResult || aMsgCode != WM_GETOBJECT ||
static_cast<DWORD>(aLParam) != OBJID_CLIENT ||
!WinUtils::GetNSWindowPtr(aHwnd) ||
::GetWindowThreadProcessId(aHwnd, nullptr) != ::GetCurrentThreadId() ||
!IsA11yBlocked()) {
return sSendMessageTimeoutWStub(aHwnd, aMsgCode, aWParam, aLParam,
aFlags, aTimeout, aMsgResult);
}
// In this case we want to fake the result that would happen if we had
// decided not to handle WM_GETOBJECT in our WndProc. We hand the message
// off to DefWindowProc to accomplish this.
*aMsgResult = static_cast<DWORD_PTR>(::DefWindowProcW(aHwnd, aMsgCode,
aWParam, aLParam));
return static_cast<LRESULT>(TRUE);
}
static WindowsDllInterceptor sTipTsfInterceptor;
static WINEVENTPROC sProcessCaretEventsStub;
static decltype(&SendMessageTimeoutW) sSendMessageTimeoutWStub;
static StaticAutoPtr<TIPMessageHandler> sInstance;
HHOOK mHook;
UINT mMessages[7];
uint32_t mA11yBlockCount;
};
WindowsDllInterceptor TIPMessageHandler::sTipTsfInterceptor;
WINEVENTPROC TIPMessageHandler::sProcessCaretEventsStub;
decltype(&SendMessageTimeoutW) TIPMessageHandler::sSendMessageTimeoutWStub;
StaticAutoPtr<TIPMessageHandler> TIPMessageHandler::sInstance;
} // namespace mozilla
#endif // defined(ACCESSIBILITY)
/**************************************************************
**************************************************************
**
** BLOCK: nsIWidget impl.
**
** nsIWidget interface implementation, broken down into
** sections.
**
**************************************************************
**************************************************************/
/**************************************************************
*
* SECTION: nsWindow construction and destruction
*
**************************************************************/
nsWindow::nsWindow()
: nsWindowBase()
, mResizeState(NOT_RESIZING)
{
mIconSmall = nullptr;
mIconBig = nullptr;
mWnd = nullptr;
mTransitionWnd = nullptr;
mPaintDC = nullptr;
mPrevWndProc = nullptr;
mNativeDragTarget = nullptr;
mInDtor = false;
mIsVisible = false;
mIsTopWidgetWindow = false;
mUnicodeWidget = true;
mDisplayPanFeedback = false;
mTouchWindow = false;
mFutureMarginsToUse = false;
mCustomNonClient = false;
mHideChrome = false;
mFullscreenMode = false;
mMousePresent = false;
mDestroyCalled = false;
mHasTaskbarIconBeenCreated = false;
mMouseTransparent = false;
mPickerDisplayCount = 0;
mWindowType = eWindowType_child;
mBorderStyle = eBorderStyle_default;
mOldSizeMode = nsSizeMode_Normal;
mLastSizeMode = nsSizeMode_Normal;
mLastSize.width = 0;
mLastSize.height = 0;
mOldStyle = 0;
mOldExStyle = 0;
mPainting = 0;
mLastKeyboardLayout = 0;
mBlurSuppressLevel = 0;
mLastPaintEndTime = TimeStamp::Now();
mCachedHitTestPoint.x = 0;
mCachedHitTestPoint.y = 0;
mCachedHitTestTime = TimeStamp::Now();
mCachedHitTestResult = 0;
#ifdef MOZ_XUL
mTransparencyMode = eTransparencyOpaque;
memset(&mGlassMargins, 0, sizeof mGlassMargins);
#endif
DWORD background = ::GetSysColor(COLOR_BTNFACE);
mBrush = ::CreateSolidBrush(NSRGB_2_COLOREF(background));
mSendingSetText = false;
mDefaultScale = -1.0; // not yet set, will be calculated on first use
mTaskbarPreview = nullptr;
// Global initialization
if (!sInstanceCount) {
// Global app registration id for Win7 and up. See
// WinTaskbar.cpp for details.
mozilla::widget::WinTaskbar::RegisterAppUserModelID();
KeyboardLayout::GetInstance()->OnLayoutChange(::GetKeyboardLayout(0));
#if defined(ACCESSIBILITY)
mozilla::TIPMessageHandler::Initialize();
#endif // defined(ACCESSIBILITY)
IMEHandler::Initialize();
if (SUCCEEDED(::OleInitialize(nullptr))) {
sIsOleInitialized = TRUE;
}
NS_ASSERTION(sIsOleInitialized, "***** OLE is not initialized!\n");
MouseScrollHandler::Initialize();
// Init titlebar button info for custom frames.
nsUXThemeData::InitTitlebarInfo();
// Init theme data
nsUXThemeData::UpdateNativeThemeInfo();
RedirectedKeyDownMessageManager::Forget();
if (mPointerEvents.ShouldEnableInkCollector()) {
InkCollector::sInkCollector = new InkCollector();
}
Preferences::AddBoolVarCache(&gIsPointerEventsEnabled,
"dom.w3c_pointer_events.enabled",
gIsPointerEventsEnabled);
Preferences::AddBoolVarCache(&gIsPopupCompositingEnabled,
"layers.popups.compositing.enabled",
gIsPopupCompositingEnabled);
} // !sInstanceCount
mIdleService = nullptr;
mSizeConstraintsScale = GetDefaultScale().scale;
sInstanceCount++;
}
nsWindow::~nsWindow()
{
mInDtor = true;
// If the widget was released without calling Destroy() then the native window still
// exists, and we need to destroy it.
// Destroy() will early-return if it was already called. In any case it is important
// to call it before destroying mPresentLock (cf. 1156182).
Destroy();
// Free app icon resources. This must happen after `OnDestroy` (see bug 708033).
if (mIconSmall)
::DestroyIcon(mIconSmall);
if (mIconBig)
::DestroyIcon(mIconBig);
sInstanceCount--;
// Global shutdown
if (sInstanceCount == 0) {
if (InkCollector::sInkCollector) {
InkCollector::sInkCollector->Shutdown();
InkCollector::sInkCollector = nullptr;
}
IMEHandler::Terminate();
NS_IF_RELEASE(sCursorImgContainer);
if (sIsOleInitialized) {
::OleFlushClipboard();
::OleUninitialize();
sIsOleInitialized = FALSE;
}
}
NS_IF_RELEASE(mNativeDragTarget);
}
NS_IMPL_ISUPPORTS_INHERITED0(nsWindow, nsBaseWidget)
/**************************************************************
*
* SECTION: nsIWidget::Create, nsIWidget::Destroy
*
* Creating and destroying windows for this widget.
*
**************************************************************/
// Allow Derived classes to modify the height that is passed
// when the window is created or resized.
int32_t nsWindow::GetHeight(int32_t aProposedHeight)
{
return aProposedHeight;
}
static bool
ShouldCacheTitleBarInfo(nsWindowType aWindowType, nsBorderStyle aBorderStyle)
{
return (aWindowType == eWindowType_toplevel) &&
(aBorderStyle == eBorderStyle_default ||
aBorderStyle == eBorderStyle_all) &&
(!nsUXThemeData::sTitlebarInfoPopulatedThemed ||
!nsUXThemeData::sTitlebarInfoPopulatedAero);
}
// Create the proper widget
nsresult
nsWindow::Create(nsIWidget* aParent,
nsNativeWidget aNativeParent,
const LayoutDeviceIntRect& aRect,
nsWidgetInitData* aInitData)
{
nsWidgetInitData defaultInitData;
if (!aInitData)
aInitData = &defaultInitData;
mUnicodeWidget = aInitData->mUnicode;
nsIWidget *baseParent = aInitData->mWindowType == eWindowType_dialog ||
aInitData->mWindowType == eWindowType_toplevel ||
aInitData->mWindowType == eWindowType_invisible ?
nullptr : aParent;
mIsTopWidgetWindow = (nullptr == baseParent);
mBounds = aRect;
// Ensure that the toolkit is created.
nsToolkit::GetToolkit();
BaseCreate(baseParent, aInitData);
HWND parent;
if (aParent) { // has a nsIWidget parent
parent = aParent ? (HWND)aParent->GetNativeData(NS_NATIVE_WINDOW) : nullptr;
mParent = aParent;
} else { // has a nsNative parent
parent = (HWND)aNativeParent;
mParent = aNativeParent ?
WinUtils::GetNSWindowPtr((HWND)aNativeParent) : nullptr;
}
mIsRTL = aInitData->mRTL;
mOpeningAnimationSuppressed = aInitData->mIsAnimationSuppressed;
DWORD style = WindowStyle();
DWORD extendedStyle = WindowExStyle();
if (mWindowType == eWindowType_popup) {
if (!aParent) {
parent = nullptr;
}
if (!IsWin8OrLater() &&
HasBogusPopupsDropShadowOnMultiMonitor()) {
extendedStyle |= WS_EX_COMPOSITED;
}
if (aInitData->mMouseTransparent) {
// This flag makes the window transparent to mouse events
mMouseTransparent = true;
extendedStyle |= WS_EX_TRANSPARENT;
}
} else if (mWindowType == eWindowType_invisible) {
// Make sure CreateWindowEx succeeds at creating a toplevel window
style &= ~0x40000000; // WS_CHILDWINDOW
} else {
// See if the caller wants to explictly set clip children and clip siblings
if (aInitData->clipChildren) {
style |= WS_CLIPCHILDREN;
} else {
style &= ~WS_CLIPCHILDREN;
}
if (aInitData->clipSiblings) {
style |= WS_CLIPSIBLINGS;
}
}
const wchar_t* className;
if (aInitData->mDropShadow) {
className = GetWindowPopupClass();
} else {
className = GetWindowClass();
}
// Plugins are created in the disabled state so that they can't
// steal focus away from our main window. This is especially
// important if the plugin has loaded in a background tab.
if (aInitData->mWindowType == eWindowType_plugin ||
aInitData->mWindowType == eWindowType_plugin_ipc_chrome ||
aInitData->mWindowType == eWindowType_plugin_ipc_content) {
style |= WS_DISABLED;
}
mWnd = ::CreateWindowExW(extendedStyle,
className,
L"",
style,
aRect.x,
aRect.y,
aRect.width,
GetHeight(aRect.height),
parent,
nullptr,
nsToolkit::mDllInstance,
nullptr);
if (!mWnd) {
NS_WARNING("nsWindow CreateWindowEx failed.");
return NS_ERROR_FAILURE;
}
if (mIsRTL) {
DWORD dwAttribute = TRUE;
DwmSetWindowAttribute(mWnd, DWMWA_NONCLIENT_RTL_LAYOUT, &dwAttribute, sizeof dwAttribute);
}
if (mOpeningAnimationSuppressed) {
DWORD dwAttribute = TRUE;
DwmSetWindowAttribute(mWnd, DWMWA_TRANSITIONS_FORCEDISABLED,
&dwAttribute, sizeof dwAttribute);
}
if (!IsPlugin() &&
mWindowType != eWindowType_invisible &&
MouseScrollHandler::Device::IsFakeScrollableWindowNeeded()) {
// Ugly Thinkpad Driver Hack (Bugs 507222 and 594977)
//
// We create two zero-sized windows as descendants of the top-level window,
// like so:
//
// Top-level window (MozillaWindowClass)
// FAKETRACKPOINTSCROLLCONTAINER (MozillaWindowClass)
// FAKETRACKPOINTSCROLLABLE (MozillaWindowClass)
//
// We need to have the middle window, otherwise the Trackpoint driver
// will fail to deliver scroll messages. WM_MOUSEWHEEL messages are
// sent to the FAKETRACKPOINTSCROLLABLE, which then propagate up the
// window hierarchy until they are handled by nsWindow::WindowProc.
// WM_HSCROLL messages are also sent to the FAKETRACKPOINTSCROLLABLE,
// but these do not propagate automatically, so we have the window
// procedure pretend that they were dispatched to the top-level window
// instead.
//
// The FAKETRACKPOINTSCROLLABLE needs to have the specific window styles it
// is given below so that it catches the Trackpoint driver's heuristics.
HWND scrollContainerWnd = ::CreateWindowW
(className, L"FAKETRACKPOINTSCROLLCONTAINER",
WS_CHILD | WS_VISIBLE,
0, 0, 0, 0, mWnd, nullptr, nsToolkit::mDllInstance, nullptr);
HWND scrollableWnd = ::CreateWindowW
(className, L"FAKETRACKPOINTSCROLLABLE",
WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_TABSTOP | 0x30,
0, 0, 0, 0, scrollContainerWnd, nullptr, nsToolkit::mDllInstance,
nullptr);
// Give the FAKETRACKPOINTSCROLLABLE window a specific ID so that
// WindowProcInternal can distinguish it from the top-level window
// easily.
::SetWindowLongPtrW(scrollableWnd, GWLP_ID, eFakeTrackPointScrollableID);
// Make FAKETRACKPOINTSCROLLABLE use nsWindow::WindowProc, and store the
// old window procedure in its "user data".
WNDPROC oldWndProc;
if (mUnicodeWidget)
oldWndProc = (WNDPROC)::SetWindowLongPtrW(scrollableWnd, GWLP_WNDPROC,
(LONG_PTR)nsWindow::WindowProc);
else
oldWndProc = (WNDPROC)::SetWindowLongPtrA(scrollableWnd, GWLP_WNDPROC,
(LONG_PTR)nsWindow::WindowProc);
::SetWindowLongPtrW(scrollableWnd, GWLP_USERDATA, (LONG_PTR)oldWndProc);
}
SubclassWindow(TRUE);
// Starting with Windows XP, a process always runs within a terminal services
// session. In order to play nicely with RDP, fast user switching, and the
// lock screen, we should be handling WM_WTSSESSION_CHANGE. We must register
// our HWND in order to receive this message.
DebugOnly<BOOL> wtsRegistered = ::WTSRegisterSessionNotification(mWnd,
NOTIFY_FOR_THIS_SESSION);
NS_ASSERTION(wtsRegistered, "WTSRegisterSessionNotification failed!\n");
mDefaultIMC.Init(this);
IMEHandler::InitInputContext(this, mInputContext);
// Do some initialization work, but only if (a) it hasn't already been done,
// and (b) this is the hidden window (which is conveniently created before
// any visible windows but after the profile has been initialized).
if (!sHaveInitializedPrefs && mWindowType == eWindowType_invisible) {
sSwitchKeyboardLayout =
Preferences::GetBool("intl.keyboard.per_window_layout", false);
sHaveInitializedPrefs = true;
}
// Query for command button metric data for rendering the titlebar. We
// only do this once on the first window that has an actual titlebar
if (ShouldCacheTitleBarInfo(mWindowType, mBorderStyle)) {
nsUXThemeData::UpdateTitlebarInfo(mWnd);
}
static bool a11yPrimed = false;
if (!a11yPrimed &&
mWindowType == eWindowType_toplevel) {
a11yPrimed = true;
if (Preferences::GetInt("accessibility.force_disabled", 0) == -1) {
::PostMessage(mWnd, MOZ_WM_STARTA11Y, 0, 0);
}
}
return NS_OK;
}
// Close this nsWindow
void nsWindow::Destroy()
{
// WM_DESTROY has already fired, avoid calling it twice
if (mOnDestroyCalled)
return;
// Don't destroy windows that have file pickers open, we'll tear these down
// later once the picker is closed.
mDestroyCalled = true;
if (mPickerDisplayCount)
return;
// During the destruction of all of our children, make sure we don't get deleted.
nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
/**
* On windows the LayerManagerOGL destructor wants the widget to be around for
* cleanup. It also would like to have the HWND intact, so we nullptr it here.
*/
DestroyLayerManager();
/* We should clear our cached resources now and not wait for the GC to
* delete the nsWindow. */
ClearCachedResources();
// The DestroyWindow function destroys the specified window. The function sends WM_DESTROY
// and WM_NCDESTROY messages to the window to deactivate it and remove the keyboard focus
// from it. The function also destroys the window's menu, flushes the thread message queue,
// destroys timers, removes clipboard ownership, and breaks the clipboard viewer chain (if
// the window is at the top of the viewer chain).
//
// If the specified window is a parent or owner window, DestroyWindow automatically destroys
// the associated child or owned windows when it destroys the parent or owner window. The
// function first destroys child or owned windows, and then it destroys the parent or owner
// window.
VERIFY(::DestroyWindow(mWnd));
// Our windows can be subclassed which may prevent us receiving WM_DESTROY. If OnDestroy()
// didn't get called, call it now.
if (false == mOnDestroyCalled) {
MSGResult msgResult;
mWindowHook.Notify(mWnd, WM_DESTROY, 0, 0, msgResult);
OnDestroy();
}
}
/**************************************************************
*
* SECTION: Window class utilities
*
* Utilities for calculating the proper window class name for
* Create window.
*
**************************************************************/
const wchar_t*
nsWindow::RegisterWindowClass(const wchar_t* aClassName,
UINT aExtraStyle, LPWSTR aIconID) const
{
WNDCLASSW wc;
if (::GetClassInfoW(nsToolkit::mDllInstance, aClassName, &wc)) {
// already registered
return aClassName;
}
wc.style = CS_DBLCLKS | aExtraStyle;
wc.lpfnWndProc = WinUtils::GetDefWindowProc();
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = nsToolkit::mDllInstance;
wc.hIcon = aIconID ? ::LoadIconW(::GetModuleHandleW(nullptr), aIconID) : nullptr;
wc.hCursor = nullptr;
wc.hbrBackground = mBrush;
wc.lpszMenuName = nullptr;
wc.lpszClassName = aClassName;
if (!::RegisterClassW(&wc)) {
// For older versions of Win32 (i.e., not XP), the registration may
// fail with aExtraStyle, so we have to re-register without it.
wc.style = CS_DBLCLKS;
::RegisterClassW(&wc);
}
return aClassName;
}
static LPWSTR const gStockApplicationIcon = MAKEINTRESOURCEW(32512);
// Return the proper window class for everything except popups.
const wchar_t*
nsWindow::GetWindowClass() const
{
switch (mWindowType) {
case eWindowType_invisible:
return RegisterWindowClass(kClassNameHidden, 0, gStockApplicationIcon);
case eWindowType_dialog:
return RegisterWindowClass(kClassNameDialog, 0, 0);
default:
return RegisterWindowClass(GetMainWindowClass(), 0, gStockApplicationIcon);
}
}
// Return the proper popup window class
const wchar_t*
nsWindow::GetWindowPopupClass() const
{
return RegisterWindowClass(kClassNameDropShadow,
CS_XP_DROPSHADOW, gStockApplicationIcon);
}
/**************************************************************
*
* SECTION: Window styles utilities
*
* Return the proper windows styles and extended styles.
*
**************************************************************/
// Return nsWindow styles
DWORD nsWindow::WindowStyle()
{
DWORD style;
switch (mWindowType) {
case eWindowType_plugin:
case eWindowType_plugin_ipc_chrome:
case eWindowType_plugin_ipc_content:
case eWindowType_child:
style = WS_OVERLAPPED;
break;
case eWindowType_dialog:
style = WS_OVERLAPPED | WS_BORDER | WS_DLGFRAME | WS_SYSMENU | DS_3DLOOK |
DS_MODALFRAME | WS_CLIPCHILDREN;
if (mBorderStyle != eBorderStyle_default)
style |= WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
break;
case eWindowType_popup:
style = WS_POPUP;
if (!HasGlass()) {
style |= WS_OVERLAPPED;
}
break;
default:
NS_ERROR("unknown border style");
// fall through
case eWindowType_toplevel:
case eWindowType_invisible:
style = WS_OVERLAPPED | WS_BORDER | WS_DLGFRAME | WS_SYSMENU |
WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CLIPCHILDREN;
break;
}
if (mBorderStyle != eBorderStyle_default && mBorderStyle != eBorderStyle_all) {
if (mBorderStyle == eBorderStyle_none || !(mBorderStyle & eBorderStyle_border))
style &= ~WS_BORDER;
if (mBorderStyle == eBorderStyle_none || !(mBorderStyle & eBorderStyle_title)) {
style &= ~WS_DLGFRAME;
style |= WS_POPUP;
style &= ~WS_CHILD;
}
if (mBorderStyle == eBorderStyle_none || !(mBorderStyle & eBorderStyle_close))
style &= ~0;
// XXX The close box can only be removed by changing the window class,
// as far as I know --- roc+moz@cs.cmu.edu
if (mBorderStyle == eBorderStyle_none ||
!(mBorderStyle & (eBorderStyle_menu | eBorderStyle_close)))
style &= ~WS_SYSMENU;
// Looks like getting rid of the system menu also does away with the
// close box. So, we only get rid of the system menu if you want neither it
// nor the close box. How does the Windows "Dialog" window class get just
// closebox and no sysmenu? Who knows.
if (mBorderStyle == eBorderStyle_none || !(mBorderStyle & eBorderStyle_resizeh))
style &= ~WS_THICKFRAME;
if (mBorderStyle == eBorderStyle_none || !(mBorderStyle & eBorderStyle_minimize))
style &= ~WS_MINIMIZEBOX;
if (mBorderStyle == eBorderStyle_none || !(mBorderStyle & eBorderStyle_maximize))
style &= ~WS_MAXIMIZEBOX;
if (IsPopupWithTitleBar()) {
style |= WS_CAPTION;
if (mBorderStyle & eBorderStyle_close) {
style |= WS_SYSMENU;
}
}
}
VERIFY_WINDOW_STYLE(style);
return style;
}
// Return nsWindow extended styles
DWORD nsWindow::WindowExStyle()
{
switch (mWindowType)
{
case eWindowType_plugin:
case eWindowType_plugin_ipc_chrome:
case eWindowType_plugin_ipc_content:
case eWindowType_child:
return 0;
case eWindowType_dialog:
return WS_EX_WINDOWEDGE | WS_EX_DLGMODALFRAME;
case eWindowType_popup:
{
DWORD extendedStyle = WS_EX_TOOLWINDOW;
if (mPopupLevel == ePopupLevelTop)
extendedStyle |= WS_EX_TOPMOST;
return extendedStyle;
}
default:
NS_ERROR("unknown border style");
// fall through
case eWindowType_toplevel:
case eWindowType_invisible:
return WS_EX_WINDOWEDGE;
}
}
/**************************************************************
*
* SECTION: Window subclassing utilities
*
* Set or clear window subclasses on native windows. Used in
* Create and Destroy.
*
**************************************************************/
// Subclass (or remove the subclass from) this component's nsWindow
void nsWindow::SubclassWindow(BOOL bState)
{
if (bState) {
if (!mWnd || !IsWindow(mWnd)) {
NS_ERROR("Invalid window handle");
}
if (mUnicodeWidget) {
mPrevWndProc =
reinterpret_cast<WNDPROC>(
SetWindowLongPtrW(mWnd,
GWLP_WNDPROC,
reinterpret_cast<LONG_PTR>(nsWindow::WindowProc)));
} else {
mPrevWndProc =
reinterpret_cast<WNDPROC>(
SetWindowLongPtrA(mWnd,
GWLP_WNDPROC,
reinterpret_cast<LONG_PTR>(nsWindow::WindowProc)));
}
NS_ASSERTION(mPrevWndProc, "Null standard window procedure");
// connect the this pointer to the nsWindow handle
WinUtils::SetNSWindowBasePtr(mWnd, this);
} else {
if (IsWindow(mWnd)) {
if (mUnicodeWidget) {
SetWindowLongPtrW(mWnd,
GWLP_WNDPROC,
reinterpret_cast<LONG_PTR>(mPrevWndProc));
} else {
SetWindowLongPtrA(mWnd,
GWLP_WNDPROC,
reinterpret_cast<LONG_PTR>(mPrevWndProc));
}
}
WinUtils::SetNSWindowBasePtr(mWnd, nullptr);
mPrevWndProc = nullptr;
}
}
/**************************************************************
*
* SECTION: nsIWidget::SetParent, nsIWidget::GetParent
*
* Set or clear the parent widgets using window properties, and
* handles calculating native parent handles.
*
**************************************************************/
// Get and set parent widgets
void
nsWindow::SetParent(nsIWidget *aNewParent)
{
nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
nsIWidget* parent = GetParent();
if (parent) {
parent->RemoveChild(this);
}
mParent = aNewParent;
if (aNewParent) {
ReparentNativeWidget(aNewParent);
aNewParent->AddChild(this);
return;
}
if (mWnd) {
// If we have no parent, SetParent should return the desktop.
VERIFY(::SetParent(mWnd, nullptr));
}
}
void
nsWindow::ReparentNativeWidget(nsIWidget* aNewParent)
{
NS_PRECONDITION(aNewParent, "");
mParent = aNewParent;
if (mWindowType == eWindowType_popup) {
return;
}
HWND newParent = (HWND)aNewParent->GetNativeData(NS_NATIVE_WINDOW);
NS_ASSERTION(newParent, "Parent widget has a null native window handle");
if (newParent && mWnd) {
::SetParent(mWnd, newParent);
}
}
nsIWidget* nsWindow::GetParent(void)
{
if (mIsTopWidgetWindow) {
return nullptr;
}
if (mInDtor || mOnDestroyCalled) {
return nullptr;
}
return mParent;
}
static int32_t RoundDown(double aDouble)
{
return aDouble > 0 ? static_cast<int32_t>(floor(aDouble)) :
static_cast<int32_t>(ceil(aDouble));
}
float nsWindow::GetDPI()
{
HDC dc = ::GetDC(mWnd);
if (!dc)
return 96.0f;
double heightInches = ::GetDeviceCaps(dc, VERTSIZE)/MM_PER_INCH_FLOAT;
int heightPx = ::GetDeviceCaps(dc, VERTRES);
::ReleaseDC(mWnd, dc);
if (heightInches < 0.25) {
// Something's broken
return 96.0f;
}
return float(heightPx/heightInches);
}
double nsWindow::GetDefaultScaleInternal()
{
if (mDefaultScale <= 0.0) {
mDefaultScale = WinUtils::LogToPhysFactor(mWnd);
}
return mDefaultScale;
}
int32_t nsWindow::LogToPhys(double aValue)
{
return WinUtils::LogToPhys(::MonitorFromWindow(mWnd,
MONITOR_DEFAULTTOPRIMARY),
aValue);
}
nsWindow*
nsWindow::GetParentWindow(bool aIncludeOwner)
{
return static_cast<nsWindow*>(GetParentWindowBase(aIncludeOwner));
}
nsWindowBase*
nsWindow::GetParentWindowBase(bool aIncludeOwner)
{
if (mIsTopWidgetWindow) {
// Must use a flag instead of mWindowType to tell if the window is the
// owned by the topmost widget, because a child window can be embedded inside
// a HWND which is not associated with a nsIWidget.
return nullptr;
}
// If this widget has already been destroyed, pretend we have no parent.
// This corresponds to code in Destroy which removes the destroyed
// widget from its parent's child list.
if (mInDtor || mOnDestroyCalled)
return nullptr;
// aIncludeOwner set to true implies walking the parent chain to retrieve the
// root owner. aIncludeOwner set to false implies the search will stop at the
// true parent (default).
nsWindow* widget = nullptr;
if (mWnd) {
HWND parent = nullptr;
if (aIncludeOwner)
parent = ::GetParent(mWnd);
else
parent = ::GetAncestor(mWnd, GA_PARENT);
if (parent) {
widget = WinUtils::GetNSWindowPtr(parent);
if (widget) {
// If the widget is in the process of being destroyed then
// do NOT return it
if (widget->mInDtor) {
widget = nullptr;
}
}
}
}
return static_cast<nsWindowBase*>(widget);
}
BOOL CALLBACK
nsWindow::EnumAllChildWindProc(HWND aWnd, LPARAM aParam)
{
nsWindow *wnd = WinUtils::GetNSWindowPtr(aWnd);
if (wnd) {
reinterpret_cast<nsTArray<nsWindow*>*>(aParam)->AppendElement(wnd);
}
return TRUE;
}
BOOL CALLBACK
nsWindow::EnumAllThreadWindowProc(HWND aWnd, LPARAM aParam)
{
nsWindow *wnd = WinUtils::GetNSWindowPtr(aWnd);
if (wnd) {
reinterpret_cast<nsTArray<nsWindow*>*>(aParam)->AppendElement(wnd);
}
EnumChildWindows(aWnd, EnumAllChildWindProc, aParam);
return TRUE;
}
/* static*/ nsTArray<nsWindow*>
nsWindow::EnumAllWindows()
{
nsTArray<nsWindow*> windows;
EnumThreadWindows(GetCurrentThreadId(),
EnumAllThreadWindowProc,
reinterpret_cast<LPARAM>(&windows));
return windows;
}
static already_AddRefed<SourceSurface>
CreateSourceSurfaceForGfxSurface(gfxASurface* aSurface)
{
MOZ_ASSERT(aSurface);
return Factory::CreateSourceSurfaceForCairoSurface(
aSurface->CairoSurface(), aSurface->GetSize(),
aSurface->GetSurfaceFormat());
}
nsWindow::ScrollSnapshot*
nsWindow::EnsureSnapshotSurface(ScrollSnapshot& aSnapshotData,
const mozilla::gfx::IntSize& aSize)
{
// If the surface doesn't exist or is the wrong size then create new one.
if (!aSnapshotData.surface || aSnapshotData.surface->GetSize() != aSize) {
aSnapshotData.surface = new gfxWindowsSurface(aSize, kScrollCaptureFormat);
aSnapshotData.surfaceHasSnapshot = false;
}
return &aSnapshotData;
}
already_AddRefed<SourceSurface>
nsWindow::CreateScrollSnapshot()
{
RECT clip = { 0 };
int rgnType = ::GetWindowRgnBox(mWnd, &clip);
if (rgnType == RGN_ERROR) {
// We failed to get the clip assume that we need a full fallback.
clip.left = 0;
clip.top = 0;
clip.right = mBounds.width;
clip.bottom = mBounds.height;
return GetFallbackScrollSnapshot(clip);
}
// Check that the window is in a position to snapshot. We don't check for
// clipped width as that doesn't currently matter for APZ scrolling.
if (clip.top || clip.bottom != mBounds.height) {
return GetFallbackScrollSnapshot(clip);
}
HDC windowDC = ::GetDC(mWnd);
if (!windowDC) {
return GetFallbackScrollSnapshot(clip);
}
auto releaseDC = MakeScopeExit([&] {
::ReleaseDC(mWnd, windowDC);
});
gfx::IntSize snapshotSize(mBounds.width, mBounds.height);
ScrollSnapshot* snapshot;
if (clip.left || clip.right != mBounds.width) {
// Can't do a full snapshot, so use the partial snapshot.
snapshot = EnsureSnapshotSurface(mPartialSnapshot, snapshotSize);
} else {
snapshot = EnsureSnapshotSurface(mFullSnapshot, snapshotSize);
}
// Note that we know that the clip is full height.
if (!::BitBlt(snapshot->surface->GetDC(), clip.left, 0, clip.right - clip.left,
clip.bottom, windowDC, clip.left, 0, SRCCOPY)) {
return GetFallbackScrollSnapshot(clip);
}
::GdiFlush();
snapshot->surface->Flush();
snapshot->surfaceHasSnapshot = true;
snapshot->clip = clip;
mCurrentSnapshot = snapshot;
return CreateSourceSurfaceForGfxSurface(mCurrentSnapshot->surface);
}
already_AddRefed<SourceSurface>
nsWindow::GetFallbackScrollSnapshot(const RECT& aRequiredClip)
{
gfx::IntSize snapshotSize(mBounds.width, mBounds.height);
// If the current snapshot is the correct size and covers the required clip,
// just keep that by returning null.
// Note: we know the clip is always full height.
if (mCurrentSnapshot &&
mCurrentSnapshot->surface->GetSize() == snapshotSize &&
mCurrentSnapshot->clip.left <= aRequiredClip.left &&
mCurrentSnapshot->clip.right >= aRequiredClip.right) {
return nullptr;
}
// Otherwise we'll use the full snapshot, making sure it is big enough first.
mCurrentSnapshot = EnsureSnapshotSurface(mFullSnapshot, snapshotSize);
// If there is no snapshot, create a default.
if (!mCurrentSnapshot->surfaceHasSnapshot) {
gfx::SurfaceFormat format = mCurrentSnapshot->surface->GetSurfaceFormat();
RefPtr<DrawTarget> dt = Factory::CreateDrawTargetForCairoSurface(
mCurrentSnapshot->surface->CairoSurface(),
mCurrentSnapshot->surface->GetSize(), &format);
DefaultFillScrollCapture(dt);
}
return CreateSourceSurfaceForGfxSurface(mCurrentSnapshot->surface);
}
/**************************************************************
*
* SECTION: nsIWidget::Show
*
* Hide or show this component.
*
**************************************************************/
void
nsWindow::Show(bool bState)
{
if (mWindowType == eWindowType_popup) {
// See bug 603793. When we try to draw D3D9/10 windows with a drop shadow
// without the DWM on a secondary monitor, windows fails to composite
// our windows correctly. We therefor switch off the drop shadow for
// pop-up windows when the DWM is disabled and two monitors are
// connected.
if (HasBogusPopupsDropShadowOnMultiMonitor() &&
WinUtils::GetMonitorCount() > 1 &&
!nsUXThemeData::CheckForCompositor())
{
if (sDropShadowEnabled) {
::SetClassLongA(mWnd, GCL_STYLE, 0);
sDropShadowEnabled = false;
}
} else {
if (!sDropShadowEnabled) {
::SetClassLongA(mWnd, GCL_STYLE, CS_DROPSHADOW);
sDropShadowEnabled = true;
}
}
// WS_EX_COMPOSITED conflicts with the WS_EX_LAYERED style and causes
// some popup menus to become invisible.
LONG_PTR exStyle = ::GetWindowLongPtrW(mWnd, GWL_EXSTYLE);
if (exStyle & WS_EX_LAYERED) {
::SetWindowLongPtrW(mWnd, GWL_EXSTYLE, exStyle & ~WS_EX_COMPOSITED);
}
}
bool syncInvalidate = false;
bool wasVisible = mIsVisible;
// Set the status now so that anyone asking during ShowWindow or
// SetWindowPos would get the correct answer.
mIsVisible = bState;
// We may have cached an out of date visible state. This can happen
// when session restore sets the full screen mode.
if (mIsVisible)
mOldStyle |= WS_VISIBLE;
else
mOldStyle &= ~WS_VISIBLE;
if (!mIsVisible && wasVisible) {
ClearCachedResources();
}
if (mWnd) {
if (bState) {
if (!wasVisible && mWindowType == eWindowType_toplevel) {
// speed up the initial paint after show for
// top level windows:
syncInvalidate = true;
switch (mSizeMode) {
case nsSizeMode_Fullscreen:
::ShowWindow(mWnd, SW_SHOW);
break;
case nsSizeMode_Maximized :
::ShowWindow(mWnd, SW_SHOWMAXIMIZED);
break;
case nsSizeMode_Minimized :
::ShowWindow(mWnd, SW_SHOWMINIMIZED);
break;
default:
if (CanTakeFocus()) {
::ShowWindow(mWnd, SW_SHOWNORMAL);
} else {
::ShowWindow(mWnd, SW_SHOWNOACTIVATE);
Unused << GetAttention(2);
}
break;
}
} else {
DWORD flags = SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW;
if (wasVisible)
flags |= SWP_NOZORDER;
if (mWindowType == eWindowType_popup) {
// ensure popups are the topmost of the TOPMOST
// layer. Remember not to set the SWP_NOZORDER
// flag as that might allow the taskbar to overlap
// the popup.
flags |= SWP_NOACTIVATE;
HWND owner = ::GetWindow(mWnd, GW_OWNER);
::SetWindowPos(mWnd, owner ? 0 : HWND_TOPMOST, 0, 0, 0, 0, flags);
} else {
if (mWindowType == eWindowType_dialog && !CanTakeFocus())
flags |= SWP_NOACTIVATE;
::SetWindowPos(mWnd, HWND_TOP, 0, 0, 0, 0, flags);
}
}
if (!wasVisible && (mWindowType == eWindowType_toplevel || mWindowType == eWindowType_dialog)) {
// when a toplevel window or dialog is shown, initialize the UI state
::SendMessageW(mWnd, WM_CHANGEUISTATE, MAKEWPARAM(UIS_INITIALIZE, UISF_HIDEFOCUS | UISF_HIDEACCEL), 0);
}
} else {
// Clear contents to avoid ghosting of old content if we display
// this window again.
if (wasVisible && mTransparencyMode == eTransparencyTransparent) {
if (mCompositorWidgetDelegate) {
mCompositorWidgetDelegate->ClearTransparentWindow();
}
}
if (mWindowType != eWindowType_dialog) {
::ShowWindow(mWnd, SW_HIDE);
} else {
::SetWindowPos(mWnd, 0, 0, 0, 0, 0, SWP_HIDEWINDOW | SWP_NOSIZE | SWP_NOMOVE |
SWP_NOZORDER | SWP_NOACTIVATE);
}
}
}
#ifdef MOZ_XUL
if (!wasVisible && bState) {
Invalidate();
if (syncInvalidate && !mInDtor && !mOnDestroyCalled) {
::UpdateWindow(mWnd);
}
}
#endif
if (mOpeningAnimationSuppressed) {
DWORD dwAttribute = FALSE;
DwmSetWindowAttribute(mWnd, DWMWA_TRANSITIONS_FORCEDISABLED,
&dwAttribute, sizeof dwAttribute);
}
}
/**************************************************************
*
* SECTION: nsIWidget::IsVisible
*
* Returns the visibility state.
*
**************************************************************/
// Return true if the whether the component is visible, false otherwise
bool nsWindow::IsVisible() const
{
return mIsVisible;
}
/**************************************************************
*
* SECTION: Window clipping utilities
*
* Used in Size and Move operations for setting the proper
* window clipping regions for window transparency.
*
**************************************************************/
// XP and Vista visual styles sometimes require window clipping regions to be applied for proper
// transparency. These routines are called on size and move operations.
// XXX this is apparently still needed in Windows 7 and later
void nsWindow::ClearThemeRegion()
{
if (!HasGlass() &&
(mWindowType == eWindowType_popup && !IsPopupWithTitleBar() &&
(mPopupType == ePopupTypeTooltip || mPopupType == ePopupTypePanel))) {
SetWindowRgn(mWnd, nullptr, false);
}
}
void nsWindow::SetThemeRegion()
{
// Popup types that have a visual styles region applied (bug 376408). This can be expanded
// for other window types as needed. The regions are applied generically to the base window
// so default constants are used for part and state. At some point we might need part and
// state values from nsNativeThemeWin's GetThemePartAndState, but currently windows that
// change shape based on state haven't come up.
if (!HasGlass() &&
(mWindowType == eWindowType_popup && !IsPopupWithTitleBar() &&
(mPopupType == ePopupTypeTooltip || mPopupType == ePopupTypePanel))) {
HRGN hRgn = nullptr;
RECT rect = {0,0,mBounds.width,mBounds.height};
HDC dc = ::GetDC(mWnd);
GetThemeBackgroundRegion(nsUXThemeData::GetTheme(eUXTooltip), dc, TTP_STANDARD, TS_NORMAL, &rect, &hRgn);
if (hRgn) {
if (!SetWindowRgn(mWnd, hRgn, false)) // do not delete or alter hRgn if accepted.
DeleteObject(hRgn);
}
::ReleaseDC(mWnd, dc);
}
}
/**************************************************************
*
* SECTION: Touch and APZ-related functions
*
**************************************************************/
void nsWindow::RegisterTouchWindow() {
mTouchWindow = true;
mGesture.RegisterTouchWindow(mWnd);
::EnumChildWindows(mWnd, nsWindow::RegisterTouchForDescendants, 0);
}
BOOL CALLBACK nsWindow::RegisterTouchForDescendants(HWND aWnd, LPARAM aMsg) {
nsWindow* win = WinUtils::GetNSWindowPtr(aWnd);
if (win)
win->mGesture.RegisterTouchWindow(aWnd);
return TRUE;
}
/**************************************************************
*
* SECTION: nsIWidget::Move, nsIWidget::Resize,
* nsIWidget::Size, nsIWidget::BeginResizeDrag
*
* Repositioning and sizing a window.
*
**************************************************************/
void
nsWindow::SetSizeConstraints(const SizeConstraints& aConstraints)
{
SizeConstraints c = aConstraints;
if (mWindowType != eWindowType_popup) {
c.mMinSize.width = std::max(int32_t(::GetSystemMetrics(SM_CXMINTRACK)), c.mMinSize.width);
c.mMinSize.height = std::max(int32_t(::GetSystemMetrics(SM_CYMINTRACK)), c.mMinSize.height);
}
KnowsCompositor* knowsCompositor = GetLayerManager()->AsKnowsCompositor();
if (knowsCompositor) {
int32_t maxSize = knowsCompositor->GetMaxTextureSize();
// We can't make ThebesLayers bigger than this anyway.. no point it letting
// a window grow bigger as we won't be able to draw content there in
// general.
c.mMaxSize.width = std::min(c.mMaxSize.width, maxSize);
c.mMaxSize.height = std::min(c.mMaxSize.height, maxSize);
}
mSizeConstraintsScale = GetDefaultScale().scale;
nsBaseWidget::SetSizeConstraints(c);
}
const SizeConstraints
nsWindow::GetSizeConstraints()
{
double scale = GetDefaultScale().scale;
if (mSizeConstraintsScale == scale || mSizeConstraintsScale == 0.0) {
return mSizeConstraints;
}
scale /= mSizeConstraintsScale;
SizeConstraints c = mSizeConstraints;
if (c.mMinSize.width != NS_MAXSIZE) {
c.mMinSize.width = NSToIntRound(c.mMinSize.width * scale);
}
if (c.mMinSize.height != NS_MAXSIZE) {
c.mMinSize.height = NSToIntRound(c.mMinSize.height * scale);
}
if (c.mMaxSize.width != NS_MAXSIZE) {
c.mMaxSize.width = NSToIntRound(c.mMaxSize.width * scale);
}
if (c.mMaxSize.height != NS_MAXSIZE) {
c.mMaxSize.height = NSToIntRound(c.mMaxSize.height * scale);
}
return c;
}
// Move this component
void
nsWindow::Move(double aX, double aY)
{
if (mWindowType == eWindowType_toplevel ||
mWindowType == eWindowType_dialog) {
SetSizeMode(nsSizeMode_Normal);
}
// for top-level windows only, convert coordinates from desktop pixels
// (the "parent" coordinate space) to the window's device pixel space
double scale = BoundsUseDesktopPixels() ? GetDesktopToDeviceScale().scale : 1.0;
int32_t x = NSToIntRound(aX * scale);
int32_t y = NSToIntRound(aY * scale);
// Check to see if window needs to be moved first
// to avoid a costly call to SetWindowPos. This check
// can not be moved to the calling code in nsView, because
// some platforms do not position child windows correctly
// Only perform this check for non-popup windows, since the positioning can
// in fact change even when the x/y do not. We always need to perform the
// check. See bug #97805 for details.
if (mWindowType != eWindowType_popup && (mBounds.x == x) && (mBounds.y == y))
{
// Nothing to do, since it is already positioned correctly.
return;
}
mBounds.x = x;
mBounds.y = y;
if (mWnd) {
#ifdef DEBUG
// complain if a window is moved offscreen (legal, but potentially worrisome)
if (mIsTopWidgetWindow) { // only a problem for top-level windows
// Make sure this window is actually on the screen before we move it
// XXX: Needs multiple monitor support
HDC dc = ::GetDC(mWnd);
if (dc) {
if (::GetDeviceCaps(dc, TECHNOLOGY) == DT_RASDISPLAY) {
RECT workArea;
::SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);
// no annoying assertions. just mention the issue.
if (x < 0 || x >= workArea.right || y < 0 || y >= workArea.bottom) {
MOZ_LOG(gWindowsLog, LogLevel::Info,
("window moved to offscreen position\n"));
}
}
::ReleaseDC(mWnd, dc);
}
}
#endif
ClearThemeRegion();
UINT flags = SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOSIZE;
// Workaround SetWindowPos bug with D3D9. If our window has a clip
// region, some drivers or OSes may incorrectly copy into the clipped-out
// area.
if (IsPlugin() &&
!mLayerManager &&
mClipRects &&
(mClipRectCount != 1 || !mClipRects[0].IsEqualInterior(LayoutDeviceIntRect(0, 0, mBounds.width, mBounds.height)))) {
flags |= SWP_NOCOPYBITS;
}
double oldScale = mDefaultScale;
mResizeState = IN_SIZEMOVE;
VERIFY(::SetWindowPos(mWnd, nullptr, x, y, 0, 0, flags));
mResizeState = NOT_RESIZING;
if (WinUtils::LogToPhysFactor(mWnd) != oldScale) {
ChangedDPI();
}
SetThemeRegion();
}
NotifyRollupGeometryChange();
}
// Resize this component
void
nsWindow::Resize(double aWidth, double aHeight, bool aRepaint)
{
// for top-level windows only, convert coordinates from desktop pixels
// (the "parent" coordinate space) to the window's device pixel space
double scale = BoundsUseDesktopPixels() ? GetDesktopToDeviceScale().scale : 1.0;
int32_t width = NSToIntRound(aWidth * scale);
int32_t height = NSToIntRound(aHeight * scale);
NS_ASSERTION((width >= 0) , "Negative width passed to nsWindow::Resize");
NS_ASSERTION((height >= 0), "Negative height passed to nsWindow::Resize");
ConstrainSize(&width, &height);
// Avoid unnecessary resizing calls
if (mBounds.width == width && mBounds.height == height) {
if (aRepaint) {
Invalidate();
}
return;
}
// Set cached value for lightweight and printing
mBounds.width = width;
mBounds.height = height;
if (mWnd) {
UINT flags = SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE;
if (!aRepaint) {
flags |= SWP_NOREDRAW;
}
ClearThemeRegion();
double oldScale = mDefaultScale;
VERIFY(::SetWindowPos(mWnd, nullptr, 0, 0,
width, GetHeight(height), flags));
if (WinUtils::LogToPhysFactor(mWnd) != oldScale) {
ChangedDPI();
}
SetThemeRegion();
}
if (aRepaint)
Invalidate();
NotifyRollupGeometryChange();
}
// Resize this component
void
nsWindow::Resize(double aX, double aY, double aWidth,
double aHeight, bool aRepaint)
{
// for top-level windows only, convert coordinates from desktop pixels
// (the "parent" coordinate space) to the window's device pixel space
double scale = BoundsUseDesktopPixels() ? GetDesktopToDeviceScale().scale : 1.0;
int32_t x = NSToIntRound(aX * scale);
int32_t y = NSToIntRound(aY * scale);
int32_t width = NSToIntRound(aWidth * scale);
int32_t height = NSToIntRound(aHeight * scale);
NS_ASSERTION((width >= 0), "Negative width passed to nsWindow::Resize");
NS_ASSERTION((height >= 0), "Negative height passed to nsWindow::Resize");
ConstrainSize(&width, &height);
// Avoid unnecessary resizing calls
if (mBounds.x == x && mBounds.y == y &&
mBounds.width == width && mBounds.height == height) {
if (aRepaint) {
Invalidate();
}
return;
}
// Set cached value for lightweight and printing
mBounds.x = x;
mBounds.y = y;
mBounds.width = width;
mBounds.height = height;
if (mWnd) {
UINT flags = SWP_NOZORDER | SWP_NOACTIVATE;
if (!aRepaint) {
flags |= SWP_NOREDRAW;
}
ClearThemeRegion();
double oldScale = mDefaultScale;
VERIFY(::SetWindowPos(mWnd, nullptr, x, y,
width, GetHeight(height), flags));
if (WinUtils::LogToPhysFactor(mWnd) != oldScale) {
ChangedDPI();
}
if (mTransitionWnd) {
// If we have a fullscreen transition window, we need to make
// it topmost again, otherwise the taskbar may be raised by
// the system unexpectedly when we leave fullscreen state.
::SetWindowPos(mTransitionWnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
// Every transition window is only used once.
mTransitionWnd = nullptr;
}
SetThemeRegion();
}
if (aRepaint)
Invalidate();
NotifyRollupGeometryChange();
}
nsresult
nsWindow::BeginResizeDrag(WidgetGUIEvent* aEvent,
int32_t aHorizontal,
int32_t aVertical)
{
NS_ENSURE_ARG_POINTER(aEvent);
if (aEvent->mClass != eMouseEventClass) {
// you can only begin a resize drag with a mouse event
return NS_ERROR_INVALID_ARG;
}
if (aEvent->AsMouseEvent()->button != WidgetMouseEvent::eLeftButton) {
// you can only begin a resize drag with the left mouse button
return NS_ERROR_INVALID_ARG;
}
// work out what sizemode we're talking about
WPARAM syscommand;
if (aVertical < 0) {
if (aHorizontal < 0) {
syscommand = SC_SIZE | WMSZ_TOPLEFT;
} else if (aHorizontal == 0) {
syscommand = SC_SIZE | WMSZ_TOP;
} else {
syscommand = SC_SIZE | WMSZ_TOPRIGHT;
}
} else if (aVertical == 0) {
if (aHorizontal < 0) {
syscommand = SC_SIZE | WMSZ_LEFT;
} else if (aHorizontal == 0) {
return NS_ERROR_INVALID_ARG;
} else {
syscommand = SC_SIZE | WMSZ_RIGHT;
}
} else {
if (aHorizontal < 0) {
syscommand = SC_SIZE | WMSZ_BOTTOMLEFT;
} else if (aHorizontal == 0) {
syscommand = SC_SIZE | WMSZ_BOTTOM;
} else {
syscommand = SC_SIZE | WMSZ_BOTTOMRIGHT;
}
}
// resizing doesn't work if the mouse is already captured
CaptureMouse(false);
// find the top-level window
HWND toplevelWnd = WinUtils::GetTopLevelHWND(mWnd, true);
// tell Windows to start the resize
::PostMessage(toplevelWnd, WM_SYSCOMMAND, syscommand,
POINTTOPOINTS(aEvent->mRefPoint));
return NS_OK;
}
/**************************************************************
*
* SECTION: Window Z-order and state.
*
* nsIWidget::PlaceBehind, nsIWidget::SetSizeMode,
* nsIWidget::ConstrainPosition
*
* Z-order, positioning, restore, minimize, and maximize.
*
**************************************************************/
// Position the window behind the given window
void
nsWindow::PlaceBehind(nsTopLevelWidgetZPlacement aPlacement,
nsIWidget *aWidget, bool aActivate)
{
HWND behind = HWND_TOP;
if (aPlacement == eZPlacementBottom)
behind = HWND_BOTTOM;
else if (aPlacement == eZPlacementBelow && aWidget)
behind = (HWND)aWidget->GetNativeData(NS_NATIVE_WINDOW);
UINT flags = SWP_NOMOVE | SWP_NOREPOSITION | SWP_NOSIZE;
if (!aActivate)
flags |= SWP_NOACTIVATE;
if (!CanTakeFocus() && behind == HWND_TOP)
{
// Can't place the window to top so place it behind the foreground window
// (as long as it is not topmost)
HWND wndAfter = ::GetForegroundWindow();
if (!wndAfter)
behind = HWND_BOTTOM;
else if (!(GetWindowLongPtrW(wndAfter, GWL_EXSTYLE) & WS_EX_TOPMOST))
behind = wndAfter;
flags |= SWP_NOACTIVATE;
}
::SetWindowPos(mWnd, behind, 0, 0, 0, 0, flags);
}
static UINT
GetCurrentShowCmd(HWND aWnd)
{
WINDOWPLACEMENT pl;
pl.length = sizeof(pl);
::GetWindowPlacement(aWnd, &pl);
return pl.showCmd;
}
// Maximize, minimize or restore the window.
void
nsWindow::SetSizeMode(nsSizeMode aMode)
{
// Let's not try and do anything if we're already in that state.
// (This is needed to prevent problems when calling window.minimize(), which
// calls us directly, and then the OS triggers another call to us.)
if (aMode == mSizeMode)
return;
// save the requested state
mLastSizeMode = mSizeMode;
nsBaseWidget::SetSizeMode(aMode);
if (mIsVisible) {
int mode;
switch (aMode) {
case nsSizeMode_Fullscreen :
mode = SW_SHOW;
break;
case nsSizeMode_Maximized :
mode = SW_MAXIMIZE;
break;
case nsSizeMode_Minimized :
mode = SW_MINIMIZE;
break;
default :
mode = SW_RESTORE;
}
// Don't call ::ShowWindow if we're trying to "restore" a window that is
// already in a normal state. Prevents a bug where snapping to one side
// of the screen and then minimizing would cause Windows to forget our
// window's correct restored position/size.
if(!(GetCurrentShowCmd(mWnd) == SW_SHOWNORMAL && mode == SW_RESTORE)) {
::ShowWindow(mWnd, mode);
}
// we activate here to ensure that the right child window is focused
if (mode == SW_MAXIMIZE || mode == SW_SHOW)
DispatchFocusToTopLevelWindow(true);
}
}
// Constrain a potential move to fit onscreen
// Position (aX, aY) is specified in Windows screen (logical) pixels,
// except when using per-monitor DPI, in which case it's device pixels.
void
nsWindow::ConstrainPosition(bool aAllowSlop, int32_t *aX, int32_t *aY)
{
if (!mIsTopWidgetWindow) // only a problem for top-level windows
return;
double dpiScale = GetDesktopToDeviceScale().scale;
// We need to use the window size in the kind of pixels used for window-
// manipulation APIs.
int32_t logWidth = std::max<int32_t>(NSToIntRound(mBounds.width / dpiScale), 1);
int32_t logHeight = std::max<int32_t>(NSToIntRound(mBounds.height / dpiScale), 1);
/* get our playing field. use the current screen, or failing that
for any reason, use device caps for the default screen. */
RECT screenRect;
nsCOMPtr<nsIScreenManager> screenmgr = do_GetService(sScreenManagerContractID);
if (!screenmgr) {
return;
}
nsCOMPtr<nsIScreen> screen;
int32_t left, top, width, height;
screenmgr->ScreenForRect(*aX, *aY, logWidth, logHeight,
getter_AddRefs(screen));
if (mSizeMode != nsSizeMode_Fullscreen) {
// For normalized windows, use the desktop work area.
nsresult rv = screen->GetAvailRectDisplayPix(&left, &top, &width, &height);
if (NS_FAILED(rv)) {
return;
}
} else {
// For full screen windows, use the desktop.
nsresult rv = screen->GetRectDisplayPix(&left, &top, &width, &height);
if (NS_FAILED(rv)) {
return;
}
}
screenRect.left = left;
screenRect.right = left + width;
screenRect.top = top;
screenRect.bottom = top + height;
if (aAllowSlop) {
if (*aX < screenRect.left - logWidth + kWindowPositionSlop)
*aX = screenRect.left - logWidth + kWindowPositionSlop;
else if (*aX >= screenRect.right - kWindowPositionSlop)
*aX = screenRect.right - kWindowPositionSlop;
if (*aY < screenRect.top - logHeight + kWindowPositionSlop)
*aY = screenRect.top - logHeight + kWindowPositionSlop;
else if (*aY >= screenRect.bottom - kWindowPositionSlop)
*aY = screenRect.bottom - kWindowPositionSlop;
} else {
if (*aX < screenRect.left)
*aX = screenRect.left;
else if (*aX >= screenRect.right - logWidth)
*aX = screenRect.right - logWidth;
if (*aY < screenRect.top)
*aY = screenRect.top;
else if (*aY >= screenRect.bottom - logHeight)
*aY = screenRect.bottom - logHeight;
}
}
/**************************************************************
*
* SECTION: nsIWidget::Enable, nsIWidget::IsEnabled
*
* Enabling and disabling the widget.
*
**************************************************************/
// Enable/disable this component
void
nsWindow::Enable(bool bState)
{
if (mWnd) {
::EnableWindow(mWnd, bState);
}
}
// Return the current enable state
bool nsWindow::IsEnabled() const
{
return !mWnd ||
(::IsWindowEnabled(mWnd) &&
::IsWindowEnabled(::GetAncestor(mWnd, GA_ROOT)));
}
/**************************************************************
*
* SECTION: nsIWidget::SetFocus
*
* Give the focus to this widget.
*
**************************************************************/
nsresult
nsWindow::SetFocus(bool aRaise)
{
if (mWnd) {
#ifdef WINSTATE_DEBUG_OUTPUT
if (mWnd == WinUtils::GetTopLevelHWND(mWnd)) {
MOZ_LOG(gWindowsLog, LogLevel::Info,
("*** SetFocus: [ top] raise=%d\n", aRaise));
} else {
MOZ_LOG(gWindowsLog, LogLevel::Info,
("*** SetFocus: [child] raise=%d\n", aRaise));
}
#endif
// Uniconify, if necessary
HWND toplevelWnd = WinUtils::GetTopLevelHWND(mWnd);
if (aRaise && ::IsIconic(toplevelWnd)) {
::ShowWindow(toplevelWnd, SW_RESTORE);
}
::SetFocus(mWnd);
}
return NS_OK;
}
/**************************************************************
*
* SECTION: Bounds
*
* GetBounds, GetClientBounds, GetScreenBounds,
* GetRestoredBounds, GetClientOffset
* SetDrawsInTitlebar, SetNonClientMargins
*
* Bound calculations.
*
**************************************************************/
// Return the window's full dimensions in screen coordinates.
// If the window has a parent, converts the origin to an offset
// of the parent's screen origin.
LayoutDeviceIntRect
nsWindow::GetBounds()
{
if (!mWnd) {
return mBounds;
}
RECT r;
VERIFY(::GetWindowRect(mWnd, &r));
LayoutDeviceIntRect rect;
// assign size
rect.width = r.right - r.left;
rect.height = r.bottom - r.top;
// popup window bounds' are in screen coordinates, not relative to parent
// window
if (mWindowType == eWindowType_popup) {
rect.x = r.left;
rect.y = r.top;
return rect;
}
// chrome on parent:
// ___ 5,5 (chrome start)
// | ____ 10,10 (client start)
// | | ____ 20,20 (child start)
// | | |
// 20,20 - 5,5 = 15,15 (??)
// minus GetClientOffset:
// 15,15 - 5,5 = 10,10
//
// no chrome on parent:
// ______ 10,10 (win start)
// | ____ 20,20 (child start)
// | |
// 20,20 - 10,10 = 10,10
//
// walking the chain:
// ___ 5,5 (chrome start)
// | ___ 10,10 (client start)
// | | ___ 20,20 (child start)
// | | | __ 30,30 (child start)
// | | | |
// 30,30 - 20,20 = 10,10 (offset from second child to first)
// 20,20 - 5,5 = 15,15 + 10,10 = 25,25 (??)
// minus GetClientOffset:
// 25,25 - 5,5 = 20,20 (offset from second child to parent client)
// convert coordinates if parent exists
HWND parent = ::GetParent(mWnd);
if (parent) {
RECT pr;
VERIFY(::GetWindowRect(parent, &pr));
r.left -= pr.left;
r.top -= pr.top;
// adjust for chrome
nsWindow* pWidget = static_cast<nsWindow*>(GetParent());
if (pWidget && pWidget->IsTopLevelWidget()) {
LayoutDeviceIntPoint clientOffset = pWidget->GetClientOffset();
r.left -= clientOffset.x;
r.top -= clientOffset.y;
}
}
rect.x = r.left;
rect.y = r.top;
return rect;
}
// Get this component dimension
LayoutDeviceIntRect
nsWindow::GetClientBounds()
{
if (!mWnd) {
return LayoutDeviceIntRect(0, 0, 0, 0);
}
RECT r;
VERIFY(::GetClientRect(mWnd, &r));
LayoutDeviceIntRect bounds = GetBounds();
LayoutDeviceIntRect rect;
rect.MoveTo(bounds.TopLeft() + GetClientOffset());
rect.width = r.right - r.left;
rect.height = r.bottom - r.top;
return rect;
}
// Like GetBounds, but don't offset by the parent
LayoutDeviceIntRect
nsWindow::GetScreenBounds()
{
if (!mWnd) {
return mBounds;
}
RECT r;
VERIFY(::GetWindowRect(mWnd, &r));
LayoutDeviceIntRect rect;
rect.x = r.left;
rect.y = r.top;
rect.width = r.right - r.left;
rect.height = r.bottom - r.top;
return rect;
}
nsresult
nsWindow::GetRestoredBounds(LayoutDeviceIntRect &aRect)
{
if (SizeMode() == nsSizeMode_Normal) {
aRect = GetScreenBounds();
return NS_OK;
}
if (!mWnd) {
return NS_ERROR_FAILURE;
}
WINDOWPLACEMENT pl = { sizeof(WINDOWPLACEMENT) };
VERIFY(::GetWindowPlacement(mWnd, &pl));
const RECT& r = pl.rcNormalPosition;
HMONITOR monitor = ::MonitorFromWindow(mWnd, MONITOR_DEFAULTTONULL);
if (!monitor) {
return NS_ERROR_FAILURE;
}
MONITORINFO mi = { sizeof(MONITORINFO) };
VERIFY(::GetMonitorInfo(monitor, &mi));
aRect.SetRect(r.left, r.top, r.right - r.left, r.bottom - r.top);
aRect.MoveBy(mi.rcWork.left - mi.rcMonitor.left,
mi.rcWork.top - mi.rcMonitor.top);
return NS_OK;
}
// Return the x,y offset of the client area from the origin of the window. If
// the window is borderless returns (0,0).
LayoutDeviceIntPoint
nsWindow::GetClientOffset()
{
if (!mWnd) {
return LayoutDeviceIntPoint(0, 0);
}
RECT r1;
GetWindowRect(mWnd, &r1);
LayoutDeviceIntPoint pt = WidgetToScreenOffset();
return LayoutDeviceIntPoint(pt.x - r1.left, pt.y - r1.top);
}
void
nsWindow::SetDrawsInTitlebar(bool aState)
{
nsWindow * window = GetTopLevelWindow(true);
if (window && window != this) {
return window->SetDrawsInTitlebar(aState);
}
if (aState) {
// top, right, bottom, left for nsIntMargin
LayoutDeviceIntMargin margins(0, -1, -1, -1);
SetNonClientMargins(margins);
}
else {
LayoutDeviceIntMargin margins(-1, -1, -1, -1);
SetNonClientMargins(margins);
}
}
void
nsWindow::ResetLayout()
{
// This will trigger a frame changed event, triggering
// nc calc size and a sizemode gecko event.
SetWindowPos(mWnd, 0, 0, 0, 0, 0,
SWP_FRAMECHANGED|SWP_NOACTIVATE|SWP_NOMOVE|
SWP_NOOWNERZORDER|SWP_NOSIZE|SWP_NOZORDER);
// If hidden, just send the frame changed event for now.
if (!mIsVisible)
return;
// Send a gecko size event to trigger reflow.
RECT clientRc = {0};
GetClientRect(mWnd, &clientRc);
nsIntRect evRect(WinUtils::ToIntRect(clientRc));
OnResize(evRect);
// Invalidate and update
Invalidate();
}
// Internally track the caption status via a window property. Required
// due to our internal handling of WM_NCACTIVATE when custom client
// margins are set.
static const wchar_t kManageWindowInfoProperty[] = L"ManageWindowInfoProperty";
typedef BOOL (WINAPI *GetWindowInfoPtr)(HWND hwnd, PWINDOWINFO pwi);
static GetWindowInfoPtr sGetWindowInfoPtrStub = nullptr;
BOOL WINAPI
GetWindowInfoHook(HWND hWnd, PWINDOWINFO pwi)
{
if (!sGetWindowInfoPtrStub) {
NS_ASSERTION(FALSE, "Something is horribly wrong in GetWindowInfoHook!");
return FALSE;
}
int windowStatus =
reinterpret_cast<LONG_PTR>(GetPropW(hWnd, kManageWindowInfoProperty));
// No property set, return the default data.
if (!windowStatus)
return sGetWindowInfoPtrStub(hWnd, pwi);
// Call GetWindowInfo and update dwWindowStatus with our
// internally tracked value.
BOOL result = sGetWindowInfoPtrStub(hWnd, pwi);
if (result && pwi)
pwi->dwWindowStatus = (windowStatus == 1 ? 0 : WS_ACTIVECAPTION);
return result;
}
void
nsWindow::UpdateGetWindowInfoCaptionStatus(bool aActiveCaption)
{
if (!mWnd)
return;
if (!sGetWindowInfoPtrStub) {
sUser32Intercept.Init("user32.dll");
if (!sUser32Intercept.AddHook("GetWindowInfo", reinterpret_cast<intptr_t>(GetWindowInfoHook),
(void**) &sGetWindowInfoPtrStub))
return;
}
// Update our internally tracked caption status
SetPropW(mWnd, kManageWindowInfoProperty,
reinterpret_cast<HANDLE>(static_cast<INT_PTR>(aActiveCaption) + 1));
}
/**
* Called when the window layout changes: full screen mode transitions,
* theme changes, and composition changes. Calculates the new non-client
* margins and fires off a frame changed event, which triggers an nc calc
* size windows event, kicking the changes in.
*
* The offsets calculated here are based on the value of `mNonClientMargins`
* which is specified in the "chromemargins" attribute of the window. For
* each margin, the value specified has the following meaning:
* -1 - leave the default frame in place
* 0 - remove the frame
* >0 - frame size equals min(0, (default frame size - margin value))
*
* This function calculates and populates `mNonClientOffset`.
* In our processing of `WM_NCCALCSIZE`, the frame size will be calculated
* as (default frame size - offset). For example, if the left frame should
* be 1 pixel narrower than the default frame size, `mNonClientOffset.left`
* will equal 1.
*
* For maximized, fullscreen, and minimized windows, the values stored in
* `mNonClientMargins` are ignored, and special processing takes place.
*
* For non-glass windows, we only allow frames to be their default size
* or removed entirely.
*/
bool
nsWindow::UpdateNonClientMargins(int32_t aSizeMode, bool aReflowWindow)
{
if (!mCustomNonClient)
return false;
if (aSizeMode == -1) {
aSizeMode = mSizeMode;
}
bool hasCaption = (mBorderStyle
& (eBorderStyle_all
| eBorderStyle_title
| eBorderStyle_menu
| eBorderStyle_default));
// mCaptionHeight is the default size of the NC area at
// the top of the window. If the window has a caption,
// the size is calculated as the sum of:
// SM_CYFRAME - The thickness of the sizing border
// around a resizable window
// SM_CXPADDEDBORDER - The amount of border padding
// for captioned windows
// SM_CYCAPTION - The height of the caption area
//
// If the window does not have a caption, mCaptionHeight will be equal to
// `GetSystemMetrics(SM_CYFRAME)`
mCaptionHeight = GetSystemMetrics(SM_CYFRAME)
+ (hasCaption ? GetSystemMetrics(SM_CYCAPTION)
+ GetSystemMetrics(SM_CXPADDEDBORDER)
: 0);
// mHorResizeMargin is the size of the default NC areas on the
// left and right sides of our window. It is calculated as
// the sum of:
// SM_CXFRAME - The thickness of the sizing border
// SM_CXPADDEDBORDER - The amount of border padding
// for captioned windows
//
// If the window does not have a caption, mHorResizeMargin will be equal to
// `GetSystemMetrics(SM_CXFRAME)`
mHorResizeMargin = GetSystemMetrics(SM_CXFRAME)
+ (hasCaption ? GetSystemMetrics(SM_CXPADDEDBORDER) : 0);
// mVertResizeMargin is the size of the default NC area at the
// bottom of the window. It is calculated as the sum of:
// SM_CYFRAME - The thickness of the sizing border
// SM_CXPADDEDBORDER - The amount of border padding
// for captioned windows.
//
// If the window does not have a caption, mVertResizeMargin will be equal to
// `GetSystemMetrics(SM_CYFRAME)`
mVertResizeMargin = GetSystemMetrics(SM_CYFRAME)
+ (hasCaption ? GetSystemMetrics(SM_CXPADDEDBORDER) : 0);
if (aSizeMode == nsSizeMode_Minimized) {
// Use default frame size for minimized windows
mNonClientOffset.top = 0;
mNonClientOffset.left = 0;
mNonClientOffset.right = 0;
mNonClientOffset.bottom = 0;
} else if (aSizeMode == nsSizeMode_Fullscreen) {
// Remove the default frame from the top of our fullscreen window. This
// makes the whole caption part of our client area, allowing us to draw
// in the whole caption area. Additionally remove the default frame from
// the left, right, and bottom.
mNonClientOffset.top = mCaptionHeight;
mNonClientOffset.bottom = mVertResizeMargin;
mNonClientOffset.left = mHorResizeMargin;
mNonClientOffset.right = mHorResizeMargin;
} else if (aSizeMode == nsSizeMode_Maximized) {
// Remove the default frame from the top of our maximized window. This
// makes the whole caption part of our client area, allowing us to draw
// in the whole caption area. Use default frame size on left, right, and
// bottom. The reason this works is that, for maximized windows,
// Windows positions them so that their frames fall off the screen.
// This gives the illusion of windows having no frames when they are
// maximized. If we try to mess with the frame sizes by setting these
// offsets to positive values, our client area will fall off the screen.
mNonClientOffset.top = mCaptionHeight;
mNonClientOffset.bottom = 0;
mNonClientOffset.left = 0;
mNonClientOffset.right = 0;
APPBARDATA appBarData;
appBarData.cbSize = sizeof(appBarData);
UINT taskbarState = SHAppBarMessage(ABM_GETSTATE, &appBarData);
if (ABS_AUTOHIDE & taskbarState) {
UINT edge = -1;
appBarData.hWnd = FindWindow(L"Shell_TrayWnd", nullptr);
if (appBarData.hWnd) {
HMONITOR taskbarMonitor = ::MonitorFromWindow(appBarData.hWnd,
MONITOR_DEFAULTTOPRIMARY);
HMONITOR windowMonitor = ::MonitorFromWindow(mWnd,
MONITOR_DEFAULTTONEAREST);
if (taskbarMonitor == windowMonitor) {
SHAppBarMessage(ABM_GETTASKBARPOS, &appBarData);
edge = appBarData.uEdge;
}
}
if (ABE_LEFT == edge) {
mNonClientOffset.left -= 1;
} else if (ABE_RIGHT == edge) {
mNonClientOffset.right -= 1;
} else if (ABE_BOTTOM == edge || ABE_TOP == edge) {
mNonClientOffset.bottom -= 1;
}
}
} else {
bool glass = nsUXThemeData::CheckForCompositor();
// We're dealing with a "normal" window (not maximized, minimized, or
// fullscreen), so process `mNonClientMargins` and set `mNonClientOffset`
// accordingly.
//
// Setting `mNonClientOffset` to 0 has the effect of leaving the default
// frame intact. Setting it to a value greater than 0 reduces the frame
// size by that amount.
if (mNonClientMargins.top > 0 && glass) {
mNonClientOffset.top = std::min(mCaptionHeight, mNonClientMargins.top);
} else if (mNonClientMargins.top == 0) {
mNonClientOffset.top = mCaptionHeight;
} else {
mNonClientOffset.top = 0;
}
if (mNonClientMargins.bottom > 0 && glass) {
mNonClientOffset.bottom = std::min(mVertResizeMargin, mNonClientMargins.bottom);
} else if (mNonClientMargins.bottom == 0) {
mNonClientOffset.bottom = mVertResizeMargin;
} else {
mNonClientOffset.bottom = 0;
}
if (mNonClientMargins.left > 0 && glass) {
mNonClientOffset.left = std::min(mHorResizeMargin, mNonClientMargins.left);
} else if (mNonClientMargins.left == 0) {
mNonClientOffset.left = mHorResizeMargin;
} else {
mNonClientOffset.left = 0;
}
if (mNonClientMargins.right > 0 && glass) {
mNonClientOffset.right = std::min(mHorResizeMargin, mNonClientMargins.right);
} else if (mNonClientMargins.right == 0) {
mNonClientOffset.right = mHorResizeMargin;
} else {
mNonClientOffset.right = 0;
}
}
if (aReflowWindow) {
// Force a reflow of content based on the new client
// dimensions.
ResetLayout();
}
return true;
}
nsresult
nsWindow::SetNonClientMargins(LayoutDeviceIntMargin &margins)
{
if (!mIsTopWidgetWindow ||
mBorderStyle == eBorderStyle_none)
return NS_ERROR_INVALID_ARG;
if (mHideChrome) {
mFutureMarginsOnceChromeShows = margins;
mFutureMarginsToUse = true;
return NS_OK;
}
mFutureMarginsToUse = false;
// Request for a reset
if (margins.top == -1 && margins.left == -1 &&
margins.right == -1 && margins.bottom == -1) {
mCustomNonClient = false;
mNonClientMargins = margins;
// Force a reflow of content based on the new client
// dimensions.
ResetLayout();
int windowStatus =
reinterpret_cast<LONG_PTR>(GetPropW(mWnd, kManageWindowInfoProperty));
if (windowStatus) {
::SendMessageW(mWnd, WM_NCACTIVATE, 1 != windowStatus, 0);
}
return NS_OK;
}
if (margins.top < -1 || margins.bottom < -1 ||
margins.left < -1 || margins.right < -1)
return NS_ERROR_INVALID_ARG;
mNonClientMargins = margins;
mCustomNonClient = true;
if (!UpdateNonClientMargins()) {
NS_WARNING("UpdateNonClientMargins failed!");
return NS_OK;
}
return NS_OK;
}
void
nsWindow::InvalidateNonClientRegion()
{
// +-+-----------------------+-+
// | | app non-client chrome | |
// | +-----------------------+ |
// | | app client chrome | | }
// | +-----------------------+ | }
// | | app content | | } area we don't want to invalidate
// | +-----------------------+ | }
// | | app client chrome | | }
// | +-----------------------+ |
// +---------------------------+ <
// ^ ^ windows non-client chrome
// client area = app *
RECT rect;
GetWindowRect(mWnd, &rect);
MapWindowPoints(nullptr, mWnd, (LPPOINT)&rect, 2);
HRGN winRgn = CreateRectRgnIndirect(&rect);
// Subtract app client chrome and app content leaving
// windows non-client chrome and app non-client chrome
// in winRgn.
GetWindowRect(mWnd, &rect);
rect.top += mCaptionHeight;
rect.right -= mHorResizeMargin;
rect.bottom -= mHorResizeMargin;
rect.left += mVertResizeMargin;
MapWindowPoints(nullptr, mWnd, (LPPOINT)&rect, 2);
HRGN clientRgn = CreateRectRgnIndirect(&rect);
CombineRgn(winRgn, winRgn, clientRgn, RGN_DIFF);
DeleteObject(clientRgn);
// triggers ncpaint and paint events for the two areas
RedrawWindow(mWnd, nullptr, winRgn, RDW_FRAME | RDW_INVALIDATE);
DeleteObject(winRgn);
}
HRGN
nsWindow::ExcludeNonClientFromPaintRegion(HRGN aRegion)
{
RECT rect;
HRGN rgn = nullptr;
if (aRegion == (HRGN)1) { // undocumented value indicating a full refresh
GetWindowRect(mWnd, &rect);
rgn = CreateRectRgnIndirect(&rect);
} else {
rgn = aRegion;
}
GetClientRect(mWnd, &rect);
MapWindowPoints(mWnd, nullptr, (LPPOINT)&rect, 2);
HRGN nonClientRgn = CreateRectRgnIndirect(&rect);
CombineRgn(rgn, rgn, nonClientRgn, RGN_DIFF);
DeleteObject(nonClientRgn);
return rgn;
}
/**************************************************************
*
* SECTION: nsIWidget::SetBackgroundColor
*
* Sets the window background paint color.
*
**************************************************************/
void nsWindow::SetBackgroundColor(const nscolor &aColor)
{
if (mBrush)
::DeleteObject(mBrush);
mBrush = ::CreateSolidBrush(NSRGB_2_COLOREF(aColor));
if (mWnd != nullptr) {
::SetClassLongPtrW(mWnd, GCLP_HBRBACKGROUND, (LONG_PTR)mBrush);
}
}
/**************************************************************
*
* SECTION: nsIWidget::SetCursor
*
* SetCursor and related utilities for manging cursor state.
*
**************************************************************/
// Set this component cursor
void
nsWindow::SetCursor(nsCursor aCursor)
{
// Only change cursor if it's changing
//XXX mCursor isn't always right. Scrollbars and others change it, too.
//XXX If we want this optimization we need a better way to do it.
//if (aCursor != mCursor) {
HCURSOR newCursor = nullptr;
switch (aCursor) {
case eCursor_select:
newCursor = ::LoadCursor(nullptr, IDC_IBEAM);
break;
case eCursor_wait:
newCursor = ::LoadCursor(nullptr, IDC_WAIT);
break;
case eCursor_hyperlink:
{
newCursor = ::LoadCursor(nullptr, IDC_HAND);
break;
}
case eCursor_standard:
case eCursor_context_menu: // XXX See bug 258960.
newCursor = ::LoadCursor(nullptr, IDC_ARROW);
break;
case eCursor_n_resize:
case eCursor_s_resize:
newCursor = ::LoadCursor(nullptr, IDC_SIZENS);
break;
case eCursor_w_resize:
case eCursor_e_resize:
newCursor = ::LoadCursor(nullptr, IDC_SIZEWE);
break;
case eCursor_nw_resize:
case eCursor_se_resize:
newCursor = ::LoadCursor(nullptr, IDC_SIZENWSE);
break;
case eCursor_ne_resize:
case eCursor_sw_resize:
newCursor = ::LoadCursor(nullptr, IDC_SIZENESW);
break;
case eCursor_crosshair:
newCursor = ::LoadCursor(nullptr, IDC_CROSS);
break;
case eCursor_move:
newCursor = ::LoadCursor(nullptr, IDC_SIZEALL);
break;
case eCursor_help:
newCursor = ::LoadCursor(nullptr, IDC_HELP);
break;
case eCursor_copy: // CSS3
newCursor = ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_COPY));
break;
case eCursor_alias:
newCursor = ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_ALIAS));
break;
case eCursor_cell:
newCursor = ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_CELL));
break;
case eCursor_grab:
newCursor = ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_GRAB));
break;
case eCursor_grabbing:
newCursor = ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_GRABBING));
break;
case eCursor_spinning:
newCursor = ::LoadCursor(nullptr, IDC_APPSTARTING);
break;
case eCursor_zoom_in:
newCursor = ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_ZOOMIN));
break;
case eCursor_zoom_out:
newCursor = ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_ZOOMOUT));
break;
case eCursor_not_allowed:
case eCursor_no_drop:
newCursor = ::LoadCursor(nullptr, IDC_NO);
break;
case eCursor_col_resize:
newCursor = ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_COLRESIZE));
break;
case eCursor_row_resize:
newCursor = ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_ROWRESIZE));
break;
case eCursor_vertical_text:
newCursor = ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_VERTICALTEXT));
break;
case eCursor_all_scroll:
// XXX not 100% appropriate perhaps
newCursor = ::LoadCursor(nullptr, IDC_SIZEALL);
break;
case eCursor_nesw_resize:
newCursor = ::LoadCursor(nullptr, IDC_SIZENESW);
break;
case eCursor_nwse_resize:
newCursor = ::LoadCursor(nullptr, IDC_SIZENWSE);
break;
case eCursor_ns_resize:
newCursor = ::LoadCursor(nullptr, IDC_SIZENS);
break;
case eCursor_ew_resize:
newCursor = ::LoadCursor(nullptr, IDC_SIZEWE);
break;
case eCursor_none:
newCursor = ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_NONE));
break;
default:
NS_ERROR("Invalid cursor type");
break;
}
if (nullptr != newCursor) {
mCursor = aCursor;
HCURSOR oldCursor = ::SetCursor(newCursor);
if (sHCursor == oldCursor) {
NS_IF_RELEASE(sCursorImgContainer);
if (sHCursor != nullptr)
::DestroyIcon(sHCursor);
sHCursor = nullptr;
}
}
}
// Setting the actual cursor
nsresult
nsWindow::SetCursor(imgIContainer* aCursor,
uint32_t aHotspotX, uint32_t aHotspotY)
{
if (sCursorImgContainer == aCursor && sHCursor) {
::SetCursor(sHCursor);
return NS_OK;
}
int32_t width;
int32_t height;
nsresult rv;
rv = aCursor->GetWidth(&width);
NS_ENSURE_SUCCESS(rv, rv);
rv = aCursor->GetHeight(&height);
NS_ENSURE_SUCCESS(rv, rv);
// Reject cursors greater than 128 pixels in either direction, to prevent
// spoofing.
// XXX ideally we should rescale. Also, we could modify the API to
// allow trusted content to set larger cursors.
if (width > 128 || height > 128)
return NS_ERROR_NOT_AVAILABLE;
HCURSOR cursor;
double scale = GetDefaultScale().scale;
IntSize size = RoundedToInt(Size(width * scale, height * scale));
rv = nsWindowGfx::CreateIcon(aCursor, true, aHotspotX, aHotspotY, size, &cursor);
NS_ENSURE_SUCCESS(rv, rv);
mCursor = nsCursor(-1);
::SetCursor(cursor);
NS_IF_RELEASE(sCursorImgContainer);
sCursorImgContainer = aCursor;
NS_ADDREF(sCursorImgContainer);
if (sHCursor != nullptr)
::DestroyIcon(sHCursor);
sHCursor = cursor;
return NS_OK;
}
/**************************************************************
*
* SECTION: nsIWidget::Get/SetTransparencyMode
*
* Manage the transparency mode of the window containing this
* widget. Only works for popup and dialog windows when the
* Desktop Window Manager compositor is not enabled.
*
**************************************************************/
#ifdef MOZ_XUL
nsTransparencyMode nsWindow::GetTransparencyMode()
{
return GetTopLevelWindow(true)->GetWindowTranslucencyInner();
}
void nsWindow::SetTransparencyMode(nsTransparencyMode aMode)
{
nsWindow* window = GetTopLevelWindow(true);
MOZ_ASSERT(window);
if (!window || window->DestroyCalled()) {
return;
}
if (nsWindowType::eWindowType_toplevel == window->mWindowType &&
mTransparencyMode != aMode &&
!nsUXThemeData::CheckForCompositor()) {
NS_WARNING("Cannot set transparency mode on top-level windows.");
return;
}
window->SetWindowTranslucencyInner(aMode);
}
void nsWindow::UpdateOpaqueRegion(const LayoutDeviceIntRegion& aOpaqueRegion)
{
if (!HasGlass() || GetParent())
return;
// If there is no opaque region or hidechrome=true, set margins
// to support a full sheet of glass. Comments in MSDN indicate
// all values must be set to -1 to get a full sheet of glass.
MARGINS margins = { -1, -1, -1, -1 };
if (!aOpaqueRegion.IsEmpty()) {
LayoutDeviceIntRect pluginBounds;
for (nsIWidget* child = GetFirstChild(); child; child = child->GetNextSibling()) {
if (child->IsPlugin()) {
// Collect the bounds of all plugins for GetLargestRectangle.
LayoutDeviceIntRect childBounds = child->GetBounds();
pluginBounds.UnionRect(pluginBounds, childBounds);
}
}
LayoutDeviceIntRect clientBounds = GetClientBounds();
// Find the largest rectangle and use that to calculate the inset. Our top
// priority is to include the bounds of all plugins.
LayoutDeviceIntRect largest =
aOpaqueRegion.GetLargestRectangle(pluginBounds);
margins.cxLeftWidth = largest.x;
margins.cxRightWidth = clientBounds.width - largest.XMost();
margins.cyBottomHeight = clientBounds.height - largest.YMost();
if (mCustomNonClient) {
// The minimum glass height must be the caption buttons height,
// otherwise the buttons are drawn incorrectly.
largest.y = std::max<uint32_t>(largest.y,
nsUXThemeData::sCommandButtons[CMDBUTTONIDX_BUTTONBOX].cy);
}
margins.cyTopHeight = largest.y;
}
// Only update glass area if there are changes
if (memcmp(&mGlassMargins, &margins, sizeof mGlassMargins)) {
mGlassMargins = margins;
UpdateGlass();
}
}
/**************************************************************
*
* SECTION: nsIWidget::UpdateWindowDraggingRegion
*
* For setting the draggable titlebar region from CSS
* with -moz-window-dragging: drag.
*
**************************************************************/
void
nsWindow::UpdateWindowDraggingRegion(const LayoutDeviceIntRegion& aRegion)
{
if (mDraggableRegion != aRegion) {
mDraggableRegion = aRegion;
}
}
void nsWindow::UpdateGlass()
{
MARGINS margins = mGlassMargins;
// DWMNCRP_USEWINDOWSTYLE - The non-client rendering area is
// rendered based on the window style.
// DWMNCRP_ENABLED - The non-client area rendering is
// enabled; the window style is ignored.
DWMNCRENDERINGPOLICY policy = DWMNCRP_USEWINDOWSTYLE;
switch (mTransparencyMode) {
case eTransparencyBorderlessGlass:
// Only adjust if there is some opaque rectangle
if (margins.cxLeftWidth >= 0) {
margins.cxLeftWidth += kGlassMarginAdjustment;
margins.cyTopHeight += kGlassMarginAdjustment;
margins.cxRightWidth += kGlassMarginAdjustment;
margins.cyBottomHeight += kGlassMarginAdjustment;
}
// Fall through
case eTransparencyGlass:
policy = DWMNCRP_ENABLED;
break;
default:
break;
}
MOZ_LOG(gWindowsLog, LogLevel::Info,
("glass margins: left:%d top:%d right:%d bottom:%d\n",
margins.cxLeftWidth, margins.cyTopHeight,
margins.cxRightWidth, margins.cyBottomHeight));
// Extends the window frame behind the client area
if (nsUXThemeData::CheckForCompositor()) {
DwmExtendFrameIntoClientArea(mWnd, &margins);
DwmSetWindowAttribute(mWnd, DWMWA_NCRENDERING_POLICY, &policy, sizeof policy);
}
}
#endif
/**************************************************************
*
* SECTION: nsIWidget::HideWindowChrome
*
* Show or hide window chrome.
*
**************************************************************/
void
nsWindow::HideWindowChrome(bool aShouldHide)
{
HWND hwnd = WinUtils::GetTopLevelHWND(mWnd, true);
if (!WinUtils::GetNSWindowPtr(hwnd))
{
NS_WARNING("Trying to hide window decorations in an embedded context");
return;
}
if (mHideChrome == aShouldHide)
return;
DWORD_PTR style, exStyle;
mHideChrome = aShouldHide;
if (aShouldHide) {
DWORD_PTR tempStyle = ::GetWindowLongPtrW(hwnd, GWL_STYLE);
DWORD_PTR tempExStyle = ::GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
style = tempStyle & ~(WS_CAPTION | WS_THICKFRAME);
exStyle = tempExStyle & ~(WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE |
WS_EX_CLIENTEDGE | WS_EX_STATICEDGE);
mOldStyle = tempStyle;
mOldExStyle = tempExStyle;
}
else {
if (!mOldStyle || !mOldExStyle) {
mOldStyle = ::GetWindowLongPtrW(hwnd, GWL_STYLE);
mOldExStyle = ::GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
}
style = mOldStyle;
exStyle = mOldExStyle;
if (mFutureMarginsToUse) {
SetNonClientMargins(mFutureMarginsOnceChromeShows);
}
}
VERIFY_WINDOW_STYLE(style);
::SetWindowLongPtrW(hwnd, GWL_STYLE, style);
::SetWindowLongPtrW(hwnd, GWL_EXSTYLE, exStyle);
}
/**************************************************************
*
* SECTION: nsWindow::Invalidate
*
* Invalidate an area of the client for painting.
*
**************************************************************/
// Invalidate this component visible area
void
nsWindow::Invalidate(bool aEraseBackground,
bool aUpdateNCArea,
bool aIncludeChildren)
{
if (!mWnd) {
return;
}
#ifdef WIDGET_DEBUG_OUTPUT
debug_DumpInvalidate(stdout,
this,
nullptr,
"noname",
(int32_t) mWnd);
#endif // WIDGET_DEBUG_OUTPUT
DWORD flags = RDW_INVALIDATE;
if (aEraseBackground) {
flags |= RDW_ERASE;
}
if (aUpdateNCArea) {
flags |= RDW_FRAME;
}
if (aIncludeChildren) {
flags |= RDW_ALLCHILDREN;
}
VERIFY(::RedrawWindow(mWnd, nullptr, nullptr, flags));
}
// Invalidate this component visible area
void
nsWindow::Invalidate(const LayoutDeviceIntRect& aRect)
{
if (mWnd) {
#ifdef WIDGET_DEBUG_OUTPUT
debug_DumpInvalidate(stdout,
this,
&aRect,
"noname",
(int32_t) mWnd);
#endif // WIDGET_DEBUG_OUTPUT
RECT rect;
rect.left = aRect.x;
rect.top = aRect.y;
rect.right = aRect.x + aRect.width;
rect.bottom = aRect.y + aRect.height;
VERIFY(::InvalidateRect(mWnd, &rect, FALSE));
}
}
static LRESULT CALLBACK
FullscreenTransitionWindowProc(HWND hWnd, UINT uMsg,
WPARAM wParam, LPARAM lParam)
{
switch (uMsg) {
case WM_FULLSCREEN_TRANSITION_BEFORE:
case WM_FULLSCREEN_TRANSITION_AFTER: {
DWORD duration = (DWORD)lParam;
DWORD flags = AW_BLEND;
if (uMsg == WM_FULLSCREEN_TRANSITION_AFTER) {
flags |= AW_HIDE;
}
::AnimateWindow(hWnd, duration, flags);
// The message sender should have added ref for us.
NS_DispatchToMainThread(
already_AddRefed<nsIRunnable>((nsIRunnable*)wParam));
break;
}
case WM_DESTROY:
::PostQuitMessage(0);
break;
default:
return ::DefWindowProcW(hWnd, uMsg, wParam, lParam);
}
return 0;
}
struct FullscreenTransitionInitData
{
nsIntRect mBounds;
HANDLE mSemaphore;
HANDLE mThread;
HWND mWnd;
FullscreenTransitionInitData()
: mSemaphore(nullptr)
, mThread(nullptr)
, mWnd(nullptr) { }
~FullscreenTransitionInitData()
{
if (mSemaphore) {
::CloseHandle(mSemaphore);
}
if (mThread) {
::CloseHandle(mThread);
}
}
};
static DWORD WINAPI
FullscreenTransitionThreadProc(LPVOID lpParam)
{
// Initialize window class
static bool sInitialized = false;
if (!sInitialized) {
WNDCLASSW wc = {};
wc.lpfnWndProc = ::FullscreenTransitionWindowProc;
wc.hInstance = nsToolkit::mDllInstance;
wc.hbrBackground = ::CreateSolidBrush(RGB(0, 0, 0));
wc.lpszClassName = kClassNameTransition;
::RegisterClassW(&wc);
sInitialized = true;
}
auto data = static_cast<FullscreenTransitionInitData*>(lpParam);
HWND wnd = ::CreateWindowW(
kClassNameTransition, L"", 0, 0, 0, 0, 0,
nullptr, nullptr, nsToolkit::mDllInstance, nullptr);
if (!wnd) {
::ReleaseSemaphore(data->mSemaphore, 1, nullptr);
return 0;
}
// Since AnimateWindow blocks the thread of the transition window,
// we need to hide the cursor for that window, otherwise the system
// would show the busy pointer to the user.
::ShowCursor(false);
::SetWindowLongW(wnd, GWL_STYLE, 0);
::SetWindowLongW(wnd, GWL_EXSTYLE, WS_EX_LAYERED |
WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE);
::SetWindowPos(wnd, HWND_TOPMOST, data->mBounds.x, data->mBounds.y,
data->mBounds.width, data->mBounds.height, 0);
data->mWnd = wnd;
::ReleaseSemaphore(data->mSemaphore, 1, nullptr);
// The initialization data may no longer be valid
// after we release the semaphore.
data = nullptr;
MSG msg;
while (::GetMessageW(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::ShowCursor(true);
::DestroyWindow(wnd);
return 0;
}
class FullscreenTransitionData final : public nsISupports
{
public:
NS_DECL_ISUPPORTS
explicit FullscreenTransitionData(HWND aWnd)
: mWnd(aWnd)
{
MOZ_ASSERT(NS_IsMainThread(), "FullscreenTransitionData "
"should be constructed in the main thread");
}
const HWND mWnd;
private:
~FullscreenTransitionData()
{
MOZ_ASSERT(NS_IsMainThread(), "FullscreenTransitionData "
"should be deconstructed in the main thread");
::PostMessageW(mWnd, WM_DESTROY, 0, 0);
}
};
NS_IMPL_ISUPPORTS0(FullscreenTransitionData)
/* virtual */ bool
nsWindow::PrepareForFullscreenTransition(nsISupports** aData)
{
// We don't support fullscreen transition when composition is not
// enabled, which could make the transition broken and annoying.
// See bug 1184201.
if (!nsUXThemeData::CheckForCompositor()) {
return false;
}
FullscreenTransitionInitData initData;
nsCOMPtr<nsIScreen> screen = GetWidgetScreen();
int32_t x, y, width, height;
screen->GetRectDisplayPix(&x, &y, &width, &height);
MOZ_ASSERT(BoundsUseDesktopPixels(),
"Should only be called on top-level window");
double scale = GetDesktopToDeviceScale().scale; // XXX or GetDefaultScale() ?
initData.mBounds.x = NSToIntRound(x * scale);
initData.mBounds.y = NSToIntRound(y * scale);
initData.mBounds.width = NSToIntRound(width * scale);
initData.mBounds.height = NSToIntRound(height * scale);
// Create a semaphore for synchronizing the window handle which will
// be created by the transition thread and used by the main thread for
// posting the transition messages.
initData.mSemaphore = ::CreateSemaphore(nullptr, 0, 1, nullptr);
if (initData.mSemaphore) {
initData.mThread = ::CreateThread(
nullptr, 0, FullscreenTransitionThreadProc, &initData, 0, nullptr);
if (initData.mThread) {
::WaitForSingleObject(initData.mSemaphore, INFINITE);
}
}
if (!initData.mWnd) {
return false;
}
mTransitionWnd = initData.mWnd;
auto data = new FullscreenTransitionData(initData.mWnd);
*aData = data;
NS_ADDREF(data);
return true;
}
/* virtual */ void
nsWindow::PerformFullscreenTransition(FullscreenTransitionStage aStage,
uint16_t aDuration, nsISupports* aData,
nsIRunnable* aCallback)
{
auto data = static_cast<FullscreenTransitionData*>(aData);
nsCOMPtr<nsIRunnable> callback = aCallback;
UINT msg = aStage == eBeforeFullscreenToggle ?
WM_FULLSCREEN_TRANSITION_BEFORE : WM_FULLSCREEN_TRANSITION_AFTER;
WPARAM wparam = (WPARAM)callback.forget().take();
::PostMessage(data->mWnd, msg, wparam, (LPARAM)aDuration);
}
nsresult
nsWindow::MakeFullScreen(bool aFullScreen, nsIScreen* aTargetScreen)
{
// taskbarInfo will be nullptr pre Windows 7 until Bug 680227 is resolved.
nsCOMPtr<nsIWinTaskbar> taskbarInfo =
do_GetService(NS_TASKBAR_CONTRACTID);
mFullscreenMode = aFullScreen;
if (aFullScreen) {
if (mSizeMode == nsSizeMode_Fullscreen)
return NS_OK;
mOldSizeMode = mSizeMode;
SetSizeMode(nsSizeMode_Fullscreen);
// Notify the taskbar that we will be entering full screen mode.
if (taskbarInfo) {
taskbarInfo->PrepareFullScreenHWND(mWnd, TRUE);
}
} else {
if (mSizeMode != nsSizeMode_Fullscreen)
return NS_OK;
SetSizeMode(mOldSizeMode);
}
// If we are going fullscreen, the window size continues to change
// and the window will be reflow again then.
UpdateNonClientMargins(mSizeMode, /* Reflow */ !aFullScreen);
// Will call hide chrome, reposition window. Note this will
// also cache dimensions for restoration, so it should only
// be called once per fullscreen request.
nsBaseWidget::InfallibleMakeFullScreen(aFullScreen, aTargetScreen);
if (mIsVisible && !aFullScreen && mOldSizeMode == nsSizeMode_Normal) {
// Ensure the window exiting fullscreen get activated. Window
// activation might be bypassed in SetSizeMode.
DispatchFocusToTopLevelWindow(true);
}
// Notify the taskbar that we have exited full screen mode.
if (!aFullScreen && taskbarInfo) {
taskbarInfo->PrepareFullScreenHWND(mWnd, FALSE);
}
if (mWidgetListener) {
mWidgetListener->SizeModeChanged(mSizeMode);
mWidgetListener->FullscreenChanged(aFullScreen);
}
// Send a eMouseEnterIntoWidget event since Windows has already sent
// a WM_MOUSELEAVE that caused us to send a eMouseExitFromWidget event.
if (aFullScreen && !sCurrentWindow) {
sCurrentWindow = this;
LPARAM pos = sCurrentWindow->lParamToClient(sMouseExitlParamScreen);
sCurrentWindow->DispatchMouseEvent(eMouseEnterIntoWidget,
sMouseExitwParam, pos, false,
WidgetMouseEvent::eLeftButton,
MOUSE_INPUT_SOURCE());
}
return NS_OK;
}
/**************************************************************
*
* SECTION: Native data storage
*
* nsIWidget::GetNativeData
* nsIWidget::FreeNativeData
*
* Set or clear native data based on a constant.
*
**************************************************************/
// Return some native data according to aDataType
void* nsWindow::GetNativeData(uint32_t aDataType)
{
switch (aDataType) {
case NS_NATIVE_TMP_WINDOW:
return (void*)::CreateWindowExW(mIsRTL ? WS_EX_LAYOUTRTL : 0,
GetWindowClass(),
L"",
WS_CHILD,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
mWnd,
nullptr,
nsToolkit::mDllInstance,
nullptr);
case NS_NATIVE_PLUGIN_ID:
case NS_NATIVE_PLUGIN_PORT:
case NS_NATIVE_WIDGET:
case NS_NATIVE_WINDOW:
return (void*)mWnd;
case NS_NATIVE_SHAREABLE_WINDOW:
return (void*) WinUtils::GetTopLevelHWND(mWnd);
case NS_NATIVE_GRAPHIC:
MOZ_ASSERT_UNREACHABLE("Not supported on Windows:");
return nullptr;
case NS_RAW_NATIVE_IME_CONTEXT: {
void* pseudoIMEContext = GetPseudoIMEContext();
if (pseudoIMEContext) {
return pseudoIMEContext;
}
MOZ_FALLTHROUGH;
}
case NS_NATIVE_TSF_THREAD_MGR:
case NS_NATIVE_TSF_CATEGORY_MGR:
case NS_NATIVE_TSF_DISPLAY_ATTR_MGR:
return IMEHandler::GetNativeData(this, aDataType);
default:
break;
}
return nullptr;
}
static void
SetChildStyleAndParent(HWND aChildWindow, HWND aParentWindow)
{
// Make sure the window is styled to be a child window.
LONG_PTR style = GetWindowLongPtr(aChildWindow, GWL_STYLE);
style |= WS_CHILD;
style &= ~WS_POPUP;
SetWindowLongPtr(aChildWindow, GWL_STYLE, style);
// Do the reparenting. Note that this call will probably cause a sync native
// message to the process that owns the child window.
::SetParent(aChildWindow, aParentWindow);
}
void
nsWindow::SetNativeData(uint32_t aDataType, uintptr_t aVal)
{
switch (aDataType) {
case NS_NATIVE_CHILD_WINDOW:
case NS_NATIVE_CHILD_OF_SHAREABLE_WINDOW:
{
HWND childHwnd = reinterpret_cast<HWND>(aVal);
DWORD childProc = 0;
GetWindowThreadProcessId(childHwnd, &childProc);
if (!PluginProcessParent::IsPluginProcessId(static_cast<base::ProcessId>(childProc))) {
MOZ_ASSERT_UNREACHABLE("SetNativeData window origin was not a plugin process.");
break;
}
HWND parentHwnd =
aDataType == NS_NATIVE_CHILD_WINDOW ? mWnd : WinUtils::GetTopLevelHWND(mWnd);
SetChildStyleAndParent(childHwnd, parentHwnd);
break;
}
default:
NS_ERROR("SetNativeData called with unsupported data type.");
}
}
// Free some native data according to aDataType
void nsWindow::FreeNativeData(void * data, uint32_t aDataType)
{
switch (aDataType)
{
case NS_NATIVE_GRAPHIC:
case NS_NATIVE_WIDGET:
case NS_NATIVE_WINDOW:
case NS_NATIVE_PLUGIN_PORT:
break;
default:
break;
}
}
/**************************************************************
*
* SECTION: nsIWidget::SetTitle
*
* Set the main windows title text.
*
**************************************************************/
nsresult
nsWindow::SetTitle(const nsAString& aTitle)
{
const nsString& strTitle = PromiseFlatString(aTitle);
AutoRestore<bool> sendingText(mSendingSetText);
mSendingSetText = true;
::SendMessageW(mWnd, WM_SETTEXT, (WPARAM)0, (LPARAM)(LPCWSTR)strTitle.get());
return NS_OK;
}
/**************************************************************
*
* SECTION: nsIWidget::SetIcon
*
* Set the main windows icon.
*
**************************************************************/
void
nsWindow::SetIcon(const nsAString& aIconSpec)
{
// Assume the given string is a local identifier for an icon file.
nsCOMPtr<nsIFile> iconFile;
ResolveIconName(aIconSpec, NS_LITERAL_STRING(".ico"),
getter_AddRefs(iconFile));
if (!iconFile)
return;
nsAutoString iconPath;
iconFile->GetPath(iconPath);
// XXX this should use MZLU (see bug 239279)
::SetLastError(0);
HICON bigIcon = (HICON)::LoadImageW(nullptr,
(LPCWSTR)iconPath.get(),
IMAGE_ICON,
::GetSystemMetrics(SM_CXICON),
::GetSystemMetrics(SM_CYICON),
LR_LOADFROMFILE );
HICON smallIcon = (HICON)::LoadImageW(nullptr,
(LPCWSTR)iconPath.get(),
IMAGE_ICON,
::GetSystemMetrics(SM_CXSMICON),
::GetSystemMetrics(SM_CYSMICON),
LR_LOADFROMFILE );
if (bigIcon) {
HICON icon = (HICON) ::SendMessageW(mWnd, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)bigIcon);
if (icon)
::DestroyIcon(icon);
mIconBig = bigIcon;
}
#ifdef DEBUG_SetIcon
else {
NS_LossyConvertUTF16toASCII cPath(iconPath);
MOZ_LOG(gWindowsLog, LogLevel::Info,
("\nIcon load error; icon=%s, rc=0x%08X\n\n",
cPath.get(), ::GetLastError()));
}
#endif
if (smallIcon) {
HICON icon = (HICON) ::SendMessageW(mWnd, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)smallIcon);
if (icon)
::DestroyIcon(icon);
mIconSmall = smallIcon;
}
#ifdef DEBUG_SetIcon
else {
NS_LossyConvertUTF16toASCII cPath(iconPath);
MOZ_LOG(gWindowsLog, LogLevel::Info,
("\nSmall icon load error; icon=%s, rc=0x%08X\n\n",
cPath.get(), ::GetLastError()));
}
#endif
}
/**************************************************************
*
* SECTION: nsIWidget::WidgetToScreenOffset
*
* Return this widget's origin in screen coordinates.
*
**************************************************************/
LayoutDeviceIntPoint nsWindow::WidgetToScreenOffset()
{
POINT point;
point.x = 0;
point.y = 0;
::ClientToScreen(mWnd, &point);
return LayoutDeviceIntPoint(point.x, point.y);
}
LayoutDeviceIntSize
nsWindow::ClientToWindowSize(const LayoutDeviceIntSize& aClientSize)
{
if (mWindowType == eWindowType_popup && !IsPopupWithTitleBar())
return aClientSize;
// just use (200, 200) as the position
RECT r;
r.left = 200;
r.top = 200;
r.right = 200 + aClientSize.width;
r.bottom = 200 + aClientSize.height;
::AdjustWindowRectEx(&r, WindowStyle(), false, WindowExStyle());
return LayoutDeviceIntSize(r.right - r.left, r.bottom - r.top);
}
/**************************************************************
*
* SECTION: nsIWidget::EnableDragDrop
*
* Enables/Disables drag and drop of files on this widget.
*
**************************************************************/
void
nsWindow::EnableDragDrop(bool aEnable)
{
NS_ASSERTION(mWnd, "nsWindow::EnableDragDrop() called after Destroy()");
nsresult rv = NS_ERROR_FAILURE;
if (aEnable) {
if (!mNativeDragTarget) {
mNativeDragTarget = new nsNativeDragTarget(this);
mNativeDragTarget->AddRef();
if (SUCCEEDED(::CoLockObjectExternal((LPUNKNOWN)mNativeDragTarget,
TRUE, FALSE))) {
::RegisterDragDrop(mWnd, (LPDROPTARGET)mNativeDragTarget);
}
}
} else {
if (mWnd && mNativeDragTarget) {
::RevokeDragDrop(mWnd);
::CoLockObjectExternal((LPUNKNOWN)mNativeDragTarget, FALSE, TRUE);
mNativeDragTarget->DragCancel();
NS_RELEASE(mNativeDragTarget);
}
}
}
/**************************************************************
*
* SECTION: nsIWidget::CaptureMouse
*
* Enables/Disables system mouse capture.
*
**************************************************************/
void nsWindow::CaptureMouse(bool aCapture)
{
TRACKMOUSEEVENT mTrack;
mTrack.cbSize = sizeof(TRACKMOUSEEVENT);
mTrack.dwHoverTime = 0;
mTrack.hwndTrack = mWnd;
if (aCapture) {
mTrack.dwFlags = TME_CANCEL | TME_LEAVE;
::SetCapture(mWnd);
} else {
mTrack.dwFlags = TME_LEAVE;
::ReleaseCapture();
}
sIsInMouseCapture = aCapture;
TrackMouseEvent(&mTrack);
}
/**************************************************************
*
* SECTION: nsIWidget::CaptureRollupEvents
*
* Dealing with event rollup on destroy for popups. Enables &
* Disables system capture of any and all events that would
* cause a dropdown to be rolled up.
*
**************************************************************/
void
nsWindow::CaptureRollupEvents(nsIRollupListener* aListener, bool aDoCapture)
{
if (aDoCapture) {
gRollupListener = aListener;
if (!sMsgFilterHook && !sCallProcHook && !sCallMouseHook) {
RegisterSpecialDropdownHooks();
}
sProcessHook = true;
} else {
gRollupListener = nullptr;
sProcessHook = false;
UnregisterSpecialDropdownHooks();
}
}
/**************************************************************
*
* SECTION: nsIWidget::GetAttention
*
* Bring this window to the user's attention.
*
**************************************************************/
// Draw user's attention to this window until it comes to foreground.
nsresult
nsWindow::GetAttention(int32_t aCycleCount)
{
// Got window?
if (!mWnd)
return NS_ERROR_NOT_INITIALIZED;
HWND flashWnd = WinUtils::GetTopLevelHWND(mWnd, false, false);
HWND fgWnd = ::GetForegroundWindow();
// Don't flash if the flash count is 0 or if the foreground window is our
// window handle or that of our owned-most window.
if (aCycleCount == 0 ||
flashWnd == fgWnd ||
flashWnd == WinUtils::GetTopLevelHWND(fgWnd, false, false)) {
return NS_OK;
}
DWORD defaultCycleCount = 0;
::SystemParametersInfo(SPI_GETFOREGROUNDFLASHCOUNT, 0, &defaultCycleCount, 0);
FLASHWINFO flashInfo = { sizeof(FLASHWINFO), flashWnd,
FLASHW_ALL, aCycleCount > 0 ? aCycleCount : defaultCycleCount, 0 };
::FlashWindowEx(&flashInfo);
return NS_OK;
}
void nsWindow::StopFlashing()
{
HWND flashWnd = mWnd;
while (HWND ownerWnd = ::GetWindow(flashWnd, GW_OWNER)) {
flashWnd = ownerWnd;
}
FLASHWINFO flashInfo = { sizeof(FLASHWINFO), flashWnd,
FLASHW_STOP, 0, 0 };
::FlashWindowEx(&flashInfo);
}
/**************************************************************
*
* SECTION: nsIWidget::HasPendingInputEvent
*
* Ask whether there user input events pending. All input events are
* included, including those not targeted at this nsIwidget instance.
*
**************************************************************/
bool
nsWindow::HasPendingInputEvent()
{
// If there is pending input or the user is currently
// moving the window then return true.
// Note: When the user is moving the window WIN32 spins
// a separate event loop and input events are not
// reported to the application.
if (HIWORD(GetQueueStatus(QS_INPUT)))
return true;
GUITHREADINFO guiInfo;
guiInfo.cbSize = sizeof(GUITHREADINFO);
if (!GetGUIThreadInfo(GetCurrentThreadId(), &guiInfo))
return false;
return GUI_INMOVESIZE == (guiInfo.flags & GUI_INMOVESIZE);
}
/**************************************************************
*
* SECTION: nsIWidget::GetLayerManager
*
* Get the layer manager associated with this widget.
*
**************************************************************/
LayerManager*
nsWindow::GetLayerManager(PLayerTransactionChild* aShadowManager,
LayersBackend aBackendHint,
LayerManagerPersistence aPersistence)
{
RECT windowRect;
::GetClientRect(mWnd, &windowRect);
// Try OMTC first.
if (!mLayerManager && ShouldUseOffMainThreadCompositing()) {
gfxWindowsPlatform::GetPlatform()->UpdateRenderMode();
// e10s uses the parameter to pass in the shadow manager from the TabChild
// so we don't expect to see it there since this doesn't support e10s.
NS_ASSERTION(aShadowManager == nullptr, "Async Compositor not supported with e10s");
CreateCompositor();
}
if (!mLayerManager) {
MOZ_ASSERT(!mCompositorSession && !mCompositorBridgeChild);
MOZ_ASSERT(!mCompositorWidgetDelegate);
// Ensure we have a widget proxy even if we're not using the compositor,
// since all our transparent window handling lives there.
CompositorWidgetInitData initData(
reinterpret_cast<uintptr_t>(mWnd),
reinterpret_cast<uintptr_t>(static_cast<nsIWidget*>(this)),
mTransparencyMode);
// If we're not using the compositor, the options don't actually matter.
CompositorOptions options(false, false);
mBasicLayersSurface = new InProcessWinCompositorWidget(initData, options, this);
mCompositorWidgetDelegate = mBasicLayersSurface;
mLayerManager = CreateBasicLayerManager();
}
NS_ASSERTION(mLayerManager, "Couldn't provide a valid layer manager.");
return mLayerManager;
}
/**************************************************************
*
* SECTION: nsIWidget::OnDefaultButtonLoaded
*
* Called after the dialog is loaded and it has a default button.
*
**************************************************************/
nsresult
nsWindow::OnDefaultButtonLoaded(const LayoutDeviceIntRect& aButtonRect)
{
if (aButtonRect.IsEmpty())
return NS_OK;
// Don't snap when we are not active.
HWND activeWnd = ::GetActiveWindow();
if (activeWnd != ::GetForegroundWindow() ||
WinUtils::GetTopLevelHWND(mWnd, true) !=
WinUtils::GetTopLevelHWND(activeWnd, true)) {
return NS_OK;
}
bool isAlwaysSnapCursor =
Preferences::GetBool("ui.cursor_snapping.always_enabled", false);
if (!isAlwaysSnapCursor) {
BOOL snapDefaultButton;
if (!::SystemParametersInfo(SPI_GETSNAPTODEFBUTTON, 0,
&snapDefaultButton, 0) || !snapDefaultButton)
return NS_OK;
}
LayoutDeviceIntRect widgetRect = GetScreenBounds();
LayoutDeviceIntRect buttonRect(aButtonRect + widgetRect.TopLeft());
LayoutDeviceIntPoint centerOfButton(buttonRect.x + buttonRect.width / 2,
buttonRect.y + buttonRect.height / 2);
// The center of the button can be outside of the widget.
// E.g., it could be hidden by scrolling.
if (!widgetRect.Contains(centerOfButton)) {
return NS_OK;
}
if (!::SetCursorPos(centerOfButton.x, centerOfButton.y)) {
NS_ERROR("SetCursorPos failed");
return NS_ERROR_FAILURE;
}
return NS_OK;
}
void
nsWindow::UpdateThemeGeometries(const nsTArray<ThemeGeometry>& aThemeGeometries)
{
RefPtr<LayerManager> layerManager = GetLayerManager();
if (!layerManager) {
return;
}
nsIntRegion clearRegion;
if (!HasGlass() || !nsUXThemeData::CheckForCompositor()) {
// Make sure and clear old regions we've set previously. Note HasGlass can be false
// for glass desktops if the window we are rendering to doesn't make use of glass
// (e.g. fullscreen browsing).
layerManager->SetRegionToClear(clearRegion);
return;
}
// On Win10, force show the top border:
if (IsWin10OrLater() && mCustomNonClient && mSizeMode == nsSizeMode_Normal) {
RECT rect;
::GetWindowRect(mWnd, &rect);
// We want 1 pixel of border for every whole 100% of scaling
double borderSize = std::min(1, RoundDown(GetDesktopToDeviceScale().scale));
clearRegion.Or(clearRegion, gfx::IntRect::Truncate(0, 0, rect.right - rect.left, borderSize));
}
if (!IsWin10OrLater()) {
for (size_t i = 0; i < aThemeGeometries.Length(); i++) {
if (aThemeGeometries[i].mType == nsNativeThemeWin::eThemeGeometryTypeWindowButtons) {
LayoutDeviceIntRect bounds = aThemeGeometries[i].mRect;
clearRegion.Or(clearRegion, gfx::IntRect::Truncate(bounds.X(), bounds.Y(), bounds.Width(), bounds.Height() - 2.0));
clearRegion.Or(clearRegion, gfx::IntRect::Truncate(bounds.X() + 1.0, bounds.YMost() - 2.0, bounds.Width() - 1.0, 1.0));
clearRegion.Or(clearRegion, gfx::IntRect::Truncate(bounds.X() + 2.0, bounds.YMost() - 1.0, bounds.Width() - 3.0, 1.0));
}
}
}
layerManager->SetRegionToClear(clearRegion);
}
uint32_t
nsWindow::GetMaxTouchPoints() const
{
return WinUtils::GetMaxTouchPoints();
}
/**************************************************************
**************************************************************
**
** BLOCK: Moz Events
**
** Moz GUI event management.
**
**************************************************************
**************************************************************/
/**************************************************************
*
* SECTION: Mozilla event initialization
*
* Helpers for initializing moz events.
*
**************************************************************/
// Event initialization
void nsWindow::InitEvent(WidgetGUIEvent& event, LayoutDeviceIntPoint* aPoint)
{
if (nullptr == aPoint) { // use the point from the event
// get the message position in client coordinates
if (mWnd != nullptr) {
DWORD pos = ::GetMessagePos();
POINT cpos;
cpos.x = GET_X_LPARAM(pos);
cpos.y = GET_Y_LPARAM(pos);
::ScreenToClient(mWnd, &cpos);
event.mRefPoint = LayoutDeviceIntPoint(cpos.x, cpos.y);
} else {
event.mRefPoint = LayoutDeviceIntPoint(0, 0);
}
} else {
// use the point override if provided
event.mRefPoint = *aPoint;
}
event.AssignEventTime(CurrentMessageWidgetEventTime());
}
WidgetEventTime
nsWindow::CurrentMessageWidgetEventTime() const
{
LONG messageTime = ::GetMessageTime();
return WidgetEventTime(messageTime, GetMessageTimeStamp(messageTime));
}
/**************************************************************
*
* SECTION: Moz event dispatch helpers
*
* Helpers for dispatching different types of moz events.
*
**************************************************************/
// Main event dispatch. Invokes callback and ProcessEvent method on
// Event Listener object. Part of nsIWidget.
nsresult
nsWindow::DispatchEvent(WidgetGUIEvent* event, nsEventStatus& aStatus)
{
#ifdef WIDGET_DEBUG_OUTPUT
debug_DumpEvent(stdout,
event->mWidget,
event,
"something",
(int32_t) mWnd);
#endif // WIDGET_DEBUG_OUTPUT
aStatus = nsEventStatus_eIgnore;
// Top level windows can have a view attached which requires events be sent
// to the underlying base window and the view. Added when we combined the
// base chrome window with the main content child for nc client area (title
// bar) rendering.
if (mAttachedWidgetListener) {
aStatus = mAttachedWidgetListener->HandleEvent(event, mUseAttachedEvents);
}
else if (mWidgetListener) {
aStatus = mWidgetListener->HandleEvent(event, mUseAttachedEvents);
}
// the window can be destroyed during processing of seemingly innocuous events like, say,
// mousedowns due to the magic of scripting. mousedowns will return nsEventStatus_eIgnore,
// which causes problems with the deleted window. therefore:
if (mOnDestroyCalled)
aStatus = nsEventStatus_eConsumeNoDefault;
return NS_OK;
}
bool nsWindow::DispatchStandardEvent(EventMessage aMsg)
{
WidgetGUIEvent event(true, aMsg, this);
InitEvent(event);
bool result = DispatchWindowEvent(&event);
return result;
}
bool nsWindow::DispatchKeyboardEvent(WidgetKeyboardEvent* event)
{
nsEventStatus status = DispatchInputEvent(event);
return ConvertStatus(status);
}
bool nsWindow::DispatchContentCommandEvent(WidgetContentCommandEvent* aEvent)
{
nsEventStatus status;
DispatchEvent(aEvent, status);
return ConvertStatus(status);
}
bool nsWindow::DispatchWheelEvent(WidgetWheelEvent* aEvent)
{
nsEventStatus status = DispatchInputEvent(aEvent->AsInputEvent());
return ConvertStatus(status);
}
bool nsWindow::DispatchWindowEvent(WidgetGUIEvent* event)
{
nsEventStatus status;
DispatchEvent(event, status);
return ConvertStatus(status);
}
bool nsWindow::DispatchWindowEvent(WidgetGUIEvent* event,
nsEventStatus& aStatus)
{
DispatchEvent(event, aStatus);
return ConvertStatus(aStatus);
}
// Recursively dispatch synchronous paints for nsIWidget
// descendants with invalidated rectangles.
BOOL CALLBACK nsWindow::DispatchStarvedPaints(HWND aWnd, LPARAM aMsg)
{
LONG_PTR proc = ::GetWindowLongPtrW(aWnd, GWLP_WNDPROC);
if (proc == (LONG_PTR)&nsWindow::WindowProc) {
// its one of our windows so check to see if it has a
// invalidated rect. If it does. Dispatch a synchronous
// paint.
if (GetUpdateRect(aWnd, nullptr, FALSE))
VERIFY(::UpdateWindow(aWnd));
}
return TRUE;
}
// Check for pending paints and dispatch any pending paint
// messages for any nsIWidget which is a descendant of the
// top-level window that *this* window is embedded within.
//
// Note: We do not dispatch pending paint messages for non
// nsIWidget managed windows.
void nsWindow::DispatchPendingEvents()
{
if (mPainting) {
NS_WARNING("We were asked to dispatch pending events during painting, "
"denying since that's unsafe.");
return;
}
// We need to ensure that reflow events do not get starved.
// At the same time, we don't want to recurse through here
// as that would prevent us from dispatching starved paints.
static int recursionBlocker = 0;
if (recursionBlocker++ == 0) {
NS_ProcessPendingEvents(nullptr, PR_MillisecondsToInterval(100));
--recursionBlocker;
}
// Quickly check to see if there are any paint events pending,
// but only dispatch them if it has been long enough since the
// last paint completed.
if (::GetQueueStatus(QS_PAINT) &&
((TimeStamp::Now() - mLastPaintEndTime).ToMilliseconds() >= 50)) {
// Find the top level window.
HWND topWnd = WinUtils::GetTopLevelHWND(mWnd);
// Dispatch pending paints for topWnd and all its descendant windows.
// Note: EnumChildWindows enumerates all descendant windows not just
// the children (but not the window itself).
nsWindow::DispatchStarvedPaints(topWnd, 0);
::EnumChildWindows(topWnd, nsWindow::DispatchStarvedPaints, 0);
}
}
bool nsWindow::DispatchPluginEvent(UINT aMessage,
WPARAM aWParam,
LPARAM aLParam,
bool aDispatchPendingEvents)
{
bool ret = nsWindowBase::DispatchPluginEvent(
WinUtils::InitMSG(aMessage, aWParam, aLParam, mWnd));
if (aDispatchPendingEvents && !Destroyed()) {
DispatchPendingEvents();
}
return ret;
}
// Deal with all sort of mouse event
bool
nsWindow::DispatchMouseEvent(EventMessage aEventMessage, WPARAM wParam,
LPARAM lParam, bool aIsContextMenuKey,
int16_t aButton, uint16_t aInputSource,
WinPointerInfo* aPointerInfo)
{
enum
{
eUnset,
ePrecise,
eTouch
};
static int sTouchInputActiveState = eUnset;
bool result = false;
UserActivity();
if (!mWidgetListener) {
return result;
}
LayoutDeviceIntPoint eventPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
LayoutDeviceIntPoint mpScreen = eventPoint + WidgetToScreenOffset();
// Suppress mouse moves caused by widget creation. Make sure to do this early
// so that we update sLastMouseMovePoint even for touch-induced mousemove events.
if (aEventMessage == eMouseMove) {
if ((sLastMouseMovePoint.x == mpScreen.x) && (sLastMouseMovePoint.y == mpScreen.y)) {
return result;
}
sLastMouseMovePoint.x = mpScreen.x;
sLastMouseMovePoint.y = mpScreen.y;
}
if (WinUtils::GetIsMouseFromTouch(aEventMessage)) {
if (aEventMessage == eMouseDown) {
Telemetry::Accumulate(Telemetry::FX_TOUCH_USED, 1);
}
// Fire an observer when the user initially touches a touch screen. Front end
// uses this to modify UX.
if (sTouchInputActiveState != eTouch) {
sTouchInputActiveState = eTouch;
nsCOMPtr<nsIObserverService> obsServ =
mozilla::services::GetObserverService();
obsServ->NotifyObservers(nullptr, "touch-input-detected", nullptr);
}
if (mTouchWindow) {
// If mTouchWindow is true, then we must have APZ enabled and be
// feeding it raw touch events. In that case we don't need to
// send touch-generated mouse events to content. The only exception is
// the touch-generated mouse double-click, which is used to start off the
// touch-based drag-and-drop gesture.
MOZ_ASSERT(mAPZC);
if (aEventMessage == eMouseDoubleClick) {
aEventMessage = eMouseTouchDrag;
} else {
return result;
}
}
} else {
// Fire an observer when the user initially uses a mouse or pen.
if (sTouchInputActiveState != ePrecise) {
sTouchInputActiveState = ePrecise;
nsCOMPtr<nsIObserverService> obsServ =
mozilla::services::GetObserverService();
obsServ->NotifyObservers(nullptr, "precise-input-detected", nullptr);
}
}
uint32_t pointerId = aPointerInfo ? aPointerInfo->pointerId :
MOUSE_POINTERID();
// Since it is unclear whether a user will use the digitizer,
// Postpone initialization until first PEN message will be found.
if (nsIDOMMouseEvent::MOZ_SOURCE_PEN == aInputSource
// Messages should be only at topLevel window.
&& nsWindowType::eWindowType_toplevel == mWindowType
// Currently this scheme is used only when pointer events is enabled.
&& gfxPrefs::PointerEventsEnabled() && InkCollector::sInkCollector) {
InkCollector::sInkCollector->SetTarget(mWnd);
InkCollector::sInkCollector->SetPointerId(pointerId);
}
switch (aEventMessage) {
case eMouseDown:
CaptureMouse(true);
break;
// eMouseMove and eMouseExitFromWidget are here because we need to make
// sure capture flag isn't left on after a drag where we wouldn't see a
// button up message (see bug 324131).
case eMouseUp:
case eMouseMove:
case eMouseExitFromWidget:
if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)) && sIsInMouseCapture)
CaptureMouse(false);
break;
default:
break;
} // switch
WidgetMouseEvent event(true, aEventMessage, this, WidgetMouseEvent::eReal,
aIsContextMenuKey ? WidgetMouseEvent::eContextMenuKey :
WidgetMouseEvent::eNormal);
if (aEventMessage == eContextMenu && aIsContextMenuKey) {
LayoutDeviceIntPoint zero(0, 0);
InitEvent(event, &zero);
} else {
InitEvent(event, &eventPoint);
}
ModifierKeyState modifierKeyState;
modifierKeyState.InitInputEvent(event);
// eContextMenu with Shift state is special. It won't fire "contextmenu"
// event in the web content for blocking web content to prevent its default.
// However, Shift+F10 is a standard shortcut key on Windows. Therefore,
// this should not block web page to prevent its default. I.e., it should
// behave same as ContextMenu key without Shift key.
// XXX Should we allow to block web page to prevent its default with
// Ctrl+Shift+F10 or Alt+Shift+F10 instead?
if (aEventMessage == eContextMenu && aIsContextMenuKey && event.IsShift() &&
NativeKey::LastKeyMSG().message == WM_SYSKEYDOWN &&
NativeKey::LastKeyMSG().wParam == VK_F10) {
event.mModifiers &= ~MODIFIER_SHIFT;
}
event.button = aButton;
event.inputSource = aInputSource;
if (aPointerInfo) {
// Mouse events from Windows WM_POINTER*. Fill more information in
// WidgetMouseEvent.
event.AssignPointerHelperData(*aPointerInfo);
event.pressure = aPointerInfo->mPressure;
event.buttons = aPointerInfo->mButtons;
} else {
// If we get here the mouse events must be from non-touch sources, so
// convert it to pointer events as well
event.convertToPointer = true;
event.pointerId = pointerId;
}
bool insideMovementThreshold = (DeprecatedAbs(sLastMousePoint.x - eventPoint.x) < (short)::GetSystemMetrics(SM_CXDOUBLECLK)) &&
(DeprecatedAbs(sLastMousePoint.y - eventPoint.y) < (short)::GetSystemMetrics(SM_CYDOUBLECLK));
BYTE eventButton;
switch (aButton) {
case WidgetMouseEvent::eLeftButton:
eventButton = VK_LBUTTON;
break;
case WidgetMouseEvent::eMiddleButton:
eventButton = VK_MBUTTON;
break;
case WidgetMouseEvent::eRightButton:
eventButton = VK_RBUTTON;
break;
default:
eventButton = 0;
break;
}
// Doubleclicks are used to set the click count, then changed to mousedowns
// We're going to time double-clicks from mouse *up* to next mouse *down*
LONG curMsgTime = ::GetMessageTime();
switch (aEventMessage) {
case eMouseDoubleClick:
event.mMessage = eMouseDown;
event.button = aButton;
sLastClickCount = 2;
sLastMouseDownTime = curMsgTime;
break;
case eMouseUp:
// remember when this happened for the next mouse down
sLastMousePoint.x = eventPoint.x;
sLastMousePoint.y = eventPoint.y;
sLastMouseButton = eventButton;
break;
case eMouseDown:
// now look to see if we want to convert this to a double- or triple-click
if (((curMsgTime - sLastMouseDownTime) < (LONG)::GetDoubleClickTime()) &&
insideMovementThreshold &&
eventButton == sLastMouseButton) {
sLastClickCount ++;
} else {
// reset the click count, to count *this* click
sLastClickCount = 1;
}
// Set last Click time on MouseDown only
sLastMouseDownTime = curMsgTime;
break;
case eMouseMove:
if (!insideMovementThreshold) {
sLastClickCount = 0;
}
break;
case eMouseExitFromWidget:
event.mExitFrom =
IsTopLevelMouseExit(mWnd) ? WidgetMouseEvent::eTopLevel :
WidgetMouseEvent::eChild;
break;
default:
break;
}
event.mClickCount = sLastClickCount;
#ifdef NS_DEBUG_XX
MOZ_LOG(gWindowsLog, LogLevel::Info,
("Msg Time: %d Click Count: %d\n", curMsgTime, event.mClickCount));
#endif
NPEvent pluginEvent;
switch (aEventMessage) {
case eMouseDown:
switch (aButton) {
case WidgetMouseEvent::eLeftButton:
pluginEvent.event = WM_LBUTTONDOWN;
break;
case WidgetMouseEvent::eMiddleButton:
pluginEvent.event = WM_MBUTTONDOWN;
break;
case WidgetMouseEvent::eRightButton:
pluginEvent.event = WM_RBUTTONDOWN;
break;
default:
break;
}
break;
case eMouseUp:
switch (aButton) {
case WidgetMouseEvent::eLeftButton:
pluginEvent.event = WM_LBUTTONUP;
break;
case WidgetMouseEvent::eMiddleButton:
pluginEvent.event = WM_MBUTTONUP;
break;
case WidgetMouseEvent::eRightButton:
pluginEvent.event = WM_RBUTTONUP;
break;
default:
break;
}
break;
case eMouseDoubleClick:
switch (aButton) {
case WidgetMouseEvent::eLeftButton:
pluginEvent.event = WM_LBUTTONDBLCLK;
break;
case WidgetMouseEvent::eMiddleButton:
pluginEvent.event = WM_MBUTTONDBLCLK;
break;
case WidgetMouseEvent::eRightButton:
pluginEvent.event = WM_RBUTTONDBLCLK;
break;
default:
break;
}
break;
case eMouseMove:
pluginEvent.event = WM_MOUSEMOVE;
break;
case eMouseExitFromWidget:
pluginEvent.event = WM_MOUSELEAVE;
break;
default:
pluginEvent.event = WM_NULL;
break;
}
pluginEvent.wParam = wParam; // plugins NEED raw OS event flags!
pluginEvent.lParam = lParam;
event.mPluginEvent.Copy(pluginEvent);
// call the event callback
if (mWidgetListener) {
if (aEventMessage == eMouseMove) {
LayoutDeviceIntRect rect = GetBounds();
rect.x = 0;
rect.y = 0;
if (rect.Contains(event.mRefPoint)) {
if (sCurrentWindow == nullptr || sCurrentWindow != this) {
if ((nullptr != sCurrentWindow) && (!sCurrentWindow->mInDtor)) {
LPARAM pos = sCurrentWindow->lParamToClient(lParamToScreen(lParam));
sCurrentWindow->DispatchMouseEvent(eMouseExitFromWidget,
wParam, pos, false,
WidgetMouseEvent::eLeftButton,
aInputSource, aPointerInfo);
}
sCurrentWindow = this;
if (!mInDtor) {
LPARAM pos = sCurrentWindow->lParamToClient(lParamToScreen(lParam));
sCurrentWindow->DispatchMouseEvent(eMouseEnterIntoWidget,
wParam, pos, false,
WidgetMouseEvent::eLeftButton,
aInputSource, aPointerInfo);
}
}
}
} else if (aEventMessage == eMouseExitFromWidget) {
sMouseExitwParam = wParam;
sMouseExitlParamScreen = lParamToScreen(lParam);
if (sCurrentWindow == this) {
sCurrentWindow = nullptr;
}
}
result = ConvertStatus(DispatchInputEvent(&event));
// Release the widget with NS_IF_RELEASE() just in case
// the context menu key code in EventListenerManager::HandleEvent()
// released it already.
return result;
}
return result;
}
void nsWindow::DispatchFocusToTopLevelWindow(bool aIsActivate)
{
if (aIsActivate)
sJustGotActivate = false;
sJustGotDeactivate = false;
// retrive the toplevel window or dialog
HWND curWnd = mWnd;
HWND toplevelWnd = nullptr;
while (curWnd) {
toplevelWnd = curWnd;
nsWindow *win = WinUtils::GetNSWindowPtr(curWnd);
if (win) {
nsWindowType wintype = win->WindowType();
if (wintype == eWindowType_toplevel || wintype == eWindowType_dialog)
break;
}
curWnd = ::GetParent(curWnd); // Parent or owner (if has no parent)
}
if (toplevelWnd) {
nsWindow *win = WinUtils::GetNSWindowPtr(toplevelWnd);
if (win && win->mWidgetListener) {
if (aIsActivate) {
win->mWidgetListener->WindowActivated();
} else {
if (!win->BlurEventsSuppressed()) {
win->mWidgetListener->WindowDeactivated();
}
}
}
}
}
bool nsWindow::IsTopLevelMouseExit(HWND aWnd)
{
DWORD pos = ::GetMessagePos();
POINT mp;
mp.x = GET_X_LPARAM(pos);
mp.y = GET_Y_LPARAM(pos);
HWND mouseWnd = ::WindowFromPoint(mp);
// WinUtils::GetTopLevelHWND() will return a HWND for the window frame
// (which includes the non-client area). If the mouse has moved into
// the non-client area, we should treat it as a top-level exit.
HWND mouseTopLevel = WinUtils::GetTopLevelHWND(mouseWnd);
if (mouseWnd == mouseTopLevel)
return true;
return WinUtils::GetTopLevelHWND(aWnd) != mouseTopLevel;
}
bool nsWindow::BlurEventsSuppressed()
{
// are they suppressed in this window?
if (mBlurSuppressLevel > 0)
return true;
// are they suppressed by any container widget?
HWND parentWnd = ::GetParent(mWnd);
if (parentWnd) {
nsWindow *parent = WinUtils::GetNSWindowPtr(parentWnd);
if (parent)
return parent->BlurEventsSuppressed();
}
return false;
}
// In some circumstances (opening dependent windows) it makes more sense
// (and fixes a crash bug) to not blur the parent window. Called from
// nsFilePicker.
void nsWindow::SuppressBlurEvents(bool aSuppress)
{
if (aSuppress)
++mBlurSuppressLevel; // for this widget
else {
NS_ASSERTION(mBlurSuppressLevel > 0, "unbalanced blur event suppression");
if (mBlurSuppressLevel > 0)
--mBlurSuppressLevel;
}
}
bool nsWindow::ConvertStatus(nsEventStatus aStatus)
{
return aStatus == nsEventStatus_eConsumeNoDefault;
}
/**************************************************************
*
* SECTION: IPC
*
* IPC related helpers.
*
**************************************************************/
// static
bool
nsWindow::IsAsyncResponseEvent(UINT aMsg, LRESULT& aResult)
{
switch(aMsg) {
case WM_SETFOCUS:
case WM_KILLFOCUS:
case WM_ENABLE:
case WM_WINDOWPOSCHANGING:
case WM_WINDOWPOSCHANGED:
case WM_PARENTNOTIFY:
case WM_ACTIVATEAPP:
case WM_NCACTIVATE:
case WM_ACTIVATE:
case WM_CHILDACTIVATE:
case WM_IME_SETCONTEXT:
case WM_IME_NOTIFY:
case WM_SHOWWINDOW:
case WM_CANCELMODE:
case WM_MOUSEACTIVATE:
case WM_CONTEXTMENU:
aResult = 0;
return true;
case WM_SETTINGCHANGE:
case WM_SETCURSOR:
return false;
}
#ifdef DEBUG
char szBuf[200];
sprintf(szBuf,
"An unhandled ISMEX_SEND message was received during spin loop! (%X)", aMsg);
NS_WARNING(szBuf);
#endif
return false;
}
void
nsWindow::IPCWindowProcHandler(UINT& msg, WPARAM& wParam, LPARAM& lParam)
{
MOZ_ASSERT_IF(msg != WM_GETOBJECT,
!mozilla::ipc::MessageChannel::IsPumpingMessages() ||
mozilla::ipc::SuppressedNeuteringRegion::IsNeuteringSuppressed());
// Modal UI being displayed in windowless plugins.
if (mozilla::ipc::MessageChannel::IsSpinLoopActive() &&
(InSendMessageEx(nullptr) & (ISMEX_REPLIED|ISMEX_SEND)) == ISMEX_SEND) {
LRESULT res;
if (IsAsyncResponseEvent(msg, res)) {
ReplyMessage(res);
}
return;
}
// Handle certain sync plugin events sent to the parent which
// trigger ipc calls that result in deadlocks.
DWORD dwResult = 0;
bool handled = false;
switch(msg) {
// Windowless flash sending WM_ACTIVATE events to the main window
// via calls to ShowWindow.
case WM_ACTIVATE:
if (lParam != 0 && LOWORD(wParam) == WA_ACTIVE &&
IsWindow((HWND)lParam)) {
// Check for Adobe Reader X sync activate message from their
// helper window and ignore. Fixes an annoying focus problem.
if ((InSendMessageEx(nullptr) & (ISMEX_REPLIED|ISMEX_SEND)) == ISMEX_SEND) {
wchar_t szClass[10];
HWND focusWnd = (HWND)lParam;
if (IsWindowVisible(focusWnd) &&
GetClassNameW(focusWnd, szClass,
sizeof(szClass)/sizeof(char16_t)) &&
!wcscmp(szClass, L"Edit") &&
!WinUtils::IsOurProcessWindow(focusWnd)) {
break;
}
}
handled = true;
}
break;
// Plugins taking or losing focus triggering focus app messages.
case WM_SETFOCUS:
case WM_KILLFOCUS:
// Windowed plugins that pass sys key events to defwndproc generate
// WM_SYSCOMMAND events to the main window.
case WM_SYSCOMMAND:
// Windowed plugins that fire context menu selection events to parent
// windows.
case WM_CONTEXTMENU:
// IME events fired as a result of synchronous focus changes
case WM_IME_SETCONTEXT:
handled = true;
break;
}
if (handled &&
(InSendMessageEx(nullptr) & (ISMEX_REPLIED|ISMEX_SEND)) == ISMEX_SEND) {
ReplyMessage(dwResult);
}
}
/**************************************************************
**************************************************************
**
** BLOCK: Native events
**
** Main Windows message handlers and OnXXX handlers for
** Windows event handling.
**
**************************************************************
**************************************************************/
/**************************************************************
*
* SECTION: Wind proc.
*
* The main Windows event procedures and associated
* message processing methods.
*
**************************************************************/
static bool
DisplaySystemMenu(HWND hWnd, nsSizeMode sizeMode, bool isRtl, int32_t x, int32_t y)
{
HMENU hMenu = GetSystemMenu(hWnd, FALSE);
if (hMenu) {
MENUITEMINFO mii;
mii.cbSize = sizeof(MENUITEMINFO);
mii.fMask = MIIM_STATE;
mii.fType = 0;
// update the options
mii.fState = MF_ENABLED;
SetMenuItemInfo(hMenu, SC_RESTORE, FALSE, &mii);
SetMenuItemInfo(hMenu, SC_SIZE, FALSE, &mii);
SetMenuItemInfo(hMenu, SC_MOVE, FALSE, &mii);
SetMenuItemInfo(hMenu, SC_MAXIMIZE, FALSE, &mii);
SetMenuItemInfo(hMenu, SC_MINIMIZE, FALSE, &mii);
mii.fState = MF_GRAYED;
switch(sizeMode) {
case nsSizeMode_Fullscreen:
// intentional fall through
case nsSizeMode_Maximized:
SetMenuItemInfo(hMenu, SC_SIZE, FALSE, &mii);
SetMenuItemInfo(hMenu, SC_MOVE, FALSE, &mii);
SetMenuItemInfo(hMenu, SC_MAXIMIZE, FALSE, &mii);
break;
case nsSizeMode_Minimized:
SetMenuItemInfo(hMenu, SC_MINIMIZE, FALSE, &mii);
break;
case nsSizeMode_Normal:
SetMenuItemInfo(hMenu, SC_RESTORE, FALSE, &mii);
break;
}
LPARAM cmd =
TrackPopupMenu(hMenu,
(TPM_LEFTBUTTON|TPM_RIGHTBUTTON|
TPM_RETURNCMD|TPM_TOPALIGN|
(isRtl ? TPM_RIGHTALIGN : TPM_LEFTALIGN)),
x, y, 0, hWnd, nullptr);
if (cmd) {
PostMessage(hWnd, WM_SYSCOMMAND, cmd, 0);
return true;
}
}
return false;
}
inline static mozilla::HangMonitor::ActivityType ActivityTypeForMessage(UINT msg)
{
if ((msg >= WM_KEYFIRST && msg <= WM_IME_KEYLAST) ||
(msg >= WM_MOUSEFIRST && msg <= WM_MOUSELAST) ||
(msg >= MOZ_WM_MOUSEWHEEL_FIRST && msg <= MOZ_WM_MOUSEWHEEL_LAST) ||
(msg >= NS_WM_IMEFIRST && msg <= NS_WM_IMELAST)) {
return mozilla::HangMonitor::kUIActivity;
}
// This may not actually be right, but we don't want to reset the timer if
// we're not actually processing a UI message.
return mozilla::HangMonitor::kActivityUIAVail;
}
// The WndProc procedure for all nsWindows in this toolkit. This merely catches
// exceptions and passes the real work to WindowProcInternal. See bug 587406
// and http://msdn.microsoft.com/en-us/library/ms633573%28VS.85%29.aspx
LRESULT CALLBACK nsWindow::WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
mozilla::ipc::CancelCPOWs();
HangMonitor::NotifyActivity(ActivityTypeForMessage(msg));
return mozilla::CallWindowProcCrashProtected(WindowProcInternal, hWnd, msg, wParam, lParam);
}
LRESULT CALLBACK nsWindow::WindowProcInternal(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (::GetWindowLongPtrW(hWnd, GWLP_ID) == eFakeTrackPointScrollableID) {
// This message was sent to the FAKETRACKPOINTSCROLLABLE.
if (msg == WM_HSCROLL) {
// Route WM_HSCROLL messages to the main window.
hWnd = ::GetParent(::GetParent(hWnd));
} else {
// Handle all other messages with its original window procedure.
WNDPROC prevWindowProc = (WNDPROC)::GetWindowLongPtr(hWnd, GWLP_USERDATA);
return ::CallWindowProcW(prevWindowProc, hWnd, msg, wParam, lParam);
}
}
if (msg == MOZ_WM_TRACE) {
// This is a tracer event for measuring event loop latency.
// See WidgetTraceEvent.cpp for more details.
mozilla::SignalTracerThread();
return 0;
}
// Get the window which caused the event and ask it to process the message
nsWindow *targetWindow = WinUtils::GetNSWindowPtr(hWnd);
NS_ASSERTION(targetWindow, "nsWindow* is null!");
if (!targetWindow)
return ::DefWindowProcW(hWnd, msg, wParam, lParam);
// Hold the window for the life of this method, in case it gets
// destroyed during processing, unless we're in the dtor already.
nsCOMPtr<nsIWidget> kungFuDeathGrip;
if (!targetWindow->mInDtor)
kungFuDeathGrip = targetWindow;
targetWindow->IPCWindowProcHandler(msg, wParam, lParam);
// Create this here so that we store the last rolled up popup until after
// the event has been processed.
nsAutoRollup autoRollup;
LRESULT popupHandlingResult;
if (DealWithPopups(hWnd, msg, wParam, lParam, &popupHandlingResult))
return popupHandlingResult;
// Call ProcessMessage
LRESULT retValue;
if (targetWindow->ProcessMessage(msg, wParam, lParam, &retValue)) {
return retValue;
}
LRESULT res = ::CallWindowProcW(targetWindow->GetPrevWindowProc(),
hWnd, msg, wParam, lParam);
return res;
}
// The main windows message processing method for plugins.
// The result means whether this method processed the native
// event for plugin. If false, the native event should be
// processed by the caller self.
bool
nsWindow::ProcessMessageForPlugin(const MSG &aMsg,
MSGResult& aResult)
{
aResult.mResult = 0;
aResult.mConsumed = true;
bool eventDispatched = false;
switch (aMsg.message) {
case WM_CHAR:
case WM_SYSCHAR:
aResult.mResult = ProcessCharMessage(aMsg, &eventDispatched);
break;
case WM_KEYUP:
case WM_SYSKEYUP:
aResult.mResult = ProcessKeyUpMessage(aMsg, &eventDispatched);
break;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
aResult.mResult = ProcessKeyDownMessage(aMsg, &eventDispatched);
break;
case WM_DEADCHAR:
case WM_SYSDEADCHAR:
case WM_CUT:
case WM_COPY:
case WM_PASTE:
case WM_CLEAR:
case WM_UNDO:
break;
default:
return false;
}
if (!eventDispatched) {
aResult.mConsumed = nsWindowBase::DispatchPluginEvent(aMsg);
}
if (!Destroyed()) {
DispatchPendingEvents();
}
return true;
}
static void ForceFontUpdate()
{
// update device context font cache
// Dirty but easiest way:
// Changing nsIPrefBranch entry which triggers callbacks
// and flows into calling mDeviceContext->FlushFontCache()
// to update the font cache in all the instance of Browsers
static const char kPrefName[] = "font.internaluseonly.changed";
bool fontInternalChange =
Preferences::GetBool(kPrefName, false);
Preferences::SetBool(kPrefName, !fontInternalChange);
}
static bool CleartypeSettingChanged()
{
static int currentQuality = -1;
BYTE quality = cairo_win32_get_system_text_quality();
if (currentQuality == quality)
return false;
if (currentQuality < 0) {
currentQuality = quality;
return false;
}
currentQuality = quality;
return true;
}
bool
nsWindow::ExternalHandlerProcessMessage(UINT aMessage,
WPARAM& aWParam,
LPARAM& aLParam,
MSGResult& aResult)
{
if (mWindowHook.Notify(mWnd, aMessage, aWParam, aLParam, aResult)) {
return true;
}
if (IMEHandler::ProcessMessage(this, aMessage, aWParam, aLParam, aResult)) {
return true;
}
if (MouseScrollHandler::ProcessMessage(this, aMessage, aWParam, aLParam,
aResult)) {
return true;
}
if (PluginHasFocus()) {
MSG nativeMsg = WinUtils::InitMSG(aMessage, aWParam, aLParam, mWnd);
if (ProcessMessageForPlugin(nativeMsg, aResult)) {
return true;
}
}
return false;
}
// The main windows message processing method.
bool
nsWindow::ProcessMessage(UINT msg, WPARAM& wParam, LPARAM& lParam,
LRESULT *aRetValue)
{
#if defined(EVENT_DEBUG_OUTPUT)
// First param shows all events, second param indicates whether
// to show mouse move events. See nsWindowDbg for details.
PrintEvent(msg, SHOW_REPEAT_EVENTS, SHOW_MOUSEMOVE_EVENTS);
#endif
MSGResult msgResult(aRetValue);
if (ExternalHandlerProcessMessage(msg, wParam, lParam, msgResult)) {
return (msgResult.mConsumed || !mWnd);
}
bool result = false; // call the default nsWindow proc
*aRetValue = 0;
// Glass hit testing w/custom transparent margins
LRESULT dwmHitResult;
if (mCustomNonClient &&
nsUXThemeData::CheckForCompositor() &&
/* We don't do this for win10 glass with a custom titlebar,
* in order to avoid the caption buttons breaking. */
!(IsWin10OrLater() && HasGlass()) &&
DwmDefWindowProc(mWnd, msg, wParam, lParam, &dwmHitResult)) {
*aRetValue = dwmHitResult;
return true;
}
// (Large blocks of code should be broken out into OnEvent handlers.)
switch (msg) {
// WM_QUERYENDSESSION must be handled by all windows.
// Otherwise Windows thinks the window can just be killed at will.
case WM_QUERYENDSESSION:
if (sCanQuit == TRI_UNKNOWN)
{
// Ask if it's ok to quit, and store the answer until we
// get WM_ENDSESSION signaling the round is complete.
nsCOMPtr<nsIObserverService> obsServ =
mozilla::services::GetObserverService();
nsCOMPtr<nsISupportsPRBool> cancelQuit =
do_CreateInstance(NS_SUPPORTS_PRBOOL_CONTRACTID);
cancelQuit->SetData(false);
obsServ->NotifyObservers(cancelQuit, "quit-application-requested", nullptr);
bool abortQuit;
cancelQuit->GetData(&abortQuit);
sCanQuit = abortQuit ? TRI_FALSE : TRI_TRUE;
}
*aRetValue = sCanQuit ? TRUE : FALSE;
result = true;
break;
case MOZ_WM_STARTA11Y:
#if defined(ACCESSIBILITY)
(void*)GetAccessible();
result = true;
#else
result = false;
#endif
break;
case WM_ENDSESSION:
case MOZ_WM_APP_QUIT:
if (msg == MOZ_WM_APP_QUIT || (wParam == TRUE && sCanQuit == TRI_TRUE))
{
// Let's fake a shutdown sequence without actually closing windows etc.
// to avoid Windows killing us in the middle. A proper shutdown would
// require having a chance to pump some messages. Unfortunately
// Windows won't let us do that. Bug 212316.
nsCOMPtr<nsIObserverService> obsServ =
mozilla::services::GetObserverService();
const char16_t* context = u"shutdown-persist";
const char16_t* syncShutdown = u"syncShutdown";
obsServ->NotifyObservers(nullptr, "quit-application-granted", syncShutdown);
obsServ->NotifyObservers(nullptr, "quit-application-forced", nullptr);
obsServ->NotifyObservers(nullptr, "quit-application", nullptr);
obsServ->NotifyObservers(nullptr, "profile-change-net-teardown", context);
obsServ->NotifyObservers(nullptr, "profile-change-teardown", context);
obsServ->NotifyObservers(nullptr, "profile-before-change", context);
obsServ->NotifyObservers(nullptr, "profile-before-change-qm", context);
obsServ->NotifyObservers(nullptr, "profile-before-change-telemetry", context);
// Then a controlled but very quick exit.
_exit(0);
}
sCanQuit = TRI_UNKNOWN;
result = true;
break;
case WM_SYSCOLORCHANGE:
OnSysColorChanged();
break;
case WM_THEMECHANGED:
{
// Update non-client margin offsets
UpdateNonClientMargins();
nsUXThemeData::InitTitlebarInfo();
nsUXThemeData::UpdateNativeThemeInfo();
NotifyThemeChanged();
// Invalidate the window so that the repaint will
// pick up the new theme.
Invalidate(true, true, true);
}
break;
case WM_WTSSESSION_CHANGE:
{
switch (wParam) {
case WTS_CONSOLE_CONNECT:
case WTS_REMOTE_CONNECT:
case WTS_SESSION_UNLOCK:
// When a session becomes visible, we should invalidate.
Invalidate(true, true, true);
break;
default:
break;
}
}
break;
case WM_FONTCHANGE:
{
// We only handle this message for the hidden window,
// as we only need to update the (global) font list once
// for any given change, not once per window!
if (mWindowType != eWindowType_invisible) {
break;
}
nsresult rv;
bool didChange = false;
// update the global font list
nsCOMPtr<nsIFontEnumerator> fontEnum = do_GetService("@mozilla.org/gfx/fontenumerator;1", &rv);
if (NS_SUCCEEDED(rv)) {
fontEnum->UpdateFontList(&didChange);
ForceFontUpdate();
} //if (NS_SUCCEEDED(rv))
}
break;
case WM_SETTINGCHANGE:
{
if (IsWin10OrLater() && mWindowType == eWindowType_invisible && lParam) {
auto lParamString = reinterpret_cast<const wchar_t*>(lParam);
if (!wcscmp(lParamString, L"UserInteractionMode")) {
nsCOMPtr<nsIWindowsUIUtils> uiUtils(do_GetService("@mozilla.org/windows-ui-utils;1"));
if (uiUtils) {
uiUtils->UpdateTabletModeState();
}
}
}
}
break;
case WM_NCCALCSIZE:
{
if (mCustomNonClient) {
// If `wParam` is `FALSE`, `lParam` points to a `RECT` that contains
// the proposed window rectangle for our window. During our
// processing of the `WM_NCCALCSIZE` message, we are expected to
// modify the `RECT` that `lParam` points to, so that its value upon
// our return is the new client area. We must return 0 if `wParam`
// is `FALSE`.
//
// If `wParam` is `TRUE`, `lParam` points to a `NCCALCSIZE_PARAMS`
// struct. This struct contains an array of 3 `RECT`s, the first of
// which has the exact same meaning as the `RECT` that is pointed to
// by `lParam` when `wParam` is `FALSE`. The remaining `RECT`s, in
// conjunction with our return value, can
// be used to specify portions of the source and destination window
// rectangles that are valid and should be preserved. We opt not to
// implement an elaborate client-area preservation technique, and
// simply return 0, which means "preserve the entire old client area
// and align it with the upper-left corner of our new client area".
RECT *clientRect = wParam
? &(reinterpret_cast<NCCALCSIZE_PARAMS*>(lParam))->rgrc[0]
: (reinterpret_cast<RECT*>(lParam));
double scale = WinUtils::IsPerMonitorDPIAware()
? WinUtils::LogToPhysFactor(mWnd) / WinUtils::SystemScaleFactor()
: 1.0;
clientRect->top +=
NSToIntRound((mCaptionHeight - mNonClientOffset.top) * scale);
clientRect->left +=
NSToIntRound((mHorResizeMargin - mNonClientOffset.left) * scale);
clientRect->right -=
NSToIntRound((mHorResizeMargin - mNonClientOffset.right) * scale);
clientRect->bottom -=
NSToIntRound((mVertResizeMargin - mNonClientOffset.bottom) * scale);
// Make client rect's width and height more than 0 to
// avoid problems of webrender and angle.
clientRect->right = std::max(clientRect->right, clientRect->left + 1);
clientRect->bottom = std::max(clientRect->bottom, clientRect->top + 1);
result = true;
*aRetValue = 0;
}
break;
}
case WM_NCHITTEST:
{
if (mMouseTransparent) {
// Treat this window as transparent.
*aRetValue = HTTRANSPARENT;
result = true;
break;
}
/*
* If an nc client area margin has been moved, we are responsible
* for calculating where the resize margins are and returning the
* appropriate set of hit test constants. DwmDefWindowProc (above)
* will handle hit testing on it's command buttons if we are on a
* composited desktop.
*/
if (!mCustomNonClient)
break;
*aRetValue =
ClientMarginHitTestPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
result = true;
break;
}
case WM_SETTEXT:
/*
* WM_SETTEXT paints the titlebar area. Avoid this if we have a
* custom titlebar we paint ourselves, or if we're the ones
* sending the message with an updated title
*/
if ((mSendingSetText && nsUXThemeData::CheckForCompositor()) ||
!mCustomNonClient || mNonClientMargins.top == -1)
break;
{
// From msdn, the way around this is to disable the visible state
// temporarily. We need the text to be set but we don't want the
// redraw to occur. However, we need to make sure that we don't
// do this at the same time that a Present is happening.
//
// To do this we take mPresentLock in nsWindow::PreRender and
// if that lock is taken we wait before doing WM_SETTEXT
if (mCompositorWidgetDelegate) {
mCompositorWidgetDelegate->EnterPresentLock();
}
DWORD style = GetWindowLong(mWnd, GWL_STYLE);
SetWindowLong(mWnd, GWL_STYLE, style & ~WS_VISIBLE);
*aRetValue = CallWindowProcW(GetPrevWindowProc(), mWnd,
msg, wParam, lParam);
SetWindowLong(mWnd, GWL_STYLE, style);
if (mCompositorWidgetDelegate) {
mCompositorWidgetDelegate->LeavePresentLock();
}
return true;
}
case WM_NCACTIVATE:
{
/*
* WM_NCACTIVATE paints nc areas. Avoid this and re-route painting
* through WM_NCPAINT via InvalidateNonClientRegion.
*/
UpdateGetWindowInfoCaptionStatus(FALSE != wParam);
if (!mCustomNonClient)
break;
// There is a case that rendered result is not kept. Bug 1237617
if (wParam == TRUE &&
!gfxEnv::DisableForcePresent() &&
gfxWindowsPlatform::GetPlatform()->DwmCompositionEnabled()) {
NS_DispatchToMainThread(NewRunnableMethod(this, &nsWindow::ForcePresent));
}
// let the dwm handle nc painting on glass
// Never allow native painting if we are on fullscreen
if(mSizeMode != nsSizeMode_Fullscreen &&
nsUXThemeData::CheckForCompositor())
break;
if (wParam == TRUE) {
// going active
*aRetValue = FALSE; // ignored
result = true;
// invalidate to trigger a paint
InvalidateNonClientRegion();
break;
} else {
// going inactive
*aRetValue = TRUE; // go ahead and deactive
result = true;
// invalidate to trigger a paint
InvalidateNonClientRegion();
break;
}
}
case WM_NCPAINT:
{
/*
* Reset the non-client paint region so that it excludes the
* non-client areas we paint manually. Then call defwndproc
* to do the actual painting.
*/
if (!mCustomNonClient)
break;
// let the dwm handle nc painting on glass
if(nsUXThemeData::CheckForCompositor())
break;
HRGN paintRgn = ExcludeNonClientFromPaintRegion((HRGN)wParam);
LRESULT res = CallWindowProcW(GetPrevWindowProc(), mWnd,
msg, (WPARAM)paintRgn, lParam);
if (paintRgn != (HRGN)wParam)
DeleteObject(paintRgn);
*aRetValue = res;
result = true;
}
break;
case WM_POWERBROADCAST:
switch (wParam)
{
case PBT_APMSUSPEND:
PostSleepWakeNotification(true);
break;
case PBT_APMRESUMEAUTOMATIC:
case PBT_APMRESUMECRITICAL:
case PBT_APMRESUMESUSPEND:
PostSleepWakeNotification(false);
break;
}
break;
case WM_CLOSE: // close request
if (mWidgetListener)
mWidgetListener->RequestWindowClose(this);
result = true; // abort window closure
break;
case WM_DESTROY:
// clean up.
DestroyLayerManager();
OnDestroy();
result = true;
break;
case WM_PAINT:
if (CleartypeSettingChanged()) {
ForceFontUpdate();
gfxFontCache *fc = gfxFontCache::GetCache();
if (fc) {
fc->Flush();
}
}
*aRetValue = (int) OnPaint(nullptr, 0);
result = true;
break;
case WM_PRINTCLIENT:
result = OnPaint((HDC) wParam, 0);
break;
case WM_HOTKEY:
result = OnHotKey(wParam, lParam);
break;
case WM_SYSCHAR:
case WM_CHAR:
{
MSG nativeMsg = WinUtils::InitMSG(msg, wParam, lParam, mWnd);
result = ProcessCharMessage(nativeMsg, nullptr);
DispatchPendingEvents();
}
break;
case WM_SYSKEYUP:
case WM_KEYUP:
{
MSG nativeMsg = WinUtils::InitMSG(msg, wParam, lParam, mWnd);
nativeMsg.time = ::GetMessageTime();
result = ProcessKeyUpMessage(nativeMsg, nullptr);
DispatchPendingEvents();
}
break;
case WM_SYSKEYDOWN:
case WM_KEYDOWN:
{
MSG nativeMsg = WinUtils::InitMSG(msg, wParam, lParam, mWnd);
result = ProcessKeyDownMessage(nativeMsg, nullptr);
DispatchPendingEvents();
}
break;
// say we've dealt with erase background if widget does
// not need auto-erasing
case WM_ERASEBKGND:
if (!AutoErase((HDC)wParam)) {
*aRetValue = 1;
result = true;
}
break;
case WM_MOUSEMOVE:
{
if (!mMousePresent && !sIsInMouseCapture) {
// First MOUSEMOVE over the client area. Ask for MOUSELEAVE
TRACKMOUSEEVENT mTrack;
mTrack.cbSize = sizeof(TRACKMOUSEEVENT);
mTrack.dwFlags = TME_LEAVE;
mTrack.dwHoverTime = 0;
mTrack.hwndTrack = mWnd;
TrackMouseEvent(&mTrack);
}
mMousePresent = true;
// Suppress dispatch of pending events
// when mouse moves are generated by widget
// creation instead of user input.
LPARAM lParamScreen = lParamToScreen(lParam);
POINT mp;
mp.x = GET_X_LPARAM(lParamScreen);
mp.y = GET_Y_LPARAM(lParamScreen);
bool userMovedMouse = false;
if ((sLastMouseMovePoint.x != mp.x) || (sLastMouseMovePoint.y != mp.y)) {
userMovedMouse = true;
}
result = DispatchMouseEvent(eMouseMove, wParam, lParam,
false, WidgetMouseEvent::eLeftButton,
MOUSE_INPUT_SOURCE(),
mPointerEvents.GetCachedPointerInfo(msg, wParam));
if (userMovedMouse) {
DispatchPendingEvents();
}
}
break;
case WM_NCMOUSEMOVE:
// If we receive a mouse move event on non-client chrome, make sure and
// send an eMouseExitFromWidget event as well.
if (mMousePresent && !sIsInMouseCapture)
SendMessage(mWnd, WM_MOUSELEAVE, 0, 0);
break;
case WM_LBUTTONDOWN:
{
result = DispatchMouseEvent(eMouseDown, wParam, lParam,
false, WidgetMouseEvent::eLeftButton,
MOUSE_INPUT_SOURCE(),
mPointerEvents.GetCachedPointerInfo(msg, wParam));
DispatchPendingEvents();
}
break;
case WM_LBUTTONUP:
{
result = DispatchMouseEvent(eMouseUp, wParam, lParam,
false, WidgetMouseEvent::eLeftButton,
MOUSE_INPUT_SOURCE(),
mPointerEvents.GetCachedPointerInfo(msg, wParam));
DispatchPendingEvents();
}
break;
case WM_MOUSELEAVE:
{
if (!mMousePresent)
break;
mMousePresent = false;
// We need to check mouse button states and put them in for
// wParam.
WPARAM mouseState = (GetKeyState(VK_LBUTTON) ? MK_LBUTTON : 0)
| (GetKeyState(VK_MBUTTON) ? MK_MBUTTON : 0)
| (GetKeyState(VK_RBUTTON) ? MK_RBUTTON : 0);
// Synthesize an event position because we don't get one from
// WM_MOUSELEAVE.
LPARAM pos = lParamToClient(::GetMessagePos());
DispatchMouseEvent(eMouseExitFromWidget, mouseState, pos, false,
WidgetMouseEvent::eLeftButton,
MOUSE_INPUT_SOURCE());
}
break;
case MOZ_WM_PEN_LEAVES_HOVER_OF_DIGITIZER:
{
LPARAM pos = lParamToClient(::GetMessagePos());
MOZ_ASSERT(InkCollector::sInkCollector);
uint16_t pointerId = InkCollector::sInkCollector->GetPointerId();
if (pointerId != 0) {
WinPointerInfo pointerInfo;
pointerInfo.pointerId = pointerId;
DispatchMouseEvent(eMouseExitFromWidget, wParam, pos, false,
WidgetMouseEvent::eLeftButton,
nsIDOMMouseEvent::MOZ_SOURCE_PEN, &pointerInfo);
InkCollector::sInkCollector->ClearTarget();
InkCollector::sInkCollector->ClearPointerId();
}
}
break;
case WM_CONTEXTMENU:
{
// If the context menu is brought up by a touch long-press, then
// the APZ code is responsible for dealing with this, so we don't
// need to do anything.
if (mTouchWindow && MOUSE_INPUT_SOURCE() == nsIDOMMouseEvent::MOZ_SOURCE_TOUCH) {
MOZ_ASSERT(mAPZC); // since mTouchWindow is true, APZ must be enabled
result = true;
break;
}
// if the context menu is brought up from the keyboard, |lParam|
// will be -1.
LPARAM pos;
bool contextMenukey = false;
if (lParam == -1)
{
contextMenukey = true;
pos = lParamToClient(GetMessagePos());
}
else
{
pos = lParamToClient(lParam);
}
result = DispatchMouseEvent(eContextMenu, wParam, pos, contextMenukey,
contextMenukey ?
WidgetMouseEvent::eLeftButton :
WidgetMouseEvent::eRightButton,
MOUSE_INPUT_SOURCE());
if (lParam != -1 && !result && mCustomNonClient &&
mDraggableRegion.Contains(GET_X_LPARAM(pos), GET_Y_LPARAM(pos))) {
// Blank area hit, throw up the system menu.
DisplaySystemMenu(mWnd, mSizeMode, mIsRTL, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
result = true;
}
}
break;
case WM_POINTERLEAVE:
case WM_POINTERDOWN:
case WM_POINTERUP:
case WM_POINTERUPDATE:
result = OnPointerEvents(msg, wParam, lParam);
if (result) {
DispatchPendingEvents();
}
break;
case WM_LBUTTONDBLCLK:
result = DispatchMouseEvent(eMouseDoubleClick, wParam,
lParam, false,
WidgetMouseEvent::eLeftButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
case WM_MBUTTONDOWN:
result = DispatchMouseEvent(eMouseDown, wParam,
lParam, false,
WidgetMouseEvent::eMiddleButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
case WM_MBUTTONUP:
result = DispatchMouseEvent(eMouseUp, wParam,
lParam, false,
WidgetMouseEvent::eMiddleButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
case WM_MBUTTONDBLCLK:
result = DispatchMouseEvent(eMouseDoubleClick, wParam,
lParam, false,
WidgetMouseEvent::eMiddleButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
case WM_NCMBUTTONDOWN:
result = DispatchMouseEvent(eMouseDown, 0,
lParamToClient(lParam), false,
WidgetMouseEvent::eMiddleButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
case WM_NCMBUTTONUP:
result = DispatchMouseEvent(eMouseUp, 0,
lParamToClient(lParam), false,
WidgetMouseEvent::eMiddleButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
case WM_NCMBUTTONDBLCLK:
result = DispatchMouseEvent(eMouseDoubleClick, 0,
lParamToClient(lParam), false,
WidgetMouseEvent::eMiddleButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
case WM_RBUTTONDOWN:
result = DispatchMouseEvent(eMouseDown, wParam,
lParam, false,
WidgetMouseEvent::eRightButton,
MOUSE_INPUT_SOURCE(),
mPointerEvents.GetCachedPointerInfo(msg, wParam));
DispatchPendingEvents();
break;
case WM_RBUTTONUP:
result = DispatchMouseEvent(eMouseUp, wParam,
lParam, false,
WidgetMouseEvent::eRightButton,
MOUSE_INPUT_SOURCE(),
mPointerEvents.GetCachedPointerInfo(msg, wParam));
DispatchPendingEvents();
break;
case WM_RBUTTONDBLCLK:
result = DispatchMouseEvent(eMouseDoubleClick, wParam,
lParam, false,
WidgetMouseEvent::eRightButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
case WM_NCRBUTTONDOWN:
result = DispatchMouseEvent(eMouseDown, 0,
lParamToClient(lParam), false,
WidgetMouseEvent::eRightButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
case WM_NCRBUTTONUP:
result = DispatchMouseEvent(eMouseUp, 0,
lParamToClient(lParam), false,
WidgetMouseEvent::eRightButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
case WM_NCRBUTTONDBLCLK:
result = DispatchMouseEvent(eMouseDoubleClick, 0,
lParamToClient(lParam), false,
WidgetMouseEvent::eRightButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
// Windows doesn't provide to customize the behavior of 4th nor 5th button
// of mouse. If 5-button mouse works with standard mouse deriver of
// Windows, users cannot disable 4th button (browser back) nor 5th button
// (browser forward). We should allow to do it with our prefs since we can
// prevent Windows to generate WM_APPCOMMAND message if WM_XBUTTONUP
// messages are not sent to DefWindowProc.
case WM_XBUTTONDOWN:
case WM_XBUTTONUP:
case WM_NCXBUTTONDOWN:
case WM_NCXBUTTONUP:
*aRetValue = TRUE;
switch (GET_XBUTTON_WPARAM(wParam)) {
case XBUTTON1:
result = !Preferences::GetBool("mousebutton.4th.enabled", true);
break;
case XBUTTON2:
result = !Preferences::GetBool("mousebutton.5th.enabled", true);
break;
default:
break;
}
break;
case WM_SIZING:
{
// When we get WM_ENTERSIZEMOVE we don't know yet if we're in a live
// resize or move event. Instead we wait for first VM_SIZING message
// within a ENTERSIZEMOVE to consider this a live resize event.
if (mResizeState == IN_SIZEMOVE) {
mResizeState = RESIZING;
NotifyLiveResizeStarted();
}
break;
}
case WM_MOVING:
FinishLiveResizing(MOVING);
if (WinUtils::IsPerMonitorDPIAware()) {
// Sometimes, we appear to miss a WM_DPICHANGED message while moving
// a window around. Therefore, call ChangedDPI and ResetLayout here
// if it appears that the window's scaling is not what we expect.
// This causes the prescontext and appshell window management code to
// check the appUnitsPerDevPixel value and current widget size, and
// refresh them if necessary. If nothing has changed, these calls will
// return without actually triggering any extra reflow or painting.
if (WinUtils::LogToPhysFactor(mWnd) != mDefaultScale) {
ChangedDPI();
ResetLayout();
}
}
break;
case WM_ENTERSIZEMOVE:
{
if (mResizeState == NOT_RESIZING) {
mResizeState = IN_SIZEMOVE;
}
break;
}
case WM_EXITSIZEMOVE:
{
FinishLiveResizing(NOT_RESIZING);
if (!sIsInMouseCapture) {
NotifySizeMoveDone();
}
break;
}
case WM_DISPLAYCHANGE:
{
ScreenHelperWin::RefreshScreens();
break;
}
case WM_NCLBUTTONDBLCLK:
DispatchMouseEvent(eMouseDoubleClick, 0, lParamToClient(lParam),
false, WidgetMouseEvent::eLeftButton,
MOUSE_INPUT_SOURCE());
result =
DispatchMouseEvent(eMouseUp, 0, lParamToClient(lParam),
false, WidgetMouseEvent::eLeftButton,
MOUSE_INPUT_SOURCE());
DispatchPendingEvents();
break;
case WM_APPCOMMAND:
{
MSG nativeMsg = WinUtils::InitMSG(msg, wParam, lParam, mWnd);
result = HandleAppCommandMsg(nativeMsg, aRetValue);
break;
}
// The WM_ACTIVATE event is fired when a window is raised or lowered,
// and the loword of wParam specifies which. But we don't want to tell
// the focus system about this until the WM_SETFOCUS or WM_KILLFOCUS
// events are fired. Instead, set either the sJustGotActivate or
// gJustGotDeactivate flags and activate/deactivate once the focus
// events arrive.
case WM_ACTIVATE:
if (mWidgetListener) {
int32_t fActive = LOWORD(wParam);
if (WA_INACTIVE == fActive) {
// when minimizing a window, the deactivation and focus events will
// be fired in the reverse order. Instead, just deactivate right away.
if (HIWORD(wParam))
DispatchFocusToTopLevelWindow(false);
else
sJustGotDeactivate = true;
if (mIsTopWidgetWindow)
mLastKeyboardLayout = KeyboardLayout::GetInstance()->GetLayout();
} else {
StopFlashing();
sJustGotActivate = true;
WidgetMouseEvent event(true, eMouseActivate, this,
WidgetMouseEvent::eReal);
InitEvent(event);
ModifierKeyState modifierKeyState;
modifierKeyState.InitInputEvent(event);
DispatchInputEvent(&event);
if (sSwitchKeyboardLayout && mLastKeyboardLayout)
ActivateKeyboardLayout(mLastKeyboardLayout, 0);
}
}
break;
case WM_MOUSEACTIVATE:
// A popup with a parent owner should not be activated when clicked but
// should still allow the mouse event to be fired, so the return value
// is set to MA_NOACTIVATE. But if the owner isn't the frontmost window,
// just use default processing so that the window is activated.
if (IsPopup() && IsOwnerForegroundWindow()) {
*aRetValue = MA_NOACTIVATE;
result = true;
}
break;
case WM_WINDOWPOSCHANGING:
{
LPWINDOWPOS info = (LPWINDOWPOS)lParam;
OnWindowPosChanging(info);
result = true;
}
break;
case WM_GETMINMAXINFO:
{
MINMAXINFO* mmi = (MINMAXINFO*)lParam;
// Set the constraints. The minimum size should also be constrained to the
// default window maximum size so that it fits on screen.
mmi->ptMinTrackSize.x =
std::min((int32_t)mmi->ptMaxTrackSize.x,
std::max((int32_t)mmi->ptMinTrackSize.x, mSizeConstraints.mMinSize.width));
mmi->ptMinTrackSize.y =
std::min((int32_t)mmi->ptMaxTrackSize.y,
std::max((int32_t)mmi->ptMinTrackSize.y, mSizeConstraints.mMinSize.height));
mmi->ptMaxTrackSize.x = std::min((int32_t)mmi->ptMaxTrackSize.x, mSizeConstraints.mMaxSize.width);
mmi->ptMaxTrackSize.y = std::min((int32_t)mmi->ptMaxTrackSize.y, mSizeConstraints.mMaxSize.height);
}
break;
case WM_SETFOCUS:
// If previous focused window isn't ours, it must have received the
// redirected message. So, we should forget it.
if (!WinUtils::IsOurProcessWindow(HWND(wParam))) {
RedirectedKeyDownMessageManager::Forget();
}
if (sJustGotActivate) {
DispatchFocusToTopLevelWindow(true);
}
break;
case WM_KILLFOCUS:
if (sJustGotDeactivate) {
DispatchFocusToTopLevelWindow(false);
}
break;
case WM_WINDOWPOSCHANGED:
{
WINDOWPOS* wp = (LPWINDOWPOS)lParam;
OnWindowPosChanged(wp);
result = true;
}
break;
case WM_INPUTLANGCHANGEREQUEST:
*aRetValue = TRUE;
result = false;
break;
case WM_INPUTLANGCHANGE:
KeyboardLayout::GetInstance()->
OnLayoutChange(reinterpret_cast<HKL>(lParam));
nsBidiKeyboard::OnLayoutChange();
result = false; // always pass to child window
break;
case WM_DESTROYCLIPBOARD:
{
nsIClipboard* clipboard;
nsresult rv = CallGetService(kCClipboardCID, &clipboard);
if(NS_SUCCEEDED(rv)) {
clipboard->EmptyClipboard(nsIClipboard::kGlobalClipboard);
NS_RELEASE(clipboard);
}
}
break;
#ifdef ACCESSIBILITY
case WM_GETOBJECT:
{
*aRetValue = 0;
// Do explicit casting to make it working on 64bit systems (see bug 649236
// for details).
int32_t objId = static_cast<DWORD>(lParam);
if (objId == OBJID_CLIENT) { // oleacc.dll will be loaded dynamically
a11y::Accessible* rootAccessible = GetAccessible(); // Held by a11y cache
if (rootAccessible) {
IAccessible *msaaAccessible = nullptr;
rootAccessible->GetNativeInterface((void**)&msaaAccessible); // does an addref
if (msaaAccessible) {
*aRetValue = LresultFromObject(IID_IAccessible, wParam, msaaAccessible); // does an addref
msaaAccessible->Release(); // release extra addref
result = true; // We handled the WM_GETOBJECT message
}
}
}
}
break;
#endif
case WM_SYSCOMMAND:
{
WPARAM filteredWParam = (wParam &0xFFF0);
if (mSizeMode == nsSizeMode_Fullscreen &&
filteredWParam == SC_RESTORE &&
GetCurrentShowCmd(mWnd) != SW_SHOWMINIMIZED) {
MakeFullScreen(false);
result = true;
}
// Handle the system menu manually when we're in full screen mode
// so we can set the appropriate options.
if (filteredWParam == SC_KEYMENU && lParam == VK_SPACE &&
mSizeMode == nsSizeMode_Fullscreen) {
DisplaySystemMenu(mWnd, mSizeMode, mIsRTL,
MOZ_SYSCONTEXT_X_POS,
MOZ_SYSCONTEXT_Y_POS);
result = true;
}
}
break;
case WM_DWMCOMPOSITIONCHANGED:
// First, update the compositor state to latest one. All other methods
// should use same state as here for consistency painting.
nsUXThemeData::CheckForCompositor(true);
UpdateNonClientMargins();
BroadcastMsg(mWnd, WM_DWMCOMPOSITIONCHANGED);
NotifyThemeChanged();
UpdateGlass();
Invalidate(true, true, true);
break;
case WM_DPICHANGED:
{
LPRECT rect = (LPRECT) lParam;
OnDPIChanged(rect->left, rect->top, rect->right - rect->left,
rect->bottom - rect->top);
break;
}
case WM_UPDATEUISTATE:
{
// If the UI state has changed, fire an event so the UI updates the
// keyboard cues based on the system setting and how the window was
// opened. For example, a dialog opened via a keyboard press on a button
// should enable cues, whereas the same dialog opened via a mouse click of
// the button should not.
if (mWindowType == eWindowType_toplevel ||
mWindowType == eWindowType_dialog) {
int32_t action = LOWORD(wParam);
if (action == UIS_SET || action == UIS_CLEAR) {
int32_t flags = HIWORD(wParam);
UIStateChangeType showAccelerators = UIStateChangeType_NoChange;
UIStateChangeType showFocusRings = UIStateChangeType_NoChange;
if (flags & UISF_HIDEACCEL)
showAccelerators = (action == UIS_SET) ? UIStateChangeType_Clear : UIStateChangeType_Set;
if (flags & UISF_HIDEFOCUS)
showFocusRings = (action == UIS_SET) ? UIStateChangeType_Clear : UIStateChangeType_Set;
NotifyUIStateChanged(showAccelerators, showFocusRings);
}
}
break;
}
/* Gesture support events */
case WM_TABLET_QUERYSYSTEMGESTURESTATUS:
// According to MS samples, this must be handled to enable
// rotational support in multi-touch drivers.
result = true;
*aRetValue = TABLET_ROTATE_GESTURE_ENABLE;
break;
case WM_TOUCH:
result = OnTouch(wParam, lParam);
if (result) {
*aRetValue = 0;
}
break;
case WM_GESTURE:
result = OnGesture(wParam, lParam);
break;
case WM_GESTURENOTIFY:
{
if (mWindowType != eWindowType_invisible &&
!IsPlugin()) {
// A GestureNotify event is dispatched to decide which single-finger panning
// direction should be active (including none) and if pan feedback should
// be displayed. Java and plugin windows can make their own calls.
GESTURENOTIFYSTRUCT * gestureinfo = (GESTURENOTIFYSTRUCT*)lParam;
nsPointWin touchPoint;
touchPoint = gestureinfo->ptsLocation;
touchPoint.ScreenToClient(mWnd);
WidgetGestureNotifyEvent gestureNotifyEvent(true, eGestureNotify, this);
gestureNotifyEvent.mRefPoint =
LayoutDeviceIntPoint::FromUnknownPoint(touchPoint);
nsEventStatus status;
DispatchEvent(&gestureNotifyEvent, status);
mDisplayPanFeedback = gestureNotifyEvent.mDisplayPanFeedback;
if (!mTouchWindow)
mGesture.SetWinGestureSupport(mWnd, gestureNotifyEvent.mPanDirection);
}
result = false; //should always bubble to DefWindowProc
}
break;
case WM_CLEAR:
{
WidgetContentCommandEvent command(true, eContentCommandDelete, this);
DispatchWindowEvent(&command);
result = true;
}
break;
case WM_CUT:
{
WidgetContentCommandEvent command(true, eContentCommandCut, this);
DispatchWindowEvent(&command);
result = true;
}
break;
case WM_COPY:
{
WidgetContentCommandEvent command(true, eContentCommandCopy, this);
DispatchWindowEvent(&command);
result = true;
}
break;
case WM_PASTE:
{
WidgetContentCommandEvent command(true, eContentCommandPaste, this);
DispatchWindowEvent(&command);
result = true;
}
break;
case EM_UNDO:
{
WidgetContentCommandEvent command(true, eContentCommandUndo, this);
DispatchWindowEvent(&command);
*aRetValue = (LRESULT)(command.mSucceeded && command.mIsEnabled);
result = true;
}
break;
case EM_REDO:
{
WidgetContentCommandEvent command(true, eContentCommandRedo, this);
DispatchWindowEvent(&command);
*aRetValue = (LRESULT)(command.mSucceeded && command.mIsEnabled);
result = true;
}
break;
case EM_CANPASTE:
{
// Support EM_CANPASTE message only when wParam isn't specified or
// is plain text format.
if (wParam == 0 || wParam == CF_TEXT || wParam == CF_UNICODETEXT) {
WidgetContentCommandEvent command(true, eContentCommandPaste,
this, true);
DispatchWindowEvent(&command);
*aRetValue = (LRESULT)(command.mSucceeded && command.mIsEnabled);
result = true;
}
}
break;
case EM_CANUNDO:
{
WidgetContentCommandEvent command(true, eContentCommandUndo, this, true);
DispatchWindowEvent(&command);
*aRetValue = (LRESULT)(command.mSucceeded && command.mIsEnabled);
result = true;
}
break;
case EM_CANREDO:
{
WidgetContentCommandEvent command(true, eContentCommandRedo, this, true);
DispatchWindowEvent(&command);
*aRetValue = (LRESULT)(command.mSucceeded && command.mIsEnabled);
result = true;
}
break;
case MOZ_WM_SKEWFIX:
{
TimeStamp skewStamp;
if (CurrentWindowsTimeGetter::GetAndClearBackwardsSkewStamp(wParam, &skewStamp)) {
TimeConverter().CompensateForBackwardsSkew(::GetMessageTime(), skewStamp);
}
}
break;
default:
{
if (msg == nsAppShell::GetTaskbarButtonCreatedMessage()) {
SetHasTaskbarIconBeenCreated();
}
}
break;
}
//*aRetValue = result;
if (mWnd) {
return result;
}
else {
//Events which caused mWnd destruction and aren't consumed
//will crash during the Windows default processing.
return true;
}
}
void
nsWindow::FinishLiveResizing(ResizeState aNewState)
{
if (mResizeState == RESIZING) {
NotifyLiveResizeStopped();
}
mResizeState = aNewState;
ForcePresent();
}
/**************************************************************
*
* SECTION: Broadcast messaging
*
* Broadcast messages to all windows.
*
**************************************************************/
// Enumerate all child windows sending aMsg to each of them
BOOL CALLBACK nsWindow::BroadcastMsgToChildren(HWND aWnd, LPARAM aMsg)
{
WNDPROC winProc = (WNDPROC)::GetWindowLongPtrW(aWnd, GWLP_WNDPROC);
if (winProc == &nsWindow::WindowProc) {
// it's one of our windows so go ahead and send a message to it
::CallWindowProcW(winProc, aWnd, aMsg, 0, 0);
}
return TRUE;
}
// Enumerate all top level windows specifying that the children of each
// top level window should be enumerated. Do *not* send the message to
// each top level window since it is assumed that the toolkit will send
// aMsg to them directly.
BOOL CALLBACK nsWindow::BroadcastMsg(HWND aTopWindow, LPARAM aMsg)
{
// Iterate each of aTopWindows child windows sending the aMsg
// to each of them.
::EnumChildWindows(aTopWindow, nsWindow::BroadcastMsgToChildren, aMsg);
return TRUE;
}
/**************************************************************
*
* SECTION: Event processing helpers
*
* Special processing for certain event types and
* synthesized events.
*
**************************************************************/
int32_t
nsWindow::ClientMarginHitTestPoint(int32_t mx, int32_t my)
{
if (mSizeMode == nsSizeMode_Minimized ||
mSizeMode == nsSizeMode_Fullscreen) {
return HTCLIENT;
}
// Calculations are done in screen coords
RECT winRect;
GetWindowRect(mWnd, &winRect);
// hit return constants:
// HTBORDER - non-resizable border
// HTBOTTOM, HTLEFT, HTRIGHT, HTTOP - resizable border
// HTBOTTOMLEFT, HTBOTTOMRIGHT - resizable corner
// HTTOPLEFT, HTTOPRIGHT - resizable corner
// HTCAPTION - general title bar area
// HTCLIENT - area considered the client
// HTCLOSE - hovering over the close button
// HTMAXBUTTON - maximize button
// HTMINBUTTON - minimize button
int32_t testResult = HTCLIENT;
bool isResizable = (mBorderStyle & (eBorderStyle_all |
eBorderStyle_resizeh |
eBorderStyle_default)) > 0 ? true : false;
if (mSizeMode == nsSizeMode_Maximized)
isResizable = false;
// Ensure being accessible to borders of window. Even if contents are in
// this area, the area must behave as border.
nsIntMargin nonClientSize(std::max(mCaptionHeight - mNonClientOffset.top,
kResizableBorderMinSize),
std::max(mHorResizeMargin - mNonClientOffset.right,
kResizableBorderMinSize),
std::max(mVertResizeMargin - mNonClientOffset.bottom,
kResizableBorderMinSize),
std::max(mHorResizeMargin - mNonClientOffset.left,
kResizableBorderMinSize));
bool allowContentOverride = mSizeMode == nsSizeMode_Maximized ||
(mx >= winRect.left + nonClientSize.left &&
mx <= winRect.right - nonClientSize.right &&
my >= winRect.top + nonClientSize.top &&
my <= winRect.bottom - nonClientSize.bottom);
// The border size. If there is no content under mouse cursor, the border
// size should be larger than the values in system settings. Otherwise,
// contents under the mouse cursor should be able to override the behavior.
// E.g., user must expect that Firefox button always opens the popup menu
// even when the user clicks on the above edge of it.
nsIntMargin borderSize(std::max(nonClientSize.top, mVertResizeMargin),
std::max(nonClientSize.right, mHorResizeMargin),
std::max(nonClientSize.bottom, mVertResizeMargin),
std::max(nonClientSize.left, mHorResizeMargin));
bool top = false;
bool bottom = false;
bool left = false;
bool right = false;
if (my >= winRect.top && my < winRect.top + borderSize.top) {
top = true;
} else if (my <= winRect.bottom && my > winRect.bottom - borderSize.bottom) {
bottom = true;
}
// (the 2x case here doubles the resize area for corners)
int multiplier = (top || bottom) ? 2 : 1;
if (mx >= winRect.left &&
mx < winRect.left + (multiplier * borderSize.left)) {
left = true;
} else if (mx <= winRect.right &&
mx > winRect.right - (multiplier * borderSize.right)) {
right = true;
}
if (isResizable) {
if (top) {
testResult = HTTOP;
if (left)
testResult = HTTOPLEFT;
else if (right)
testResult = HTTOPRIGHT;
} else if (bottom) {
testResult = HTBOTTOM;
if (left)
testResult = HTBOTTOMLEFT;
else if (right)
testResult = HTBOTTOMRIGHT;
} else {
if (left)
testResult = HTLEFT;
if (right)
testResult = HTRIGHT;
}
} else {
if (top)
testResult = HTCAPTION;
else if (bottom || left || right)
testResult = HTBORDER;
}
if (!sIsInMouseCapture && allowContentOverride) {
POINT pt = { mx, my };
::ScreenToClient(mWnd, &pt);
if (pt.x == mCachedHitTestPoint.x && pt.y == mCachedHitTestPoint.y &&
TimeStamp::Now() - mCachedHitTestTime < TimeDuration::FromMilliseconds(HITTEST_CACHE_LIFETIME_MS)) {
return mCachedHitTestResult;
}
if (mDraggableRegion.Contains(pt.x, pt.y)) {
testResult = HTCAPTION;
} else {
testResult = HTCLIENT;
}
mCachedHitTestPoint = pt;
mCachedHitTestTime = TimeStamp::Now();
mCachedHitTestResult = testResult;
}
return testResult;
}
TimeStamp
nsWindow::GetMessageTimeStamp(LONG aEventTime) const
{
CurrentWindowsTimeGetter getCurrentTime(mWnd);
return TimeConverter().GetTimeStampFromSystemTime(aEventTime,
getCurrentTime);
}
void nsWindow::PostSleepWakeNotification(const bool aIsSleepMode)
{
if (aIsSleepMode == gIsSleepMode)
return;
gIsSleepMode = aIsSleepMode;
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (observerService)
observerService->NotifyObservers(nullptr,
aIsSleepMode ? NS_WIDGET_SLEEP_OBSERVER_TOPIC :
NS_WIDGET_WAKE_OBSERVER_TOPIC, nullptr);
}
LRESULT nsWindow::ProcessCharMessage(const MSG &aMsg, bool *aEventDispatched)
{
if (IMEHandler::IsComposingOn(this)) {
IMEHandler::NotifyIME(this, REQUEST_TO_COMMIT_COMPOSITION);
}
// These must be checked here too as a lone WM_CHAR could be received
// if a child window didn't handle it (for example Alt+Space in a content
// window)
ModifierKeyState modKeyState;
NativeKey nativeKey(this, aMsg, modKeyState);
return static_cast<LRESULT>(nativeKey.HandleCharMessage(aEventDispatched));
}
LRESULT nsWindow::ProcessKeyUpMessage(const MSG &aMsg, bool *aEventDispatched)
{
ModifierKeyState modKeyState;
NativeKey nativeKey(this, aMsg, modKeyState);
return static_cast<LRESULT>(nativeKey.HandleKeyUpMessage(aEventDispatched));
}
LRESULT nsWindow::ProcessKeyDownMessage(const MSG &aMsg,
bool *aEventDispatched)
{
// If this method doesn't call NativeKey::HandleKeyDownMessage(), this method
// must clean up the redirected message information itself. For more
// information, see above comment of
// RedirectedKeyDownMessageManager::AutoFlusher class definition in
// KeyboardLayout.h.
RedirectedKeyDownMessageManager::AutoFlusher redirectedMsgFlusher(this, aMsg);
ModifierKeyState modKeyState;
NativeKey nativeKey(this, aMsg, modKeyState);
LRESULT result =
static_cast<LRESULT>(nativeKey.HandleKeyDownMessage(aEventDispatched));
// HandleKeyDownMessage cleaned up the redirected message information
// itself, so, we should do nothing.
redirectedMsgFlusher.Cancel();
if (aMsg.wParam == VK_MENU ||
(aMsg.wParam == VK_F10 && !modKeyState.IsShift())) {
// We need to let Windows handle this keypress,
// by returning false, if there's a native menu
// bar somewhere in our containing window hierarchy.
// Otherwise we handle the keypress and don't pass
// it on to Windows, by returning true.
bool hasNativeMenu = false;
HWND hWnd = mWnd;
while (hWnd) {
if (::GetMenu(hWnd)) {
hasNativeMenu = true;
break;
}
hWnd = ::GetParent(hWnd);
}
result = !hasNativeMenu;
}
return result;
}
nsresult
nsWindow::SynthesizeNativeKeyEvent(int32_t aNativeKeyboardLayout,
int32_t aNativeKeyCode,
uint32_t aModifierFlags,
const nsAString& aCharacters,
const nsAString& aUnmodifiedCharacters,
nsIObserver* aObserver)
{
AutoObserverNotifier notifier(aObserver, "keyevent");
KeyboardLayout* keyboardLayout = KeyboardLayout::GetInstance();
return keyboardLayout->SynthesizeNativeKeyEvent(
this, aNativeKeyboardLayout, aNativeKeyCode, aModifierFlags,
aCharacters, aUnmodifiedCharacters);
}
nsresult
nsWindow::SynthesizeNativeMouseEvent(LayoutDeviceIntPoint aPoint,
uint32_t aNativeMessage,
uint32_t aModifierFlags,
nsIObserver* aObserver)
{
AutoObserverNotifier notifier(aObserver, "mouseevent");
if (aNativeMessage == MOUSEEVENTF_MOVE) {
// Reset sLastMouseMovePoint so that even if we're moving the mouse
// to the position it's already at, we still dispatch a mousemove
// event, because the callers of this function expect that.
sLastMouseMovePoint = {0};
}
::SetCursorPos(aPoint.x, aPoint.y);
INPUT input;
memset(&input, 0, sizeof(input));
input.type = INPUT_MOUSE;
input.mi.dwFlags = aNativeMessage;
::SendInput(1, &input, sizeof(INPUT));
return NS_OK;
}
nsresult
nsWindow::SynthesizeNativeMouseScrollEvent(LayoutDeviceIntPoint aPoint,
uint32_t aNativeMessage,
double aDeltaX,
double aDeltaY,
double aDeltaZ,
uint32_t aModifierFlags,
uint32_t aAdditionalFlags,
nsIObserver* aObserver)
{
AutoObserverNotifier notifier(aObserver, "mousescrollevent");
return MouseScrollHandler::SynthesizeNativeMouseScrollEvent(
this, aPoint, aNativeMessage,
(aNativeMessage == WM_MOUSEWHEEL || aNativeMessage == WM_VSCROLL) ?
static_cast<int32_t>(aDeltaY) : static_cast<int32_t>(aDeltaX),
aModifierFlags, aAdditionalFlags);
}
/**************************************************************
*
* SECTION: OnXXX message handlers
*
* For message handlers that need to be broken out or
* implemented in specific platform code.
*
**************************************************************/
void nsWindow::OnWindowPosChanged(WINDOWPOS* wp)
{
if (wp == nullptr)
return;
#ifdef WINSTATE_DEBUG_OUTPUT
if (mWnd == WinUtils::GetTopLevelHWND(mWnd)) {
MOZ_LOG(gWindowsLog, LogLevel::Info, ("*** OnWindowPosChanged: [ top] "));
} else {
MOZ_LOG(gWindowsLog, LogLevel::Info, ("*** OnWindowPosChanged: [child] "));
}
MOZ_LOG(gWindowsLog, LogLevel::Info, ("WINDOWPOS flags:"));
if (wp->flags & SWP_FRAMECHANGED) {
MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_FRAMECHANGED "));
}
if (wp->flags & SWP_SHOWWINDOW) {
MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_SHOWWINDOW "));
}
if (wp->flags & SWP_NOSIZE) {
MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_NOSIZE "));
}
if (wp->flags & SWP_HIDEWINDOW) {
MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_HIDEWINDOW "));
}
if (wp->flags & SWP_NOZORDER) {
MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_NOZORDER "));
}
if (wp->flags & SWP_NOACTIVATE) {
MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_NOACTIVATE "));
}
MOZ_LOG(gWindowsLog, LogLevel::Info, ("\n"));
#endif
// Handle window size mode changes
if (wp->flags & SWP_FRAMECHANGED && mSizeMode != nsSizeMode_Fullscreen) {
// Bug 566135 - Windows theme code calls show window on SW_SHOWMINIMIZED
// windows when fullscreen games disable desktop composition. If we're
// minimized and not being activated, ignore the event and let windows
// handle it.
if (mSizeMode == nsSizeMode_Minimized && (wp->flags & SWP_NOACTIVATE))
return;
WINDOWPLACEMENT pl;
pl.length = sizeof(pl);
::GetWindowPlacement(mWnd, &pl);
nsSizeMode previousSizeMode = mSizeMode;
// Windows has just changed the size mode of this window. The call to
// SizeModeChanged will trigger a call into SetSizeMode where we will
// set the min/max window state again or for nsSizeMode_Normal, call
// SetWindow with a parameter of SW_RESTORE. There's no need however as
// this window's mode has already changed. Updating mSizeMode here
// insures the SetSizeMode call is a no-op. Addresses a bug on Win7 related
// to window docking. (bug 489258)
if (pl.showCmd == SW_SHOWMAXIMIZED)
mSizeMode = (mFullscreenMode ? nsSizeMode_Fullscreen : nsSizeMode_Maximized);
else if (pl.showCmd == SW_SHOWMINIMIZED)
mSizeMode = nsSizeMode_Minimized;
else if (mFullscreenMode)
mSizeMode = nsSizeMode_Fullscreen;
else
mSizeMode = nsSizeMode_Normal;
#ifdef WINSTATE_DEBUG_OUTPUT
switch (mSizeMode) {
case nsSizeMode_Normal:
MOZ_LOG(gWindowsLog, LogLevel::Info,
("*** mSizeMode: nsSizeMode_Normal\n"));
break;
case nsSizeMode_Minimized:
MOZ_LOG(gWindowsLog, LogLevel::Info,
("*** mSizeMode: nsSizeMode_Minimized\n"));
break;
case nsSizeMode_Maximized:
MOZ_LOG(gWindowsLog, LogLevel::Info,
("*** mSizeMode: nsSizeMode_Maximized\n"));
break;
default:
MOZ_LOG(gWindowsLog, LogLevel::Info, ("*** mSizeMode: ??????\n"));
break;
}
#endif
if (mWidgetListener && mSizeMode != previousSizeMode)
mWidgetListener->SizeModeChanged(mSizeMode);
// If window was restored, window activation was bypassed during the
// SetSizeMode call originating from OnWindowPosChanging to avoid saving
// pre-restore attributes. Force activation now to get correct attributes.
if (mLastSizeMode != nsSizeMode_Normal && mSizeMode == nsSizeMode_Normal)
DispatchFocusToTopLevelWindow(true);
mLastSizeMode = mSizeMode;
// Skip window size change events below on minimization.
if (mSizeMode == nsSizeMode_Minimized)
return;
}
// Handle window position changes
if (!(wp->flags & SWP_NOMOVE)) {
mBounds.x = wp->x;
mBounds.y = wp->y;
NotifyWindowMoved(wp->x, wp->y);
}
// Handle window size changes
if (!(wp->flags & SWP_NOSIZE)) {
RECT r;
int32_t newWidth, newHeight;
::GetWindowRect(mWnd, &r);
newWidth = r.right - r.left;
newHeight = r.bottom - r.top;
nsIntRect rect(wp->x, wp->y, newWidth, newHeight);
if (newWidth > mLastSize.width)
{
RECT drect;
// getting wider
drect.left = wp->x + mLastSize.width;
drect.top = wp->y;
drect.right = drect.left + (newWidth - mLastSize.width);
drect.bottom = drect.top + newHeight;
::RedrawWindow(mWnd, &drect, nullptr,
RDW_INVALIDATE |
RDW_NOERASE |
RDW_NOINTERNALPAINT |
RDW_ERASENOW |
RDW_ALLCHILDREN);
}
if (newHeight > mLastSize.height)
{
RECT drect;
// getting taller
drect.left = wp->x;
drect.top = wp->y + mLastSize.height;
drect.right = drect.left + newWidth;
drect.bottom = drect.top + (newHeight - mLastSize.height);
::RedrawWindow(mWnd, &drect, nullptr,
RDW_INVALIDATE |
RDW_NOERASE |
RDW_NOINTERNALPAINT |
RDW_ERASENOW |
RDW_ALLCHILDREN);
}
mBounds.width = newWidth;
mBounds.height = newHeight;
mLastSize.width = newWidth;
mLastSize.height = newHeight;
#ifdef WINSTATE_DEBUG_OUTPUT
MOZ_LOG(gWindowsLog, LogLevel::Info,
("*** Resize window: %d x %d x %d x %d\n", wp->x, wp->y,
newWidth, newHeight));
#endif
// If a maximized window is resized, recalculate the non-client margins.
if (mSizeMode == nsSizeMode_Maximized) {
if (UpdateNonClientMargins(nsSizeMode_Maximized, true)) {
// gecko resize event already sent by UpdateNonClientMargins.
return;
}
}
// Recalculate the width and height based on the client area for gecko events.
if (::GetClientRect(mWnd, &r)) {
rect.width = r.right - r.left;
rect.height = r.bottom - r.top;
}
// Send a gecko resize event
OnResize(rect);
}
}
void nsWindow::OnWindowPosChanging(LPWINDOWPOS& info)
{
// Update non-client margins if the frame size is changing, and let the
// browser know we are changing size modes, so alternative css can kick in.
// If we're going into fullscreen mode, ignore this, since it'll reset
// margins to normal mode.
if ((info->flags & SWP_FRAMECHANGED && !(info->flags & SWP_NOSIZE)) &&
mSizeMode != nsSizeMode_Fullscreen) {
WINDOWPLACEMENT pl;
pl.length = sizeof(pl);
::GetWindowPlacement(mWnd, &pl);
nsSizeMode sizeMode;
if (pl.showCmd == SW_SHOWMAXIMIZED)
sizeMode = (mFullscreenMode ? nsSizeMode_Fullscreen : nsSizeMode_Maximized);
else if (pl.showCmd == SW_SHOWMINIMIZED)
sizeMode = nsSizeMode_Minimized;
else if (mFullscreenMode)
sizeMode = nsSizeMode_Fullscreen;
else
sizeMode = nsSizeMode_Normal;
if (mWidgetListener)
mWidgetListener->SizeModeChanged(sizeMode);
UpdateNonClientMargins(sizeMode, false);
}
// enforce local z-order rules
if (!(info->flags & SWP_NOZORDER)) {
HWND hwndAfter = info->hwndInsertAfter;
nsWindow *aboveWindow = 0;
nsWindowZ placement;
if (hwndAfter == HWND_BOTTOM)
placement = nsWindowZBottom;
else if (hwndAfter == HWND_TOP || hwndAfter == HWND_TOPMOST || hwndAfter == HWND_NOTOPMOST)
placement = nsWindowZTop;
else {
placement = nsWindowZRelative;
aboveWindow = WinUtils::GetNSWindowPtr(hwndAfter);
}
if (mWidgetListener) {
nsCOMPtr<nsIWidget> actualBelow = nullptr;
if (mWidgetListener->ZLevelChanged(false, &placement,
aboveWindow, getter_AddRefs(actualBelow))) {
if (placement == nsWindowZBottom)
info->hwndInsertAfter = HWND_BOTTOM;
else if (placement == nsWindowZTop)
info->hwndInsertAfter = HWND_TOP;
else {
info->hwndInsertAfter = (HWND)actualBelow->GetNativeData(NS_NATIVE_WINDOW);
}
}
}
}
// prevent rude external programs from making hidden window visible
if (mWindowType == eWindowType_invisible)
info->flags &= ~SWP_SHOWWINDOW;
}
void nsWindow::UserActivity()
{
// Check if we have the idle service, if not we try to get it.
if (!mIdleService) {
mIdleService = do_GetService("@mozilla.org/widget/idleservice;1");
}
// Check that we now have the idle service.
if (mIdleService) {
mIdleService->ResetIdleTimeOut(0);
}
}
nsIntPoint nsWindow::GetTouchCoordinates(WPARAM wParam, LPARAM lParam)
{
nsIntPoint ret;
uint32_t cInputs = LOWORD(wParam);
if (cInputs != 1) {
// Just return 0,0 if there isn't exactly one touch point active
return ret;
}
PTOUCHINPUT pInputs = new TOUCHINPUT[cInputs];
if (mGesture.GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs)) {
ret.x = TOUCH_COORD_TO_PIXEL(pInputs[0].x);
ret.y = TOUCH_COORD_TO_PIXEL(pInputs[0].y);
}
delete[] pInputs;
// Note that we don't call CloseTouchInputHandle here because we need
// to read the touch input info again in OnTouch later.
return ret;
}
bool nsWindow::OnTouch(WPARAM wParam, LPARAM lParam)
{
uint32_t cInputs = LOWORD(wParam);
PTOUCHINPUT pInputs = new TOUCHINPUT[cInputs];
if (mGesture.GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs)) {
MultiTouchInput touchInput, touchEndInput;
// Walk across the touch point array processing each contact point.
for (uint32_t i = 0; i < cInputs; i++) {
bool addToEvent = false, addToEndEvent = false;
// N.B.: According with MS documentation
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd317334(v=vs.85).aspx
// TOUCHEVENTF_DOWN cannot be combined with TOUCHEVENTF_MOVE or TOUCHEVENTF_UP.
// Possibly, it means that TOUCHEVENTF_MOVE and TOUCHEVENTF_UP can be combined together.
if (pInputs[i].dwFlags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE)) {
if (touchInput.mTimeStamp.IsNull()) {
// Initialize a touch event to send.
touchInput.mType = MultiTouchInput::MULTITOUCH_MOVE;
touchInput.mTime = ::GetMessageTime();
touchInput.mTimeStamp = GetMessageTimeStamp(touchInput.mTime);
ModifierKeyState modifierKeyState;
touchInput.modifiers = modifierKeyState.GetModifiers();
}
// Pres shell expects this event to be a eTouchStart
// if any new contact points have been added since the last event sent.
if (pInputs[i].dwFlags & TOUCHEVENTF_DOWN) {
touchInput.mType = MultiTouchInput::MULTITOUCH_START;
}
addToEvent = true;
}
if (pInputs[i].dwFlags & TOUCHEVENTF_UP) {
// Pres shell expects removed contacts points to be delivered in a separate
// eTouchEnd event containing only the contact points that were removed.
if (touchEndInput.mTimeStamp.IsNull()) {
// Initialize a touch event to send.
touchEndInput.mType = MultiTouchInput::MULTITOUCH_END;
touchEndInput.mTime = ::GetMessageTime();
touchEndInput.mTimeStamp = GetMessageTimeStamp(touchEndInput.mTime);
ModifierKeyState modifierKeyState;
touchEndInput.modifiers = modifierKeyState.GetModifiers();
}
addToEndEvent = true;
}
if (!addToEvent && !addToEndEvent) {
// Filter out spurious Windows events we don't understand, like palm contact.
continue;
}
// Setup the touch point we'll append to the touch event array.
nsPointWin touchPoint;
touchPoint.x = TOUCH_COORD_TO_PIXEL(pInputs[i].x);
touchPoint.y = TOUCH_COORD_TO_PIXEL(pInputs[i].y);
touchPoint.ScreenToClient(mWnd);
// Initialize the touch data.
SingleTouchData touchData(pInputs[i].dwID, // aIdentifier
ScreenIntPoint::FromUnknownPoint(touchPoint), // aScreenPoint
/* radius, if known */
pInputs[i].dwFlags & TOUCHINPUTMASKF_CONTACTAREA
? ScreenSize(
TOUCH_COORD_TO_PIXEL(pInputs[i].cxContact) / 2,
TOUCH_COORD_TO_PIXEL(pInputs[i].cyContact) / 2)
: ScreenSize(1, 1), // aRadius
0.0f, // aRotationAngle
0.0f); // aForce
// Append touch data to the appropriate event.
if (addToEvent) {
touchInput.mTouches.AppendElement(touchData);
}
if (addToEndEvent) {
touchEndInput.mTouches.AppendElement(touchData);
}
}
// Dispatch touch start and touch move event if we have one.
if (!touchInput.mTimeStamp.IsNull()) {
DispatchTouchInput(touchInput);
}
// Dispatch touch end event if we have one.
if (!touchEndInput.mTimeStamp.IsNull()) {
DispatchTouchInput(touchEndInput);
}
}
delete [] pInputs;
mGesture.CloseTouchInputHandle((HTOUCHINPUT)lParam);
return true;
}
// Gesture event processing. Handles WM_GESTURE events.
bool nsWindow::OnGesture(WPARAM wParam, LPARAM lParam)
{
// Treatment for pan events which translate into scroll events:
if (mGesture.IsPanEvent(lParam)) {
if ( !mGesture.ProcessPanMessage(mWnd, wParam, lParam) )
return false; // ignore
nsEventStatus status;
WidgetWheelEvent wheelEvent(true, eWheel, this);
ModifierKeyState modifierKeyState;
modifierKeyState.InitInputEvent(wheelEvent);
wheelEvent.button = 0;
wheelEvent.mTime = ::GetMessageTime();
wheelEvent.mTimeStamp = GetMessageTimeStamp(wheelEvent.mTime);
wheelEvent.inputSource = nsIDOMMouseEvent::MOZ_SOURCE_TOUCH;
bool endFeedback = true;
if (mGesture.PanDeltaToPixelScroll(wheelEvent)) {
mozilla::Telemetry::Accumulate(mozilla::Telemetry::SCROLL_INPUT_METHODS,
(uint32_t) ScrollInputMethod::MainThreadTouch);
DispatchEvent(&wheelEvent, status);
}
if (mDisplayPanFeedback) {
mGesture.UpdatePanFeedbackX(
mWnd,
DeprecatedAbs(RoundDown(wheelEvent.mOverflowDeltaX)),
endFeedback);
mGesture.UpdatePanFeedbackY(
mWnd,
DeprecatedAbs(RoundDown(wheelEvent.mOverflowDeltaY)),
endFeedback);
mGesture.PanFeedbackFinalize(mWnd, endFeedback);
}
mGesture.CloseGestureInfoHandle((HGESTUREINFO)lParam);
return true;
}
// Other gestures translate into simple gesture events:
WidgetSimpleGestureEvent event(true, eVoidEvent, this);
if ( !mGesture.ProcessGestureMessage(mWnd, wParam, lParam, event) ) {
return false; // fall through to DefWndProc
}
// Polish up and send off the new event
ModifierKeyState modifierKeyState;
modifierKeyState.InitInputEvent(event);
event.button = 0;
event.mTime = ::GetMessageTime();
event.mTimeStamp = GetMessageTimeStamp(event.mTime);
event.inputSource = nsIDOMMouseEvent::MOZ_SOURCE_TOUCH;
nsEventStatus status;
DispatchEvent(&event, status);
if (status == nsEventStatus_eIgnore) {
return false; // Ignored, fall through
}
// Only close this if we process and return true.
mGesture.CloseGestureInfoHandle((HGESTUREINFO)lParam);
return true; // Handled
}
nsresult
nsWindow::ConfigureChildren(const nsTArray<Configuration>& aConfigurations)
{
// If this is a remotely updated widget we receive clipping, position, and
// size information from a source other than our owner. Don't let our parent
// update this information.
if (mWindowType == eWindowType_plugin_ipc_chrome) {
return NS_OK;
}
// XXXroc we could use BeginDeferWindowPos/DeferWindowPos/EndDeferWindowPos
// here, if that helps in some situations. So far I haven't seen a
// need.
for (uint32_t i = 0; i < aConfigurations.Length(); ++i) {
const Configuration& configuration = aConfigurations[i];
nsWindow* w = static_cast<nsWindow*>(configuration.mChild.get());
NS_ASSERTION(w->GetParent() == this,
"Configured widget is not a child");
nsresult rv = w->SetWindowClipRegion(configuration.mClipRegion, true);
NS_ENSURE_SUCCESS(rv, rv);
LayoutDeviceIntRect bounds = w->GetBounds();
if (bounds.Size() != configuration.mBounds.Size()) {
w->Resize(configuration.mBounds.x, configuration.mBounds.y,
configuration.mBounds.width, configuration.mBounds.height,
true);
} else if (bounds.TopLeft() != configuration.mBounds.TopLeft()) {
w->Move(configuration.mBounds.x, configuration.mBounds.y);
if (gfxWindowsPlatform::GetPlatform()->IsDirect2DBackend() ||
GetLayerManager()->GetBackendType() != LayersBackend::LAYERS_BASIC) {
// XXX - Workaround for Bug 587508. This will invalidate the part of the
// plugin window that might be touched by moving content somehow. The
// underlying problem should be found and fixed!
LayoutDeviceIntRegion r;
r.Sub(bounds, configuration.mBounds);
r.MoveBy(-bounds.x,
-bounds.y);
LayoutDeviceIntRect toInvalidate = r.GetBounds();
WinUtils::InvalidatePluginAsWorkaround(w, toInvalidate);
}
}
rv = w->SetWindowClipRegion(configuration.mClipRegion, false);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
static HRGN
CreateHRGNFromArray(const nsTArray<LayoutDeviceIntRect>& aRects)
{
int32_t size = sizeof(RGNDATAHEADER) + sizeof(RECT)*aRects.Length();
AutoTArray<uint8_t,100> buf;
buf.SetLength(size);
RGNDATA* data = reinterpret_cast<RGNDATA*>(buf.Elements());
RECT* rects = reinterpret_cast<RECT*>(data->Buffer);
data->rdh.dwSize = sizeof(data->rdh);
data->rdh.iType = RDH_RECTANGLES;
data->rdh.nCount = aRects.Length();
LayoutDeviceIntRect bounds;
for (uint32_t i = 0; i < aRects.Length(); ++i) {
const LayoutDeviceIntRect& r = aRects[i];
bounds.UnionRect(bounds, r);
::SetRect(&rects[i], r.x, r.y, r.XMost(), r.YMost());
}
::SetRect(&data->rdh.rcBound, bounds.x, bounds.y, bounds.XMost(), bounds.YMost());
return ::ExtCreateRegion(nullptr, buf.Length(), data);
}
nsresult
nsWindow::SetWindowClipRegion(const nsTArray<LayoutDeviceIntRect>& aRects,
bool aIntersectWithExisting)
{
if (IsWindowClipRegionEqual(aRects)) {
return NS_OK;
}
nsBaseWidget::SetWindowClipRegion(aRects, aIntersectWithExisting);
HRGN dest = CreateHRGNFromArray(aRects);
if (!dest)
return NS_ERROR_OUT_OF_MEMORY;
if (aIntersectWithExisting) {
HRGN current = ::CreateRectRgn(0, 0, 0, 0);
if (current) {
if (::GetWindowRgn(mWnd, current) != 0 /*ERROR*/) {
::CombineRgn(dest, dest, current, RGN_AND);
}
::DeleteObject(current);
}
}
// If a plugin is not visible, especially if it is in a background tab,
// it should not be able to steal keyboard focus. This code checks whether
// the region that the plugin is being clipped to is NULLREGION. If it is,
// the plugin window gets disabled.
if (IsPlugin()) {
if (NULLREGION == ::CombineRgn(dest, dest, dest, RGN_OR)) {
::ShowWindow(mWnd, SW_HIDE);
::EnableWindow(mWnd, FALSE);
} else {
::EnableWindow(mWnd, TRUE);
::ShowWindow(mWnd, SW_SHOW);
}
}
if (!::SetWindowRgn(mWnd, dest, TRUE)) {
::DeleteObject(dest);
return NS_ERROR_FAILURE;
}
return NS_OK;
}
// WM_DESTROY event handler
void nsWindow::OnDestroy()
{
mOnDestroyCalled = true;
// Make sure we don't get destroyed in the process of tearing down.
nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
// Dispatch the destroy notification.
if (!mInDtor)
NotifyWindowDestroyed();
// Prevent the widget from sending additional events.
mWidgetListener = nullptr;
mAttachedWidgetListener = nullptr;
// Unregister notifications from terminal services
::WTSUnRegisterSessionNotification(mWnd);
// Free our subclass and clear |this| stored in the window props. We will no longer
// receive events from Windows after this point.
SubclassWindow(FALSE);
// Once mWidgetListener is cleared and the subclass is reset, sCurrentWindow can be
// cleared. (It's used in tracking windows for mouse events.)
if (sCurrentWindow == this)
sCurrentWindow = nullptr;
// Disconnects us from our parent, will call our GetParent().
nsBaseWidget::Destroy();
// Release references to children, device context, toolkit, and app shell.
nsBaseWidget::OnDestroy();
// Clear our native parent handle.
// XXX Windows will take care of this in the proper order, and SetParent(nullptr)'s
// remove child on the parent already took place in nsBaseWidget's Destroy call above.
//SetParent(nullptr);
mParent = nullptr;
// We have to destroy the native drag target before we null out our window pointer.
EnableDragDrop(false);
// If we're going away and for some reason we're still the rollup widget, rollup and
// turn off capture.
nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener();
nsCOMPtr<nsIWidget> rollupWidget;
if (rollupListener) {
rollupWidget = rollupListener->GetRollupWidget();
}
if (this == rollupWidget) {
if ( rollupListener )
rollupListener->Rollup(0, false, nullptr, nullptr);
CaptureRollupEvents(nullptr, false);
}
IMEHandler::OnDestroyWindow(this);
// Free GDI window class objects
if (mBrush) {
VERIFY(::DeleteObject(mBrush));
mBrush = nullptr;
}
// Destroy any custom cursor resources.
if (mCursor == -1)
SetCursor(eCursor_standard);
if (mCompositorWidgetDelegate) {
mCompositorWidgetDelegate->OnDestroyWindow();
}
mBasicLayersSurface = nullptr;
// Finalize panning feedback to possibly restore window displacement
mGesture.PanFeedbackFinalize(mWnd, true);
// Clear the main HWND.
mWnd = nullptr;
}
// Send a resize message to the listener
bool nsWindow::OnResize(nsIntRect &aWindowRect)
{
bool result = mWidgetListener ?
mWidgetListener->WindowResized(this, aWindowRect.width, aWindowRect.height) : false;
// If there is an attached view, inform it as well as the normal widget listener.
if (mAttachedWidgetListener) {
return mAttachedWidgetListener->WindowResized(this, aWindowRect.width, aWindowRect.height);
}
return result;
}
bool nsWindow::OnHotKey(WPARAM wParam, LPARAM lParam)
{
return true;
}
// Can be overriden. Controls auto-erase of background.
bool nsWindow::AutoErase(HDC dc)
{
return false;
}
bool
nsWindow::IsPopup()
{
return mWindowType == eWindowType_popup;
}
bool
nsWindow::ShouldUseOffMainThreadCompositing()
{
// We don't currently support using an accelerated layer manager with
// transparent windows so don't even try. I'm also not sure if we even
// want to support this case. See bug 593471
if (!(HasRemoteContent() && gIsPopupCompositingEnabled) && mTransparencyMode == eTransparencyTransparent) {
return false;
}
return nsBaseWidget::ShouldUseOffMainThreadCompositing();
}
void
nsWindow::WindowUsesOMTC()
{
ULONG_PTR style = ::GetClassLongPtr(mWnd, GCL_STYLE);
if (!style) {
NS_WARNING("Could not get window class style");
return;
}
style |= CS_HREDRAW | CS_VREDRAW;
DebugOnly<ULONG_PTR> result = ::SetClassLongPtr(mWnd, GCL_STYLE, style);
NS_WARNING_ASSERTION(result, "Could not reset window class style");
}
bool
nsWindow::HasBogusPopupsDropShadowOnMultiMonitor() {
if (sHasBogusPopupsDropShadowOnMultiMonitor == TRI_UNKNOWN) {
// Since any change in the preferences requires a restart, this can be
// done just once.
// Check for Direct2D first.
sHasBogusPopupsDropShadowOnMultiMonitor =
gfxWindowsPlatform::GetPlatform()->IsDirect2DBackend() ? TRI_TRUE : TRI_FALSE;
if (!sHasBogusPopupsDropShadowOnMultiMonitor) {
// Otherwise check if Direct3D 9 may be used.
if (gfxConfig::IsEnabled(Feature::HW_COMPOSITING) &&
!gfxConfig::IsEnabled(Feature::OPENGL_COMPOSITING))
{
nsCOMPtr<nsIGfxInfo> gfxInfo = services::GetGfxInfo();
if (gfxInfo) {
int32_t status;
nsCString discardFailureId;
if (NS_SUCCEEDED(gfxInfo->GetFeatureStatus(nsIGfxInfo::FEATURE_DIRECT3D_9_LAYERS,
discardFailureId, &status))) {
if (status == nsIGfxInfo::FEATURE_STATUS_OK ||
gfxConfig::IsForcedOnByUser(Feature::HW_COMPOSITING))
{
sHasBogusPopupsDropShadowOnMultiMonitor = TRI_TRUE;
}
}
}
}
}
}
return !!sHasBogusPopupsDropShadowOnMultiMonitor;
}
void
nsWindow::OnSysColorChanged()
{
if (mWindowType == eWindowType_invisible) {
::EnumThreadWindows(GetCurrentThreadId(), nsWindow::BroadcastMsg, WM_SYSCOLORCHANGE);
}
else {
// Note: This is sent for child windows as well as top-level windows.
// The Win32 toolkit normally only sends these events to top-level windows.
// But we cycle through all of the childwindows and send it to them as well
// so all presentations get notified properly.
// See nsWindow::GlobalMsgWindowProc.
NotifySysColorChanged();
}
}
void
nsWindow::OnDPIChanged(int32_t x, int32_t y, int32_t width, int32_t height)
{
// Don't try to handle WM_DPICHANGED for popup windows (see bug 1239353);
// they remain tied to their original parent's resolution.
if (mWindowType == eWindowType_popup) {
return;
}
if (DefaultScaleOverride() > 0.0) {
return;
}
double oldScale = mDefaultScale;
mDefaultScale = -1.0; // force recomputation of scale factor
double newScale = GetDefaultScaleInternal();
if (mResizeState != RESIZING && mSizeMode == nsSizeMode_Normal) {
// Limit the position (if not in the middle of a drag-move) & size,
// if it would overflow the destination screen
nsCOMPtr<nsIScreenManager> sm = do_GetService(sScreenManagerContractID);
if (sm) {
nsCOMPtr<nsIScreen> screen;
sm->ScreenForRect(x, y, width, height, getter_AddRefs(screen));
if (screen) {
int32_t availLeft, availTop, availWidth, availHeight;
screen->GetAvailRect(&availLeft, &availTop, &availWidth, &availHeight);
if (mResizeState != MOVING) {
x = std::max(x, availLeft);
y = std::max(y, availTop);
}
width = std::min(width, availWidth);
height = std::min(height, availHeight);
}
}
Resize(x, y, width, height, true);
}
ChangedDPI();
ResetLayout();
}
/**************************************************************
**************************************************************
**
** BLOCK: IME management and accessibility
**
** Handles managing IME input and accessibility.
**
**************************************************************
**************************************************************/
void
nsWindow::SetInputContext(const InputContext& aContext,
const InputContextAction& aAction)
{
InputContext newInputContext = aContext;
IMEHandler::SetInputContext(this, newInputContext, aAction);
mInputContext = newInputContext;
}
InputContext
nsWindow::GetInputContext()
{
mInputContext.mIMEState.mOpen = IMEState::CLOSED;
if (WinUtils::IsIMEEnabled(mInputContext) && IMEHandler::GetOpenState(this)) {
mInputContext.mIMEState.mOpen = IMEState::OPEN;
} else {
mInputContext.mIMEState.mOpen = IMEState::CLOSED;
}
return mInputContext;
}
TextEventDispatcherListener*
nsWindow::GetNativeTextEventDispatcherListener()
{
return IMEHandler::GetNativeTextEventDispatcherListener();
}
#ifdef ACCESSIBILITY
#ifdef DEBUG
#define NS_LOG_WMGETOBJECT(aWnd, aHwnd, aAcc) \
if (a11y::logging::IsEnabled(a11y::logging::ePlatforms)) { \
printf("Get the window:\n {\n HWND: %p, parent HWND: %p, wndobj: %p,\n",\
aHwnd, ::GetParent(aHwnd), aWnd); \
printf(" acc: %p", aAcc); \
if (aAcc) { \
nsAutoString name; \
aAcc->Name(name); \
printf(", accname: %s", NS_ConvertUTF16toUTF8(name).get()); \
} \
printf("\n }\n"); \
}
#else
#define NS_LOG_WMGETOBJECT(aWnd, aHwnd, aAcc)
#endif
a11y::Accessible*
nsWindow::GetAccessible()
{
// If the pref was ePlatformIsDisabled, return null here, disabling a11y.
if (a11y::PlatformDisabledState() == a11y::ePlatformIsDisabled)
return nullptr;
if (mInDtor || mOnDestroyCalled || mWindowType == eWindowType_invisible) {
return nullptr;
}
// In case of popup window return a popup accessible.
nsView* view = nsView::GetViewFor(this);
if (view) {
nsIFrame* frame = view->GetFrame();
if (frame && nsLayoutUtils::IsPopup(frame)) {
nsAccessibilityService* accService = GetOrCreateAccService();
if (accService) {
a11y::DocAccessible* docAcc =
GetAccService()->GetDocAccessible(frame->PresContext()->PresShell());
if (docAcc) {
NS_LOG_WMGETOBJECT(this, mWnd,
docAcc->GetAccessibleOrDescendant(frame->GetContent()));
return docAcc->GetAccessibleOrDescendant(frame->GetContent());
}
}
}
}
// otherwise root document accessible.
NS_LOG_WMGETOBJECT(this, mWnd, GetRootAccessible());
return GetRootAccessible();
}
#endif
/**************************************************************
**************************************************************
**
** BLOCK: Transparency
**
** Window transparency helpers.
**
**************************************************************
**************************************************************/
#ifdef MOZ_XUL
void nsWindow::SetWindowTranslucencyInner(nsTransparencyMode aMode)
{
if (aMode == mTransparencyMode)
return;
// stop on dialogs and popups!
HWND hWnd = WinUtils::GetTopLevelHWND(mWnd, true);
nsWindow* parent = WinUtils::GetNSWindowPtr(hWnd);
if (!parent)
{
NS_WARNING("Trying to use transparent chrome in an embedded context");
return;
}
if (parent != this) {
NS_WARNING("Setting SetWindowTranslucencyInner on a parent this is not us!");
}
if (aMode == eTransparencyTransparent) {
// If we're switching to the use of a transparent window, hide the chrome
// on our parent.
HideWindowChrome(true);
} else if (mHideChrome && mTransparencyMode == eTransparencyTransparent) {
// if we're switching out of transparent, re-enable our parent's chrome.
HideWindowChrome(false);
}
LONG_PTR style = ::GetWindowLongPtrW(hWnd, GWL_STYLE),
exStyle = ::GetWindowLongPtr(hWnd, GWL_EXSTYLE);
if (parent->mIsVisible)
style |= WS_VISIBLE;
if (parent->mSizeMode == nsSizeMode_Maximized)
style |= WS_MAXIMIZE;
else if (parent->mSizeMode == nsSizeMode_Minimized)
style |= WS_MINIMIZE;
if (aMode == eTransparencyTransparent)
exStyle |= WS_EX_LAYERED;
else
exStyle &= ~WS_EX_LAYERED;
VERIFY_WINDOW_STYLE(style);
::SetWindowLongPtrW(hWnd, GWL_STYLE, style);
::SetWindowLongPtrW(hWnd, GWL_EXSTYLE, exStyle);
if (HasGlass())
memset(&mGlassMargins, 0, sizeof mGlassMargins);
mTransparencyMode = aMode;
if (mCompositorWidgetDelegate) {
mCompositorWidgetDelegate->UpdateTransparency(aMode);
}
UpdateGlass();
}
#endif //MOZ_XUL
/**************************************************************
**************************************************************
**
** BLOCK: Popup rollup hooks
**
** Deals with CaptureRollup on popup windows.
**
**************************************************************
**************************************************************/
// Schedules a timer for a window, so we can rollup after processing the hook event
void nsWindow::ScheduleHookTimer(HWND aWnd, UINT aMsgId)
{
// In some cases multiple hooks may be scheduled
// so ignore any other requests once one timer is scheduled
if (sHookTimerId == 0) {
// Remember the window handle and the message ID to be used later
sRollupMsgId = aMsgId;
sRollupMsgWnd = aWnd;
// Schedule native timer for doing the rollup after
// this event is done being processed
sHookTimerId = ::SetTimer(nullptr, 0, 0, (TIMERPROC)HookTimerForPopups);
NS_ASSERTION(sHookTimerId, "Timer couldn't be created.");
}
}
#ifdef POPUP_ROLLUP_DEBUG_OUTPUT
int gLastMsgCode = 0;
extern MSGFEventMsgInfo gMSGFEvents[];
#endif
// Process Menu messages, rollup when popup is clicked.
LRESULT CALLBACK nsWindow::MozSpecialMsgFilter(int code, WPARAM wParam, LPARAM lParam)
{
#ifdef POPUP_ROLLUP_DEBUG_OUTPUT
if (sProcessHook) {
MSG* pMsg = (MSG*)lParam;
int inx = 0;
while (gMSGFEvents[inx].mId != code && gMSGFEvents[inx].mStr != nullptr) {
inx++;
}
if (code != gLastMsgCode) {
if (gMSGFEvents[inx].mId == code) {
#ifdef DEBUG
MOZ_LOG(gWindowsLog, LogLevel::Info,
("MozSpecialMessageProc - code: 0x%X - %s hw: %p\n",
code, gMSGFEvents[inx].mStr, pMsg->hwnd));
#endif
} else {
#ifdef DEBUG
MOZ_LOG(gWindowsLog, LogLevel::Info,
("MozSpecialMessageProc - code: 0x%X - %d hw: %p\n",
code, gMSGFEvents[inx].mId, pMsg->hwnd));
#endif
}
gLastMsgCode = code;
}
PrintEvent(pMsg->message, FALSE, FALSE);
}
#endif // #ifdef POPUP_ROLLUP_DEBUG_OUTPUT
if (sProcessHook && code == MSGF_MENU) {
MSG* pMsg = (MSG*)lParam;
ScheduleHookTimer( pMsg->hwnd, pMsg->message);
}
return ::CallNextHookEx(sMsgFilterHook, code, wParam, lParam);
}
// Process all mouse messages. Roll up when a click is in a native window
// that doesn't have an nsIWidget.
LRESULT CALLBACK nsWindow::MozSpecialMouseProc(int code, WPARAM wParam, LPARAM lParam)
{
if (sProcessHook) {
switch (WinUtils::GetNativeMessage(wParam)) {
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_MOUSEWHEEL:
case WM_MOUSEHWHEEL:
{
MOUSEHOOKSTRUCT* ms = (MOUSEHOOKSTRUCT*)lParam;
nsIWidget* mozWin = WinUtils::GetNSWindowPtr(ms->hwnd);
if (mozWin) {
// If this window is windowed plugin window, the mouse events are not
// sent to us.
if (static_cast<nsWindow*>(mozWin)->IsPlugin())
ScheduleHookTimer(ms->hwnd, (UINT)wParam);
} else {
ScheduleHookTimer(ms->hwnd, (UINT)wParam);
}
break;
}
}
}
return ::CallNextHookEx(sCallMouseHook, code, wParam, lParam);
}
// Process all messages. Roll up when the window is moving, or
// is resizing or when maximized or mininized.
LRESULT CALLBACK nsWindow::MozSpecialWndProc(int code, WPARAM wParam, LPARAM lParam)
{
#ifdef POPUP_ROLLUP_DEBUG_OUTPUT
if (sProcessHook) {
CWPSTRUCT* cwpt = (CWPSTRUCT*)lParam;
PrintEvent(cwpt->message, FALSE, FALSE);
}
#endif
if (sProcessHook) {
CWPSTRUCT* cwpt = (CWPSTRUCT*)lParam;
if (cwpt->message == WM_MOVING ||
cwpt->message == WM_SIZING ||
cwpt->message == WM_GETMINMAXINFO) {
ScheduleHookTimer(cwpt->hwnd, (UINT)cwpt->message);
}
}
return ::CallNextHookEx(sCallProcHook, code, wParam, lParam);
}
// Register the special "hooks" for dropdown processing.
void nsWindow::RegisterSpecialDropdownHooks()
{
NS_ASSERTION(!sMsgFilterHook, "sMsgFilterHook must be NULL!");
NS_ASSERTION(!sCallProcHook, "sCallProcHook must be NULL!");
DISPLAY_NMM_PRT("***************** Installing Msg Hooks ***************\n");
// Install msg hook for moving the window and resizing
if (!sMsgFilterHook) {
DISPLAY_NMM_PRT("***** Hooking sMsgFilterHook!\n");
sMsgFilterHook = SetWindowsHookEx(WH_MSGFILTER, MozSpecialMsgFilter,
nullptr, GetCurrentThreadId());
#ifdef POPUP_ROLLUP_DEBUG_OUTPUT
if (!sMsgFilterHook) {
MOZ_LOG(gWindowsLog, LogLevel::Info,
("***** SetWindowsHookEx is NOT installed for WH_MSGFILTER!\n"));
}
#endif
}
// Install msg hook for menus
if (!sCallProcHook) {
DISPLAY_NMM_PRT("***** Hooking sCallProcHook!\n");
sCallProcHook = SetWindowsHookEx(WH_CALLWNDPROC, MozSpecialWndProc,
nullptr, GetCurrentThreadId());
#ifdef POPUP_ROLLUP_DEBUG_OUTPUT
if (!sCallProcHook) {
MOZ_LOG(gWindowsLog, LogLevel::Info,
("***** SetWindowsHookEx is NOT installed for WH_CALLWNDPROC!\n"));
}
#endif
}
// Install msg hook for the mouse
if (!sCallMouseHook) {
DISPLAY_NMM_PRT("***** Hooking sCallMouseHook!\n");
sCallMouseHook = SetWindowsHookEx(WH_MOUSE, MozSpecialMouseProc,
nullptr, GetCurrentThreadId());
#ifdef POPUP_ROLLUP_DEBUG_OUTPUT
if (!sCallMouseHook) {
MOZ_LOG(gWindowsLog, LogLevel::Info,
("***** SetWindowsHookEx is NOT installed for WH_MOUSE!\n"));
}
#endif
}
}
// Unhook special message hooks for dropdowns.
void nsWindow::UnregisterSpecialDropdownHooks()
{
DISPLAY_NMM_PRT("***************** De-installing Msg Hooks ***************\n");
if (sCallProcHook) {
DISPLAY_NMM_PRT("***** Unhooking sCallProcHook!\n");
if (!::UnhookWindowsHookEx(sCallProcHook)) {
DISPLAY_NMM_PRT("***** UnhookWindowsHookEx failed for sCallProcHook!\n");
}
sCallProcHook = nullptr;
}
if (sMsgFilterHook) {
DISPLAY_NMM_PRT("***** Unhooking sMsgFilterHook!\n");
if (!::UnhookWindowsHookEx(sMsgFilterHook)) {
DISPLAY_NMM_PRT("***** UnhookWindowsHookEx failed for sMsgFilterHook!\n");
}
sMsgFilterHook = nullptr;
}
if (sCallMouseHook) {
DISPLAY_NMM_PRT("***** Unhooking sCallMouseHook!\n");
if (!::UnhookWindowsHookEx(sCallMouseHook)) {
DISPLAY_NMM_PRT("***** UnhookWindowsHookEx failed for sCallMouseHook!\n");
}
sCallMouseHook = nullptr;
}
}
// This timer is designed to only fire one time at most each time a "hook" function
// is used to rollup the dropdown. In some cases, the timer may be scheduled from the
// hook, but that hook event or a subsequent event may roll up the dropdown before
// this timer function is executed.
//
// For example, if an MFC control takes focus, the combobox will lose focus and rollup
// before this function fires.
VOID CALLBACK nsWindow::HookTimerForPopups(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime)
{
if (sHookTimerId != 0) {
// if the window is nullptr then we need to use the ID to kill the timer
BOOL status = ::KillTimer(nullptr, sHookTimerId);
NS_ASSERTION(status, "Hook Timer was not killed.");
sHookTimerId = 0;
}
if (sRollupMsgId != 0) {
// Note: DealWithPopups does the check to make sure that the rollup widget is set.
LRESULT popupHandlingResult;
nsAutoRollup autoRollup;
DealWithPopups(sRollupMsgWnd, sRollupMsgId, 0, 0, &popupHandlingResult);
sRollupMsgId = 0;
sRollupMsgWnd = nullptr;
}
}
BOOL CALLBACK nsWindow::ClearResourcesCallback(HWND aWnd, LPARAM aMsg)
{
nsWindow *window = WinUtils::GetNSWindowPtr(aWnd);
if (window) {
window->ClearCachedResources();
}
return TRUE;
}
void
nsWindow::ClearCachedResources()
{
if (mLayerManager &&
mLayerManager->GetBackendType() == LayersBackend::LAYERS_BASIC) {
mLayerManager->ClearCachedResources();
}
::EnumChildWindows(mWnd, nsWindow::ClearResourcesCallback, 0);
}
static bool IsDifferentThreadWindow(HWND aWnd)
{
return ::GetCurrentThreadId() != ::GetWindowThreadProcessId(aWnd, nullptr);
}
// static
bool
nsWindow::EventIsInsideWindow(nsWindow* aWindow)
{
RECT r;
::GetWindowRect(aWindow->mWnd, &r);
DWORD pos = ::GetMessagePos();
POINT mp;
mp.x = GET_X_LPARAM(pos);
mp.y = GET_Y_LPARAM(pos);
// was the event inside this window?
return static_cast<bool>(::PtInRect(&r, mp));
}
// static
bool
nsWindow::GetPopupsToRollup(nsIRollupListener* aRollupListener,
uint32_t* aPopupsToRollup)
{
// If we're dealing with menus, we probably have submenus and we don't want
// to rollup some of them if the click is in a parent menu of the current
// submenu.
*aPopupsToRollup = UINT32_MAX;
AutoTArray<nsIWidget*, 5> widgetChain;
uint32_t sameTypeCount =
aRollupListener->GetSubmenuWidgetChain(&widgetChain);
for (uint32_t i = 0; i < widgetChain.Length(); ++i) {
nsIWidget* widget = widgetChain[i];
if (EventIsInsideWindow(static_cast<nsWindow*>(widget))) {
// Don't roll up if the mouse event occurred within a menu of the
// same type. If the mouse event occurred in a menu higher than that,
// roll up, but pass the number of popups to Rollup so that only those
// of the same type close up.
if (i < sameTypeCount) {
return false;
}
*aPopupsToRollup = sameTypeCount;
break;
}
}
return true;
}
// static
bool
nsWindow::NeedsToHandleNCActivateDelayed(HWND aWnd)
{
// While popup is open, popup window might be activated by other application.
// At this time, we need to take back focus to the previous window but it
// causes flickering its nonclient area because WM_NCACTIVATE comes before
// WM_ACTIVATE and we cannot know which window will take focus at receiving
// WM_NCACTIVATE. Therefore, we need a hack for preventing the flickerling.
//
// If non-popup window receives WM_NCACTIVATE at deactivating, default
// wndproc shouldn't handle it as deactivating. Instead, at receiving
// WM_ACTIVIATE after that, WM_NCACTIVATE should be sent again manually.
// This returns true if the window needs to handle WM_NCACTIVATE later.
nsWindow* window = WinUtils::GetNSWindowPtr(aWnd);
return window && !window->IsPopup();
}
static bool
IsTouchSupportEnabled(HWND aWnd)
{
nsWindow* topWindow = WinUtils::GetNSWindowPtr(WinUtils::GetTopLevelHWND(aWnd, true));
return topWindow ? topWindow->IsTouchWindow() : false;
}
// static
bool
nsWindow::DealWithPopups(HWND aWnd, UINT aMessage,
WPARAM aWParam, LPARAM aLParam, LRESULT* aResult)
{
NS_ASSERTION(aResult, "Bad outResult");
// XXX Why do we use the return value of WM_MOUSEACTIVATE for all messages?
*aResult = MA_NOACTIVATE;
if (!::IsWindowVisible(aWnd)) {
return false;
}
nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener();
NS_ENSURE_TRUE(rollupListener, false);
nsCOMPtr<nsIWidget> popup = rollupListener->GetRollupWidget();
if (!popup) {
return false;
}
static bool sSendingNCACTIVATE = false;
static bool sPendingNCACTIVATE = false;
uint32_t popupsToRollup = UINT32_MAX;
bool consumeRollupEvent = false;
nsWindow* popupWindow = static_cast<nsWindow*>(popup.get());
UINT nativeMessage = WinUtils::GetNativeMessage(aMessage);
switch (nativeMessage) {
case WM_TOUCH:
if (!IsTouchSupportEnabled(aWnd)) {
// If APZ is disabled, don't allow touch inputs to dismiss popups. The
// compatibility mouse events will do it instead.
return false;
}
MOZ_FALLTHROUGH;
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_NCLBUTTONDOWN:
case WM_NCRBUTTONDOWN:
case WM_NCMBUTTONDOWN:
if (nativeMessage != WM_TOUCH &&
IsTouchSupportEnabled(aWnd) &&
MOUSE_INPUT_SOURCE() == nsIDOMMouseEvent::MOZ_SOURCE_TOUCH) {
// If any of these mouse events are really compatibility events that
// Windows is sending for touch inputs, then don't allow them to dismiss
// popups when APZ is enabled (instead we do the dismissing as part of
// WM_TOUCH handling which is more correct).
// If we don't do this, then when the user lifts their finger after a
// long-press, the WM_RBUTTONDOWN compatibility event that Windows sends
// us will dismiss the contextmenu popup that we displayed as part of
// handling the long-tap-up.
return false;
}
if (!EventIsInsideWindow(popupWindow) &&
GetPopupsToRollup(rollupListener, &popupsToRollup)) {
break;
}
return false;
case WM_POINTERDOWN:
{
WinPointerEvents pointerEvents;
if (!pointerEvents.ShouldRollupOnPointerEvent(nativeMessage, aWParam)) {
return false;
}
if (!GetPopupsToRollup(rollupListener, &popupsToRollup)) {
return false;
}
// Can't use EventIsInsideWindow to check whether the event is inside
// the popup window. It's because EventIsInsideWindow gets message
// coordinates by GetMessagePos, which returns physical screen
// coordinates at WM_POINTERDOWN.
POINT pt;
pt.x = GET_X_LPARAM(aLParam);
pt.y = GET_Y_LPARAM(aLParam);
RECT r;
::GetWindowRect(popupWindow->mWnd, &r);
if (::PtInRect(&r, pt) != 0) {
// Don't roll up if the event is inside the popup window.
return false;
}
}
break;
case WM_MOUSEWHEEL:
case WM_MOUSEHWHEEL:
// We need to check if the popup thinks that it should cause closing
// itself when mouse wheel events are fired outside the rollup widget.
if (!EventIsInsideWindow(popupWindow)) {
// Check if we should consume this event even if we don't roll-up:
consumeRollupEvent =
rollupListener->ShouldConsumeOnMouseWheelEvent();
*aResult = MA_ACTIVATE;
if (rollupListener->ShouldRollupOnMouseWheelEvent() &&
GetPopupsToRollup(rollupListener, &popupsToRollup)) {
break;
}
}
return consumeRollupEvent;
case WM_ACTIVATEAPP:
break;
case WM_ACTIVATE:
// NOTE: Don't handle WA_INACTIVE for preventing popup taking focus
// because we cannot distinguish it's caused by mouse or not.
if (LOWORD(aWParam) == WA_ACTIVE && aLParam) {
nsWindow* window = WinUtils::GetNSWindowPtr(aWnd);
if (window && window->IsPopup()) {
// Cancel notifying widget listeners of deactivating the previous
// active window (see WM_KILLFOCUS case in ProcessMessage()).
sJustGotDeactivate = false;
// Reactivate the window later.
::PostMessageW(aWnd, MOZ_WM_REACTIVATE, aWParam, aLParam);
return true;
}
// Don't rollup the popup when focus moves back to the parent window
// from a popup because such case is caused by strange mouse drivers.
nsWindow* prevWindow =
WinUtils::GetNSWindowPtr(reinterpret_cast<HWND>(aLParam));
if (prevWindow && prevWindow->IsPopup()) {
return false;
}
} else if (LOWORD(aWParam) == WA_INACTIVE) {
nsWindow* activeWindow =
WinUtils::GetNSWindowPtr(reinterpret_cast<HWND>(aLParam));
if (sPendingNCACTIVATE && NeedsToHandleNCActivateDelayed(aWnd)) {
// If focus moves to non-popup widget or focusable popup, the window
// needs to update its nonclient area.
if (!activeWindow || !activeWindow->IsPopup()) {
sSendingNCACTIVATE = true;
::SendMessageW(aWnd, WM_NCACTIVATE, false, 0);
sSendingNCACTIVATE = false;
}
sPendingNCACTIVATE = false;
}
// If focus moves from/to popup, we don't need to rollup the popup
// because such case is caused by strange mouse drivers.
if (activeWindow) {
if (activeWindow->IsPopup()) {
return false;
}
nsWindow* deactiveWindow = WinUtils::GetNSWindowPtr(aWnd);
if (deactiveWindow && deactiveWindow->IsPopup()) {
return false;
}
}
} else if (LOWORD(aWParam) == WA_CLICKACTIVE) {
// If the WM_ACTIVATE message is caused by a click in a popup,
// we should not rollup any popups.
nsWindow* window = WinUtils::GetNSWindowPtr(aWnd);
if ((window && window->IsPopup()) ||
!GetPopupsToRollup(rollupListener, &popupsToRollup)) {
return false;
}
}
break;
case MOZ_WM_REACTIVATE:
// The previous active window should take back focus.
if (::IsWindow(reinterpret_cast<HWND>(aLParam))) {
::SetForegroundWindow(reinterpret_cast<HWND>(aLParam));
}
return true;
case WM_NCACTIVATE:
if (!aWParam && !sSendingNCACTIVATE &&
NeedsToHandleNCActivateDelayed(aWnd)) {
// Don't just consume WM_NCACTIVATE. It doesn't handle only the
// nonclient area state change.
::DefWindowProcW(aWnd, aMessage, TRUE, aLParam);
// Accept the deactivating because it's necessary to receive following
// WM_ACTIVATE.
*aResult = TRUE;
sPendingNCACTIVATE = true;
return true;
}
return false;
case WM_MOUSEACTIVATE:
if (!EventIsInsideWindow(popupWindow) &&
GetPopupsToRollup(rollupListener, &popupsToRollup)) {
// WM_MOUSEACTIVATE may be caused by moving the mouse (e.g., X-mouse
// of TweakUI is enabled. Then, check if the popup should be rolled up
// with rollup listener. If not, just consume the message.
if (HIWORD(aLParam) == WM_MOUSEMOVE &&
!rollupListener->ShouldRollupOnMouseActivate()) {
return true;
}
// Otherwise, it should be handled by wndproc.
return false;
}
// Prevent the click inside the popup from causing a change in window
// activation. Since the popup is shown non-activated, we need to eat any
// requests to activate the window while it is displayed. Windows will
// automatically activate the popup on the mousedown otherwise.
return true;
case WM_SHOWWINDOW:
// If the window is being minimized, close popups.
if (aLParam == SW_PARENTCLOSING) {
break;
}
return false;
case WM_KILLFOCUS:
// If focus moves to other window created in different process/thread,
// e.g., a plugin window, popups should be rolled up.
if (IsDifferentThreadWindow(reinterpret_cast<HWND>(aWParam))) {
break;
}
return false;
case WM_MOVING:
case WM_MENUSELECT:
break;
default:
return false;
}
// Only need to deal with the last rollup for left mouse down events.
NS_ASSERTION(!nsAutoRollup::GetLastRollup(), "last rollup is null");
if (nativeMessage == WM_TOUCH || nativeMessage == WM_LBUTTONDOWN || nativeMessage == WM_POINTERDOWN) {
nsIntPoint pos;
if (nativeMessage == WM_TOUCH) {
if (nsWindow* win = WinUtils::GetNSWindowPtr(aWnd)) {
pos = win->GetTouchCoordinates(aWParam, aLParam);
}
} else {
POINT pt;
pt.x = GET_X_LPARAM(aLParam);
pt.y = GET_Y_LPARAM(aLParam);
::ClientToScreen(aWnd, &pt);
pos = nsIntPoint(pt.x, pt.y);
}
nsIContent* lastRollup;
consumeRollupEvent =
rollupListener->Rollup(popupsToRollup, true, &pos, &lastRollup);
nsAutoRollup::SetLastRollup(lastRollup);
} else {
consumeRollupEvent =
rollupListener->Rollup(popupsToRollup, true, nullptr, nullptr);
}
// Tell hook to stop processing messages
sProcessHook = false;
sRollupMsgId = 0;
sRollupMsgWnd = nullptr;
// If we are NOT supposed to be consuming events, let it go through
if (consumeRollupEvent && nativeMessage != WM_RBUTTONDOWN) {
*aResult = MA_ACTIVATE;
return true;
}
return false;
}
/**************************************************************
**************************************************************
**
** BLOCK: Misc. utility methods and functions.
**
** General use.
**
**************************************************************
**************************************************************/
// Note that the result of GetTopLevelWindow method can be different from the
// result of WinUtils::GetTopLevelHWND(). The result can be non-floating
// window. Because our top level window may be contained in another window
// which is not managed by us.
nsWindow* nsWindow::GetTopLevelWindow(bool aStopOnDialogOrPopup)
{
nsWindow* curWindow = this;
while (true) {
if (aStopOnDialogOrPopup) {
switch (curWindow->mWindowType) {
case eWindowType_dialog:
case eWindowType_popup:
return curWindow;
default:
break;
}
}
// Retrieve the top level parent or owner window
nsWindow* parentWindow = curWindow->GetParentWindow(true);
if (!parentWindow)
return curWindow;
curWindow = parentWindow;
}
}
static BOOL CALLBACK gEnumWindowsProc(HWND hwnd, LPARAM lParam)
{
DWORD pid;
::GetWindowThreadProcessId(hwnd, &pid);
if (pid == GetCurrentProcessId() && ::IsWindowVisible(hwnd))
{
gWindowsVisible = true;
return FALSE;
}
return TRUE;
}
bool nsWindow::CanTakeFocus()
{
gWindowsVisible = false;
EnumWindows(gEnumWindowsProc, 0);
if (!gWindowsVisible) {
return true;
} else {
HWND fgWnd = ::GetForegroundWindow();
if (!fgWnd) {
return true;
}
DWORD pid;
GetWindowThreadProcessId(fgWnd, &pid);
if (pid == GetCurrentProcessId()) {
return true;
}
}
return false;
}
/* static */ const wchar_t*
nsWindow::GetMainWindowClass()
{
static const wchar_t* sMainWindowClass = nullptr;
if (!sMainWindowClass) {
nsAdoptingString className =
Preferences::GetString("ui.window_class_override");
if (!className.IsEmpty()) {
sMainWindowClass = wcsdup(className.get());
} else {
sMainWindowClass = kClassNameGeneral;
}
}
return sMainWindowClass;
}
LPARAM nsWindow::lParamToScreen(LPARAM lParam)
{
POINT pt;
pt.x = GET_X_LPARAM(lParam);
pt.y = GET_Y_LPARAM(lParam);
::ClientToScreen(mWnd, &pt);
return MAKELPARAM(pt.x, pt.y);
}
LPARAM nsWindow::lParamToClient(LPARAM lParam)
{
POINT pt;
pt.x = GET_X_LPARAM(lParam);
pt.y = GET_Y_LPARAM(lParam);
::ScreenToClient(mWnd, &pt);
return MAKELPARAM(pt.x, pt.y);
}
void nsWindow::PickerOpen()
{
mPickerDisplayCount++;
}
void nsWindow::PickerClosed()
{
NS_ASSERTION(mPickerDisplayCount > 0, "mPickerDisplayCount out of sync!");
if (!mPickerDisplayCount)
return;
mPickerDisplayCount--;
if (!mPickerDisplayCount && mDestroyCalled) {
Destroy();
}
}
bool
nsWindow::WidgetTypeSupportsAcceleration()
{
// We don't currently support using an accelerated layer manager with
// transparent windows so don't even try. I'm also not sure if we even
// want to support this case. See bug 593471.
//
// Also see bug 1150376, D3D11 composition can cause issues on some devices
// on Windows 7 where presentation fails randomly for windows with drop
// shadows.
return mTransparencyMode != eTransparencyTransparent &&
!(IsPopup() && DeviceManagerDx::Get()->IsWARP());
}
void
nsWindow::SetCandidateWindowForPlugin(const CandidateWindowPosition& aPosition)
{
CANDIDATEFORM form;
form.dwIndex = 0;
if (aPosition.mExcludeRect) {
form.dwStyle = CFS_EXCLUDE;
form.rcArea.left = aPosition.mRect.x;
form.rcArea.top = aPosition.mRect.y;
form.rcArea.right = aPosition.mRect.x + aPosition.mRect.width;
form.rcArea.bottom = aPosition.mRect.y + aPosition.mRect.height;
} else {
form.dwStyle = CFS_CANDIDATEPOS;
}
form.ptCurrentPos.x = aPosition.mPoint.x;
form.ptCurrentPos.y = aPosition.mPoint.y;
IMEHandler::SetCandidateWindow(this, &form);
}
void
nsWindow::DefaultProcOfPluginEvent(const WidgetPluginEvent& aEvent)
{
const NPEvent* pPluginEvent =
static_cast<const NPEvent*>(aEvent.mPluginEvent);
if (NS_WARN_IF(!pPluginEvent)) {
return;
}
if (!mWnd) {
return;
}
// For WM_IME_*COMPOSITION
IMEHandler::DefaultProcOfPluginEvent(this, pPluginEvent);
CallWindowProcW(GetPrevWindowProc(), mWnd, pPluginEvent->event,
pPluginEvent->wParam, pPluginEvent->lParam);
}
nsresult
nsWindow::OnWindowedPluginKeyEvent(const NativeEventData& aKeyEventData,
nsIKeyEventInPluginCallback* aCallback)
{
if (NS_WARN_IF(!mWnd)) {
return NS_OK;
}
const WinNativeKeyEventData* eventData =
static_cast<const WinNativeKeyEventData*>(aKeyEventData);
switch (eventData->mMessage) {
case WM_KEYDOWN:
case WM_SYSKEYDOWN: {
MSG mozMsg =
WinUtils::InitMSG(MOZ_WM_KEYDOWN, eventData->mWParam,
eventData->mLParam, mWnd);
ModifierKeyState modifierKeyState(eventData->mModifiers);
NativeKey nativeKey(this, mozMsg, modifierKeyState,
eventData->GetKeyboardLayout());
return nativeKey.HandleKeyDownMessage() ? NS_SUCCESS_EVENT_CONSUMED :
NS_OK;
}
case WM_KEYUP:
case WM_SYSKEYUP: {
MSG mozMsg =
WinUtils::InitMSG(MOZ_WM_KEYUP, eventData->mWParam,
eventData->mLParam, mWnd);
ModifierKeyState modifierKeyState(eventData->mModifiers);
NativeKey nativeKey(this, mozMsg, modifierKeyState,
eventData->GetKeyboardLayout());
return nativeKey.HandleKeyUpMessage() ? NS_SUCCESS_EVENT_CONSUMED : NS_OK;
}
default:
// We shouldn't consume WM_*CHAR messages here even if the preceding
// keydown or keyup event on the plugin is consumed. It should be
// managed in each plugin window rather than top level window.
return NS_OK;
}
}
bool nsWindow::OnPointerEvents(UINT msg, WPARAM aWParam, LPARAM aLParam)
{
if (!mPointerEvents.ShouldHandleWinPointerMessages(msg, aWParam)) {
return false;
}
if (!mPointerEvents.ShouldFirePointerEventByWinPointerMessages()) {
// We have to handle WM_POINTER* to fetch and cache pen related information
// and fire WidgetMouseEvent with the cached information the WM_*BUTTONDOWN
// handler. This is because Windows doesn't support ::DoDragDrop in the touch
// or pen message handlers.
mPointerEvents.ConvertAndCachePointerInfo(msg, aWParam);
// Don't consume the Windows WM_POINTER* messages
return false;
}
// When dispatching mouse events with pen, there may be some
// WM_POINTERUPDATE messages between WM_POINTERDOWN and WM_POINTERUP with
// small movements. Those events will reset sLastMousePoint and reset
// sLastClickCount. To prevent that, we keep the last pen down position
// and compare it with the subsequent WM_POINTERUPDATE. If the movement is
// smaller than GetSystemMetrics(SM_CXDRAG), then we suppress firing
// eMouseMove for WM_POINTERUPDATE.
static POINT sLastPointerDownPoint = {0};
// We don't support chorded buttons for pen. Keep the button at
// WM_POINTERDOWN.
static WidgetMouseEvent::buttonType sLastPenDownButton =
WidgetMouseEvent::eLeftButton;
static bool sPointerDown = false;
EventMessage message;
WidgetMouseEvent::buttonType button = WidgetMouseEvent::eLeftButton;
switch (msg) {
case WM_POINTERDOWN:
{
LayoutDeviceIntPoint eventPoint(GET_X_LPARAM(aLParam),
GET_Y_LPARAM(aLParam));
sLastPointerDownPoint.x = eventPoint.x;
sLastPointerDownPoint.y = eventPoint.y;
message = eMouseDown;
button = IS_POINTER_SECONDBUTTON_WPARAM(aWParam) ?
WidgetMouseEvent::eRightButton : WidgetMouseEvent::eLeftButton;
sLastPenDownButton = button;
sPointerDown = true;
}
break;
case WM_POINTERUP:
message = eMouseUp;
MOZ_ASSERT(sPointerDown, "receive WM_POINTERUP w/o WM_POINTERDOWN");
button = sPointerDown ? sLastPenDownButton : WidgetMouseEvent::eLeftButton;
sPointerDown = false;
break;
case WM_POINTERUPDATE:
message = eMouseMove;
if (sPointerDown) {
LayoutDeviceIntPoint eventPoint(GET_X_LPARAM(aLParam),
GET_Y_LPARAM(aLParam));
int32_t movementX = sLastPointerDownPoint.x > eventPoint.x ?
sLastPointerDownPoint.x - eventPoint.x :
eventPoint.x - sLastPointerDownPoint.x;
int32_t movementY = sLastPointerDownPoint.y > eventPoint.y ?
sLastPointerDownPoint.y - eventPoint.y :
eventPoint.y - sLastPointerDownPoint.y;
bool insideMovementThreshold =
movementX < (int32_t)::GetSystemMetrics(SM_CXDRAG) &&
movementY < (int32_t)::GetSystemMetrics(SM_CYDRAG);
if (insideMovementThreshold) {
// Suppress firing eMouseMove for WM_POINTERUPDATE if the movement
// from last WM_POINTERDOWN is smaller than SM_CXDRAG / SM_CYDRAG
return false;
}
button = sLastPenDownButton;
}
break;
case WM_POINTERLEAVE:
message = eMouseExitFromWidget;
break;
default:
return false;
}
uint32_t pointerId = mPointerEvents.GetPointerId(aWParam);
POINTER_PEN_INFO penInfo;
mPointerEvents.GetPointerPenInfo(pointerId, &penInfo);
// Windows defines the pen pressure is normalized to a range between 0 and
// 1024. Convert it to float.
float pressure = penInfo.pressure ? (float)penInfo.pressure / 1024 : 0;
int16_t buttons =
sPointerDown ? button == WidgetMouseEvent::eLeftButton ?
WidgetMouseEvent::eLeftButtonFlag :
WidgetMouseEvent::eRightButtonFlag :
WidgetMouseEvent::eNoButtonFlag;
WinPointerInfo pointerInfo(pointerId, penInfo.tiltX, penInfo.tiltY, pressure,
buttons);
// The aLParam of WM_POINTER* is the screen location. Convert it to client
// location
LPARAM newLParam = lParamToClient(aLParam);
DispatchMouseEvent(message, aWParam, newLParam, false, button,
nsIDOMMouseEvent::MOZ_SOURCE_PEN, &pointerInfo);
// Consume WM_POINTER* to stop Windows fires WM_*BUTTONDOWN / WM_*BUTTONUP
// WM_MOUSEMOVE.
return true;
}
/**************************************************************
**************************************************************
**
** BLOCK: ChildWindow impl.
**
** Child window overrides.
**
**************************************************************
**************************************************************/
// return the style for a child nsWindow
DWORD ChildWindow::WindowStyle()
{
DWORD style = WS_CLIPCHILDREN | nsWindow::WindowStyle();
if (!(style & WS_POPUP))
style |= WS_CHILD; // WS_POPUP and WS_CHILD are mutually exclusive.
VERIFY_WINDOW_STYLE(style);
return style;
}
void
nsWindow::GetCompositorWidgetInitData(mozilla::widget::CompositorWidgetInitData* aInitData)
{
aInitData->hWnd() = reinterpret_cast<uintptr_t>(mWnd);
aInitData->widgetKey() = reinterpret_cast<uintptr_t>(static_cast<nsIWidget*>(this));
aInitData->transparencyMode() = mTransparencyMode;
}
bool
nsWindow::SynchronouslyRepaintOnResize()
{
return !gfxWindowsPlatform::GetPlatform()->DwmCompositionEnabled();
}
| [
"jiangchang@jiangchangdeMacBook-Pro.local"
] | jiangchang@jiangchangdeMacBook-Pro.local |
f5e47a5aeec5354eaf79e6ac91b82bf5472a7524 | e9e8064dd3848b85b65e871877c55f025628fb49 | /code/MapEngine/VOSBase/VOSURL.cpp | 29883c01f2859a09b0becaea7ed0565fc425d140 | [] | no_license | xxh0078/gmapx | eb5ae8eefc2308b8ca3a07f575ee3a27b3e90d95 | e265ad90b302db7da05345e2467ec2587e501e90 | refs/heads/master | 2021-06-02T14:42:30.372998 | 2019-08-29T02:45:10 | 2019-08-29T02:45:10 | 12,397,909 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,082 | cpp | #include "StdAfx.h"
#include "VOSURL.h"
#pragma comment(lib,"../lib/libcurl_imp.lib")
#include "../../include/curl/curl.h"
#pragma comment(lib,"wininet.lib")
#include<wininet.h>
void *myrealloc(void *ptr, size_t size)
{ /* There might be a realloc() out there that doesn't like reallocing NULL pointers, so we take care of it here */
if(ptr)
return realloc(ptr, size);
else
return malloc(size);
}
size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)data;
mem->memory = (char *)myrealloc(mem->memory, mem->size + realsize + 1);
if (mem->memory) {
memcpy(&(mem->memory[mem->size]), ptr, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
}
return realsize;
}
size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp)
{
struct WriteThis *pooh = (struct WriteThis *)userp;
if(size*nmemb < 1)
return 0;
if(pooh->sizeleft) {
*(char *)ptr = pooh->readptr[0]; /* copy one single byte */
pooh->readptr++; /* advance pointer */
pooh->sizeleft--; /* less data left */
return 1; /* we return 1 byte at a time! */
}
return -1; /* no more data left to deliver */
}
int curl_httpget(const char* URLbuf,struct MemoryStruct *chunk,const char* cookiefile)
{
CURL *curl_handle;
int errcode=0;
chunk->memory=NULL; /* we expect realloc(NULL, size) to work */
chunk->size = 0; /* no data at this point */
curl_global_init(CURL_GLOBAL_ALL);
/* init the curl session */
curl_handle = curl_easy_init();
curl_easy_setopt(curl_handle, CURLOPT_URL, URLbuf);
curl_easy_setopt(curl_handle, CURLOPT_COOKIEFILE,cookiefile);
/* send all data to this function */
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)chunk);
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
curl_easy_setopt(curl_handle, CURLOPT_COOKIEJAR,cookiefile);
/* get it! */
errcode=curl_easy_perform(curl_handle);
/* cleanup curl stuff */
curl_easy_cleanup(curl_handle);
return errcode;
}
bool curl_httppost( const char* URLbuf,char* data, int len,struct MemoryStruct *chunk )
{
CURL *curl;
CURLcode res;
chunk->memory=NULL; /* we expect realloc(NULL, size) to work */
chunk->size = 0; /* no data at this point */
struct WriteThis pooh;
pooh.readptr = data;
pooh.sizeleft = len;
curl = curl_easy_init();
if(curl) {
/* First set the URL that is about to receive our POST. */
/**
curl_easy_setopt(curl, CURLOPT_URL,
"http://receivingsite.com.pooh/index.cgi");
**/
curl_easy_setopt(curl, CURLOPT_URL,URLbuf);
/* Now specify we want to POST data */
curl_easy_setopt(curl, CURLOPT_POST, TRUE);
/* we want to use our own read function */
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
/* pointer to pass to our read function */
curl_easy_setopt(curl, CURLOPT_READDATA, &pooh);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)chunk);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
/* get verbose debug output please */
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
/*
If you use POST to a HTTP 1.1 server, you can send data without knowing
the size before starting the POST if you use chunked encoding. You
enable this by adding a header like "Transfer-Encoding: chunked" with
CURLOPT_HTTPHEADER. With HTTP 1.0 or without chunked transfer, you must
specify the size in the request.
*/
#ifdef USE_CHUNKED
{
curl_slist *chunk = NULL;
chunk = curl_slist_append(chunk, "Transfer-Encoding: chunked");
res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
/* use curl_slist_free_all() after the *perform() call to free this
list again */
}
#else
/* Set the expected POST size. If you want to POST large amounts of data,
consider CURLOPT_POSTFIELDSIZE_LARGE */
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, pooh.sizeleft);
#endif
#ifdef DISABLE_EXPECT
/*
Using POST with HTTP 1.1 implies the use of a "Expect: 100-continue"
header. You can disable this header with CURLOPT_HTTPHEADER as usual.
NOTE: if you want chunked transfer too, you need to combine these two
since you can only set one list of headers with CURLOPT_HTTPHEADER. */
/* A less good option would be to enforce HTTP 1.0, but that might also
have other implications. */
{
curl_slist *chunk = NULL;
chunk = curl_slist_append(chunk, "Expect:");
res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
/* use curl_slist_free_all() after the *perform() call to free this
list again */
}
#endif
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
CVOSURL::CVOSURL(void)
{
}
CVOSURL::~CVOSURL(void)
{
}
int InterNet_httpget(char* strURL,struct MemoryStruct *chunk )
{
HINTERNET internet=InternetOpen("HTTP Downloader 1", INTERNET_OPEN_TYPE_PRECONFIG,
NULL, NULL, NULL);
if(!internet)
{
throw "InternetOpen error!";
return 1 ;
}
//打开一个http url地址
HINTERNET file_handle = InternetOpenUrl(internet, strURL, NULL, 0, INTERNET_FLAG_RELOAD, 0);
if(!file_handle)
{
//throw "InternetOpenUrl error! - Maybe you should add Http:// or Ftp://";
return 2 ;
}
chunk->size = 0;
char* ptemp = chunk->memory;
int b=false;
unsigned long ilen = 0 ;
while(1)
{
if ( chunk->size >1024*1023 )
{
break;
}
b = InternetReadFile( file_handle, ptemp, 1024, &ilen);
if(!b )
{
//throw "InternetReadFile error!";
int iiii = ::GetLastError();
break;
}
if( ilen <= 0 )
{
break;
}
ptemp += ilen;
chunk->size += ilen;
}
//关闭连接
InternetCloseHandle(internet);
return 0;
} | [
"you@example.com"
] | you@example.com |
4aa45ab47e66723ac15bc3312eb0c126265186fa | 10b334ee4661eddb4221686326995f8e4bf332fd | /camera/track.cpp | 64767759cfbd1e9e1771d7d5dd81479ce1e796d2 | [] | no_license | niraj-r/RCXD | 85968ad56ba6993da8c4875ee6cb28ce7a3502ce | 08cb92f3d583aebdb4b7d0f7e8a2c49ec4b5387b | refs/heads/master | 2021-05-01T10:19:53.080917 | 2016-08-05T23:47:16 | 2016-08-05T23:47:16 | 62,970,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,964 | cpp | // g++ -std=c++11 track.cpp -o track `pkg-config --cflags --libs opencv`
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "iostream"
using namespace cv;
using namespace std;
void NonUniformIlluminationMorph(const cv::Mat &src, cv::Mat &dst, int minThickess = 5, bool restoreMean = true, cv::Mat *background=NULL);
int main( int argc, char** argv ) {
//Scalar greenLower = (29, 86, 6);
//Scalar greenUpper = (64, 255, 255);
Scalar greenLower = (0, 0, 0);
Scalar greenUpper = (0, 0, 255);
VideoCapture cap(0); // open the default camera
if (!cap.isOpened()) // check if we succeeded
return -1;
Mat edges;
Mat mask;
Mat hsv;
namedWindow("hsv", 1);
for (;;) {
Mat frame, illum;
cap >> frame; // get a new frame from camera
//NonUniformIlluminationMorph(frame, illum);
//imwrite("illum.jpg",illum);
GaussianBlur(frame, illum, Size(21,21), 0, 0);
imshow("blur", illum);
cvtColor(illum, hsv, COLOR_BGR2HSV);
imshow("hsv", hsv);
// Apply erosion or dilation on the image
// (in, out, kernel, anchor, iteration, bordertype, bordervalue)
// hsv(0-360, 0-100, 0-100) => hsv(0-180, 0-255, 0-255)
inRange(hsv, Scalar(5,165,110), Scalar(20,195,130), mask);
erode( mask, mask, Mat(), Point(-1, -1), 2, BORDER_CONSTANT, morphologyDefaultBorderValue() );
dilate( mask, mask, Mat(), Point(-1, -1), 2, BORDER_CONSTANT, morphologyDefaultBorderValue() );
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
RNG rng(12345);
findContours( mask, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE, Point(0, 0) );
Mat drawing = Mat::zeros( mask.size(), CV_8UC3 );
for( int i = 0; i< contours.size(); i++ ){
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() );
}
imshow("contours", drawing);
if (waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
/** @brief Remove non-uniform illumination using morphology
Morphology OPEN can detects bright structures larger that a given size.
If you consider large structures as background you can use OPEN
to detect background than remove it from the original image.
This is same as to do MORPH_TOPHAT.
@Param [in]src input image GRAY, BGR or BGRA.
With BGR(A) image this function uses Brightness from image HSV.
@Param [out]dst destination image. If alpha channel is present in src it will be cloned in dst
@Param minThickess size used by morphology operation to estimate background. Use small size to
enhance details flatting larger structures.
@c minThickess should be just larger than maximum thickness in objects you want to keep.
Example:
- Take thickest object, suppose is circle 100 * 100px
- Measure its maximum thickness let's say is 20px: In this case @c minThickess could be 20+5.
- If the circle is filled than thickness=diameter, consequently @c minThickess should be 100+5px
@Param restoreMean if true, the mean of input brightness will be restored in destination image.
if false, the destination brightness will be close to darker region of input image.
@Param [out]background if not NULL the removed background will be returned here.
This will be Mat(src.size(),CV_8UC1)
*/
void NonUniformIlluminationMorph(const cv::Mat &src, cv::Mat &dst, int minThickess, bool restoreMean, cv::Mat *background)
{
CV_Assert(minThickess >= 0);
CV_Assert((src.type() == CV_8UC1) || (src.type() == CV_8UC3) || (src.type() == CV_8UC4));
cv::Mat brightness, src_hsv;
vector<cv::Mat> hsv_planes;
// GET THE BRIGHTNESS
if (src.type() == CV_8UC1)
src.copyTo(brightness);
else if (src.type() == CV_8UC3)
{
cv::cvtColor(src, src_hsv, cv::COLOR_BGR2HSV);
cv::split(src_hsv, hsv_planes);
brightness = hsv_planes[2];
}
else if (src.type() == CV_8UC4)
{
cv::cvtColor(src, src_hsv, cv::COLOR_BGRA2BGR);
cv::cvtColor(src_hsv, src_hsv, cv::COLOR_BGR2HSV);
cv::split(src_hsv, hsv_planes);
brightness = hsv_planes[2];
}
//to restore previous brightness we need its current mean
Scalar m;
if (restoreMean)
m = mean(brightness);
// REMOVE THE BACKGROUND
int size = minThickess / 2;
Point anchor = Point(size, size);
Mat element = getStructuringElement(MORPH_ELLIPSE, Size(2 * size + 1, 2 * size + 1), anchor);
if (background != NULL) // to keep background we need to use MORPH_OPEN
{
//get the background
cv::Mat bkg(brightness.size(), CV_8UC1);
morphologyEx(brightness, bkg, MORPH_OPEN, element, anchor);
//save the background
(*background) = bkg;
//remove the background
brightness = brightness - bkg;
}
else //tophat(I) <=> open(I) - I;
{
//remove background
morphologyEx(brightness, brightness, MORPH_TOPHAT, element, anchor);
}
// RESTORE PREVIOUS BRIGHTNESS MEAN
if (restoreMean)
brightness += m(0);
// BUILD THE DESTINATION
if (src.type() == CV_8UC1)
dst = brightness;
else if (src.type() == CV_8UC3)
{
merge(hsv_planes, dst);
cvtColor(dst, dst, COLOR_HSV2BGR);
}
// restore alpha channel from source
else if (src.type() == CV_8UC4)
{
cv::Mat bgr;
vector<cv::Mat> bgr_planes = { hsv_planes[0], hsv_planes[1], hsv_planes[2]};
merge(bgr_planes, bgr);
cvtColor(bgr, bgr, COLOR_HSV2BGR);
int from_toA[] = { 0, 0, 1, 1, 2, 2 };
src.copyTo(dst);
cv::mixChannels(&bgr, 1, &dst, 1, from_toA, 3);
}
imshow("NonUniformIlluminationMorph:SRC", src);
imshow("NonUniformIlluminationMorph:DST", dst);
if ((background != NULL) && (!background->empty()))
imshow("NonUniformIlluminationMorph:BKG", *background);
}
| [
"niraj.xr@gmail.com"
] | niraj.xr@gmail.com |
0c31957eb3707d1181773ceff1bf5db8603ca118 | cbd874f3f833565418642d73736d42b29e4dfcb7 | /solutions/max_kaskevich/6/sources/multicast_communication/common_message.cpp | 08b134b4dfdf1bad891a26fc9a742d00c161fcea | [] | no_license | sidorovis/cpp_craft_1013 | 4f5e67e6df30949d12d92549d1fd7eda62d98247 | 6805cfb7a059a45928c1ac6e086032df18a07524 | refs/heads/master | 2021-01-18T02:18:50.956921 | 2013-12-17T10:17:57 | 2013-12-17T10:17:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 508 | cpp | #include "common_message.h"
void multicast_communication::init_time_table()
{
const char begin_char = 48;
const char end_char = 107;
for( char c = begin_char; c <= end_char; ++c )
{
time_table[ c ] = c - begin_char;
}
}
uint32_t multicast_communication::get_seconds( const char data[3] )
{
std::call_once( time_table_init_flag, init_time_table );
return time_table[ data[ 0 ] ] * 3600 +
time_table[ data[ 1 ] ] * 60 +
time_table[ data[ 2 ] ];
}
| [
"jake@gogo.by"
] | jake@gogo.by |
0ff5686bae2ba178428172bb2b784d1cba21c668 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /components/power_bookmarks/storage/power_bookmark_sync_bridge.h | b8592f7e0ab579d342714aba53788f3d3bcb3574 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 4,761 | h | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_POWER_BOOKMARKS_STORAGE_POWER_BOOKMARK_SYNC_BRIDGE_H_
#define COMPONENTS_POWER_BOOKMARKS_STORAGE_POWER_BOOKMARK_SYNC_BRIDGE_H_
#include "base/uuid.h"
#include "components/sync/model/model_type_sync_bridge.h"
namespace syncer {
class ModelError;
} // namespace syncer
namespace power_bookmarks {
class Power;
class PowerBookmarkSyncMetadataDatabase;
// Transaction wraps a database transaction. When it's out of scope the
// underlying transaction will be cancelled if not committed.
// TODO(crbug.com/1392502): Find a better layout for this class.
class Transaction {
public:
virtual bool Commit() = 0;
virtual ~Transaction() = default;
};
// PowerBookmarkSyncBridge is responsible for syncing all powers to different
// devices. It runs on the same thread as the power bookmark database
// implementation.
class PowerBookmarkSyncBridge : public syncer::ModelTypeSyncBridge {
public:
// Delegate interface PowerBookmarkSyncBridge needs from the backend.
class Delegate {
public:
// Get all the powers from the database.
virtual std::vector<std::unique_ptr<Power>> GetAllPowers() = 0;
// Get powers for the given guids.
virtual std::vector<std::unique_ptr<Power>> GetPowersForGUIDs(
const std::vector<std::string>& guids) = 0;
// Get power for the given guid.
virtual std::unique_ptr<Power> GetPowerForGUID(const std::string& guid) = 0;
// Create a power if not exists or merge existing the power in the database.
virtual bool CreateOrMergePowerFromSync(const Power& power) = 0;
// Delete a power from the database.
virtual bool DeletePowerFromSync(const std::string& guid) = 0;
// Get the database to store power bookmarks metadata.
virtual PowerBookmarkSyncMetadataDatabase* GetSyncMetadataDatabase() = 0;
// Start a transaction. This is used to make sure power bookmark data
// and metadata are stored atomically.
virtual std::unique_ptr<Transaction> BeginTransaction() = 0;
// Notify the backend if powers are changed.
virtual void NotifyPowersChanged() {}
};
PowerBookmarkSyncBridge(
PowerBookmarkSyncMetadataDatabase* meta_db,
Delegate* delegate,
std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor);
PowerBookmarkSyncBridge(const PowerBookmarkSyncBridge&) = delete;
PowerBookmarkSyncBridge& operator=(const PowerBookmarkSyncBridge&) = delete;
~PowerBookmarkSyncBridge() override;
void Init();
// syncer::ModelTypeSyncBridge:
std::unique_ptr<syncer::MetadataChangeList> CreateMetadataChangeList()
override;
absl::optional<syncer::ModelError> MergeFullSyncData(
std::unique_ptr<syncer::MetadataChangeList> metadata_change_list,
syncer::EntityChangeList entity_changes) override;
absl::optional<syncer::ModelError> ApplyIncrementalSyncChanges(
std::unique_ptr<syncer::MetadataChangeList> metadata_change_list,
syncer::EntityChangeList entity_changes) override;
std::string GetStorageKey(const syncer::EntityData& entity_data) override;
std::string GetClientTag(const syncer::EntityData& entity_data) override;
void GetData(StorageKeyList storage_keys, DataCallback callback) override;
void GetAllDataForDebugging(DataCallback callback) override;
void SendPowerToSync(const Power& power);
void NotifySyncForDeletion(const std::string& guid);
void ReportError(const syncer::ModelError& error);
bool initialized() { return initialized_; }
private:
// Create a change list to store metadata inside the power bookmark database.
// This method should be called inside a transaction because Chrome sync
// requires saving data and metadata atomically. Also need to transfer the
// meta_data_change_list from the InMemoryMetadataChangeList created by
// CreateMetadataChangeList() within the transaction created in
// MergeFullSyncData() and ApplyIncrementalSyncChanges().
std::unique_ptr<syncer::MetadataChangeList>
CreateMetadataChangeListInTransaction();
// Helper function called by both `MergeFullSyncData` with
// is_initial_merge=true and `ApplyIncrementalSyncChanges` with
// is_initial_merge=false.
absl::optional<syncer::ModelError> ApplyChanges(
std::unique_ptr<syncer::MetadataChangeList> metadata_change_list,
syncer::EntityChangeList& entity_changes,
bool is_initial_merge);
const raw_ptr<PowerBookmarkSyncMetadataDatabase, DanglingUntriaged> meta_db_;
const raw_ptr<Delegate> delegate_;
bool initialized_ = false;
};
} // namespace power_bookmarks
#endif // COMPONENTS_POWER_BOOKMARKS_STORAGE_POWER_BOOKMARK_SYNC_BRIDGE_H_
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
26d3f13b270cf05ccbc6305942dab88051e50e97 | c6a28bb00984466a0c885e2f393adedee20b0bbc | /cmd/protoc/cpp_enum_field.cc | cb8d662a09a63a6e9619e88d7cedcc6adada0a37 | [] | no_license | seanpm2001/CockroachDB_C-ProtoBuf | 8419bb640384eda678fb11511a87c7e1c0f20ecd | 323984796a7b4794ee62a00e12456743a5b66765 | refs/heads/master | 2023-06-23T06:51:26.930756 | 2017-02-22T19:23:55 | 2017-02-22T19:23:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 65 | cc | ../../internal/src/google/protobuf/compiler/cpp/cpp_enum_field.cc | [
"tamird@gmail.com"
] | tamird@gmail.com |
f4baf7f9d2da2381bc257d630d2a0c8c32fd970f | 6915092ec690d21c301a59d9caee3a2b55ca8d15 | /C++/211-Add_and_Search_Word-Data_structure_design.cpp | 0b3497d93c8c98515a52414a3d801cc2ad19356b | [] | no_license | haoping07/Leetcode-notes | 194cc3c03b4deed3d0cd11550f169ada8abaf0f2 | 5562f39a1fb1b1dd48a1623083ef25999fb266a5 | refs/heads/master | 2020-08-04T16:05:57.688375 | 2020-07-20T10:21:33 | 2020-07-20T10:21:33 | 212,183,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,783 | cpp | /*
211. Add and Search Word - Data structure design (M)
Notes:
Ref. 211
Beware the edge case.
*/
class TrieNode
{
public:
bool isEnd;
TrieNode* children[26];
TrieNode() : isEnd(false)
{
for (int i = 0; i < 26; i++)
children[i] = nullptr;
}
};
class WordDictionary {
private:
TrieNode* head;
public:
/** Initialize your data structure here. */
WordDictionary() {
head = new TrieNode();
}
/** Adds a word into the data structure. */
void addWord(string word) {
TrieNode* cur = head;
for (int i = 0; i < word.size(); i++)
{
int index = word[i] - 'a';
if (!cur->children[index])
cur->children[index] = new TrieNode();
cur = cur->children[index];
}
cur->isEnd = true;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
if (!head) return false;
int length = word.size();
return search(word, length, 0, head);
}
bool search(string& word, int length, int pos, TrieNode* cur)
{
if (pos == length)
return cur->isEnd;
if (word[pos] == '.')
{
for (int i = 0; i < 26; i++)
{
if (cur->children[i])
{
if (search(word, length, pos + 1, cur->children[i]))
return true;
}
}
}
else
{
int index = word[pos] - 'a';
if (cur->children[index])
return search(word, length, pos + 1, cur->children[index]);
}
return false;
}
}; | [
"pinglin927@gmail.com"
] | pinglin927@gmail.com |
260adc40f5cabe3e2a52f0bc1820794d7f10897c | f529d03f30c39c8a82cff5320863094bef74732b | /inttoromanV1.cpp | b42533eae1fdfe6f2229999540daadb7a7f3f52b | [] | no_license | ashutosh28/DS_ALGO | c99971414bdd39963f123c8b7a0ee9bff21d98c4 | 370a211dcc5d3ff1921adb571b9c622613a10608 | refs/heads/master | 2021-01-19T00:38:42.982581 | 2017-04-04T14:48:26 | 2017-04-04T14:48:26 | 87,192,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,671 | cpp | #include "array.h"
#include<stdio.h>
#include<stdlib.h>
int main() {
int N;
cin>>N;
int X=N;
int i,j=0;
char *ROMAN = (char*) malloc(16*sizeof(char));
if(X>4000) return 0;
if(X<1) return 0;
if(X>=1000) {
int m = X/1000;
for(i=0;i<m;++i) {
ROMAN[j++]='M';
}
X = X % 1000;
}
if(X>=900) {
ROMAN[j++]='C';ROMAN[j++]='M';
X = X % 900;
}else if (X >= 500) {
int d = X/500;
for(i=0;i<d;++i) {
ROMAN[j++] = 'D';
}
X = X % 500;
}
if(X>=400) {
ROMAN[j++]='C';ROMAN[j++]='D';
X = X % 400;
}else if (X >= 100) {
int c = X/100;
for(i=0;i<c;++i) {
ROMAN[j++] = 'C';
}
X = X % 100;
}
if(X>=90) {
ROMAN[j++]='X';ROMAN[j++]='C';
X = X % 90;
}else if (X>=50) {
int e = X/50;
for(i=0;i<e;++i) {
ROMAN[j++]='L';
}
X = X % 50;
}
if(X>=40) {
ROMAN[j++]='X';ROMAN[j++]='L';
X = X % 40;
}else if (X>=10) {
int f = X/10;
for(i=0;i<f;i++) {
ROMAN[j++]='X';
}
X = X % 10;
}
if(X>=9) {
ROMAN[j++]='I';ROMAN[j++]='X';
X = X % 9;
}else if (X>=5) {
int g = X/5;
for(i=0;i<g;++i) {
ROMAN[j++]='V';
}
X = X % 5;
}
if(X>=4) {
ROMAN[j++]='I';ROMAN[j++]='V';
X = X % 4;
}else if (X>=1) {
int h = X/1;
for(i=0;i<h;++i) {
ROMAN[j++] = 'I';
}
}
cout<<" ROMAN NUMBER : "<<ROMAN<<endl;
return 0;
}
| [
"ashu.godara@gmail.com"
] | ashu.godara@gmail.com |
c454492476310829a310aeb7074653321fd074c2 | 6b6f5c7685bcfd8fee716797248d9dcd69f59cbb | /QHĐ - Dãy con tăng dài nhất (Chỉ có bản khó)/DPBABYL2.cpp | 2fba455b2d793578cafe2c711d810fb31b386a0b | [] | no_license | Tuanngoc2302/Vinhdinh-Coder | 8603b6df0bef9c4814cbe8b5f6a2cc3b49c0286a | 99b9afb90af2e167f8e2984d467785b13cfd1eac | refs/heads/master | 2023-06-02T23:43:01.613363 | 2021-06-22T14:29:56 | 2021-06-22T14:29:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,136 | cpp | #include <iostream>
#include <algorithm>
#include <set>
#define llong long long
using namespace std;
struct Data {
int a[4];
bool operator < (const Data &other) const {
return a[1] < other.a[1] || (a[1] == other.a[1] && a[2] > other.a[2]);
}
} P[100006];
set<int> S;
int cnt = 0, n, m;
int c[300006];
llong bit[300006];
void compress() {
cnt = 0;
for(set<int>::iterator i = S.begin(); i != S.end(); ++i) c[++cnt] = *i;
for(int i=1; i<=m; ++i) {
int j = lower_bound(c+1, c+cnt+1, P[i].a[2]) - c;
P[i].a[2] = j;
}
}
template<typename T>
bool fast_scan(T &num) {
num = 0;
register char c = getchar();
while (c != '-' && (c < '0' || '9' < c)) {
if (feof(stdin)) return false;
c = getchar();
}
bool neg = false;
if (c == '-') {
neg = true;
c = getchar();
}
for(; '0' <= c && c <= '9'; c = getchar()) num = (num << 1) + (num << 3) + (c - '0');
if (neg) num = -num;
return true;
}
void init(Data p) {
P[++m].a[1] = p.a[1];
P[m].a[2] = p.a[3];
P[m].a[3] = p.a[2];
P[++m].a[1] = p.a[2];
P[m].a[2] = p.a[3];
P[m].a[3] = p.a[1];
S.insert(p.a[2]); S.insert(p.a[3]);
}
void maximize(llong &A, llong B) {
if (B > A) A = B;
}
void update(int p, llong val) {
for(; p <= cnt; p += (p & (-p))) maximize(bit[p], val);
}
llong query(int p) {
llong ans = 0;
for(; p>0; p-=(p & (-p))) maximize(ans, bit[p]);
return ans;
}
void process() {
compress();
sort(P+1, P+m+1);
llong res = 0;
for(int i=1; i <= cnt; ++i) bit[i] = 0;
for(int i=1; i<=m; ++i) {
llong u = query(P[i].a[2] - 1) + P[i].a[3];
res = max(res, u);
update(P[i].a[2], u);
}
cout << res;
putchar('\n');
}
int main() {
while (fast_scan(n)) {
if (n == 0) break;
m = 0; S.clear();
for(int i=1; i<=n; ++i) {
fast_scan(P[++m].a[1]);
fast_scan(P[m].a[2]);
fast_scan(P[m].a[3]);
sort(P[m].a+1, P[m].a+4);
init(P[m]);
}
process();
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
fc60c9ceb1cf21f5a96a66344834466c40c4b727 | 8f601014e647f42d898545f3b9d5ca4c33b30199 | /interface/CmsPFPreIdFiller.h | fbab71caa6fec91f6b050ba312b82c6a08a43094 | [] | no_license | vecbos/HiggsAnalysis-HiggsToWW2e | 989ff20bd9ccc1172d4a2288b7149fb8a56b576d | 8f5ffd010c9cfd58961663028967e7b31dfdb13a | refs/heads/master | 2020-05-30T22:53:12.558949 | 2013-06-15T15:04:58 | 2013-06-15T15:04:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,234 | h | // -*- C++ -*-
//-----------------------------------------------------------------------
//
// Package:
// HiggsAnalysis/HiggsToWW2e
// Description:
// Class CmsPFPreIdFiller
// Simple class for dumping RECO (or AOD) contents to a ROOT tree
//
//-----------------------------------------------------------------------
#ifndef CmsPFPreIdFiller_h
#define CmsPFPreIdFiller_h
#include "FWCore/Framework/interface/Event.h"
#include "DataFormats/Common/interface/Handle.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "HiggsAnalysis/HiggsToWW2e/interface/CmsTree.h"
#include <TTree.h>
struct CmsPFPreIdFillerData {
int *ncand;
std::vector<int> *trackIndex;
std::vector<float> *deltaEtaMatch, *deltaPhiMatch;
std::vector<float> *chiEtaMatch, *chiPhiMatch, *chi2Match;
std::vector<float> *eopMatch;
std::vector<float> *kfChi2, *kfNHits;
std::vector<float> *gsfChi2, *chi2Ratio;
std::vector<bool> *ecalMatching, *psMatching;
std::vector<bool> *trackFiltered, *preided;
public:
void initialise();
void clearTrkVectors();
};
class CmsPFPreIdFiller {
public:
// Constructors
// Dump everything
CmsPFPreIdFiller(CmsTree *,
int maxTracks=500, int maxMCTracks=2000,
bool noOutputIfLimitsReached=false );
// Dump everything if fatTree is true and less informations otherwise
CmsPFPreIdFiller(CmsTree *,
bool fatTree,
int maxTracks=500, int maxMCTracks=2000,
bool noOutputIfLimitsReached=false );
// Destructor
virtual ~CmsPFPreIdFiller();
// Operators
// run number and all of that --- to implement
void writeCollectionToTree(edm::InputTag collectionTag1, edm::InputTag collectionTag2,
const edm::Event&, const edm::EventSetup&,
const std::string &columnPrefix, const std::string &columnSuffix,
bool dumpData=false);
private:
void treePFPreIdInfo(const std::string &colPrefix, const std::string &colSuffix);
// Friends
bool hitLimitsMeansNoOutput_;
int maxTracks_;
int maxMCTracks_;
std::string *trkIndexName_;
CmsPFPreIdFillerData *privateData_;
CmsTree *cmstree;
};
#endif // CmsPFPreIdFiller_h
| [
""
] | |
c153b4d1c18a11a4bab38fd18e5951da48ac7f91 | b7f1b4df5d350e0edf55521172091c81f02f639e | /chrome/browser/profiling_host/profiling_test_driver.h | 88478e699a93bd1830eac35f3ddc8b8ab448067d | [
"BSD-3-Clause"
] | permissive | blusno1/chromium-1 | f13b84547474da4d2702341228167328d8cd3083 | 9dd22fe142b48f14765a36f69344ed4dbc289eb3 | refs/heads/master | 2023-05-17T23:50:16.605396 | 2018-01-12T19:39:49 | 2018-01-12T19:39:49 | 117,339,342 | 4 | 2 | NOASSERTION | 2020-07-17T07:35:37 | 2018-01-13T11:48:57 | null | UTF-8 | C++ | false | false | 4,773 | 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 CHROME_BROWSER_PROFILING_HOST_PROFILING_TEST_DRIVER_H_
#define CHROME_BROWSER_PROFILING_HOST_PROFILING_TEST_DRIVER_H_
#include <vector>
#include "base/allocator/partition_allocator/partition_alloc.h"
#include "base/macros.h"
#include "base/memory/ref_counted_memory.h"
#include "base/synchronization/waitable_event.h"
#include "chrome/browser/profiling_host/profiling_process_host.h"
namespace base {
class Value;
} // namespace base
namespace profiling {
// This class runs tests for the profiling service, a cross-platform,
// multi-process component. Chrome on Android does not support browser_tests. It
// does support content_browsertests, but those are not multi-process tests. On
// Android, processes have to be started via the Activity mechanism, and the
// test infrastructure does not support this.
//
// To avoid test-code duplication, all tests are pulled into this class.
// browser_tests will directly call this class. The android
// chrome_public_test_apk will invoke this class via a JNI shim. Since the
// latter is not running within the gtest framework, this class cannot use
// EXPECT* and ASSERT* macros. Instead, this class will return a bool indicating
// success of the entire test. On failure, errors will be output via LOG(ERROR).
// These will show up in the browser_tests output stream, and will be captured
// by logcat [the Android logging facility]. The latter is already the canonical
// mechanism for investigating test failures.
//
// Note: Outputting to stderr will not have the desired effect, since that is
// not captured by logcat.
class ProfilingTestDriver {
public:
struct Options {
// The profiling mode to test.
ProfilingProcessHost::Mode mode;
// The stack profiling mode to test.
profiling::mojom::StackMode stack_mode;
// Whether the caller has already started profiling with the given mode.
// TODO(erikchen): Implement and test the case where this member is false.
// Starting profiling is an asynchronous operation, so this requires adding
// some more plumbing. https://crbug.com/753218.
bool profiling_already_started;
};
ProfilingTestDriver();
~ProfilingTestDriver();
// If this is called on the content::BrowserThread::UI thread, then the
// platform must support nested message loops. [This is currently not
// supported on Android].
//
// Returns whether the test run was successful. Expectation/Assertion failures
// will be printed via LOG(ERROR).
bool RunTest(const Options& options);
private:
// Populates |initialization_success_| with the result of
// |RunInitializationOnUIThread|, and then signals |wait_for_ui_thread_|.
void CheckOrStartProfilingOnUIThreadAndSignal();
// If profiling is expected to already be started, confirm it.
// Otherwise, start profiling with the given mode.
bool CheckOrStartProfiling();
// Performs allocations. These are expected to be profiled.
void MakeTestAllocations();
// Collects a trace that contains a heap dump. The result is stored in
// |serialized_trace_|.
//
// When |synchronous| is true, this method spins a nested message loop. When
// |synchronous| is false, this method posts some tasks that will eventually
// signal |wait_for_ui_thread_|.
void CollectResults(bool synchronous);
void TraceFinished(base::Closure closure,
bool success,
std::string trace_json);
bool ValidateBrowserAllocations(base::Value* dump_json);
bool ValidateRendererAllocations(base::Value* dump_json);
bool ShouldProfileBrowser();
bool HasPseudoFrames();
Options options_;
// Allocations made by this class. Intentionally leaked, since deallocating
// them would trigger a large number of IPCs, which is slow.
std::vector<char*> leaks_;
// Sum of size of all variadic allocations.
size_t total_variadic_allocations_ = 0;
// Use to make PA allocations, which should also be shimmed.
base::PartitionAllocatorGeneric partition_allocator_;
// Contains nothing until |CollectResults| has been called.
std::string serialized_trace_;
// Whether the test was invoked on the ui thread.
bool running_on_ui_thread_ = true;
// Whether an error has occurred.
bool initialization_success_ = false;
// When |true|, initialization will wait for the allocator shim to enable
// before continuing.
bool wait_for_profiling_to_start_ = false;
base::WaitableEvent wait_for_ui_thread_;
DISALLOW_COPY_AND_ASSIGN(ProfilingTestDriver);
};
} // namespace profiling
#endif // CHROME_BROWSER_PROFILING_HOST_PROFILING_TEST_DRIVER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
c266c37fe0ebe8c6f5039b9491c81f61f14458f2 | fcfcadcaa2fa0e2e81029ba8dd7e24b236cace02 | /source/core/platform/file_system/Path_Common.cpp | 0f2e1776c66cbbfaf69895882ae4eb0b61bc3c13 | [
"MIT"
] | permissive | varunamachi/vq | bc75f80ed1b7937763ce65851d7ef3dcc7726a64 | 17c9d316fa734532b9892110b5b105b6d37f3f27 | refs/heads/master | 2020-04-06T06:54:03.417301 | 2017-08-03T12:50:50 | 2017-08-03T12:50:50 | 65,648,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,323 | cpp |
#include <memory>
#include "../../common/STLUtils.h"
#include "../../common/StringUtils.h"
#include "../../logger/Logging.h"
#include "../../common/Result.h"
#include "Path.h"
namespace Vq {
class Path::Data
{
public:
Data( const Path *container )
: m_components()
, m_absolute( false )
, m_str( "" )
, m_container( container )
{
}
Data( const Path *container,
const std::vector< std::string > &components,
bool absolute )
: m_components( components )
, m_absolute( absolute )
, m_str( "" )
, m_container( container )
{
}
Data( const Path *container,
const std::vector< std::string > &&components,
bool absolute )
: m_components( components )
, m_absolute( absolute )
, m_str( "" )
, m_container( container )
{
}
Data( Data &&other )
: m_components( std::move( other.m_components ))
, m_absolute( other.m_absolute )
, m_str( std::move( other.m_str ))
, m_container( other.m_container )
{
// other.m_components.clear();
// other.m_str = "";
}
Data( const Data &other )
: m_components( other.m_components )
, m_absolute( other.m_absolute )
, m_str( other.m_str )
, m_container( other.m_container )
{
}
Data & operator = ( const Data & other )
{
m_components = other.m_components;
m_absolute = other.m_absolute;
return *this;
}
Data & operator = ( Data &&other )
{
m_components = std::move( other.m_components );
m_absolute = other.m_absolute;
other.m_components.clear();
return *this;
}
bool isAbsolute() const
{
return m_absolute;
}
const std::vector< std::string > & components() const
{
return m_components;
}
std::vector< std::string > & components()
{
return m_components;
m_str = m_container->collapse();
}
void assign( std::vector< std::string > &&comp, bool isAbs )
{
m_components = comp;
m_absolute = isAbs;
m_str = m_container->collapse();
}
const std::string & toString() const
{
return m_str;
}
// std::string toString()
// {
// return m_str;
// }
private:
std::vector< std::string > m_components;
bool m_absolute;
std::string m_str;
const Path *m_container;
};
Path::Path()
: m_data( std::make_unique< Data >( this ) )
{
}
Path::Path( const std::vector< std::string > &components, bool absolute )
: m_data( std::make_unique< Path::Data >( this, components, absolute ))
{
}
Path::Path( const std::vector< std::string > &&components, bool absolute )
: m_data( std::make_unique< Path::Data >( this, components, absolute ))
{
}
Path::Path( const Path &other )
: m_data( std::make_unique< Path::Data >( *other.m_data ))
{
}
Path::Path( Path &&other )
: m_data( std::make_unique< Path::Data >( std::move( *other.m_data )))
{
}
Path::~Path()
{
}
Path & Path::operator = ( const Path &other )
{
( * this->m_data ) = ( *other.m_data );
return *this;
}
Path & Path::operator = ( Path &&other )
{
( *this->m_data ) = ( *other.m_data );
return *this;
}
bool Path::operator == ( const Path &other ) const
{
bool result = this->m_data->components() == other.m_data->components();
return result;
}
bool Path::operator ==( const std::string &strPath ) const
{
bool result = ( toString() == strPath );
return result;
}
bool Path::operator != ( const Path &other ) const
{
return ! ( ( *this ) == other );
}
bool Path::operator != ( const std::string strPath ) const
{
return ! ( ( *this ) == strPath );
}
std::string Path::fileName() const
{
std::string name{ "" };
if( isValid() ) {
auto it = m_data->components().end();
name = * ( --it );
}
return name;
}
std::string Path::extension() const
{
auto name = fileName();
auto pos = name.find_last_of( "." );
if( pos != std::string::npos ) {
auto ext = name.substr( pos, name.size() - pos );
return ext;
}
return "";
}
std::string Path::baseName() const
{
auto name = fileName();
auto pos = name.find_last_of( "." );
if( pos != std::string::npos ) {
auto baseName = name.substr( 0, pos );
return baseName;
}
return name;
}
bool Path::isAbsolute() const
{
return m_data->isAbsolute();
}
const std::vector< std::string > & Path::components() const
{
return m_data->components();
}
const std::vector<std::string> &Path::components()
{
return m_data->components();
}
Path & Path::append( const std::string &relative )
{
if( relative.empty() ) {
return *this;
}
auto result = parse( relative );
if( result.value() ) {
for( auto &cmp : result.data() ) {
m_data->components().emplace_back( std::move( cmp ));
}
}
else {
VQ_ERROR( "Vq:Core:FS" ) << "Failed to append path " << relative
<< ", could not parse the given path";
}
return *this;
}
Path & Path::append( const Path &relative )
{
for( const auto &cmp : relative.components() ) {
m_data->components().push_back( cmp );
}
return *this;
}
Path Path::appended( const Path &other ) const
{
std::vector< std::string > comps{ this->components() };
for( const auto &comp : other.components() ) {
comps.push_back( comp );
}
return Path{ comps, this->isAbsolute() };
}
Result< Path > Path::pathOfChild( const std::string &relative ) const
{
auto compRes = parse( relative );
auto result = R::success< Path >( Path{} );
if( compRes.value() ) {
auto newComps = this->components();
for( auto &cmp : compRes.data() ) {
newComps.emplace_back( std::move( cmp ));
}
result = R::success< Path >( Path{ newComps, this->isAbsolute() });
}
else {
auto error = R::stream< Path >( Path{} )
<< "Given relative path " << relative << "is invalid "
<< R::fail;
VQ_ERROR( "Vq:Core:FS" ) << error;
}
return result;
}
Path Path::parent() const
{
std::vector< std::string > pcomps;
auto &comps = m_data->components();
if( comps.size() > 2 ) {
std::copy( m_data->components().begin(),
m_data->components().end() - 2,
pcomps.begin() );
}
return Path{ pcomps, isAbsolute() };
}
std::vector< std::string > & Path::mutableComponents()
{
return m_data->components();
}
void Path::assign( std::vector< std::string > && comp, bool isAbs )
{
m_data->assign( std::move( comp ), isAbs );
}
Result< Path > Path::mergeWith( const Path &other )
{
using CmpVec = std::vector< std::string >;
auto matchMove = []( CmpVec main, CmpVec other ) -> CmpVec::iterator
{
auto matchStarted = false;
auto mit = std::begin( main );
auto oit = std::begin( other );
for( ; mit != std::end( main ); ++ mit ) {
if( *mit == *oit ) {
++ oit;
matchStarted = true;
}
else if( matchStarted && *mit != *oit ) {
oit = std::begin( other );
matchStarted = false;
}
}
return oit;
};
auto res = R::success< Path >( *this );
if( this->isAbsolute() && other.isAbsolute() ) {
auto &main = STLUtils::largestOf( components(), other.components() );
auto &slv = STLUtils::smallestOf( components(), other.components() );
auto mit = std::begin( main );
for( auto sit = std::begin( slv ); sit != std::end( slv ); ++ sit ) {
if( *sit != *mit ) {
res = R::stream< Path >( *this )
<< "Failed to merge path, size given paths are absolute"
"and are different withing the merge range"
<< R::fail;
VQ_ERROR( "Vq:Core:FS" ) << res;
break;
}
++ mit;
}
if( res.value() && ( &main == &( other.components() ))) {
for( ; mit != std::end( main ); ++ mit ) {
this->mutableComponents().push_back( *mit );
}
}
}
else if( other.isAbsolute() ) {
auto comps = other.components();
auto oit = matchMove( comps, this->components() );
for( ; oit != std::end( this->components()); ++ oit ) {
comps.push_back( *oit );
}
this->assign( std::move( comps ), true );
}
else {
//If 'this' is absolute or both are relative 'this''s component is
//taken as main
auto oit = matchMove( this->components(), other.components() );
for( ; oit != std::end( other.components()); ++ oit ) {
this->mutableComponents().push_back( *oit );
}
}
return res;
}
Result< Path > Path::relativeTo( const Path & other ) const
{
if( ! ( this->isAbsolute() && other.isAbsolute() )) {
auto result = R::stream( Path{ std::vector< std::string >{}, false })
<< "Both path should be absolute inorder to create relative "
"path" << R::fail;
VQ_ERROR( "Vq:Core:FS" ) << result;
return result;
}
std::vector< std::string > relComps;
auto sit = std::begin( other.components() );
auto oit = std::end( this->components() );
bool mismatched = false;
for( ; sit != std::end( other.components() ); ++ sit ) {
if( ! mismatched
&& ( *sit == *oit )
&& oit != std::end( components() )) {
++ oit;
}
else {
mismatched = true;
relComps.emplace_back( ".." );
}
}
for( ; oit != std::end( components() ); ++ oit ) {
relComps.push_back( *oit );
}
return R::success( Path{ relComps, false });
}
const std::string & Path::toString() const
{
return m_data->toString();
}
std::ostream & operator<<( std::ostream &stream, const Path &path )
{
stream << path.toString();
return stream;
}
}
| [
"varunamachi@gmail.com"
] | varunamachi@gmail.com |
449dd14c057b63e86644cef0de01d4a91a657a40 | 47cb4a8a7592d2df3d7b4ddb2d8db7f155523bac | /libel/base/logging.h | 20c98a7ff49b2bcdfb7ab42cd2ac716d39f88551 | [] | no_license | irvingow/libel | 05d7d167d92688edc46a519576d63e8b88a994fe | 967122566b1b1fd79f86f9ca7149c217c6782996 | refs/heads/main | 2023-02-27T16:19:16.027148 | 2021-01-21T11:06:06 | 2021-01-21T11:06:06 | 321,997,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,521 | h | //
// Created by 刘文景 on 2020-03-26.
//
#ifndef Libel_LOGGING_H
#define Libel_LOGGING_H
#include "logstream.h"
#include "noncopyable.h"
namespace Libel {
extern int64_t MicroSecondsPerSecond;
class Logger {
public:
enum LogLevel {
TRACE,
DEBUG,
INFO,
WARN,
ERROR,
FATAL,
NUM_LOG_LEVELS,
};
/// we use this class to get compile time calculation of length of c++
/// predefine macro such as __func__ and __FILE__
class PreDefineMacroHelper {
public:
template <int N>
PreDefineMacroHelper(const char (&arr)[N]) : data_(arr), size_(N - 1) {
const char* slash = strrchr(
data_,
'/'); /// find the last '/' in filename to avoid too long pathname
if (slash) {
data_ = slash + 1;
size_ -= (data_ - arr);
}
}
// explicit PreDefineMacroHelper(const char *name) : data_(name) {
// size_ = strlen(data_);
// }
const char* data_;
size_t size_;
};
// Logger(PreDefineMacroHelper fileName, PreDefineMacroHelper functionName,
// int line, LogLevel level);
// Logger(PreDefineMacroHelper fileName, PreDefineMacroHelper functionName,
// int line, bool toAbort);
Logger(PreDefineMacroHelper fileName, const char* functionName, int line, LogLevel level);
~Logger();
LogStream& stream() { return insideHelper_.logStream_; }
static LogLevel getLogLevel();
static void setLogLevel(LogLevel level);
typedef void (*OutputFunc)(const char* msg, size_t len);
typedef void (*FlushFunc)();
static void setOutput(OutputFunc);
static void setFlush(FlushFunc);
private:
class InsideHelper {
public:
typedef Logger::LogLevel LogLevel;
// InsideHelper(PreDefineMacroHelper fileName,
// PreDefineMacroHelper functionName, int line, LogLevel level,
// int);
InsideHelper(PreDefineMacroHelper fileName, const char* functionName, int line, LogLevel level, int );
void formatTime();
void finish();
LogStream logStream_;
// PreDefineMacroHelper fileName_;
// PreDefineMacroHelper functionName_;
PreDefineMacroHelper fileName_;
const char* functionName_;
int line_;
LogLevel level_;
int64_t curtime_;
};
InsideHelper insideHelper_;
};
extern Logger::LogLevel AlogLevel;
inline Logger::LogLevel Logger::getLogLevel() { return AlogLevel; }
inline void Logger::setLogLevel(Libel::Logger::LogLevel level) {
AlogLevel = level;
}
///当输出日志的级别高于日志的级别时,LOG_XXX相当于是空的,没有运行时开销
#define LOG_TRACE \
if (Libel::Logger::getLogLevel() <= Libel::Logger::TRACE) \
Libel::Logger(__FILE__, __func__, __LINE__, Libel::Logger::TRACE).stream()
#define LOG_DEBUG \
if (Libel::Logger::getLogLevel() <= Libel::Logger::DEBUG) \
Libel::Logger(__FILE__, __func__, __LINE__, Libel::Logger::DEBUG).stream()
#define LOG_INFO \
if (Libel::Logger::getLogLevel() <= Libel::Logger::INFO) \
Libel::Logger(__FILE__, __func__, __LINE__, Libel::Logger::INFO).stream()
#define LOG_WARN \
Libel::Logger(__FILE__, __func__, __LINE__, Libel::Logger::WARN).stream()
#define LOG_ERROR \
Libel::Logger(__FILE__, __func__, __LINE__, Libel::Logger::ERROR).stream()
#define LOG_FATAL \
Libel::Logger(__FILE__, __func__, __LINE__, Libel::Logger::FATAL).stream()
} // namespace Libel
#endif // Libel_LOGGING_H
| [
"lwj102153@gmail.com"
] | lwj102153@gmail.com |
7ce7fb345fc46bc08f6b0dfd53abc930608ce2ff | 62050393a7c7ecbfe158436fcb7a21de7aa67e16 | /MCFBuild/General.hpp | d9336bb70c6fd2ec3c898886594f934ffb84d172 | [] | no_license | sunmike2002/MCF | 25f7a7f5afc696df06bb40644b87a9203e1a080a | 4291e21a31e502e1eca31f2a8aadd1c0e404b2b4 | refs/heads/master | 2020-05-29T11:51:07.905222 | 2014-01-28T13:14:48 | 2014-01-28T13:14:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,498 | hpp | // Copyleft 2013, LH_Mouse. All wrongs reserved.
#ifndef __GENERAL_HPP__
#define __GENERAL_HPP__
#ifndef NDEBUG
# define _GLIBCXX_DEBUG 1
#endif
#define WIN32_LEAN_AND_MEAN
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
// F*ck std::basic_string, f*ck copy-on-write.
#include <ext/vstring.h>
#include <cstddef>
#include <cwchar>
#include <cwctype>
#include <utility>
#include <string>
#include <set>
#include <map>
#include <list>
#include <type_traits>
#include <windows.h>
#include "countof.hpp"
namespace MCFBuild {
typedef ::__gnu_cxx::__versa_string<char> vstring;
typedef ::__gnu_cxx::__versa_string<wchar_t> wvstring;
extern int Print(const wchar_t *s, std::size_t len = (std::size_t)-1, bool to_stderr = false);
extern int VPrint(const wchar_t *fmt, bool to_stderr = false, ...);
extern int PrintCR(const wchar_t *s, std::size_t len = (std::size_t)-1);
extern int VPrintCR(const wchar_t *fmt, ...);
CRITICAL_SECTION &GetPrintLock();
template<typename... T>
static inline int Output(const wchar_t *fmt, T... args){
return VPrint(fmt, false, args...);
}
static inline int Output(const wvstring &wcs){
return Print(wcs.c_str(), wcs.size(), false);
}
static inline int Output(const wchar_t *s){
return Print(s, -1, false);
}
static inline int Output(){
return Output(L"");
}
template<typename... T>
static inline int Error(const wchar_t *fmt, T... args){
return VPrint(fmt, true, args...);
}
static inline int Error(const wvstring &wcs){
return Print(wcs.c_str(), wcs.size(), true);
}
static inline int Error(const wchar_t *s){
return Print(s, -1, true);
}
static inline int Error(){
return Error(L"");
}
template<typename... T>
static inline int Status(const wchar_t *fmt, T... args){
return VPrintCR(fmt, args...);
}
static inline int Status(const wvstring &wcs){
return PrintCR(wcs.c_str(), wcs.size());
}
static inline int Status(const wchar_t *s){
return PrintCR(s, -1);
}
static inline int Status(){
return Status(L"");
}
struct Exception {
unsigned long ulCode;
wvstring wcsDescription;
};
extern vstring WcsToU8s(const wvstring &src);
extern wvstring U8sToWcs(const vstring &src);
extern wvstring U8sToWcs(const std::string &src);
struct CriticalSection : public CRITICAL_SECTION {
CriticalSection(){
::InitializeCriticalSectionAndSpinCount(this, 0x400);
}
~CriticalSection(){
::DeleteCriticalSection(this);
}
CriticalSection(const CriticalSection &) = delete;
void operator=(const CriticalSection &) = delete;
};
class CriticalSectionHelper {
private:
PCRITICAL_SECTION m_pCriticalSection;
public:
CriticalSectionHelper(PCRITICAL_SECTION pCriticalSection){
m_pCriticalSection = pCriticalSection;
::EnterCriticalSection(m_pCriticalSection);
}
CriticalSectionHelper(const CriticalSectionHelper &rhs){
m_pCriticalSection = rhs.m_pCriticalSection;
::EnterCriticalSection(m_pCriticalSection);
}
CriticalSectionHelper(CriticalSectionHelper &&rhs){
m_pCriticalSection = rhs.m_pCriticalSection;
rhs.m_pCriticalSection = nullptr;
}
CriticalSectionHelper &operator=(const CriticalSectionHelper &rhs){
this->~CriticalSectionHelper();
return *new(this) CriticalSectionHelper(rhs);
}
CriticalSectionHelper &operator=(CriticalSectionHelper &&rhs){
this->~CriticalSectionHelper();
return *new(this) CriticalSectionHelper(std::move(rhs));
}
~CriticalSectionHelper(){
if(m_pCriticalSection != nullptr){
::LeaveCriticalSection(m_pCriticalSection);
}
}
};
#define LOCK_THROUGH(cs) const ::MCFBuild::CriticalSectionHelper __LOCK__(&cs)
struct WcsComparerNoCase {
bool operator()(const wvstring &lhs, const wvstring &rhs) const {
auto iter1 = lhs.cbegin();
auto iter2 = rhs.cbegin();
for(;;){
const auto ch1 = (std::make_unsigned<wchar_t>::type)std::towupper(*iter1);
++iter1;
const auto ch2 = (std::make_unsigned<wchar_t>::type)std::towupper(*iter2);
++iter2;
if(ch1 != ch2){
return ch1 < ch2;
}
if(ch1 == 0){
return false;
}
}
}
};
struct PROJECT {
struct PRECOMPILED_HEADER {
wvstring wcsSourceFile;
wvstring wcsCommandLine;
};
struct COMPILER {
wvstring wcsCommandLine;
wvstring wcsDependency;
};
struct LINKERS {
wvstring wcsPartial;
wvstring wcsFull;
};
long long llProjectFileTimestamp;
std::set<wvstring, WcsComparerNoCase> setIgnoredFiles;
std::map<wvstring, PRECOMPILED_HEADER, WcsComparerNoCase> mapPreCompiledHeaders;
std::map<wvstring, COMPILER, WcsComparerNoCase> mapCompilers;
LINKERS Linkers;
wvstring wcsOutputPath;
};
struct FOLDER_TREE {
std::map<wvstring, FOLDER_TREE, WcsComparerNoCase> mapSubFolders;
std::map<wvstring, long long, WcsComparerNoCase> mapFiles;
};
struct BUILD_JOBS {
struct GCH {
wvstring wcsSourceFile;
wvstring wcsCommandLine;
wvstring wcsStubFile;
};
std::map<wvstring, GCH> mapGCHs;
std::list<wvstring> lstFilesToCompile;
std::list<wvstring> lstFilesToLink;
};
extern void FixPath(wvstring &wcsSrc);
extern wvstring GetFileExtension(const wvstring &wcsPath);
extern wvstring MakeCommandLine(
const wvstring &wcsBase,
const std::map<wvstring, wvstring> &mapReplacements,
const wchar_t *pwszPrefix
);
extern void TouchFolder(const wvstring &wcsPath);
struct PROCESS_EXIT_INFO {
DWORD dwExitCode;
vstring strStdOut;
vstring strStdErr;
};
PROCESS_EXIT_INFO Execute(const wvstring &wcsCmdLine);
}
#endif
| [
"lh_mouse@126.com"
] | lh_mouse@126.com |
7f71ed133dfb2aebb4b1f73f095bfda7422a177b | dc5a8a2b4e215ef674b686f7aaa3e38c18b8e502 | /Pet Database Project/SearchableVector.h | 81f7cd7422cd721ae02374f6f692bdc53cd4c65d | [] | no_license | msuethan/CSE-335-Projects | 18d012a22e7b937f0d2d8cc5d272e1694e44265c | ba31fb667624e34c2f22d072f1d3610f5bf76337 | refs/heads/master | 2020-04-04T17:57:31.529593 | 2018-11-05T01:47:49 | 2018-11-05T01:47:49 | 156,143,727 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284 | h | #ifndef SEARCHABLEVECTOR_H
#define SEARCHABLEVECTOR_H
class SearchableVector{
public:
virtual unsigned int getSize() const = 0;
virtual bool smaller(int i, int j) const = 0;
virtual string getQuery() = 0;
virtual string compareAt(int i) = 0;
};
#endif
| [
"noreply@github.com"
] | noreply@github.com |
7d441457ed0ace70c1544fb31f93e872d220252a | e5694cdc45c5eb77f699bdccff936f341d0e87e2 | /a/zdr/ZdCtlDT.h | c053d17340d5eff212cdc80518794a2b4d718874 | [] | no_license | arksoftgit/10d | 2bee2f20d78dccf0b5401bb7129494499a3c547d | 4940b9473beebfbc2f4d934fc013b86aa32f5887 | refs/heads/master | 2020-04-16T02:26:52.876019 | 2017-10-10T20:27:34 | 2017-10-10T20:27:34 | 49,138,607 | 0 | 3 | null | 2016-08-29T13:03:58 | 2016-01-06T14:02:53 | C | WINDOWS-1252 | C++ | false | false | 46,106 | h | /////////////////////////////////////////////////////////////////////////////
// Project ZdCtl
//
// This is a part of the Zeidon Dynamic Rendering of GUI applications package.
// Copyright © 1995 - 2016 QuinSoft, Inc.
// All Rights Reserved.
//
// SUBSYSTEM: zdctl.dll - ZDr Application
// FILE: zdctlcal.h
// AUTHOR:
//
// OVERVIEW
// ========
// Class definitions for standard Zeidon DR Ctrls.
//
//
// Change log most recent first order:
//
#ifndef __zdctldt_h__ // Sentry, use file only if it's not already included
#define __zdctldt_h__
#ifndef __cplusplus
#error C++ compilation is required (use a .cpp suffix)
#endif
extern "C"
{
AFX_EXT_API
CWnd * OPERATION
DayTimer( ZSubtask *pZSubtask,
CWnd *pWndParent,
ZMapAct *pzmaComposite,
zVIEW vDialog,
zSHORT nOffsetX,
zSHORT nOffsetY,
zKZWDLGXO_Ctrl_DEF *pCtrlDef );
}
#define zDAYTIMER_SELECT_DATE 0x00000001
#define zDAYTIMER_SELECT_APPOINTMENT 0x00000002
#define zDAYTIMER_SELECT_CALENDAR 0x00000003
#define zDAYTIMER_SELECT_AGENDA 0x00000004
#define zDAYTIMER_SELECT_FULLDAY 0x00000005
#define zDAYTIMER_SELECT_FULLDAY_WND 0x00000006
#define zDAYTIMER_SELECT_DAYMONTHYEAR 0x00000007
#define zDAYTIMER_DBLCLK_DATE 0x00000010
#define zDAYTIMER_DBLCLK_APPOINTMENT 0x00000020
#define zDAYTIMER_DBLCLK_CALENDAR 0x00000030
#define zDAYTIMER_DBLCLK_AGENDA 0x00000040
#define zDAYTIMER_DBLCLK_FULLDAY 0x00000050
#define zDAYTIMER_DBLCLK_FULLDAY_WND 0x00000060
#define zDAYTIMER_DBLCLK_DAYMONTHYEAR 0x00000070
#define zDAYTIMER_RCLICK_DATE 0x00000100
#define zDAYTIMER_RCLICK_APPOINTMENT 0x00000200
#define zDAYTIMER_RCLICK_CALENDAR 0x00000300
#define zDAYTIMER_RCLICK_AGENDA 0x00000400
#define zDAYTIMER_RCLICK_FULLDAY 0x00000500
#define zDAYTIMER_RCLICK_FULLDAY_WND 0x00000600
#define zDAYTIMER_RCLICK_DAYMONTHYEAR 0x00000700
#define zDAYTIMER_APPOINTMENT_ALARM 0x00010000
#define zDAYTIMER_EDIT_CHANGE_APPOINTMENT 0x10000000
#define zMINICAL_SELECT_CHANGE 0x20000000
class ZDCTL_CLASS ZDayTimer;
class ZDayMonthYear;
class ZFullDayWnd;
class ZAgenda;
class ZMiniCalendar;
BOOL CALLBACK
IsSpecialDateCallback( ZDayTimer *pDayTimer, COleDateTime &date );
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// ZAppointment
class ZAppointment : public CObject
{
friend class ZDayTimer;
friend class ZAgenda;
friend class ZMiniCalendar;
friend class ZFullDayWnd;
friend class ZEditAppointment;
friend zLONG OPERATION
EditAppointmentWndProc( HWND hWnd,
WORD uMsg,
WPARAM wParam,
LPARAM lParam );
DECLARE_DYNAMIC( ZAppointment )
public:
ZAppointment( int nIdNbr, unsigned int uKey );
virtual ~ZAppointment( );
BOOL DrawFullDay( COleDateTime& date, CDC *pDC, const CRect& rectArea,
ZAgenda *pView, BOOL bSelected, int nSelectedDay );
void DrawAppointment( COleDateTime& date, CDC *pDC, const CRect& rectArea,
ZAgenda *pView, int nScrollPos );
void UnlinkAppointment( ZAgenda *pAgenda );
protected:
int m_nSeqNbr; // Id of appointment ... usually incremental
unsigned int m_uKey; // Zeidon key ... otw 0
CRect m_rectDraw;
ZAppointment *m_pNext;
ZAppointment *m_pPrev;
ZAppointment *m_pStartOverlap;
ZAppointment *m_pEndOverlap;
int m_nOverlap;
int m_nOverlapMax;
int m_nOverlapPos;
public:
BOOL m_bSelected;
BOOL m_bFullDay;
int m_nAlarm;
int m_nAppointmentType;
CString m_csSubject;
CString m_csMessage;
COleDateTime m_date;
COleDateTime m_timeTo;
COleDateTime m_timeFrom;
};
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// ZAutoFitLabel
class ZAutoFitLabel : public CStatic
{
// Construction
public:
ZAutoFitLabel( );
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL( ZAutoFitLabel )
protected:
virtual void PreSubclassWindow( );
//}}AFX_VIRTUAL
// Implementation
public:
void Update( );
virtual ~ZAutoFitLabel( );
// Generated message map functions
protected:
CFont *m_pFont;
//{{AFX_MSG( ZAutoFitLabel )
afx_msg void OnSize( UINT uType, int cx, int cy );
//}}AFX_MSG
DECLARE_MESSAGE_MAP( )
};
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// ZEditAppointment
class ZEditAppointment : public CEdit
{
friend class ZDayTimer;
friend class ZAgenda;
friend class ZMiniCalendar;
friend zLONG OPERATION
EditAppointmentWndProc( HWND hWnd,
WORD uMsg,
WPARAM wParam,
LPARAM lParam );
public:
ZEditAppointment( ZAgenda *pAgenda );
virtual ~ZEditAppointment( );
void CalculateSize( );
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL( ZEditAppointment )
virtual BOOL PreTranslateMessage( MSG *pMsg );
//}}AFX_VIRTUAL
// Generated message map functions
protected:
//{{AFX_MSG( ZEditAppointment )
afx_msg void OnKeyDown( UINT uKey, UINT uRepeatCnt, UINT uFlags );
afx_msg void OnChar( UINT uChar, UINT uRepeatCnt, UINT uFlags );
afx_msg int OnCreate( LPCREATESTRUCT lpCreateStruct );
afx_msg void OnSizing( UINT uSide, LPRECT pRect );
afx_msg void OnSize( UINT uType, int cx, int cy );
afx_msg void OnMove( int x, int y );
afx_msg LRESULT OnNcHitTest( CPoint pt );
afx_msg void OnNcPaint( );
afx_msg void OnWindowPosChanging( WINDOWPOS *pWndPos );
afx_msg void OnKillFocus( CWnd *pWndGetFocus );
//}}AFX_MSG
protected:
BOOL m_bESC; // to indicate whether ESC key was pressed
BOOL m_bSizeMove; // to indicate Sizing/Moving is in progress
ZAgenda *m_pAgenda;
ZAppointment *m_pA;
WNDPROC m_OldWndProc;
COleDateTime m_timeFrom;
COleDateTime m_timeTo;
CRect m_rectSizing;
DECLARE_MESSAGE_MAP( )
};
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// ZAgenda
const static int g_nTimeGutterBorder = 5;
const static int g_nGutterBandWidth = 6;
const static double g_dHalfHourDivider = 0.7;
inline int INTFRAC( int k, double dFraction )
{
return( int( k * double( dFraction ) ) );
}
class ZDCTL_CLASS ZAgenda : public CWnd
{
friend class ZDayTimer;
friend class ZMiniCalendar;
friend class ZMiniCalendarMonthCell;
friend class ZDayMonthYear;
friend class ZFullDayWnd;
friend class ZAppointment;
friend class ZEditAppointment;
friend zLONG OPERATION
EditAppointmentWndProc( HWND hWnd,
WORD uMsg,
WPARAM wParam,
LPARAM lParam );
DECLARE_DYNAMIC( ZAgenda )
public:
// ctor
ZAgenda( ZDayTimer *pDayTimer );
virtual ~ZAgenda( );
virtual BOOL PreTranslateMessage( MSG *pMsg );
virtual BOOL DestroyWindow( );
// Operations
void ShowSelectedDays( );
int GetAppointmentCountOnDate( COleDateTime& date );
int GetDayCount( );
int GetShownDayCount( );
BOOL DropAppointment( ZAppointment *pA, COleDateTime& date );
int GetDateFromPoint( COleDateTime& date, CPoint& pt );
void SetDrawRect( CRect& rectDraw, COleDateTime& timeFrom,
COleDateTime& timeTo,
const CRect& rectArea, int nScrollPos );
int GetNumberOfFulldayAppointments( );
void SortAppointments( );
void SetAppointmentOverlap( );
void UpdatePositionOfControls( );
void SetWorkday( COleDateTime& timeWorkdayStart,
COleDateTime& timeWorkdayEnd,
zLONG lWorkdayFlag );
ZAppointment * AppointmentHitTest( CPoint& pt );
void TrackEditAppointment( ZAppointment *pA, CPoint& pt );
void EditAppointment( ZAppointment *pA );
ZAppointment * GetNextShownAppointment( BOOL bBackwards );
void TraceAppointmentList( zCPCHAR cpcText );
// void MoveTop( ZAppointment *pA );
void MoveBefore( ZAppointment *pA, ZAppointment *pNext );
ZAppointment * AddAppointment( COleDateTime& date,
COleDateTime& timeFrom,
COleDateTime& timeTo,
zCPCHAR cpcSubject,
zCPCHAR cpcMessage,
zLONG lAlarm,
zLONG lAppointmentType,
zBOOL bFullDay = FALSE );
void AddAppointment( ZAppointment *pA );
int DeleteAppointment( ZAppointment *pA );
void RemoveAllAppointments( );
BOOL IsDoubleClick( UINT uMessage, CPoint ptStart );
void UpdateScrollSize( BOOL bResetPos = FALSE );
void UpdateScrollPosition( );
void GoToTime( COleDateTime& Time, BOOL bMoveToTop = TRUE );
// Overrides
protected:
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL( ZAgenda )
protected:
// virtual void OnDraw( CDC *pDC ); // overridden to draw this view
virtual BOOL PreCreateWindow( CREATESTRUCT& cs );
//}}AFX_VIRTUAL
// Generated message map functions
//{{AFX_MSG( ZAgenda )
afx_msg int OnCreate( LPCREATESTRUCT lpCreateStruct );
afx_msg void OnSize( UINT uType, int cx, int cy );
afx_msg void OnPaint( );
afx_msg void OnVScroll( UINT uSBCode, UINT uPos, CScrollBar *pScrollBar );
afx_msg BOOL OnEraseBkgnd( CDC *pDC );
afx_msg void OnLButtonDown( UINT uFlags, CPoint pt );
afx_msg void OnLButtonUp( UINT uFlags, CPoint pt );
afx_msg void OnLButtonDblClk( UINT uFlags, CPoint pt );
afx_msg void OnRButtonDown( UINT uFlags, CPoint pt );
afx_msg void OnMouseMove( UINT uFlags, CPoint pt );
afx_msg void OnKeyDown( UINT uChar, UINT uRepCnt, UINT uFlags );
afx_msg void OnContextMenu( CWnd *pWnd, CPoint pt );
afx_msg BOOL OnSetCursor( CWnd *pWnd, UINT uHitTest, UINT uMessage );
afx_msg void OnSetFocus( CWnd *pWndLostFocus );
afx_msg void OnKillFocus( CWnd *pWndGetFocus );
//}}AFX_MSG
// Attributes
protected:
ZDayTimer *m_pDayTimer;
ZDayMonthYear *m_pDayMonthYear;
ZFullDayWnd *m_pFullDayWnd;
ZAppointment *m_pAppointmentHead;
ZAppointment *m_pAppointmentLastFocus;
BOOL m_bFocusRect;
int m_nSeqNbr;
int m_nHourHeight;
int m_nTimeGutterWidth;
int m_nEditBorder;
int m_nHeightOfDayMonthYear;
CBrush m_brushAppointmentBack;
CBrush m_brushWorkdayBack;
COleDateTime m_timeWorkdayStart;
COleDateTime m_timeWorkdayEnd;
zLONG m_lWorkdayFlag;
CPen m_penShadow;
CPen m_penDivider;
CPen m_penThinBlack;
CFont m_fontAppointmentSubject;
CImageList m_Images;
CSize m_ImageSize;
BOOL m_bTrackingSelected;
COleDateTime m_dateLastSelected;
COleDateTime m_timeFirstSelected;
COleDateTime m_timeLastSelected;
ZAppointment *m_pTrackedAppointmentBand;
ZAppointment *m_pTrackedAppointment;
CPoint m_ptTracked;
// Implementation
BOOL m_bEditAppointment;
ZEditAppointment m_editAppointment;
ZToolTip m_wndToolTip;
CFont *m_pHourFont;
CFont *m_pSmallHourFont;
CPen m_penNull;
CBrush m_brushBack;
int m_nClientX;
int m_nClientY;
DECLARE_MESSAGE_MAP( )
};
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// ZDayMonthYear window
class ZDayMonthYear : public CWnd
{
friend class ZDayTimer;
friend class ZAgenda;
// Construction
public:
ZDayMonthYear( );
virtual ~ZDayMonthYear( );
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL( ZDayMonthYear )
//}}AFX_VIRTUAL
// Generated message map functions
protected:
//{{AFX_MSG( ZFullDayWnd )
afx_msg int OnCreate( LPCREATESTRUCT lpCreateStruct );
afx_msg void OnPaint( );
afx_msg void OnDestroy( );
afx_msg BOOL OnEraseBkgnd( CDC *pDC );
afx_msg void OnLButtonDown( UINT uFlags, CPoint pt );
afx_msg void OnLButtonUp( UINT uFlags, CPoint pt );
afx_msg void OnLButtonDblClk( UINT uFlags, CPoint pt );
afx_msg void OnRButtonDown( UINT uFlags, CPoint pt );
afx_msg void OnRButtonUp( UINT uFlags, CPoint pt );
afx_msg void OnContextMenu( CWnd *pWnd, CPoint pt );
afx_msg void OnSetFocus( CWnd *pWndLostFocus );
//}}AFX_MSG
protected:
ZAgenda *m_pAgenda;
DECLARE_MESSAGE_MAP( )
};
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// ZFullDayWnd window
class ZFullDayWnd : public CWnd
{
friend class ZDayTimer;
friend class ZAgenda;
// Construction
public:
ZFullDayWnd( );
virtual ~ZFullDayWnd( );
// Operations
public:
ZAppointment * AppointmentHitTest( CPoint& pt );
BOOL IsDoubleClick( UINT uMessage, CPoint ptStart );
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL( ZFullDayWnd )
//}}AFX_VIRTUAL
// Generated message map functions
protected:
//{{AFX_MSG( ZFullDayWnd )
afx_msg int OnCreate( LPCREATESTRUCT lpCreateStruct );
afx_msg void OnPaint( );
afx_msg void OnDestroy( );
afx_msg BOOL OnEraseBkgnd( CDC *pDC );
afx_msg void OnLButtonDown( UINT uFlags, CPoint pt );
afx_msg void OnLButtonUp( UINT uFlags, CPoint pt );
afx_msg void OnLButtonDblClk( UINT uFlags, CPoint pt );
afx_msg void OnRButtonDown( UINT uFlags, CPoint pt );
// afx_msg void OnMouseMove( UINT uFlags, CPoint pt );
afx_msg void OnContextMenu( CWnd *pWnd, CPoint pt );
afx_msg void OnSetFocus( CWnd *pWndLostFocus );
//}}AFX_MSG
protected:
ZAgenda *m_pAgenda;
CPoint m_ptTracked;
ZAppointment *m_pHilightAppointment;
DECLARE_MESSAGE_MAP( )
};
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// ZDayTimer
class ZDCTL_CLASS ZDayTimer : public CWnd, public ZMapAct
{
DECLARE_DYNAMIC( ZDayTimer )
public:
static CString m_csClassName;
// ctor
ZDayTimer( ZSubtask *pZSubtask,
CWnd *pWndParent,
ZMapAct *pzmaComposite,
zVIEW vDialog,
zSHORT nOffsetX,
zSHORT nOffsetY,
zKZWDLGXO_Ctrl_DEF *pCtrlDef );
// dtor
virtual ~ZDayTimer( );
virtual void CreateZ( );
virtual zLONG SetZCtrlState( zLONG lStatusType, zULONG ulValue );
virtual zSHORT MapFromOI( WPARAM wFlag = 0 ); // transfer text from OI to calendar control
virtual zSHORT MapToOI( zLONG lFlag = 0 ); // transfer text to OI from calendar control
virtual BOOL DestroyWindow( );
BOOL PreTranslateMessage( MSG *pMsg );
void UpdatePositionOfControls( );
// Generated message map functions
protected:
//{{AFX_MSG( ZMiniCalendar )
afx_msg int OnCreate( LPCREATESTRUCT lpCreateStruct );
afx_msg void OnSize( UINT uType, int cx, int cy );
afx_msg void OnLButtonDown( UINT uFlags, CPoint pt );
afx_msg void OnSetFocus( CWnd *pWndLostFocus );
afx_msg void OnKillFocus( CWnd *pWndGetFocus );
//}}AFX_MSG
public:
int GoToTime( COleDateTime& Time, BOOL bMoveToTop = TRUE );
int RemoveAllAppointments( );
int ZDayTimer::SignalAlarms( );
void OnTimer( UINT uIDEvent );
ZAppointment * AddFulldayAppointment( COleDateTime& date,
zCPCHAR cpcSubject,
zCPCHAR cpcMessage,
zLONG lAlarm,
zLONG lAppointmentType,
zULONG ulKey );
ZAppointment * AddAppointment( COleDateTime& date,
COleDateTime& timeFrom,
COleDateTime& timeTo,
zCPCHAR cpcSubject,
zCPCHAR cpcMessage,
zLONG lAlarm,
zLONG lAppointmentType,
zULONG ulKey );
ZAppointment * NewAppointment( CPoint& pt,
LPCSTR cpcSubject,
LPCSTR cpcMessage,
LONG lAppointmentType,
BOOL bFullDay );
int DeleteAppointment( ZAppointment *pA );
int UpdateAppointment( ZAppointment *pA );
int SetColorAssociation( COLORREF clrText,
COLORREF clrBack,
int lFlag,
LPCSTR cpcAttributeValue );
int SetTimeEntityAttributes( LPCSTR cpcTimeEntity,
LPCSTR cpcSubjectAttribute,
LPCSTR cpcMessageAttribute,
LPCSTR cpcTimeFromAttribute,
LPCSTR cpcTimeToAttribute,
LPCSTR cpcTimeAlarmAttribute,
LPCSTR cpcTimeAppointmentTypeAttribute,
LPCSTR cpcFullDayAttribute );
int GetHourHeight( /*[out, retval]*/ int *plVal );
int SetHourHeight( /*[in]*/ int lNewVal );
CString m_csTimeEntity;
CString m_csSubjectAttribute;
CString m_csMessageAttribute;
CString m_csTimeFromAttribute;
CString m_csTimeToAttribute;
CString m_csAlarmAttribute;
CString m_csAppointmentTypeAttribute;
CString m_csFullDayAttribute;
CRect m_rectCtrl;
ZAgenda *m_pAgenda;
ZMiniCalendar *m_pMiniCal;
zCHAR m_chStyle;
int m_nRows;
int m_nCols;
int m_nMiniCalSize;
int m_nMaxShowAppointment;
BOOL m_bMultipleSel;
BOOL m_bPermitNull;
BOOL m_bToday;
zCHAR m_chAlignment;
COLORREF m_clrSelBack;
COLORREF m_clrBackground;
zCHAR m_chScope;
zCHAR m_szScopeEntity[ 33 ];
UINT m_uAppointmentTimerId;
DECLARE_MESSAGE_MAP( )
};
/////////////////////////////////////////////////////////////////////////////
// ZMiniCalendar
// Author: Matt Gullett
// gullettm@yahoo.com
// Copyright © 2001
//
// This is a user-interface componenet similar to the MS outlook mini
// calendar control. (The one used in date picker control and the
// appointment (day view)).
//
// You may freely use this source code in personal, freeware, shareware
// or commercial applications provided that 1) my name is recognized in the
// code and if this code represents a substantial portion of the application
// that my name be included in the credits for the application (about box, etc)
//
// Use this code at your own risk. This code is provided AS-IS. No warranty
// is granted as to the correctness, usefulness or value of this code.
//
// Special thanks to Keith Rule for the CMemDC class
// http://www.codeproject.com/gdi/flickerfree.asp
//
// *******************************************************************
// TECHNICAL NOTES:
//
// See .cpp file for tech notes
//////////////////////////////////////////////////////////////////////
// Custom window styles.
#define FMC_MULTISELECT 0x0040L
#define FMC_NOHIGHLIGHTTODAY 0x0080L
#define FMC_TODAYBUTTON 0x0100L
#define FMC_NONEBUTTON 0x0200L
#define FMC_AUTOSETTINGS 0x0400L
#define FMC_NO3DBORDER 0x0800L
#define FMC_NOSHOWNONMONTHDAYS 0x1000L
// I usually don't use preprocessor macros like this
// but it makes sense here.
#define FMC_MAX_SIZE_NONE CSize( -2, -2 )
#define FMC_MAX_SIZE_PARENT CSize( -1, -1 )
// Default font settings.
#define FMC_DEFAULT_FONT "Tahoma"
#define FMC_DEFAULT_FONT_SIZE 8
#define FMC_DEFAULT_FONT_SIZE_640 7
#define FMC_DEFAULT_FONT_SIZE_800 8
#define FMC_DEFAULT_FONT_SIZE_1024 10
#define FMC_DEFAULT_FONT_SIZE_1280 12
#define FMC_DEFAULT_MIN_FONT_SIZE 5
// Used to disable Maximum selection day rules.
#define FMC_NO_MAX_SEL_DAYS -1
// Callback function (definition) for the IsSpecialDate function.
typedef BOOL (CALLBACK *fnSPECIALDATE)( ZDayTimer *pDayTimer, COleDateTime& );
// Forward declaration for list popup.
class ZMiniCalendarList;
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// ZMiniCalendar window
class ZMiniCalendarCtrlFontInfo
{
public:
ZMiniCalendarCtrlFontInfo( );
~ZMiniCalendarCtrlFontInfo( );
virtual void CreateFont( CDC *pDC );
CString m_csFontName;
int m_nFontSize;
BOOL m_bBold;
BOOL m_bItalic;
BOOL m_bUnderline;
COLORREF m_cColor;
CFont *m_pFont;
};
class ZMiniCalendarDaySpot
{
friend class ZDayTimer;
friend class ZAgenda;
friend class ZMiniCalendar;
friend class ZMiniCalendarMonthCell;
public:
ZMiniCalendarDaySpot( ) { };
~ZMiniCalendarDaySpot( ) { };
protected:
CRect m_rect;
COleDateTime m_date;
int m_nDaySpot;
BOOL m_bSelected;
BOOL m_bNonMonth;
};
class ZMiniCalendar;
class ZMiniCalendarMonthCell
{
friend class ZDayTimer;
friend class ZAgenda;
friend class ZMiniCalendar;
public:
ZMiniCalendarMonthCell( );
~ZMiniCalendarMonthCell( );
BOOL IsDaySelected( int nDaySpot );
BOOL IsLeftSelected( int nDay );
BOOL IsTopSelected( int nDay );
BOOL IsRightSelected( int nDay );
BOOL IsBottomSelected( int nDay );
ZMiniCalendarDaySpot * DaySpotHitTest( CPoint& pt ) const;
int WeekdayHitTest( CPoint& pt ) const;
void InvalidateWeekday( int nWeekday );
protected:
ZMiniCalendar *m_pMiniCal;
CRect m_rectHeader;
CRect m_rectWeekdayHeader;
CRect m_rect;
int m_nRow;
int m_nCol;
int m_nYear;
int m_nMonth;
ZMiniCalendarDaySpot *m_pDaySpots;
int m_nDaysInMonth;
int m_nDayOfWeekMonthBegins;
CRect m_rectWeekdays[ zDAYS_IN_WEEK ];
// CRect m_rectDayLocations[ zDAY_SPOTS_IN_MONTH ];
};
class ZMiniCalendarSelSpot
{
friend class ZDayTimer;
friend class ZAgenda;
friend class ZMiniCalendar;
public:
ZMiniCalendarSelSpot( COleDateTime& date )
{
m_date = date;
};
~ZMiniCalendarSelSpot( ) { };
private:
COleDateTime m_date;
};
class ZMiniCalendar : public CWnd
{
friend class ZDayTimer;
friend class ZAgenda;
friend class ZMiniCalendarMonthCell;
friend class ZDayMonthYear;
friend class ZFullDayWnd;
friend class ZMiniCalendarList;
friend zOPER_EXPORT zSHORT OPERATION
DT_SetStartDateRowsCols( zVIEW vSubtask,
zCPCHAR cpcCtrlTag,
zSHORT nYear,
zSHORT nMonth,
zSHORT nRows,
zSHORT nCols,
zLONG lFlag );
DECLARE_DYNAMIC( ZMiniCalendar )
public:
ZMiniCalendar( ZDayTimer *pDayTimer ); // ctor
virtual ~ZMiniCalendar( ); // dtor
// Attributes
static CString m_csClassName;
static CString m_csHeaderClassName;
enum eBUTTON_STATE { eFLAT, eHILIGHT, ePRESSED };
// Operations
BOOL Create( const RECT& rect, CWnd *pParentWnd, UINT uID );
void SetHeaderFont( zCPCHAR cpcFont, int nSize, BOOL bBold, BOOL bItalic,
BOOL bUnderline, COLORREF clr );
ZMiniCalendarCtrlFontInfo& GetHeaderFont( ) {return m_HeaderFontInfo;}
void SetDaysOfWeekFont( zCPCHAR cpcFont, int nSize, BOOL bBold,
BOOL bItalic, BOOL bUnderline, COLORREF clr );
ZMiniCalendarCtrlFontInfo& GetDaysOfWeekFont( ) { return m_DaysOfWeekFontInfo; }
void SetSpecialDaysFont( zCPCHAR cpcFont, int nSize, BOOL bBold,
BOOL bItalic, BOOL bUnderline, COLORREF clr );
ZMiniCalendarCtrlFontInfo& GetSpecialDaysFont( ) { return m_SpecialDaysFontInfo; }
void SetDaysFont( zCPCHAR cpcFont, int nSize, BOOL bBold, BOOL bItalic,
BOOL bUnderline, COLORREF clr );
ZMiniCalendarCtrlFontInfo& GetDaysFont( ) { return m_DaysFontInfo; }
protected:
void AutoConfigure( );
void ReinitializeCells( );
void AutoSize( );
int ComputeTodayNoneHeight( );
CSize ComputeTotalSize( );
CSize ComputeSize( );
CSize Compute3DBorderSize( );
void FireNoneButton( );
void FireNotifyDblClick( );
void FireNotifyClick( );
void FireTodayButton( );
void ScrollRight( int nCnt = 1 );
void ScrollLeft( int nCnt = 1 );
BOOL GetSelectedDateByOrder( COleDateTime& date,
int nSelectedOrder = 0 );
void SetTracking( ZMiniCalendarMonthCell **ppMonthHeader,
ZMiniCalendarMonthCell **ppMonthWeekdays,
ZMiniCalendarMonthCell **ppMonthCell,
CPoint& pt );
int MonthCellFromRowCol( int nMonthRow, int nMonthCol );
int ScrollButtonHitTest( CPoint& pt );
void RelayEvent( UINT uMessage, WPARAM wParam, LPARAM lParam );
ZMiniCalendarMonthCell * MonthHeaderHitTest( CPoint& pt );
ZMiniCalendarMonthCell * MonthWeekdayHeaderHitTest( CPoint& pt );
ZMiniCalendarMonthCell * MonthCellHitTest( CPoint& pt );
void SetCurrentDate( COleDateTime date );
// COleDateTime GetDate( );
void SetRowsAndColumns( int nRows, int nCols );
int GetRows( ) { return m_nRows; }
int GetCols( ) { return m_nCols; }
void SetShowNonMonthDays( BOOL bValue ) { m_bShowNonMonthDays = bValue; }
BOOL GetShowNonMonthDays( ) { return m_bShowNonMonthDays; }
void SetDefaultMinFontSize( int nDefaultMinFontSize );
int GetDefaultMinFontSize( ) { return m_nDefaultMinFontSize; }
void SetDefaultFont( LPCTSTR lpszValue );
CString GetDefaultFont( ) { return m_csDefaultFontName; }
void SetMonthName( int nMonth, LPCTSTR cpcMonthName );
CString GetMonthName( int nMonth );
void SetDayOfWeekName( int nDayOfWeek, LPCTSTR cpcDayName );
CString GetDayOfWeekName( int nDayOfWeek );
void SetFirstDayOfWeek( int nDayOfWeek );
int GetFirstDayOfWeek( );
void SetCurrentMonthAndYear( int nMonth, int nYear );
int GetCurrentMonth( ) { return m_nCurrentMonth; }
int GetCurrentYear( ) { return m_nCurrentYear; }
void EnableMultipleSelection( BOOL bMultiSel ) { m_bMultipleSel = bMultiSel; }
BOOL IsMultipleSelectionEnabled( ) { return m_bMultipleSel; }
void EnablePermitNull( BOOL bPermitNull ) { m_bPermitNull = bPermitNull; }
BOOL IsPermitNullEnabled( ) { return m_bPermitNull; }
void EnableToday( BOOL bToday ) { m_bToday = bToday; }
BOOL IsTodayEnabled( ) { return m_bToday; }
void SetBackColor( COLORREF clrBack ) { m_clrBack = clrBack; }
COLORREF GetBackColor( ) { return m_clrBack; }
void SetHighlightToday( BOOL bHighlightToday ) { m_bHighlightToday = bHighlightToday; }
BOOL GetHighlightToday( ) { return m_bHighlightToday; }
void SetShowTodayButton( BOOL bShowTodayButton ) { m_bShowTodayButton = bShowTodayButton; }
BOOL GetShowTodayButton( ) { return m_bShowTodayButton; }
void SetShowNoneButton( BOOL bShowNoneButton ) { m_bShowNoneButton = bShowNoneButton; }
BOOL GetShowNoneButton( ) { return m_bShowNoneButton; }
void SetNonMonthDayColor( COLORREF clr ) { m_clrNonMonthDay = clr; }
COLORREF GetNonMonthDayColor( COLORREF clr ) { m_clrNonMonthDay = clr; }
void SetShow3DBorder( BOOL bShow3dBorder ) { m_bShow3dBorder = bShow3dBorder; }
BOOL GetShow3DBorder( ) { return m_bShow3dBorder; }
void SetMaxSize( SIZE sizeMax );
CSize GetMaxSize( ) { return m_sizeMax; }
void SetUseAutoSettings( BOOL bUseAutoSettings ) { m_bUseAutoSettings = bUseAutoSettings; }
BOOL GetUseAutoSettings( ) { return m_bUseAutoSettings; }
void SetMaxSelDays( int nMaxSelDays ) { m_nMaxSelDays = nMaxSelDays; }
int GetMaxSelDays( ) { return m_nMaxSelDays; }
void SetSpecialDaysCallback( fnSPECIALDATE pfnSpecialDaysCallback );
fnSPECIALDATE GetSpecialDaysCallback( ) { return m_pfnSpecialDaysCallback; }
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL( ZMiniCalendar )
public:
BOOL PreTranslateMessage( MSG *pMsg );
//}}AFX_VIRTUAL
// Generated message map functions
protected:
//{{AFX_MSG( ZMiniCalendar )
afx_msg int OnCreate( LPCREATESTRUCT lpCreateStruct );
afx_msg BOOL OnEraseBkgnd( CDC *pDC );
afx_msg void OnPaint( );
afx_msg void OnDevModeChange( LPTSTR lpDeviceName );
afx_msg void OnFontChange( );
afx_msg void OnPaletteChanged( CWnd *pFocusWnd );
afx_msg void OnSettingChange( UINT uFlags, LPCTSTR lpszSection );
afx_msg void OnTimeChange( );
afx_msg void OnSysColorChange( );
afx_msg void OnLButtonDown( UINT uFlags, CPoint pt );
afx_msg void OnLButtonUp( UINT uFlags, CPoint pt );
afx_msg void OnLButtonDblClk( UINT uFlags, CPoint pt );
afx_msg void OnRButtonDown( UINT uFlags, CPoint pt );
afx_msg void OnMouseMove( UINT uFlags, CPoint pt );
afx_msg void OnKeyDown( UINT uChar, UINT uRepCnt, UINT uFlags );
afx_msg void OnSetFocus( CWnd *pWndLostFocus );
afx_msg void OnKillFocus( CWnd *pWndGetFocus );
//}}AFX_MSG
// Implementation
protected:
void SetValidInterval( const COleDateTime& fromDate,
const COleDateTime& toDate );
void AllocateCells( );
void SetCellPosition( int nMonthRow, int nMonthCol, RECT rect,
int nYear, int nMonth, int nPart );
void SetDaySpot( int nMonthRow, int nMonthCol, int nDay,
COleDateTime& date, RECT rect );
int DrawTodayButton( CDC& dc, int nY );
void CreateFontObjects( );
int DrawHeader( CDC& dc, int nY, int nLeftX, int nRow, int nCol,
int nYear, int nMonth );
int DrawDaysOfWeek( CDC& dc, int nY, int nLeftX, int nRow, int nCol,
int nYear, int nMonth );
int DrawDays( CDC& dc, int nY, int nLeftX, int nRow, int nCol,
int nYear, int nMonth );
void OnSelectionChanged( );
ZMiniCalendarDaySpot * FindDaySpotByDate( COleDateTime& date );
void ClearAllDaySpots( );
void ClearAllSelectedDays( );
void AddSelectedDay( COleDateTime& date, BOOL bRedraw = TRUE );
void RemoveSelectedDay( COleDateTime& date );
BOOL IsDaySelected( COleDateTime& date ) const;
int GetSelectedDayCount( );
BOOL IsToday( COleDateTime& date ) const;
BOOL IsDateValid( const COleDateTime& date ) const;
BOOL IsSpecialDay( COleDateTime& date );
BOOL MarkSpecialDay( COleDateTime& date, BOOL bMarked );
void UnMarkAllSpecialDays( );
void OnTimer( UINT uIDEvent );
// Attributes
protected:
ZDayTimer *m_pDayTimer;
COleDateTime m_dateToday;
int m_nInPaint;
int m_nCurrentMonth;
int m_nCurrentYear;
int m_nDayCnt;
ZMiniCalendarCtrlFontInfo m_HeaderFontInfo;
ZMiniCalendarCtrlFontInfo m_DaysOfWeekFontInfo;
ZMiniCalendarCtrlFontInfo m_DaysFontInfo;
ZMiniCalendarCtrlFontInfo m_SpecialDaysFontInfo;
COLORREF m_clrBack;
COLORREF m_clrLight;
COLORREF m_clrShadow;
COLORREF m_clrText;
COLORREF m_clrSelBack;
COLORREF m_clrSelText;
COLORREF m_clrNonMonthDay;
BOOL m_bHighlightToday;
BOOL m_bShowTodayButton;
BOOL m_bShowNoneButton;
CString m_csMonthNamesArray[ zMONTHS_IN_YEAR ];
CString m_csDaysOfWeekNamesArray[ zDAYS_IN_WEEK ];
int m_nFirstDayOfWeek;
int m_nRows;
int m_nCols;
BOOL m_bMultipleSel;
BOOL m_bPermitNull;
BOOL m_bToday;
BOOL m_bAbsoluteSel;
BOOL m_bShow3dBorder;
BOOL m_bUseAutoSettings;
CSize m_sizeMax;
CString m_csDefaultFontName;
int m_nDefaultMinFontSize;
int m_nMaxSelDays;
BOOL m_bShowNonMonthDays;
fnSPECIALDATE m_pfnSpecialDaysCallback;
COleDateTime m_dateMin;
COleDateTime m_dateMax;
COleDateTime m_dateTrackingStart;
BOOL m_bScrollTracking;
BOOL m_bHeaderTracking;
BOOL m_bDayTracking;
BOOL m_bTodayTracking;
BOOL m_bTodayDown;
BOOL m_bNoneTracking;
BOOL m_bNoneDown;
ZMiniCalendarList *m_pHeaderList;
ZMiniCalendarMonthCell *m_pHeaderCell;
UINT m_nHeaderTimerID;
BOOL m_bSlowTimerMode;
int m_nSlowTimerCount;
// Month button, scroll images/positions/sizes.
enum eBUTTON_ID { ePrevYear, ePrevMonth, eToday,
eNextMonth, eNextYear, eNone };
CToolTipCtrl m_ToolTip;
CImageList m_Images;
CSize m_ImageSize;
CRect m_rectScrollButtons[ zMINICAL_BUTTON_IMAGE_CNT + 1 ];
int m_nTrackedScrollButton;
int m_nPressedScrollButton;
int m_nTrackedMonthMonthYear;
int m_nPressedMonthMonthYear;
int m_nTrackedMonthWeekday;
int m_nPressedMonthWeekday;
ZMiniCalendarDaySpot *m_pTrackedDaySpot;
ZMiniCalendarDaySpot *m_pPressedDaySpot;
// Computed values of importance.
BOOL m_bFontsCreated;
BOOL m_bSizeComputed;
int m_nHeaderHeight;
int m_nIndividualDayWidth;
int m_nDaysOfWeekHeight;
int m_nDaysHeight;
CSize m_sizeMonth;
// Lists.
int m_nMonthCells;
ZMiniCalendarMonthCell *m_pMonthCells;
CList< ZMiniCalendarSelSpot *, ZMiniCalendarSelSpot * > m_MarkedDays;
CList< ZMiniCalendarSelSpot *, ZMiniCalendarSelSpot * > m_SelectedDays;
CList< ZMiniCalendarSelSpot *, ZMiniCalendarSelSpot * > m_SelectedDayOrder;
DECLARE_MESSAGE_MAP( )
};
/////////////////////////////////////////////////////////////////////////////
// ZMiniCalendarList
// Author: Matt Gullett
// gullettm@yahoo.com
// Copyright © 2001
//
// This is a companion control for use by the ZMiniCalendar.
// It is probably useless for any other purpose.
//
// You may freely use this source code in personal, freeware, shareware or
// commercial applications provided that 1) my name is recognized in the code
// and if this code represents a substantial portion of the application that
// my name be included in the credits for the application (about box, etc.)
//
// Use this code at your own risk. This code is provided AS-IS. No warranty
// is granted as to the correctness, usefulness or value of this code.
//
// Special thanks to Keith Rule for the CMemDC class
// http://www.codeproject.com/gdi/flickerfree.asp
//
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// ZMiniCalendarList window
class ZMiniCalendarList : public CWnd
{
// Construction
public:
ZMiniCalendarList( );
// Attributes
public:
// Operations
public:
int GetSelMonth( ) { return m_nSelMonth; }
int GetSelYear( ) { return m_nSelYear; }
void SetCalendar( ZMiniCalendar *pWnd );
void SetMiddleMonthYear( int nMonth, int nYear );
void SetItemsPerPage( int nItems );
void SetBackColor( COLORREF clrBack ) { m_clrBack = clrBack; }
void SetTextColor( COLORREF clrText ) { m_clrText = clrText; }
void SetFont( LPCTSTR lpszFont, int nSize, BOOL bBold, BOOL bItalic,
BOOL bUnderline, COLORREF clr );
ZMiniCalendarCtrlFontInfo& GetFont( ) { return m_FontInfo; }
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL( ZMiniCalendarList )
//}}AFX_VIRTUAL
// Implementation
public:
void ScrollDown( int nCnt = 1 );
void ScrollUp( int nCnt = 1 );
void AutoConfigure( );
void ForwardMessage( MSG *pMSG );
virtual ~ZMiniCalendarList( );
// Generated message map functions
protected:
BOOL IsSelected( int nX, CRect rectItem );
//{{AFX_MSG( ZMiniCalendarList )
afx_msg BOOL OnEraseBkgnd( CDC *pDC );
afx_msg void OnPaint( );
//}}AFX_MSG
DECLARE_MESSAGE_MAP( )
int m_nMiddleMonth;
int m_nMiddleYear;
int m_nItemsPerPage;
int m_nSelMonth;
int m_nSelYear;
COLORREF m_clrBack;
COLORREF m_clrText;
ZMiniCalendarCtrlFontInfo m_FontInfo;
ZMiniCalendar *m_pWndCalendar;
int m_nUpFactor;
int m_nDownFactor;
};
#if 0
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// ZMiniCalendarDlg
class ZMiniCalendarDlg : public CDialog
{
// Construction
public:
ZMiniCalendarDlg( CWnd *pParent = 0 ); // standard constructor
// Dialog Data
//{{AFX_DATA( ZMiniCalendarDlg )
enum { IDD = IDD_MINICALENDAR_DIALOG };
BOOL m_b3DBorder;
int m_nCols;
BOOL m_bHighlightToday;
int m_nMaxSel;
BOOL m_bMultiSelect;
BOOL m_bNoneButton;
int m_nRows;
BOOL m_bTodayButton;
int m_nFirstDayOfWeek;
BOOL m_bShowNonMonthDays;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL( ZMiniCalendarDlg )
protected:
virtual void DoDataExchange( CDataExchange *pDX ); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG( ZMiniCalendarDlg )
virtual BOOL OnInitDialog( );
afx_msg void OnSysCommand( UINT uID, LPARAM lParam );
afx_msg void OnPaint( );
afx_msg HCURSOR OnQueryDragIcon( );
afx_msg void OnUpdate( );
//}}AFX_MSG
afx_msg void OnCalendarClick( NMHDR *pNotifyStruct, LRESULT *result );
DECLARE_MESSAGE_MAP( )
ZMiniCalendar m_wndCalendar;
};
#endif
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
#if 0
#define WMID_CALENDAR 32999
// MiniCalendarDlg.cpp : implementation file
//
BEGIN_MESSAGE_MAP( ZMiniCalendarDlg, CDialog )
//{{AFX_MSG_MAP( ZMiniCalendarDlg )
ON_WM_SYSCOMMAND( )
ON_WM_PAINT( )
ON_WM_QUERYDRAGICON( )
ON_BN_CLICKED( IDC_UPDATE, OnUpdate )
//}}AFX_MSG_MAP
ON_NOTIFY( NM_CLICK, WMID_CALENDAR, OnCalendarClick )
END_MESSAGE_MAP( )
/////////////////////////////////////////////////////////////////////////////
// ZMiniCalendarDlg dialog
ZMiniCalendarDlg::ZMiniCalendarDlg( CWnd *pParent /*=0*/ ) :
CDialog( ZMiniCalendarDlg::IDD, pParent )
{
//{{AFX_DATA_INIT( ZMiniCalendarDlg )
m_b3DBorder = TRUE;
m_nCols = 1;
m_bHighlightToday = TRUE;
m_nMaxSel = 0;
m_bMultnSelect = TRUE;
m_bNoneButton = TRUE;
m_nRows = 1;
m_bTodayButton = TRUE;
m_nFirstDayOfWeek = 1;
m_bShowNonMonthDays = TRUE;
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp( )->LoadIcon( IDR_MAINFRAME );
}
void
ZMiniCalendarDlg::DoDataExchange( CDataExchange *pDX )
{
CDialog::DoDataExchange( pDX );
//{{AFX_DATA_MAP( ZMiniCalendarDlg )
DDX_Check( pDX, IDC_3D_BORDER, m_b3DBorder );
DDX_Text( pDX, IDC_COLS, m_nCols );
DDX_Check( pDX, IDC_HIGHLIGHT_TODAY, m_bHighlightToday );
DDX_Text( pDX, IDC_MAXSEL, m_nMaxSel );
DDX_Check( pDX, IDC_MULTI_SELECT, m_bMultnSelect );
DDX_Check( pDX, IDC_NONE_BUTTON, m_bNoneButton );
DDX_Text( pDX, IDC_ROWS, m_nRows );
DDX_Check( pDX, IDC_TODAY_BUTTON, m_bTodayButton );
DDX_Text( pDX, IDC_FIRST_DAY_OF_WEEK, m_nFirstDayOfWeek );
DDX_Check( pDX, IDC_SHOW_NONMONTH_DAYS, m_bShowNonMonthDays );
//}}AFX_DATA_MAP
}
/////////////////////////////////////////////////////////////////////////////
// ZMiniCalendarDlg message handlers
BOOL
ZMiniCalendarDlg::OnInitDialog( )
{
CDialog::OnInitDialog( );
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT( ( IDM_ABOUTBOX & 0xFFF0 ) == IDM_ABOUTBOX );
ASSERT( IDM_ABOUTBOX < 0xF000 );
CMenu *pSysMenu = GetSystemMenu( FALSE );
if ( pSysMenu )
{
CString csAboutMenu;
csAboutMenu.LoadString( IDS_ABOUTBOX );
if ( csAboutMenu.IsEmpty( ) == FALSE )
{
pSysMenu->AppendMenu( MF_SEPARATOR );
pSysMenu->AppendMenu( MF_STRING, IDM_ABOUTBOX, csAboutMenu );
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog.
SetIcon( m_hIcon, TRUE ); // set big icon
SetIcon( m_hIcon, FALSE ); // set small icon
CRect CalendarRect;
CWnd *pWnd = GetDlgItem( IDC_CALENDAR_GOES_HERE );
ASSERT( pWnd );
pWnd->GetWindowRect( CalendarRect );
ScreenToClient( CalendarRect );
m_wndCalendar.Create( 0, 0, WS_CHILD | WS_VISIBLE | FMC_MULTISELECT |
FMC_AUTOSETTINGS | FMC_TODAYBUTTON |
FMC_NONEBUTTON,
CalendarRect, this, WMID_CALENDAR );
m_wndCalendar.SetDate( m_dateToday );
m_wndCalendar.SetSpecialDaysCallback( IsSpecialDateCallback );
m_wndCalendar.SetRowsAndColumns( 1, 1 );
return( TRUE ); // return TRUE unless you set the focus to a control
}
void
ZMiniCalendarDlg::OnSysCommand( UINT uID, LPARAM lParam )
{
if ( (nID & 0xFFF0) == IDM_ABOUTBOX )
{
CAboutDlg dlgAbout;
dlgAbout.DoModal( );
}
else
{
CDialog::OnSysCommand( nID, lParam );
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void
ZMiniCalendarDlg::OnPaint( )
{
if ( IsIconic( ) )
{
CPaintDC dc( this ); // device context for painting
SendMessage( Wm_nCONERASEBKGND, (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( );
}
}
// The system calls this to obtain the cursor to display while the user
// drags the minimized window.
HCURSOR
ZMiniCalendarDlg::OnQueryDragIcon( )
{
return( (HCURSOR) m_hIcon );
}
void
ZMiniCalendarDlg::OnCalendarClick( NMHDR *nmhdr, LRESULT *lResult )
{
COleDateTime dateBegin;
COleDateTime dateEnd;
CString csMessage;
m_wndCalendar.GetDateSel( dateBegin, dateEnd );
if ( dateBegin.GetStatus( ) != COleDateTime::valid )
{
csMessage = "You selected none\n";
}
else
{
if ( m_bMultnSelect )
{
csMessage = "You selected: ";
csMessage += dateBegin.Format( "%m/%d/%Y" );
csMessage += " to ";
csMessage += dateEnd.Format( "%m/%d/%Y\n" );
}
else
{
csMessage = "You selected: ";
csMessage += dateBegin.Format( "%m/%d/%Y\n" );
}
}
AfxTrace( csMessage );
}
void
ZMiniCalendarDlg::OnUpdate( )
{
UpdateData( );
COleDateTime dateTemp;
dateTemp.SetStatus( COleDateTime::invalid );
m_wndCalendar.SetShow3DBorder( m_b3DBorder );
m_wndCalendar.SetHighlightToday( m_bHighlightToday );
m_wndCalendar.SetMultnSelect( m_bMultnSelect );
m_wndCalendar.SetShowNoneButton( m_bNoneButton );
m_wndCalendar.SetShowTodayButton( m_bTodayButton );
m_wndCalendar.SetDate( dateTemp );
m_wndCalendar.SetFirstDayOfWeek( m_nFirstDayOfWeek );
m_wndCalendar.SetShowNonMonthDays( m_bShowNonMonthDays );
if ( m_nMaxSel <= 0 )
m_wndCalendar.SetMaxSelDays( FMC_NO_MAX_SEL_DAYS );
else
m_wndCalendar.SetMaxSelDays( m_nMaxSel );
m_wndCalendar.SetRowsAndColumns( m_nRows, m_nCols );
m_wndCalendar.AutoConfigure( );
m_wndCalendar.RedrawWindow( );
}
#endif
#endif // __zdctldt_h__ sentry.
| [
"arksoft@comcast.net"
] | arksoft@comcast.net |
93d30652b43c898d73a1c14f7178e4dd7ab1e6c6 | 01e6591e5a01601465d8ae23411d909de0fd57a5 | /components/html_viewer/frame.h | ff4ea424f8452b6622c4cbc03b874d9c28abc9b2 | [
"BSD-3-Clause"
] | permissive | CapOM/chromium | 712a689582c418d15c2fe7777cba06ee2e52a91f | e64bf2b8f9c00e3acb2f55954c36de9f3c43d403 | refs/heads/master | 2021-01-12T22:11:06.433874 | 2015-06-25T23:49:07 | 2015-06-25T23:49:34 | 38,643,354 | 1 | 0 | null | 2015-07-06T20:13:18 | 2015-07-06T20:13:18 | null | UTF-8 | C++ | false | false | 6,989 | h | // 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.
#ifndef COMPONENTS_HTML_VIEWER_FRAME_H_
#define COMPONENTS_HTML_VIEWER_FRAME_H_
#include <vector>
#include "base/basictypes.h"
#include "base/memory/scoped_ptr.h"
#include "components/html_viewer/frame_tree_manager.h"
#include "components/view_manager/public/cpp/view_observer.h"
#include "mandoline/tab/public/interfaces/frame_tree.mojom.h"
#include "third_party/WebKit/public/platform/WebURLRequest.h"
#include "third_party/WebKit/public/web/WebFrameClient.h"
#include "third_party/WebKit/public/web/WebRemoteFrameClient.h"
#include "third_party/WebKit/public/web/WebSandboxFlags.h"
#include "third_party/WebKit/public/web/WebViewClient.h"
namespace blink {
class WebFrame;
}
namespace mojo {
class Rect;
class View;
}
namespace html_viewer {
class FrameTreeManager;
class TouchHandler;
class WebLayerTreeViewImpl;
// Frame is used to represent a single frame in the frame tree of a page. The
// frame is either local or remote. Each Frame is associated with a single
// FrameTreeManager and can not be moved to another FrameTreeManager. Local
// frames have a mojo::View, remote frames do not.
class Frame : public blink::WebFrameClient,
public blink::WebViewClient,
public blink::WebRemoteFrameClient,
public mojo::ViewObserver {
public:
Frame(FrameTreeManager* manager, Frame* parent, uint32_t id);
void Init(mojo::View* local_view);
// Closes and deletes this Frame.
void Close();
uint32_t id() const { return id_; }
// Returns the Frame whose id is |id|.
Frame* FindFrame(uint32_t id) {
return const_cast<Frame*>(const_cast<const Frame*>(this)->FindFrame(id));
}
const Frame* FindFrame(uint32_t id) const;
Frame* parent() { return parent_; }
const std::vector<Frame*>& children() { return children_; }
// Returns the WebFrame for this Frame. This is either a WebLocalFrame or
// WebRemoteFrame.
blink::WebFrame* web_frame() { return web_frame_; }
// Returns the WebView for this frame, or null if there isn't one. The root
// has a WebView, the children WebFrameWidgets.
blink::WebView* web_view();
// The mojo::View this frame renders to. This is non-null for the local frame
// the frame tree was created with as well as non-null for any frames created
// locally.
mojo::View* view() { return view_; }
private:
friend class FrameTreeManager;
virtual ~Frame();
// Returns true if the Frame is local, false if remote.
bool IsLocal() const;
void SetView(mojo::View* view);
// Creates the appropriate WebWidget implementation for the Frame.
void CreateWebWidget();
void UpdateFocus();
// Updates the size and scale factor of the webview and related classes from
// |root_|.
void UpdateWebViewSizeFromViewSize();
// Swaps this frame from a local frame to remote frame. |request| is the url
// to load in the frame.
void SwapToRemote(const blink::WebURLRequest& request);
// See comment in SwapToRemote() for details on this.
void FinishSwapToRemote();
Setup* setup() { return frame_tree_manager_->setup(); }
// Returns the Frame associated with the specified WebFrame.
Frame* FindFrameWithWebFrame(blink::WebFrame* web_frame);
// The various frameDetached() implementations call into this.
void FrameDetachedImpl(blink::WebFrame* web_frame);
// mojo::ViewObserver methods:
void OnViewBoundsChanged(mojo::View* view,
const mojo::Rect& old_bounds,
const mojo::Rect& new_bounds) override;
void OnViewDestroyed(mojo::View* view) override;
void OnViewInputEvent(mojo::View* view, const mojo::EventPtr& event) override;
void OnViewFocusChanged(mojo::View* gained_focus,
mojo::View* lost_focus) override;
// WebViewClient methods:
virtual void initializeLayerTreeView() override;
virtual blink::WebLayerTreeView* layerTreeView() override;
virtual blink::WebStorageNamespace* createSessionStorageNamespace();
// WebFrameClient methods:
virtual blink::WebMediaPlayer* createMediaPlayer(
blink::WebLocalFrame* frame,
const blink::WebURL& url,
blink::WebMediaPlayerClient* client,
blink::WebContentDecryptionModule* initial_cdm);
virtual blink::WebFrame* createChildFrame(
blink::WebLocalFrame* parent,
blink::WebTreeScopeType scope,
const blink::WebString& frame_ame,
blink::WebSandboxFlags sandbox_flags);
virtual void frameDetached(blink::WebFrame* frame);
virtual void frameDetached(blink::WebFrame* frame,
blink::WebFrameClient::DetachType type);
virtual blink::WebCookieJar* cookieJar(blink::WebLocalFrame* frame);
virtual blink::WebNavigationPolicy decidePolicyForNavigation(
const NavigationPolicyInfo& info);
virtual void didAddMessageToConsole(const blink::WebConsoleMessage& message,
const blink::WebString& source_name,
unsigned source_line,
const blink::WebString& stack_trace);
virtual void didFinishLoad(blink::WebLocalFrame* frame);
virtual void didNavigateWithinPage(blink::WebLocalFrame* frame,
const blink::WebHistoryItem& history_item,
blink::WebHistoryCommitType commit_type);
virtual blink::WebEncryptedMediaClient* encryptedMediaClient();
// blink::WebRemoteFrameClient:
virtual void frameDetached(blink::WebRemoteFrameClient::DetachType type);
virtual void postMessageEvent(blink::WebLocalFrame* source_frame,
blink::WebRemoteFrame* target_frame,
blink::WebSecurityOrigin target_origin,
blink::WebDOMMessageEvent event);
virtual void initializeChildFrame(const blink::WebRect& frame_rect,
float scale_factor);
virtual void navigate(const blink::WebURLRequest& request,
bool should_replace_current_entry);
virtual void reload(bool ignore_cache, bool is_client_redirect);
virtual void forwardInputEvent(const blink::WebInputEvent* event);
FrameTreeManager* frame_tree_manager_;
Frame* parent_;
mojo::View* view_;
// The id for this frame. If there is a view, this is the same id as the
// view has.
const uint32_t id_;
std::vector<Frame*> children_;
blink::WebFrame* web_frame_;
blink::WebWidget* web_widget_;
scoped_ptr<WebLayerTreeViewImpl> web_layer_tree_view_impl_;
scoped_ptr<TouchHandler> touch_handler_;
// TODO(sky): better factor this, maybe push to View.
blink::WebTreeScopeType scope_;
base::WeakPtrFactory<Frame> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(Frame);
};
} // namespace html_viewer
#endif // COMPONENTS_HTML_VIEWER_FRAME_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
15ccb280a57d7a46888954ce92fe96e834876b89 | d8adf9b429d441f0cbd593f684d10ca6acb7f51a | /dependencies/boost/interprocess/detail/std_fwd.hpp | c2f66dead64a2a73e75fdfe31f70ef15416d77cf | [
"BSL-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | zzsun777/cpp_multithreaded_order_matching_engine | dd16cda082a316d6f87be34c7355bb2f90d722d4 | a46209bfcac366eab83bd575ebdaa1a3bb93549c | refs/heads/master | 2020-12-11T03:24:28.763708 | 2016-04-10T09:44:29 | 2016-04-10T09:44:29 | 56,605,373 | 28 | 14 | null | 2016-04-19T14:45:07 | 2016-04-19T14:45:06 | null | UTF-8 | C++ | false | false | 2,463 | hpp | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2014-2015. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTERPROCESS_DETAIL_STD_FWD_HPP
#define BOOST_INTERPROCESS_DETAIL_STD_FWD_HPP
#ifndef BOOST_CONFIG_HPP
# include <boost/config.hpp>
#endif
#
#if defined(BOOST_HAS_PRAGMA_ONCE)
# pragma once
#endif
//////////////////////////////////////////////////////////////////////////////
// Standard predeclarations
//////////////////////////////////////////////////////////////////////////////
#if defined(_LIBCPP_VERSION)
#define BOOST_INTERPROCESS_CLANG_INLINE_STD_NS
#pragma GCC diagnostic push
#if defined(__clang__)
#pragma GCC diagnostic ignored "-Wc++11-extensions"
#endif
#define BOOST_INTERPROCESS_STD_NS_BEG _LIBCPP_BEGIN_NAMESPACE_STD
#define BOOST_INTERPROCESS_STD_NS_END _LIBCPP_END_NAMESPACE_STD
#elif defined(BOOST_GNU_STDLIB) && defined(_GLIBCXX_BEGIN_NAMESPACE_VERSION) //GCC >= 4.6
#define BOOST_INTERPROCESS_STD_NS_BEG namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION
#define BOOST_INTERPROCESS_STD_NS_END _GLIBCXX_END_NAMESPACE_VERSION } // namespace
#elif defined(BOOST_GNU_STDLIB) && defined(_GLIBCXX_BEGIN_NAMESPACE) //GCC >= 4.2
#define BOOST_INTERPROCESS_STD_NS_BEG _GLIBCXX_BEGIN_NAMESPACE(std)
#define BOOST_INTERPROCESS_STD_NS_END _GLIBCXX_END_NAMESPACE
#else
#define BOOST_INTERPROCESS_STD_NS_BEG namespace std{
#define BOOST_INTERPROCESS_STD_NS_END }
#endif
BOOST_INTERPROCESS_STD_NS_BEG
struct input_iterator_tag;
struct forward_iterator_tag;
struct bidirectional_iterator_tag;
struct random_access_iterator_tag;
template<class T>
struct char_traits;
template<class CharT, class Traits>
class basic_ostream;
template<class CharT, class Traits>
class basic_istream;
BOOST_INTERPROCESS_STD_NS_END
#ifdef BOOST_INTERPROCESS_CLANG_INLINE_STD_NS
#pragma GCC diagnostic pop
#undef BOOST_INTERPROCESS_CLANG_INLINE_STD_NS
#endif //BOOST_INTERPROCESS_CLANG_INLINE_STD_NS
#endif //#ifndef BOOST_INTERPROCESS_DETAIL_STD_FWD_HPP
| [
"akin_ocal@hotmail.com"
] | akin_ocal@hotmail.com |
d0e925e79401318d433066af074ddc750dfc5b54 | ab01b7cc84d4bc73b176dade1e94f236d256fcb8 | /utilities/USBDevice/USBDevice/USBHAL_STM32F4.cpp | 45aedbb6e1fbdaa5393043c55bae07fc5cf47c25 | [
"Apache-2.0"
] | permissive | h7ga40/PeachCam | 097a0cecabe100c92fb61c63d17455ce22fb397f | 1af2b041a4eb22b962183905ff81a2ee57babc3c | refs/heads/master | 2023-09-05T02:46:02.335574 | 2023-08-07T13:15:22 | 2023-08-07T13:15:22 | 177,606,980 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,353 | cpp | /* Copyright (c) 2010-2011 mbed.org, MIT License
*
* 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.
*/
#if defined(TARGET_STM32F4)
#include "USBHAL.h"
#include "USBRegs_STM32.h"
#include "pinmap.h"
USBHAL * USBHAL::instance;
static volatile int epComplete = 0;
static uint32_t bufferEnd = 0;
static const uint32_t rxFifoSize = 512;
static uint32_t rxFifoCount = 0;
static uint32_t setupBuffer[MAX_PACKET_SIZE_EP0 >> 2];
uint32_t USBHAL::endpointReadcore(uint8_t endpoint, uint8_t *buffer) {
return 0;
}
USBHAL::USBHAL(void) {
NVIC_DisableIRQ(OTG_FS_IRQn);
epCallback[0] = &USBHAL::EP1_OUT_callback;
epCallback[1] = &USBHAL::EP1_IN_callback;
epCallback[2] = &USBHAL::EP2_OUT_callback;
epCallback[3] = &USBHAL::EP2_IN_callback;
epCallback[4] = &USBHAL::EP3_OUT_callback;
epCallback[5] = &USBHAL::EP3_IN_callback;
// Enable power and clocking
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
#if defined(TARGET_STM32F407VG) || defined(TARGET_STM32F401RE) || defined(TARGET_STM32F411RE) || defined(TARGET_STM32F429ZI)
pin_function(PA_8, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF10_OTG_FS));
pin_function(PA_9, STM_PIN_DATA(STM_MODE_INPUT, GPIO_PULLDOWN, GPIO_AF10_OTG_FS));
pin_function(PA_10, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_PULLUP, GPIO_AF10_OTG_FS));
pin_function(PA_11, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF10_OTG_FS));
pin_function(PA_12, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF10_OTG_FS));
#else
pin_function(PA_8, STM_PIN_DATA(2, 10));
pin_function(PA_9, STM_PIN_DATA(0, 0));
pin_function(PA_10, STM_PIN_DATA(2, 10));
pin_function(PA_11, STM_PIN_DATA(2, 10));
pin_function(PA_12, STM_PIN_DATA(2, 10));
// Set ID pin to open drain with pull-up resistor
pin_mode(PA_10, OpenDrain);
GPIOA->PUPDR &= ~(0x3 << 20);
GPIOA->PUPDR |= 1 << 20;
// Set VBUS pin to open drain
pin_mode(PA_9, OpenDrain);
#endif
RCC->AHB2ENR |= RCC_AHB2ENR_OTGFSEN;
// Enable interrupts
OTG_FS->GREGS.GAHBCFG |= (1 << 0);
// Turnaround time to maximum value - too small causes packet loss
OTG_FS->GREGS.GUSBCFG |= (0xF << 10);
// Unmask global interrupts
OTG_FS->GREGS.GINTMSK |= (1 << 3) | // SOF
(1 << 4) | // RX FIFO not empty
(1 << 12); // USB reset
OTG_FS->DREGS.DCFG |= (0x3 << 0) | // Full speed
(1 << 2); // Non-zero-length status OUT handshake
OTG_FS->GREGS.GCCFG |= (1 << 19) | // Enable VBUS sensing
(1 << 16); // Power Up
instance = this;
NVIC_SetVector(OTG_FS_IRQn, (uint32_t)&_usbisr);
NVIC_SetPriority(OTG_FS_IRQn, 1);
}
USBHAL::~USBHAL(void) {
}
void USBHAL::connect(void) {
NVIC_EnableIRQ(OTG_FS_IRQn);
}
void USBHAL::disconnect(void) {
NVIC_DisableIRQ(OTG_FS_IRQn);
}
void USBHAL::configureDevice(void) {
// Not needed
}
void USBHAL::unconfigureDevice(void) {
// Not needed
}
void USBHAL::setAddress(uint8_t address) {
OTG_FS->DREGS.DCFG |= (address << 4);
EP0write(0, 0);
}
bool USBHAL::realiseEndpoint(uint8_t endpoint, uint32_t maxPacket,
uint32_t flags) {
uint32_t epIndex = endpoint >> 1;
uint32_t type;
switch (endpoint) {
case EP0IN:
case EP0OUT:
type = 0;
break;
case EPISO_IN:
case EPISO_OUT:
type = 1;
case EPBULK_IN:
case EPBULK_OUT:
type = 2;
break;
case EPINT_IN:
case EPINT_OUT:
type = 3;
break;
}
// Generic in or out EP controls
uint32_t control = (maxPacket << 0) | // Packet size
(1 << 15) | // Active endpoint
(type << 18); // Endpoint type
if (endpoint & 0x1) { // In Endpoint
// Set up the Tx FIFO
if (endpoint == EP0IN) {
OTG_FS->GREGS.DIEPTXF0_HNPTXFSIZ = ((maxPacket >> 2) << 16) |
(bufferEnd << 0);
}
else {
OTG_FS->GREGS.DIEPTXF[epIndex - 1] = ((maxPacket >> 2) << 16) |
(bufferEnd << 0);
}
bufferEnd += maxPacket >> 2;
// Set the In EP specific control settings
if (endpoint != EP0IN) {
control |= (1 << 28); // SD0PID
}
control |= (epIndex << 22) | // TxFIFO index
(1 << 27); // SNAK
OTG_FS->INEP_REGS[epIndex].DIEPCTL = control;
// Unmask the interrupt
OTG_FS->DREGS.DAINTMSK |= (1 << epIndex);
}
else { // Out endpoint
// Set the out EP specific control settings
control |= (1 << 26); // CNAK
OTG_FS->OUTEP_REGS[epIndex].DOEPCTL = control;
// Unmask the interrupt
OTG_FS->DREGS.DAINTMSK |= (1 << (epIndex + 16));
}
return true;
}
// read setup packet
void USBHAL::EP0setup(uint8_t *buffer) {
memcpy(buffer, setupBuffer, MAX_PACKET_SIZE_EP0);
}
void USBHAL::EP0readStage(void) {
}
void USBHAL::EP0read(void) {
}
uint32_t USBHAL::EP0getReadResult(uint8_t *buffer) {
uint32_t* buffer32 = (uint32_t *) buffer;
uint32_t length = rxFifoCount;
for (uint32_t i = 0; i < length; i += 4) {
buffer32[i >> 2] = OTG_FS->FIFO[0][0];
}
rxFifoCount = 0;
return length;
}
void USBHAL::EP0write(uint8_t *buffer, uint32_t size) {
endpointWrite(0, buffer, size);
}
void USBHAL::EP0getWriteResult(void) {
}
void USBHAL::EP0stall(void) {
// If we stall the out endpoint here then we have problems transferring
// and setup requests after the (stalled) get device qualifier requests.
// TODO: Find out if this is correct behavior, or whether we are doing
// something else wrong
stallEndpoint(EP0IN);
// stallEndpoint(EP0OUT);
}
EP_STATUS USBHAL::endpointRead(uint8_t endpoint, uint32_t maximumSize) {
uint32_t epIndex = endpoint >> 1;
uint32_t size = (1 << 19) | // 1 packet
(maximumSize << 0); // Packet size
// if (endpoint == EP0OUT) {
size |= (1 << 29); // 1 setup packet
// }
OTG_FS->OUTEP_REGS[epIndex].DOEPTSIZ = size;
OTG_FS->OUTEP_REGS[epIndex].DOEPCTL |= (1 << 31) | // Enable endpoint
(1 << 26); // Clear NAK
epComplete &= ~(1 << endpoint);
return EP_PENDING;
}
EP_STATUS USBHAL::endpointReadResult(uint8_t endpoint, uint8_t * buffer, uint32_t *bytesRead) {
if (!(epComplete & (1 << endpoint))) {
return EP_PENDING;
}
uint32_t* buffer32 = (uint32_t *) buffer;
uint32_t length = rxFifoCount;
for (uint32_t i = 0; i < length; i += 4) {
buffer32[i >> 2] = OTG_FS->FIFO[endpoint >> 1][0];
}
rxFifoCount = 0;
*bytesRead = length;
return EP_COMPLETED;
}
EP_STATUS USBHAL::endpointWrite(uint8_t endpoint, uint8_t *data, uint32_t size) {
uint32_t epIndex = endpoint >> 1;
OTG_FS->INEP_REGS[epIndex].DIEPTSIZ = (1 << 19) | // 1 packet
(size << 0); // Size of packet
OTG_FS->INEP_REGS[epIndex].DIEPCTL |= (1 << 31) | // Enable endpoint
(1 << 26); // CNAK
OTG_FS->DREGS.DIEPEMPMSK = (1 << epIndex);
while ((OTG_FS->INEP_REGS[epIndex].DTXFSTS & 0XFFFF) < ((size + 3) >> 2));
for (uint32_t i=0; i<(size + 3) >> 2; i++, data+=4) {
OTG_FS->FIFO[epIndex][0] = *(uint32_t *)data;
}
epComplete &= ~(1 << endpoint);
return EP_PENDING;
}
EP_STATUS USBHAL::endpointWriteResult(uint8_t endpoint) {
if (epComplete & (1 << endpoint)) {
epComplete &= ~(1 << endpoint);
return EP_COMPLETED;
}
return EP_PENDING;
}
void USBHAL::stallEndpoint(uint8_t endpoint) {
if (endpoint & 0x1) { // In EP
OTG_FS->INEP_REGS[endpoint >> 1].DIEPCTL |= (1 << 30) | // Disable
(1 << 21); // Stall
}
else { // Out EP
OTG_FS->DREGS.DCTL |= (1 << 9); // Set global out NAK
OTG_FS->OUTEP_REGS[endpoint >> 1].DOEPCTL |= (1 << 30) | // Disable
(1 << 21); // Stall
}
}
void USBHAL::unstallEndpoint(uint8_t endpoint) {
}
bool USBHAL::getEndpointStallState(uint8_t endpoint) {
return false;
}
void USBHAL::remoteWakeup(void) {
}
void USBHAL::_usbisr(void) {
instance->usbisr();
}
void USBHAL::usbisr(void) {
if (OTG_FS->GREGS.GINTSTS & (1 << 11)) { // USB Suspend
suspendStateChanged(1);
};
if (OTG_FS->GREGS.GINTSTS & (1 << 12)) { // USB Reset
suspendStateChanged(0);
// Set SNAK bits
OTG_FS->OUTEP_REGS[0].DOEPCTL |= (1 << 27);
OTG_FS->OUTEP_REGS[1].DOEPCTL |= (1 << 27);
OTG_FS->OUTEP_REGS[2].DOEPCTL |= (1 << 27);
OTG_FS->OUTEP_REGS[3].DOEPCTL |= (1 << 27);
OTG_FS->DREGS.DIEPMSK = (1 << 0);
bufferEnd = 0;
// Set the receive FIFO size
OTG_FS->GREGS.GRXFSIZ = rxFifoSize >> 2;
bufferEnd += rxFifoSize >> 2;
// Create the endpoints, and wait for setup packets on out EP0
realiseEndpoint(EP0IN, MAX_PACKET_SIZE_EP0, 0);
realiseEndpoint(EP0OUT, MAX_PACKET_SIZE_EP0, 0);
endpointRead(EP0OUT, MAX_PACKET_SIZE_EP0);
OTG_FS->GREGS.GINTSTS = (1 << 12);
}
if (OTG_FS->GREGS.GINTSTS & (1 << 4)) { // RX FIFO not empty
uint32_t status = OTG_FS->GREGS.GRXSTSP;
uint32_t endpoint = (status & 0xF) << 1;
uint32_t length = (status >> 4) & 0x7FF;
uint32_t type = (status >> 17) & 0xF;
rxFifoCount = length;
if (type == 0x6) {
// Setup packet
for (uint32_t i=0; i<length; i+=4) {
setupBuffer[i >> 2] = OTG_FS->FIFO[0][i >> 2];
}
rxFifoCount = 0;
}
if (type == 0x4) {
// Setup complete
EP0setupCallback();
endpointRead(EP0OUT, MAX_PACKET_SIZE_EP0);
}
if (type == 0x2) {
// Out packet
if (endpoint == EP0OUT) {
EP0out();
}
else {
epComplete |= (1 << endpoint);
if ((instance->*(epCallback[endpoint - 2]))()) {
epComplete &= (1 << endpoint);
}
}
}
for (uint32_t i=0; i<rxFifoCount; i+=4) {
(void) OTG_FS->FIFO[0][0];
}
OTG_FS->GREGS.GINTSTS = (1 << 4);
}
if (OTG_FS->GREGS.GINTSTS & (1 << 18)) { // In endpoint interrupt
// Loop through the in endpoints
for (uint32_t i=0; i<4; i++) {
if (OTG_FS->DREGS.DAINT & (1 << i)) { // Interrupt is on endpoint
if (OTG_FS->INEP_REGS[i].DIEPINT & (1 << 7)) {// Tx FIFO empty
// If the Tx FIFO is empty on EP0 we need to send a further
// packet, so call EP0in()
if (i == 0) {
EP0in();
}
// Clear the interrupt
OTG_FS->INEP_REGS[i].DIEPINT = (1 << 7);
// Stop firing Tx empty interrupts
// Will get turned on again if another write is called
OTG_FS->DREGS.DIEPEMPMSK &= ~(1 << i);
}
// If the transfer is complete
if (OTG_FS->INEP_REGS[i].DIEPINT & (1 << 0)) { // Tx Complete
epComplete |= (1 << (1 + (i << 1)));
OTG_FS->INEP_REGS[i].DIEPINT = (1 << 0);
}
}
}
OTG_FS->GREGS.GINTSTS = (1 << 18);
}
if (OTG_FS->GREGS.GINTSTS & (1 << 3)) { // Start of frame
SOF((OTG_FS->GREGS.GRXSTSR >> 17) & 0xF);
OTG_FS->GREGS.GINTSTS = (1 << 3);
}
}
#endif
| [
"hi6aki_7ga40@hotmail.com"
] | hi6aki_7ga40@hotmail.com |
07242f11a83e272c3ba870783c72deae5e30e46f | 5c460ed773268b5b10c56e795fcfd11bc9c86880 | /Include/TeamMock.hpp | 181306f04dbbe7d63d1f552c8dc60622239b4514 | [] | no_license | qianyubl/Car_racing_dojo | 60167cc7bb0e4d77de21311072f098baed9c72f5 | c893cf4fc485cc4869550e1f6b7b4a4cb22e0c42 | refs/heads/master | 2021-01-19T19:05:52.808812 | 2017-05-02T11:22:21 | 2017-05-02T11:22:21 | 86,648,940 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 218 | hpp | #include "ITeam.hpp"
class TeamMock : public ITeam
{
public:
MOCK_CONST_METHOD0(getCar, const ICar*());
MOCK_CONST_METHOD0(getId, int());
MOCK_CONST_METHOD0(getQualificationTime, float());
};
| [
"longjourney123@gmail.com"
] | longjourney123@gmail.com |
b165582d9efc04fbbbea2e7b631809733379564e | 6b68b51c3745d9c8de701dca4db403ba4a73ed54 | /crosbot_ogmbicp/src/main.cpp | 7e340fc64c89ff0136fd81a176e44fac06324db4 | [] | no_license | Forrest-Z/rsa-crosbot | 3b9fd1a8074b2bdc5dcdac08c2bac5d999599055 | e539b418b850132d92a8369826961e7280d4f960 | refs/heads/master | 2020-06-06T21:58:17.428140 | 2016-10-30T00:55:53 | 2016-10-30T00:55:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | cpp | /*
* main.cpp
*
* Created on: 12/9/2013
* Author: adrianr
*/
#include <ros/ros.h>
#include <crosbot_ogmbicp/OgmbicpNode.hpp>
#include <crosbot_ogmbicp/OgmbicpCPU.hpp>
int main(int argc, char **argv) {
ros::init(argc, argv, "ogmbicp");
ros::NodeHandle nh;
OgmbicpCPU posTracker;
OgmbicpNode node(posTracker);
node.initialise(nh);
while (ros::ok()) {
ros::spin();
}
node.shutdown();
return 0;
}
| [
"adrianrobolab@bugs.(none)"
] | adrianrobolab@bugs.(none) |
f1bbc9901cea4e1aacdcce508d51ca0403b47a8a | 8aba3f91a7d25a8cc5ae5eec5883c51300d9b204 | /Maximum-Subarray-Sum.cpp | 754a0025c8f0a607a37ea049089ada7a2a1342fe | [] | no_license | ShallowFeather/CSES | f452e6f8a4fc282c150da36fc03be2901c9599c4 | 35e94c4748fbb2130503fb21e12f36740e6cdf02 | refs/heads/main | 2023-04-25T04:12:11.491732 | 2021-05-17T06:06:17 | 2021-05-17T06:06:17 | 357,305,982 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
long long n;
cin >> n;
long long ans = INT_MIN, now = 0;
for(int i = 0; i < n; i++){
long long a;
cin >> a;
now += a;
if( now < 0 ) now = 0;
if(ans > 0)
ans = max(now, ans);
else {
ans = max(a, ans);
}
}
cout << ans << '\n';
}
| [
"74778927+ShallowFeather@users.noreply.github.com"
] | 74778927+ShallowFeather@users.noreply.github.com |
5269d26c395bf573217e34695428d0330393cba3 | 15d245e6934c6a940c55dd4d3278c7cb6b0248fd | /include/udp_server.hpp | 769b4b4d4826e9ffdd1e2461228b49f2193e0b33 | [] | no_license | PetroShevchenko/udp-dtls-example | 1f6453e56e816f3ba57b3f0d2937e2b51b8d9ea6 | 30618b5fb85c8cc50b4cfd50b3246acdb23a9366 | refs/heads/master | 2023-05-27T23:47:30.843695 | 2021-06-13T12:04:41 | 2021-06-13T12:04:41 | 205,551,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,371 | hpp | #ifndef UDP_SERVER_HPP
#define UDP_SERVER_HPP
#include <string>
#include <cstdint>
#include <cstdbool>
#include "udp_error.hpp"
#include "config.h"
#ifdef USE_WOLFSSL
#include <wolfssl/options.h>
#include <wolfssl/ssl.h>
#include <netdb.h>
#include <string>
#endif
class udp_server {
public:
udp_server(std::string _addr, int _port);
~udp_server();
void run();
protected:
virtual void step();
udp_error error;
int sock;
int port;
std::string addr;
struct sockaddr_in * client_address;
struct sockaddr_in * server_address;
//struct addrinfo * addrinfo;
uint8_t * buffer;
size_t length;
int state;
bool do_receive;
bool do_send;
bool do_stop;
unsigned char receive_timeout;
bool is_encripted;
#ifdef USE_WOLFSSL
WOLFSSL_CTX* ctx;
WOLFSSL * ssl;
std::string caCertLoc;
std::string servCertLoc;
std::string servKeyLoc;
#endif
private:
#ifdef USE_WOLFSSL
inline void dtls_client_hello_receive_step();
inline void dtls_connect_step();
inline void dtls_handshake_step();
inline void dtls_error_handle_step();
#endif
inline void client_hello_receive_step();
inline void client_hello_ack_step();
inline void server_hello_send_step();
inline void server_hello_ack_step();
};
#endif//UDP_SERVER__HPP
| [
"shevchenko.p.i@gmail.com"
] | shevchenko.p.i@gmail.com |
922d974e3c0338be083da7a75660fa7c3ec8627a | 6d96b4cd66cf2c6dce0ca8c0bf6f665ee0945c9e | /GLFW Application/ResourceHandle.h | 3a0c75621adba29e9d8f1c817b5a564c5fd8b1b8 | [] | no_license | ravkot/MiraiEngine | 6d8314e9efe523561617803006a8008ba6bc3fea | b9bfc166f0798dc065f9fde1e6d6eda22059d723 | refs/heads/master | 2021-09-02T21:52:50.778696 | 2018-01-03T23:20:07 | 2018-01-03T23:20:07 | 116,186,322 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 297 | h | #pragma once
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include "Serializable.h"
namespace GLFW
{
class Resource : public Serializable
{
protected:
friend class ResourceManager;
public:
Resource();
~Resource();
virtual std::string getSource();
};
}
| [
"ravkot7@gmail.com"
] | ravkot7@gmail.com |
2cd28ec2a87e843ccf5765466c6e2e2622b33f12 | 7c7ca9efe5869a805a3c5238425be185758a71ce | /marsksim/uwpproj/uwpStnCallback.cpp | 28bf38010176d9b798e1e62ecc5470c495880c4b | [] | no_license | cansou/MyCustomMars | f332e6a1332eed9184838200d21cd36f5b57d3c9 | fb62f268a1913a70c39df329ef39df6034baac60 | refs/heads/master | 2022-10-20T18:53:22.220235 | 2020-06-12T08:46:25 | 2020-06-12T08:46:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,224 | cpp | #include "uwpStnCallback.h"
#include "runtime2cs.h"
#include "runtime_utils.h"
using namespace marsksim;
Platform::Array<uint8>^ bufferToPlatformArray(const AutoBuffer & autoBuffer)
{
const void * buffer = autoBuffer.Ptr();
int iLen = autoBuffer.Length();
if (buffer == nullptr)
return ref new Platform::Array<uint8>(0);
Platform::Array<uint8>^ arrayBuffer = ref new Platform::Array<uint8>(iLen);
uint8 * ptr = (uint8*)buffer;
for (int i = 0; i< iLen; i++)
{
arrayBuffer[i] = ptr[i];
}
return arrayBuffer;
}
bool appendPlatfomrBufferToAutoBuffer(AutoBuffer& autoBuffer, Platform::Array<uint8>^ platformBuffer)
{
if (platformBuffer == nullptr || platformBuffer->Length <= 0)
{
return false;
}
if (autoBuffer.Capacity() < (size_t)platformBuffer->Length)
{
autoBuffer.AddCapacity(platformBuffer->Length);
}
autoBuffer.Write(platformBuffer->Data, platformBuffer->Length);
return true;
}
bool uwpStnCallback::MakesureAuthed()
{
ICallback_Comm^ callback = Runtime2Cs_Comm::Singletonksim()->GetCallBack();
if (nullptr == callback)
{
return false;
}
return callback->MakesureAuthed();
}
void uwpStnCallback::TrafficData(ssize_t _send, ssize_t _recv)
{
}
std::vector<std::string> uwpStnCallback::OnNewDns(const std::string& host)
{
ICallback_Comm^ callback = Runtime2Cs_Comm::Singletonksim()->GetCallBack();
std::vector<std::string> iplist;
if (nullptr == callback)
{
return iplist;
}
Platform::Array<Platform::String^>^ list = callback->OnNewDns(stdstring2String(host));
for each (Platform::String^ cstring in list)
{
std::string tmp = String2stdstring(cstring);
if (tmp.length() > 0)
{
iplist.push_back(tmp);
}
}
return iplist;
}
void uwpStnCallback::OnPush(int32_t cmdid, const AutoBuffer & msgpayload)
{
ICallback_Comm^ callback = Runtime2Cs_Comm::Singletonksim()->GetCallBack();
if (nullptr == callback)
{
return;
}
Platform::Array<uint8>^ buffer = bufferToPlatformArray(msgpayload);
callback->OnPush(cmdid, buffer);
}
bool uwpStnCallback::Req2Buf(int32_t taskid, void * const user_context, AutoBuffer & outbuffer, int & error_code, const int channel_select)
{
ICallback_Comm^ callback = Runtime2Cs_Comm::Singletonksim()->GetCallBack();
if (nullptr == callback)
{
return false;
}
Req2BufRet^ retInfo = callback->Req2Buf(taskid, (int)user_context, error_code, channel_select);
error_code = retInfo->nErrCode;
appendPlatfomrBufferToAutoBuffer(outbuffer, retInfo->outbuffer);
return retInfo->bRet;
}
int uwpStnCallback::Buf2Resp(int32_t taskid, void * const user_context, const AutoBuffer & inbuffer, int & error_code, const int channel_select)
{
ICallback_Comm^ callback = Runtime2Cs_Comm::Singletonksim()->GetCallBack();
if (nullptr == callback)
{
return 0;
}
Platform::Array<uint8>^ buffer = bufferToPlatformArray(inbuffer);
Buf2RespRet^ retInfo = callback->Buf2Resp(taskid, (int)user_context, buffer, error_code, channel_select);
error_code = retInfo->nErrCode;
return retInfo->bRet;
}
int uwpStnCallback::OnTaskEnd(int32_t taskid, void * const user_context, int error_type, int error_code)
{
ICallback_Comm^ callback = Runtime2Cs_Comm::Singletonksim()->GetCallBack();
if (nullptr == callback)
{
return 0;
}
return callback->OnTaskEnd(taskid, (int)user_context, error_type, error_code);
}
void uwpStnCallback::ReportConnectStatus(int status, int longlink_status)
{
ICallback_Comm^ callback = Runtime2Cs_Comm::Singletonksim()->GetCallBack();
if (nullptr == callback)
{
return;
}
callback->ReportConnectStatus(status, longlink_status);
}
int uwpStnCallback::GetLonglinkIdentifyCheckBuffer(AutoBuffer & identify_buffer, AutoBuffer & buffer_hash, int32_t & cmdid)
{
ICallback_Comm^ callback = Runtime2Cs_Comm::Singletonksim()->GetCallBack();
if (nullptr == callback)
{
return false;
}
GetLonglinkIdentifyRet^ retInfo = callback->GetLonglinkIdentifyCheckBuffer();
cmdid = retInfo->cmdid;
appendPlatfomrBufferToAutoBuffer(identify_buffer, retInfo->identify_buffer);
appendPlatfomrBufferToAutoBuffer(buffer_hash, retInfo->buffer_hash);
return (int)(retInfo->nRet);
}
bool uwpStnCallback::OnLonglinkIdentifyResponse(const AutoBuffer & response_buffer, const AutoBuffer & identify_buffer_hash)
{
ICallback_Comm^ callback = Runtime2Cs_Comm::Singletonksim()->GetCallBack();
if (nullptr == callback)
{
return false;
}
Platform::Array<uint8>^ platBufferResponse = bufferToPlatformArray(response_buffer);
Platform::Array<uint8>^ platBufferHash = bufferToPlatformArray(identify_buffer_hash);
return callback->OnLonglinkIdentifyResponse(platBufferResponse, platBufferHash);
}
void uwpStnCallback::RequestSync()
{
ICallback_Comm^ callback = Runtime2Cs_Comm::Singletonksim()->GetCallBack();
if (nullptr == callback)
{
return;
}
callback->RequestSync();
}
bool uwpStnCallback::IsLogoned()
{
ICallback_Comm^ callback = Runtime2Cs_Comm::Singletonksim()->GetCallBack();
if (nullptr == callback)
{
return false;
}
return callback->IsLogoned();
}
| [
""
] | |
4980346a067f0101a5f655f6a5befdc838a5c59e | 33fd5786ddde55a705d74ce2ce909017e2535065 | /build/iOS/Debug/src/Fuse.Controls.VideoImpl.g.cpp | 9f35c09bd966af82a3282ab2e6813b316aaa99d7 | [] | no_license | frpaulas/iphodfuse | 04cee30add8b50ea134eb5a83e355dce886a5d5a | e8886638c4466b3b0c6299da24156d4ee81c9112 | refs/heads/master | 2021-01-23T00:48:31.195577 | 2017-06-01T12:33:13 | 2017-06-01T12:33:13 | 92,842,106 | 3 | 3 | null | 2017-05-30T17:43:28 | 2017-05-30T14:33:26 | C++ | UTF-8 | C++ | false | false | 91,375 | cpp | // This file was generated based on '(multiple files)'.
// WARNING: Changes might be lost if you edit this file directly.
#include <_root.FuseControlsVideo_bundle.h>
#include <Fuse.Controls.Graphics.Visual.h>
#include <Fuse.Controls.VideoIm-28d4de69.h>
#include <Fuse.Controls.VideoIm-4d990014.h>
#include <Fuse.Controls.VideoIm-72c895ca.h>
#include <Fuse.Controls.VideoIm-7b2eaac1.h>
#include <Fuse.Controls.VideoIm-7c15c6f7.h>
#include <Fuse.Controls.VideoIm-aeb6ffae.h>
#include <Fuse.Controls.VideoIm-aee99c23.h>
#include <Fuse.Controls.VideoIm-b5ceac8f.h>
#include <Fuse.Controls.VideoIm-bfe06558.h>
#include <Fuse.Controls.VideoIm-c1aafe14.h>
#include <Fuse.Controls.VideoIm-e232fc69.h>
#include <Fuse.Controls.VideoIm-f0b495bd.h>
#include <Fuse.Diagnostics.h>
#include <Fuse.DrawContext.h>
#include <Fuse.Elements.Alignment.h>
#include <Fuse.Elements.StretchDirection.h>
#include <Fuse.Elements.StretchMode.h>
#include <Fuse.Elements.StretchSizing.h>
#include <Fuse.HitTestContext.h>
#include <Fuse.Internal.SizingContainer.h>
#include <Fuse.InvalidateLayoutReason.h>
#include <Fuse.IRenderViewport.h>
#include <Fuse.LayoutParams.h>
#include <Fuse.Platform.ApplicationState.h>
#include <Fuse.Platform.Lifecycle.h>
#include <Fuse.Triggers.BusyTask.h>
#include <Fuse.Triggers.BusyTaskActivity.h>
#include <Fuse.Triggers.WhileCompleted.h>
#include <Fuse.Triggers.WhilePaused.h>
#include <Fuse.Triggers.WhilePlaying.h>
#include <Fuse.UpdateManager.h>
#include <Fuse.UpdateStage.h>
#include <Fuse.Visual.h>
#include <Uno.Action.h>
#include <Uno.Action-1.h>
#include <Uno.Bool.h>
#include <Uno.Buffer.h>
#include <Uno.Byte.h>
#include <Uno.Char.h>
#include <Uno.Collections.Dicti-d1699346.h>
#include <Uno.Collections.Dictionary-2.h>
#include <Uno.Collections.KeyValuePair-2.h>
#include <Uno.Delegate.h>
#include <Uno.Diagnostics.Debug.h>
#include <Uno.Diagnostics.Debug-5d778620.h>
#include <Uno.Double.h>
#include <Uno.EventArgs.h>
#include <Uno.EventHandler.h>
#include <Uno.EventHandler-1.h>
#include <Uno.Exception.h>
#include <Uno.Float.h>
#include <Uno.Float2.h>
#include <Uno.Float3.h>
#include <Uno.Float4.h>
#include <Uno.Float4x4.h>
#include <Uno.Graphics.BlendOperand.h>
#include <Uno.Graphics.BufferUsage.h>
#include <Uno.Graphics.IndexBuffer.h>
#include <Uno.Graphics.IndexType.h>
#include <Uno.Graphics.PolygonFace.h>
#include <Uno.Graphics.SamplerState.h>
#include <Uno.Graphics.VertexAt-4a875e1d.h>
#include <Uno.Graphics.VertexBuffer.h>
#include <Uno.Graphics.VideoTexture.h>
#include <Uno.Int.h>
#include <Uno.Int2.h>
#include <Uno.IO.Directory.h>
#include <Uno.IO.File.h>
#include <Uno.IO.UserDirectory.h>
#include <Uno.Math.h>
#include <Uno.Matrix.h>
#include <Uno.Object.h>
#include <Uno.Runtime.Implement-6e9df330.h>
#include <Uno.Runtime.Implement-81e7ab4c.h>
#include <Uno.String.h>
#include <Uno.Threading.Future.h>
#include <Uno.Threading.Future-1.h>
#include <Uno.UShort.h>
#include <Uno.UX.FileSource.h>
#include <Uno.UX.ValueChangedArgs-1.h>
#include <Uno.UX.ValueChangedHandler-1.h>
static uString* STRINGS[11];
static uType* TYPES[24];
namespace g{
namespace Fuse{
namespace Controls{
namespace VideoImpl{
// /Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno
// ---------------------------------------------------------------------------------------------------
// internal sealed class EmptyVideo :32
// {
static void EmptyVideo_build(uType* type)
{
type->SetInterfaces(
::g::Fuse::Controls::VideoImpl::IVideoPlayer_typeof(), offsetof(EmptyVideo_type, interface0),
::g::Uno::IDisposable_typeof(), offsetof(EmptyVideo_type, interface1));
}
EmptyVideo_type* EmptyVideo_typeof()
{
static uSStrong<EmptyVideo_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.InterfaceCount = 2;
options.ObjectSize = sizeof(EmptyVideo);
options.TypeSize = sizeof(EmptyVideo_type);
type = (EmptyVideo_type*)uClassType::New("Fuse.Controls.VideoImpl.EmptyVideo", options);
type->fp_build_ = EmptyVideo_build;
type->fp_ctor_ = (void*)EmptyVideo__New1_fn;
type->interface1.fp_Dispose = (void(*)(uObject*))EmptyVideo__UnoIDisposableDispose_fn;
type->interface0.fp_Pause = (void(*)(uObject*))EmptyVideo__FuseControlsVideoImplIVideoPlayerPause_fn;
type->interface0.fp_Play = (void(*)(uObject*))EmptyVideo__FuseControlsVideoImplIVideoPlayerPlay_fn;
type->interface0.fp_Update = (void(*)(uObject*))EmptyVideo__FuseControlsVideoImplIVideoPlayerUpdate_fn;
type->interface0.fp_get_Duration = (void(*)(uObject*, double*))EmptyVideo__FuseControlsVideoImplIVideoPlayerget_Duration_fn;
type->interface0.fp_get_Position = (void(*)(uObject*, double*))EmptyVideo__FuseControlsVideoImplIVideoPlayerget_Position_fn;
type->interface0.fp_set_Position = (void(*)(uObject*, double*))EmptyVideo__FuseControlsVideoImplIVideoPlayerset_Position_fn;
type->interface0.fp_get_Volume = (void(*)(uObject*, float*))EmptyVideo__FuseControlsVideoImplIVideoPlayerget_Volume_fn;
type->interface0.fp_set_Volume = (void(*)(uObject*, float*))EmptyVideo__FuseControlsVideoImplIVideoPlayerset_Volume_fn;
type->interface0.fp_get_Size = (void(*)(uObject*, ::g::Uno::Int2*))EmptyVideo__FuseControlsVideoImplIVideoPlayerget_Size_fn;
type->interface0.fp_get_RotationDegrees = (void(*)(uObject*, int*))EmptyVideo__FuseControlsVideoImplIVideoPlayerget_RotationDegrees_fn;
type->interface0.fp_get_VideoTexture = (void(*)(uObject*, ::g::Uno::Graphics::VideoTexture**))EmptyVideo__FuseControlsVideoImplIVideoPlayerget_VideoTexture_fn;
type->interface0.fp_add_FrameAvailable = (void(*)(uObject*, uDelegate*))EmptyVideo__FuseControlsVideoImplIVideoPlayeradd_FrameAvailable_fn;
type->interface0.fp_remove_FrameAvailable = (void(*)(uObject*, uDelegate*))EmptyVideo__FuseControlsVideoImplIVideoPlayerremove_FrameAvailable_fn;
type->interface0.fp_add_ErrorOccurred = (void(*)(uObject*, uDelegate*))EmptyVideo__FuseControlsVideoImplIVideoPlayeradd_ErrorOccurred_fn;
type->interface0.fp_remove_ErrorOccurred = (void(*)(uObject*, uDelegate*))EmptyVideo__FuseControlsVideoImplIVideoPlayerremove_ErrorOccurred_fn;
return type;
}
// public generated EmptyVideo() :32
void EmptyVideo__ctor__fn(EmptyVideo* __this)
{
__this->ctor_();
}
// private double Fuse.Controls.VideoImpl.IVideoPlayer.get_Duration() :34
void EmptyVideo__FuseControlsVideoImplIVideoPlayerget_Duration_fn(EmptyVideo* __this, double* __retval)
{
return *__retval = 0.0, void();
}
// private void Fuse.Controls.VideoImpl.IVideoPlayer.add_ErrorOccurred(Uno.EventHandler<Uno.Exception> value) :37
void EmptyVideo__FuseControlsVideoImplIVideoPlayeradd_ErrorOccurred_fn(EmptyVideo* __this, uDelegate* value)
{
}
// private void Fuse.Controls.VideoImpl.IVideoPlayer.remove_ErrorOccurred(Uno.EventHandler<Uno.Exception> value) :37
void EmptyVideo__FuseControlsVideoImplIVideoPlayerremove_ErrorOccurred_fn(EmptyVideo* __this, uDelegate* value)
{
}
// private void Fuse.Controls.VideoImpl.IVideoPlayer.add_FrameAvailable(Uno.EventHandler value) :36
void EmptyVideo__FuseControlsVideoImplIVideoPlayeradd_FrameAvailable_fn(EmptyVideo* __this, uDelegate* value)
{
}
// private void Fuse.Controls.VideoImpl.IVideoPlayer.remove_FrameAvailable(Uno.EventHandler value) :36
void EmptyVideo__FuseControlsVideoImplIVideoPlayerremove_FrameAvailable_fn(EmptyVideo* __this, uDelegate* value)
{
}
// private void Fuse.Controls.VideoImpl.IVideoPlayer.Pause() :43
void EmptyVideo__FuseControlsVideoImplIVideoPlayerPause_fn(EmptyVideo* __this)
{
}
// private void Fuse.Controls.VideoImpl.IVideoPlayer.Play() :44
void EmptyVideo__FuseControlsVideoImplIVideoPlayerPlay_fn(EmptyVideo* __this)
{
}
// private double Fuse.Controls.VideoImpl.IVideoPlayer.get_Position() :35
void EmptyVideo__FuseControlsVideoImplIVideoPlayerget_Position_fn(EmptyVideo* __this, double* __retval)
{
return *__retval = 0.0, void();
}
// private void Fuse.Controls.VideoImpl.IVideoPlayer.set_Position(double value) :35
void EmptyVideo__FuseControlsVideoImplIVideoPlayerset_Position_fn(EmptyVideo* __this, double* value)
{
}
// private int Fuse.Controls.VideoImpl.IVideoPlayer.get_RotationDegrees() :40
void EmptyVideo__FuseControlsVideoImplIVideoPlayerget_RotationDegrees_fn(EmptyVideo* __this, int* __retval)
{
return *__retval = 0, void();
}
// private int2 Fuse.Controls.VideoImpl.IVideoPlayer.get_Size() :39
void EmptyVideo__FuseControlsVideoImplIVideoPlayerget_Size_fn(EmptyVideo* __this, ::g::Uno::Int2* __retval)
{
return *__retval = ::g::Uno::Int2__New1(0), void();
}
// private void Fuse.Controls.VideoImpl.IVideoPlayer.Update() :45
void EmptyVideo__FuseControlsVideoImplIVideoPlayerUpdate_fn(EmptyVideo* __this)
{
}
// private Uno.Graphics.VideoTexture Fuse.Controls.VideoImpl.IVideoPlayer.get_VideoTexture() :41
void EmptyVideo__FuseControlsVideoImplIVideoPlayerget_VideoTexture_fn(EmptyVideo* __this, ::g::Uno::Graphics::VideoTexture** __retval)
{
return *__retval = NULL, void();
}
// private float Fuse.Controls.VideoImpl.IVideoPlayer.get_Volume() :38
void EmptyVideo__FuseControlsVideoImplIVideoPlayerget_Volume_fn(EmptyVideo* __this, float* __retval)
{
return *__retval = 0.0f, void();
}
// private void Fuse.Controls.VideoImpl.IVideoPlayer.set_Volume(float value) :38
void EmptyVideo__FuseControlsVideoImplIVideoPlayerset_Volume_fn(EmptyVideo* __this, float* value)
{
}
// public generated EmptyVideo New() :32
void EmptyVideo__New1_fn(EmptyVideo** __retval)
{
*__retval = EmptyVideo::New1();
}
// private void Uno.IDisposable.Dispose() :42
void EmptyVideo__UnoIDisposableDispose_fn(EmptyVideo* __this)
{
}
// public generated EmptyVideo() [instance] :32
void EmptyVideo::ctor_()
{
}
// public generated EmptyVideo New() [static] :32
EmptyVideo* EmptyVideo::New1()
{
EmptyVideo* obj1 = (EmptyVideo*)uNew(EmptyVideo_typeof());
obj1->ctor_();
return obj1;
}
// }
// /Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno
// ---------------------------------------------------------------------------------------------------
// internal sealed class GraphicsVideoService :677
// {
// static GraphicsVideoService() :677
static void GraphicsVideoService__cctor__fn(uType* __type)
{
GraphicsVideoService::CompletionTimeThreshold_ = 0.05f;
}
static void GraphicsVideoService_build(uType* type)
{
::TYPES[0] = ::g::Uno::Exception_typeof();
::TYPES[1] = ::g::Uno::Action1_typeof()->MakeType(::g::Fuse::Controls::VideoImpl::IVideoPlayer_typeof(), NULL);
::TYPES[2] = ::g::Uno::Action1_typeof()->MakeType(::TYPES[0/*Uno.Exception*/], NULL);
::TYPES[3] = ::g::Fuse::Controls::VideoImpl::IVideoCallbacks_typeof();
::TYPES[4] = ::g::Fuse::Controls::VideoImpl::IVideoPlayer_typeof();
::TYPES[5] = ::g::Uno::EventHandler_typeof();
::TYPES[6] = ::g::Uno::EventHandler1_typeof()->MakeType(::TYPES[0/*Uno.Exception*/], NULL);
::TYPES[7] = ::g::Uno::IDisposable_typeof();
type->SetInterfaces(
::g::Fuse::Controls::VideoImpl::IVideoService_typeof(), offsetof(GraphicsVideoService_type, interface0),
::TYPES[7/*Uno.IDisposable*/], offsetof(GraphicsVideoService_type, interface1));
type->SetFields(0,
::g::Uno::Bool_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::GraphicsVideoService, _autoPlay), 0,
::TYPES[3/*Fuse.Controls.VideoImpl.IVideoCallbacks*/], offsetof(::g::Fuse::Controls::VideoImpl::GraphicsVideoService, _callbacks), 0,
::g::Uno::Double_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::GraphicsVideoService, _durationCache), 0,
::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/], offsetof(::g::Fuse::Controls::VideoImpl::GraphicsVideoService, _empty), 0,
::g::Uno::Bool_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::GraphicsVideoService, _isLooping), 0,
::TYPES[7/*Uno.IDisposable*/], offsetof(::g::Fuse::Controls::VideoImpl::GraphicsVideoService, _loading), 0,
::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/], offsetof(::g::Fuse::Controls::VideoImpl::GraphicsVideoService, _player), 0,
::g::Uno::Int_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::GraphicsVideoService, _rotationCache), 0,
::g::Uno::Int2_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::GraphicsVideoService, _sizeCache), 0,
::g::Uno::Float_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::GraphicsVideoService, _volume), 0,
::g::Uno::Float_typeof(), (uintptr_t)&::g::Fuse::Controls::VideoImpl::GraphicsVideoService::CompletionTimeThreshold_, uFieldFlagsStatic);
}
GraphicsVideoService_type* GraphicsVideoService_typeof()
{
static uSStrong<GraphicsVideoService_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.FieldCount = 11;
options.InterfaceCount = 2;
options.ObjectSize = sizeof(GraphicsVideoService);
options.TypeSize = sizeof(GraphicsVideoService_type);
type = (GraphicsVideoService_type*)uClassType::New("Fuse.Controls.VideoImpl.GraphicsVideoService", options);
type->fp_build_ = GraphicsVideoService_build;
type->fp_cctor_ = GraphicsVideoService__cctor__fn;
type->interface0.fp_Play = (void(*)(uObject*))GraphicsVideoService__FuseControlsVideoImplIVideoServicePlay_fn;
type->interface0.fp_Pause = (void(*)(uObject*))GraphicsVideoService__FuseControlsVideoImplIVideoServicePause_fn;
type->interface0.fp_Load = (void(*)(uObject*, uString*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceLoad_fn;
type->interface0.fp_Load1 = (void(*)(uObject*, ::g::Uno::UX::FileSource*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceLoad1_fn;
type->interface0.fp_Update = (void(*)(uObject*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceUpdate_fn;
type->interface0.fp_Unload = (void(*)(uObject*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceUnload_fn;
type->interface1.fp_Dispose = (void(*)(uObject*))GraphicsVideoService__UnoIDisposableDispose_fn;
type->interface0.fp_get_Duration = (void(*)(uObject*, double*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_Duration_fn;
type->interface0.fp_get_Size = (void(*)(uObject*, ::g::Uno::Int2*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_Size_fn;
type->interface0.fp_get_VideoTexture = (void(*)(uObject*, ::g::Uno::Graphics::VideoTexture**))GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_VideoTexture_fn;
type->interface0.fp_set_Volume = (void(*)(uObject*, float*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_Volume_fn;
type->interface0.fp_get_Position = (void(*)(uObject*, double*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_Position_fn;
type->interface0.fp_set_Position = (void(*)(uObject*, double*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_Position_fn;
type->interface0.fp_set_IsLooping = (void(*)(uObject*, bool*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_IsLooping_fn;
type->interface0.fp_set_AutoPlay = (void(*)(uObject*, bool*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_AutoPlay_fn;
type->interface0.fp_get_IsValid = (void(*)(uObject*, bool*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_IsValid_fn;
type->interface0.fp_get_RotationDegrees = (void(*)(uObject*, int*))GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_RotationDegrees_fn;
return type;
}
// public GraphicsVideoService(Fuse.Controls.VideoImpl.IVideoCallbacks callbacks) :691
void GraphicsVideoService__ctor__fn(GraphicsVideoService* __this, uObject* callbacks)
{
__this->ctor_(callbacks);
}
// private void Fuse.Controls.VideoImpl.IVideoService.set_AutoPlay(bool value) :744
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_AutoPlay_fn(GraphicsVideoService* __this, bool* value)
{
bool value_ = *value;
__this->_autoPlay = value_;
}
// private double Fuse.Controls.VideoImpl.IVideoService.get_Duration() :714
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_Duration_fn(GraphicsVideoService* __this, double* __retval)
{
return *__retval = __this->_durationCache, void();
}
// private void Fuse.Controls.VideoImpl.IVideoService.set_IsLooping(bool value) :741
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_IsLooping_fn(GraphicsVideoService* __this, bool* value)
{
bool value_ = *value;
__this->_isLooping = value_;
}
// private bool Fuse.Controls.VideoImpl.IVideoService.get_IsValid() :746
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_IsValid_fn(GraphicsVideoService* __this, bool* __retval)
{
return *__retval = __this->_player != NULL, void();
}
// private void Fuse.Controls.VideoImpl.IVideoService.Load(string url) :751
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceLoad_fn(GraphicsVideoService* __this, uString* url)
{
try
{
__this->Reset();
__this->_loading = ::g::Fuse::Controls::VideoImpl::LoadingClosure::Load(url, uDelegate::New(::TYPES[1/*Uno.Action<Fuse.Controls.VideoImpl.IVideoPlayer>*/], (void*)GraphicsVideoService__OnLoaded_fn, __this), uDelegate::New(::TYPES[2/*Uno.Action<Uno.Exception>*/], (void*)GraphicsVideoService__OnLoadingError_fn, __this));
}
catch (const uThrowable& __t)
{
::g::Uno::Exception* e = __t.Exception;
::g::Fuse::Controls::VideoImpl::IVideoCallbacks::OnError(uInterface(uPtr(__this->_callbacks), ::TYPES[3/*Fuse.Controls.VideoImpl.IVideoCallbacks*/]), e);
return;
}
::g::Fuse::Controls::VideoImpl::IVideoCallbacks::OnLoading(uInterface(uPtr(__this->_callbacks), ::TYPES[3/*Fuse.Controls.VideoImpl.IVideoCallbacks*/]));
}
// private void Fuse.Controls.VideoImpl.IVideoService.Load(Uno.UX.FileSource file) :766
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceLoad1_fn(GraphicsVideoService* __this, ::g::Uno::UX::FileSource* file)
{
try
{
__this->Reset();
__this->_loading = ::g::Fuse::Controls::VideoImpl::LoadingClosure::Load1(file, uDelegate::New(::TYPES[1/*Uno.Action<Fuse.Controls.VideoImpl.IVideoPlayer>*/], (void*)GraphicsVideoService__OnLoaded_fn, __this), uDelegate::New(::TYPES[2/*Uno.Action<Uno.Exception>*/], (void*)GraphicsVideoService__OnLoadingError_fn, __this));
}
catch (const uThrowable& __t)
{
::g::Uno::Exception* e = __t.Exception;
::g::Fuse::Controls::VideoImpl::IVideoCallbacks::OnError(uInterface(uPtr(__this->_callbacks), ::TYPES[3/*Fuse.Controls.VideoImpl.IVideoCallbacks*/]), e);
return;
}
::g::Fuse::Controls::VideoImpl::IVideoCallbacks::OnLoading(uInterface(uPtr(__this->_callbacks), ::TYPES[3/*Fuse.Controls.VideoImpl.IVideoCallbacks*/]));
}
// private void Fuse.Controls.VideoImpl.IVideoService.Pause() :706
void GraphicsVideoService__FuseControlsVideoImplIVideoServicePause_fn(GraphicsVideoService* __this)
{
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Pause(uInterface(uPtr(__this->Player()), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]));
}
// private void Fuse.Controls.VideoImpl.IVideoService.Play() :696
void GraphicsVideoService__FuseControlsVideoImplIVideoServicePlay_fn(GraphicsVideoService* __this)
{
if (__this->IsCompleted())
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Position(uInterface(uPtr(__this->Player()), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]), 0.0);
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Play(uInterface(uPtr(__this->Player()), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]));
}
// private double Fuse.Controls.VideoImpl.IVideoService.get_Position() :736
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_Position_fn(GraphicsVideoService* __this, double* __retval)
{
return *__retval = ::g::Fuse::Controls::VideoImpl::IVideoPlayer::Position(uInterface(uPtr(__this->Player()), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/])), void();
}
// private void Fuse.Controls.VideoImpl.IVideoService.set_Position(double value) :737
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_Position_fn(GraphicsVideoService* __this, double* value)
{
double value_ = *value;
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Position(uInterface(uPtr(__this->Player()), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]), value_);
}
// private int Fuse.Controls.VideoImpl.IVideoService.get_RotationDegrees() :749
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_RotationDegrees_fn(GraphicsVideoService* __this, int* __retval)
{
return *__retval = __this->_rotationCache, void();
}
// private int2 Fuse.Controls.VideoImpl.IVideoService.get_Size() :720
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_Size_fn(GraphicsVideoService* __this, ::g::Uno::Int2* __retval)
{
return *__retval = __this->_sizeCache, void();
}
// private void Fuse.Controls.VideoImpl.IVideoService.Unload() :812
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceUnload_fn(GraphicsVideoService* __this)
{
__this->Reset();
}
// private void Fuse.Controls.VideoImpl.IVideoService.Update() :790
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceUpdate_fn(GraphicsVideoService* __this)
{
if (__this->_player != NULL)
{
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Update(uInterface(uPtr(__this->_player), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]));
if (__this->IsCompleted())
{
if (__this->_isLooping)
{
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Pause(uInterface(uPtr(__this->_player), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]));
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Position(uInterface(uPtr(__this->_player), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]), 0.0);
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Play(uInterface(uPtr(__this->_player), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]));
}
else
{
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Pause(uInterface(uPtr(__this->_player), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]));
::g::Fuse::Controls::VideoImpl::IVideoCallbacks::OnCompleted(uInterface(uPtr(__this->_callbacks), ::TYPES[3/*Fuse.Controls.VideoImpl.IVideoCallbacks*/]));
}
}
}
}
// private Uno.Graphics.VideoTexture Fuse.Controls.VideoImpl.IVideoService.get_VideoTexture() :725
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceget_VideoTexture_fn(GraphicsVideoService* __this, ::g::Uno::Graphics::VideoTexture** __retval)
{
return *__retval = ::g::Fuse::Controls::VideoImpl::IVideoPlayer::VideoTexture(uInterface(uPtr(__this->Player()), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/])), void();
}
// private void Fuse.Controls.VideoImpl.IVideoService.set_Volume(float value) :731
void GraphicsVideoService__FuseControlsVideoImplIVideoServiceset_Volume_fn(GraphicsVideoService* __this, float* value)
{
float value_ = *value;
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Volume(uInterface(uPtr(__this->Player()), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]), __this->_volume = value_);
}
// private bool get_IsCompleted() :783
void GraphicsVideoService__get_IsCompleted_fn(GraphicsVideoService* __this, bool* __retval)
{
*__retval = __this->IsCompleted();
}
// public GraphicsVideoService New(Fuse.Controls.VideoImpl.IVideoCallbacks callbacks) :691
void GraphicsVideoService__New1_fn(uObject* callbacks, GraphicsVideoService** __retval)
{
*__retval = GraphicsVideoService::New1(callbacks);
}
// private void OnLoaded(Fuse.Controls.VideoImpl.IVideoPlayer player) :847
void GraphicsVideoService__OnLoaded_fn(GraphicsVideoService* __this, uObject* player)
{
__this->OnLoaded(player);
}
// private void OnLoadingError(Uno.Exception e) :859
void GraphicsVideoService__OnLoadingError_fn(GraphicsVideoService* __this, ::g::Uno::Exception* e)
{
__this->OnLoadingError(e);
}
// private void OnPlayerError(object sender, Uno.Exception e) :864
void GraphicsVideoService__OnPlayerError_fn(GraphicsVideoService* __this, uObject* sender, ::g::Uno::Exception* e)
{
__this->OnPlayerError(sender, e);
}
// private void OnPlayerFrameAvailable(object sender, Uno.EventArgs args) :870
void GraphicsVideoService__OnPlayerFrameAvailable_fn(GraphicsVideoService* __this, uObject* sender, ::g::Uno::EventArgs* args)
{
__this->OnPlayerFrameAvailable(sender, args);
}
// private Fuse.Controls.VideoImpl.IVideoPlayer get_Player() :683
void GraphicsVideoService__get_Player_fn(GraphicsVideoService* __this, uObject** __retval)
{
*__retval = __this->Player();
}
// private void Reset() :823
void GraphicsVideoService__Reset_fn(GraphicsVideoService* __this)
{
__this->Reset();
}
// private void SetPlayer(Fuse.Controls.VideoImpl.IVideoPlayer player) :839
void GraphicsVideoService__SetPlayer_fn(GraphicsVideoService* __this, uObject* player)
{
__this->SetPlayer(player);
}
// private void Uno.IDisposable.Dispose() :817
void GraphicsVideoService__UnoIDisposableDispose_fn(GraphicsVideoService* __this)
{
__this->Reset();
__this->_callbacks = NULL;
}
float GraphicsVideoService::CompletionTimeThreshold_;
// public GraphicsVideoService(Fuse.Controls.VideoImpl.IVideoCallbacks callbacks) [instance] :691
void GraphicsVideoService::ctor_(uObject* callbacks)
{
_empty = (uObject*)::g::Fuse::Controls::VideoImpl::EmptyVideo::New1();
_volume = 1.0f;
_callbacks = callbacks;
}
// private bool get_IsCompleted() [instance] :783
bool GraphicsVideoService::IsCompleted()
{
return ::g::Uno::Math::Abs(_durationCache - ::g::Fuse::Controls::VideoImpl::IVideoPlayer::Position(uInterface(uPtr(Player()), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]))) < (double)GraphicsVideoService::CompletionTimeThreshold();
}
// private void OnLoaded(Fuse.Controls.VideoImpl.IVideoPlayer player) [instance] :847
void GraphicsVideoService::OnLoaded(uObject* player)
{
_durationCache = ::g::Fuse::Controls::VideoImpl::IVideoPlayer::Duration(uInterface(uPtr(player), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]));
_sizeCache = ::g::Fuse::Controls::VideoImpl::IVideoPlayer::Size(uInterface(player, ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]));
_rotationCache = ::g::Fuse::Controls::VideoImpl::IVideoPlayer::RotationDegrees(uInterface(player, ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]));
SetPlayer(player);
::g::Fuse::Controls::VideoImpl::IVideoCallbacks::OnReady(uInterface(uPtr(_callbacks), ::TYPES[3/*Fuse.Controls.VideoImpl.IVideoCallbacks*/]));
if (_autoPlay)
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Play(uInterface(uPtr(Player()), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]));
}
// private void OnLoadingError(Uno.Exception e) [instance] :859
void GraphicsVideoService::OnLoadingError(::g::Uno::Exception* e)
{
::g::Fuse::Controls::VideoImpl::IVideoCallbacks::OnError(uInterface(uPtr(_callbacks), ::TYPES[3/*Fuse.Controls.VideoImpl.IVideoCallbacks*/]), e);
}
// private void OnPlayerError(object sender, Uno.Exception e) [instance] :864
void GraphicsVideoService::OnPlayerError(uObject* sender, ::g::Uno::Exception* e)
{
Reset();
::g::Fuse::Controls::VideoImpl::IVideoCallbacks::OnError(uInterface(uPtr(_callbacks), ::TYPES[3/*Fuse.Controls.VideoImpl.IVideoCallbacks*/]), e);
}
// private void OnPlayerFrameAvailable(object sender, Uno.EventArgs args) [instance] :870
void GraphicsVideoService::OnPlayerFrameAvailable(uObject* sender, ::g::Uno::EventArgs* args)
{
::g::Fuse::Controls::VideoImpl::IVideoCallbacks::OnFrameAvailable(uInterface(uPtr(_callbacks), ::TYPES[3/*Fuse.Controls.VideoImpl.IVideoCallbacks*/]));
}
// private Fuse.Controls.VideoImpl.IVideoPlayer get_Player() [instance] :683
uObject* GraphicsVideoService::Player()
{
uObject* ind1 = _player;
return (ind1 != NULL) ? ind1 : (uObject*)_empty;
}
// private void Reset() [instance] :823
void GraphicsVideoService::Reset()
{
if (_player != NULL)
{
::g::Fuse::Controls::VideoImpl::IVideoPlayer::remove_FrameAvailable(uInterface(uPtr(_player), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]), uDelegate::New(::TYPES[5/*Uno.EventHandler*/], (void*)GraphicsVideoService__OnPlayerFrameAvailable_fn, this));
::g::Fuse::Controls::VideoImpl::IVideoPlayer::remove_ErrorOccurred(uInterface(uPtr(_player), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]), uDelegate::New(::TYPES[6/*Uno.EventHandler<Uno.Exception>*/], (void*)GraphicsVideoService__OnPlayerError_fn, this));
::g::Uno::IDisposable::Dispose(uInterface(uPtr(_player), ::TYPES[7/*Uno.IDisposable*/]));
_player = NULL;
}
if (_loading != NULL)
{
::g::Uno::IDisposable::Dispose(uInterface(uPtr(_loading), ::TYPES[7/*Uno.IDisposable*/]));
_loading = NULL;
}
}
// private void SetPlayer(Fuse.Controls.VideoImpl.IVideoPlayer player) [instance] :839
void GraphicsVideoService::SetPlayer(uObject* player)
{
_player = player;
::g::Fuse::Controls::VideoImpl::IVideoPlayer::add_FrameAvailable(uInterface(uPtr(_player), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]), uDelegate::New(::TYPES[5/*Uno.EventHandler*/], (void*)GraphicsVideoService__OnPlayerFrameAvailable_fn, this));
::g::Fuse::Controls::VideoImpl::IVideoPlayer::add_ErrorOccurred(uInterface(uPtr(_player), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]), uDelegate::New(::TYPES[6/*Uno.EventHandler<Uno.Exception>*/], (void*)GraphicsVideoService__OnPlayerError_fn, this));
::g::Fuse::Controls::VideoImpl::IVideoPlayer::Volume(uInterface(uPtr(_player), ::TYPES[4/*Fuse.Controls.VideoImpl.IVideoPlayer*/]), _volume);
}
// public GraphicsVideoService New(Fuse.Controls.VideoImpl.IVideoCallbacks callbacks) [static] :691
GraphicsVideoService* GraphicsVideoService::New1(uObject* callbacks)
{
GraphicsVideoService* obj2 = (GraphicsVideoService*)uNew(GraphicsVideoService_typeof());
obj2->ctor_(callbacks);
return obj2;
}
// }
// /Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno
// ---------------------------------------------------------------------------------------------------
// internal abstract interface IVideoCallbacks :626
// {
uInterfaceType* IVideoCallbacks_typeof()
{
static uSStrong<uInterfaceType*> type;
if (type != NULL) return type;
type = uInterfaceType::New("Fuse.Controls.VideoImpl.IVideoCallbacks", 0, 0);
return type;
}
// }
// /Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno
// ---------------------------------------------------------------------------------------------------
// internal abstract interface IVideoPlayer :13
// {
uInterfaceType* IVideoPlayer_typeof()
{
static uSStrong<uInterfaceType*> type;
if (type != NULL) return type;
type = uInterfaceType::New("Fuse.Controls.VideoImpl.IVideoPlayer", 0, 0);
return type;
}
// }
// /Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno
// ---------------------------------------------------------------------------------------------------
// internal abstract interface IVideoService :600
// {
uInterfaceType* IVideoService_typeof()
{
static uSStrong<uInterfaceType*> type;
if (type != NULL) return type;
type = uInterfaceType::New("Fuse.Controls.VideoImpl.IVideoService", 0, 0);
return type;
}
// }
// /Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno
// ---------------------------------------------------------------------------------------------------
// internal sealed class LoadingClosure :635
// {
static void LoadingClosure_build(uType* type)
{
type->SetInterfaces(
::g::Uno::IDisposable_typeof(), offsetof(LoadingClosure_type, interface0));
type->SetFields(0,
::g::Uno::Action1_typeof()->MakeType(::g::Uno::Exception_typeof(), NULL), offsetof(::g::Fuse::Controls::VideoImpl::LoadingClosure, _error), 0,
::g::Uno::Bool_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::LoadingClosure, _isDisposed), 0,
::g::Uno::Action1_typeof()->MakeType(::g::Fuse::Controls::VideoImpl::IVideoPlayer_typeof(), NULL), offsetof(::g::Fuse::Controls::VideoImpl::LoadingClosure, _loaded), 0,
::g::Uno::Threading::Future1_typeof()->MakeType(::g::Fuse::Controls::VideoImpl::IVideoPlayer_typeof(), NULL), offsetof(::g::Fuse::Controls::VideoImpl::LoadingClosure, _loaderFuture), 0,
::g::Uno::Threading::Future1_typeof()->MakeType(::g::Fuse::Controls::VideoImpl::IVideoPlayer_typeof(), NULL), offsetof(::g::Fuse::Controls::VideoImpl::LoadingClosure, _thenFuture), 0);
}
LoadingClosure_type* LoadingClosure_typeof()
{
static uSStrong<LoadingClosure_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.FieldCount = 5;
options.InterfaceCount = 1;
options.ObjectSize = sizeof(LoadingClosure);
options.TypeSize = sizeof(LoadingClosure_type);
type = (LoadingClosure_type*)uClassType::New("Fuse.Controls.VideoImpl.LoadingClosure", options);
type->fp_build_ = LoadingClosure_build;
type->interface0.fp_Dispose = (void(*)(uObject*))LoadingClosure__UnoIDisposableDispose_fn;
return type;
}
// private LoadingClosure(Uno.Threading.Future<Fuse.Controls.VideoImpl.IVideoPlayer> loadedFuture, Uno.Action<Fuse.Controls.VideoImpl.IVideoPlayer> loaded, Uno.Action<Uno.Exception> error) :653
void LoadingClosure__ctor__fn(LoadingClosure* __this, ::g::Uno::Threading::Future1* loadedFuture, uDelegate* loaded, uDelegate* error)
{
__this->ctor_(loadedFuture, loaded, error);
}
// public static Uno.IDisposable Load(string url, Uno.Action<Fuse.Controls.VideoImpl.IVideoPlayer> loaded, Uno.Action<Uno.Exception> error) :637
void LoadingClosure__Load_fn(uString* url, uDelegate* loaded, uDelegate* error, uObject** __retval)
{
*__retval = LoadingClosure::Load(url, loaded, error);
}
// public static Uno.IDisposable Load(Uno.UX.FileSource file, Uno.Action<Fuse.Controls.VideoImpl.IVideoPlayer> loaded, Uno.Action<Uno.Exception> error) :642
void LoadingClosure__Load1_fn(::g::Uno::UX::FileSource* file, uDelegate* loaded, uDelegate* error, uObject** __retval)
{
*__retval = LoadingClosure::Load1(file, loaded, error);
}
// private LoadingClosure New(Uno.Threading.Future<Fuse.Controls.VideoImpl.IVideoPlayer> loadedFuture, Uno.Action<Fuse.Controls.VideoImpl.IVideoPlayer> loaded, Uno.Action<Uno.Exception> error) :653
void LoadingClosure__New1_fn(::g::Uno::Threading::Future1* loadedFuture, uDelegate* loaded, uDelegate* error, LoadingClosure** __retval)
{
*__retval = LoadingClosure::New1(loadedFuture, loaded, error);
}
// private void Uno.IDisposable.Dispose() :665
void LoadingClosure__UnoIDisposableDispose_fn(LoadingClosure* __this)
{
if (!__this->_isDisposed)
{
uPtr(__this->_loaderFuture)->Cancel(false);
uPtr(__this->_loaderFuture)->Dispose();
uPtr(__this->_thenFuture)->Dispose();
__this->_isDisposed = true;
}
}
// private LoadingClosure(Uno.Threading.Future<Fuse.Controls.VideoImpl.IVideoPlayer> loadedFuture, Uno.Action<Fuse.Controls.VideoImpl.IVideoPlayer> loaded, Uno.Action<Uno.Exception> error) [instance] :653
void LoadingClosure::ctor_(::g::Uno::Threading::Future1* loadedFuture, uDelegate* loaded, uDelegate* error)
{
_loaded = loaded;
_error = error;
_loaderFuture = loadedFuture;
_thenFuture = ((::g::Uno::Threading::Future1*)uPtr(_loaderFuture)->Then1(_loaded, _error));
}
// public static Uno.IDisposable Load(string url, Uno.Action<Fuse.Controls.VideoImpl.IVideoPlayer> loaded, Uno.Action<Uno.Exception> error) [static] :637
uObject* LoadingClosure::Load(uString* url, uDelegate* loaded, uDelegate* error)
{
return (uObject*)LoadingClosure::New1(::g::Fuse::Controls::VideoImpl::VideoLoader::Load(url), loaded, error);
}
// public static Uno.IDisposable Load(Uno.UX.FileSource file, Uno.Action<Fuse.Controls.VideoImpl.IVideoPlayer> loaded, Uno.Action<Uno.Exception> error) [static] :642
uObject* LoadingClosure::Load1(::g::Uno::UX::FileSource* file, uDelegate* loaded, uDelegate* error)
{
return (uObject*)LoadingClosure::New1(::g::Fuse::Controls::VideoImpl::VideoLoader::Load1(file), loaded, error);
}
// private LoadingClosure New(Uno.Threading.Future<Fuse.Controls.VideoImpl.IVideoPlayer> loadedFuture, Uno.Action<Fuse.Controls.VideoImpl.IVideoPlayer> loaded, Uno.Action<Uno.Exception> error) [static] :653
LoadingClosure* LoadingClosure::New1(::g::Uno::Threading::Future1* loadedFuture, uDelegate* loaded, uDelegate* error)
{
LoadingClosure* obj1 = (LoadingClosure*)uNew(LoadingClosure_typeof());
obj1->ctor_(loadedFuture, loaded, error);
return obj1;
}
// }
// /Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno
// ---------------------------------------------------------------------------------------------------
// internal sealed class Scale9Rectangle :1344
// {
// static Scale9Rectangle() :1344
static void Scale9Rectangle__cctor__fn(uType* __type)
{
Scale9Rectangle::Impl_ = Scale9Rectangle::New1();
}
static void Scale9Rectangle_build(uType* type)
{
::TYPES[8] = ::g::Fuse::IRenderViewport_typeof();
::TYPES[9] = ::g::Uno::UShort_typeof()->Array();
::TYPES[10] = ::g::Uno::Float3_typeof()->Array();
type->SetFields(0,
::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLDrawCall_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::Scale9Rectangle, _draw_e60caa7b), 0,
::TYPES[9/*ushort[]*/], offsetof(::g::Fuse::Controls::VideoImpl::Scale9Rectangle, Draw_indices_e60caa7b_1_2_12), 0,
::g::Uno::Graphics::IndexBuffer_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::Scale9Rectangle, Draw_xv_e60caa7b_1_3_2), 0,
::g::Uno::Graphics::VertexBuffer_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::Scale9Rectangle, Draw_xv_e60caa7b_1_3_3), 0,
::g::Uno::Graphics::VertexBuffer_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::Scale9Rectangle, Draw_yv_e60caa7b_1_4_6), 0,
type, (uintptr_t)&::g::Fuse::Controls::VideoImpl::Scale9Rectangle::Impl_, uFieldFlagsStatic);
}
uType* Scale9Rectangle_typeof()
{
static uSStrong<uType*> type;
if (type != NULL) return type;
uTypeOptions options;
options.FieldCount = 6;
options.ObjectSize = sizeof(Scale9Rectangle);
options.TypeSize = sizeof(uType);
type = uClassType::New("Fuse.Controls.VideoImpl.Scale9Rectangle", options);
type->fp_build_ = Scale9Rectangle_build;
type->fp_ctor_ = (void*)Scale9Rectangle__New1_fn;
type->fp_cctor_ = Scale9Rectangle__cctor__fn;
return type;
}
// public generated Scale9Rectangle() :1344
void Scale9Rectangle__ctor__fn(Scale9Rectangle* __this)
{
__this->ctor_();
}
// public void Draw(Fuse.DrawContext dc, Fuse.Visual element, float2 size, float2 scaleTextureSize, Uno.Graphics.VideoTexture tex, float4 margin) :1348
void Scale9Rectangle__Draw_fn(Scale9Rectangle* __this, ::g::Fuse::DrawContext* dc, ::g::Fuse::Visual* element, ::g::Uno::Float2* size, ::g::Uno::Float2* scaleTextureSize, ::g::Uno::Graphics::VideoTexture* tex, ::g::Uno::Float4* margin)
{
__this->Draw(dc, element, *size, *scaleTextureSize, tex, *margin);
}
// private generated void init_DrawCalls() :1344
void Scale9Rectangle__init_DrawCalls_fn(Scale9Rectangle* __this)
{
__this->init_DrawCalls();
}
// public generated Scale9Rectangle New() :1344
void Scale9Rectangle__New1_fn(Scale9Rectangle** __retval)
{
*__retval = Scale9Rectangle::New1();
}
uSStrong<Scale9Rectangle*> Scale9Rectangle::Impl_;
// public generated Scale9Rectangle() [instance] :1344
void Scale9Rectangle::ctor_()
{
init_DrawCalls();
}
// public void Draw(Fuse.DrawContext dc, Fuse.Visual element, float2 size, float2 scaleTextureSize, Uno.Graphics.VideoTexture tex, float4 margin) [instance] :1348
void Scale9Rectangle::Draw(::g::Fuse::DrawContext* dc, ::g::Fuse::Visual* element, ::g::Uno::Float2 size, ::g::Uno::Float2 scaleTextureSize, ::g::Uno::Graphics::VideoTexture* tex, ::g::Uno::Float4 margin)
{
_draw_e60caa7b.BlendEnabled(true);
_draw_e60caa7b.DepthTestEnabled(false);
_draw_e60caa7b.CullFace(0);
_draw_e60caa7b.BlendSrcRgb(2);
_draw_e60caa7b.BlendDstRgb(3);
_draw_e60caa7b.BlendDstAlpha(3);
_draw_e60caa7b.Use();
_draw_e60caa7b.Attrib1(0, 3, Draw_xv_e60caa7b_1_3_3, 12, 0);
_draw_e60caa7b.Attrib1(1, 3, Draw_yv_e60caa7b_1_4_6, 12, 0);
_draw_e60caa7b.Uniform(2, margin.X);
_draw_e60caa7b.Uniform(3, size.X - margin.Z);
_draw_e60caa7b.Uniform(4, size.X);
_draw_e60caa7b.Uniform(5, margin.Y);
_draw_e60caa7b.Uniform(6, size.Y - margin.W);
_draw_e60caa7b.Uniform(7, size.Y);
_draw_e60caa7b.Uniform12(8, uPtr(element)->WorldTransform());
_draw_e60caa7b.Uniform12(9, ::g::Fuse::IRenderViewport::ViewProjectionTransform(uInterface(uPtr(uPtr(dc)->Viewport()), ::TYPES[8/*Fuse.IRenderViewport*/])));
_draw_e60caa7b.Uniform(10, scaleTextureSize.X - margin.Z);
_draw_e60caa7b.Uniform(11, scaleTextureSize.X);
_draw_e60caa7b.Uniform(12, scaleTextureSize.Y - margin.W);
_draw_e60caa7b.Uniform(13, scaleTextureSize.Y);
_draw_e60caa7b.Uniform2(14, scaleTextureSize);
_draw_e60caa7b.Sampler7(15, tex, ::g::Uno::Graphics::SamplerState__LinearClamp());
_draw_e60caa7b.Draw(uPtr(Draw_indices_e60caa7b_1_2_12)->Length(), 2, Draw_xv_e60caa7b_1_3_2);
}
// private generated void init_DrawCalls() [instance] :1344
void Scale9Rectangle::init_DrawCalls()
{
uArray* indices_e60caa7b_1_2_1 = uArray::Init<int>(::TYPES[9/*ushort[]*/], 54, 0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2, 2, 6, 7, 2, 7, 3, 4, 8, 9, 4, 9, 5, 5, 9, 10, 5, 10, 6, 6, 10, 11, 6, 11, 7, 8, 12, 13, 8, 13, 9, 9, 13, 14, 9, 14, 10, 10, 14, 15, 10, 15, 11);
Draw_xv_e60caa7b_1_3_2 = ::g::Uno::Graphics::IndexBuffer::New2(::g::Uno::Runtime::Implementation::Internal::BufferConverters::ToBuffer9(indices_e60caa7b_1_2_1), 0);
Draw_xv_e60caa7b_1_3_3 = ::g::Uno::Graphics::VertexBuffer::New2(::g::Uno::Runtime::Implementation::Internal::BufferConverters::ToBuffer4(uArray::Init< ::g::Uno::Float3>(::TYPES[10/*float3[]*/], 16, ::g::Uno::Float3__New2(0.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(1.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 1.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 1.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(1.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 1.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 1.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(1.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 1.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 1.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(1.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 1.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 1.0f))), 0);
Draw_yv_e60caa7b_1_4_6 = ::g::Uno::Graphics::VertexBuffer::New2(::g::Uno::Runtime::Implementation::Internal::BufferConverters::ToBuffer4(uArray::Init< ::g::Uno::Float3>(::TYPES[10/*float3[]*/], 16, ::g::Uno::Float3__New2(0.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(1.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(1.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(1.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(1.0f, 0.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 1.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 1.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 1.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 1.0f, 0.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 1.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 1.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 1.0f), ::g::Uno::Float3__New2(0.0f, 0.0f, 1.0f))), 0);
Draw_indices_e60caa7b_1_2_12 = indices_e60caa7b_1_2_1;
_draw_e60caa7b = ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLDrawCall__New1(::g::FuseControlsVideo_bundle::Scale9Rectangleda875692());
}
// public generated Scale9Rectangle New() [static] :1344
Scale9Rectangle* Scale9Rectangle::New1()
{
Scale9Rectangle* obj1 = (Scale9Rectangle*)uNew(Scale9Rectangle_typeof());
obj1->ctor_();
return obj1;
}
// }
// /Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno
// ---------------------------------------------------------------------------------------------------
// internal static class VideoDiskCache :892
// {
// static VideoDiskCache() :898
static void VideoDiskCache__cctor__fn(uType* __type)
{
VideoDiskCache::_files_ = ((::g::Uno::Collections::Dictionary*)::g::Uno::Collections::Dictionary::New1(::TYPES[11/*Uno.Collections.Dictionary<string, string>*/]));
::g::Fuse::Platform::Lifecycle::add_Terminating(uDelegate::New(::TYPES[12/*Uno.Action<Fuse.Platform.ApplicationState>*/], (void*)VideoDiskCache__OnTerminating_fn));
}
static void VideoDiskCache_build(uType* type)
{
::STRINGS[0] = uString::Const("/tempVideo");
::STRINGS[1] = uString::Const(".");
::STRINGS[2] = uString::Const("Deleting temporary file: ");
::STRINGS[3] = uString::Const("../../../../Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno");
::TYPES[11] = ::g::Uno::Collections::Dictionary_typeof()->MakeType(::g::Uno::String_typeof(), ::g::Uno::String_typeof(), NULL);
::TYPES[12] = ::g::Uno::Action1_typeof()->MakeType(::g::Fuse::Platform::ApplicationState_typeof(), NULL);
::TYPES[13] = ::g::Uno::Char_typeof()->Array();
::TYPES[14] = ::g::Uno::Int_typeof();
::TYPES[15] = ::g::Uno::Collections::Dictionary__Enumerator_typeof()->MakeType(::g::Uno::String_typeof(), ::g::Uno::String_typeof(), NULL);
::TYPES[16] = ::g::Uno::Collections::KeyValuePair_typeof()->MakeType(::g::Uno::String_typeof(), ::g::Uno::String_typeof(), NULL);
type->SetFields(0,
::TYPES[14/*int*/], (uintptr_t)&::g::Fuse::Controls::VideoImpl::VideoDiskCache::_fileCount_, uFieldFlagsStatic,
::TYPES[11/*Uno.Collections.Dictionary<string, string>*/], (uintptr_t)&::g::Fuse::Controls::VideoImpl::VideoDiskCache::_files_, uFieldFlagsStatic);
}
uClassType* VideoDiskCache_typeof()
{
static uSStrong<uClassType*> type;
if (type != NULL) return type;
uTypeOptions options;
options.FieldCount = 2;
options.TypeSize = sizeof(uClassType);
type = uClassType::New("Fuse.Controls.VideoImpl.VideoDiskCache", options);
type->fp_build_ = VideoDiskCache_build;
type->fp_cctor_ = VideoDiskCache__cctor__fn;
return type;
}
// public static string GetFileExtension(string fileName) :929
void VideoDiskCache__GetFileExtension_fn(uString* fileName, uString** __retval)
{
*__retval = VideoDiskCache::GetFileExtension(fileName);
}
// public static string GetFilePath(Uno.UX.FileSource fileSource) :916
void VideoDiskCache__GetFilePath_fn(::g::Uno::UX::FileSource* fileSource, uString** __retval)
{
*__retval = VideoDiskCache::GetFilePath(fileSource);
}
// private static void OnTerminating(Fuse.Platform.ApplicationState newState) :903
void VideoDiskCache__OnTerminating_fn(int* newState)
{
VideoDiskCache::OnTerminating(*newState);
}
int VideoDiskCache::_fileCount_;
uSStrong< ::g::Uno::Collections::Dictionary*> VideoDiskCache::_files_;
// public static string GetFileExtension(string fileName) [static] :929
uString* VideoDiskCache::GetFileExtension(uString* fileName)
{
VideoDiskCache_typeof()->Init();
uArray* strings = ::g::Uno::String::Split(uPtr(fileName), uArray::Init<int>(::TYPES[13/*char[]*/], 1, '.'));
return uPtr(strings)->Strong<uString*>(uPtr(strings)->Length() - 1);
}
// public static string GetFilePath(Uno.UX.FileSource fileSource) [static] :916
uString* VideoDiskCache::GetFilePath(::g::Uno::UX::FileSource* fileSource)
{
VideoDiskCache_typeof()->Init();
bool ret2;
uString* ret3;
if (!(::g::Uno::Collections::Dictionary__ContainsKey_fn(uPtr(VideoDiskCache::_files()), uPtr(fileSource)->Name, &ret2), ret2))
{
uArray* bytes = uPtr(fileSource)->ReadAllBytes();
uString* path = ::g::Uno::String::op_Addition2(::g::Uno::String::op_Addition2(::g::Uno::String::op_Addition2(::g::Uno::String::op_Addition2(::g::Uno::IO::Directory::GetUserDirectory(1), ::STRINGS[0/*"/tempVideo"*/]), ::g::Uno::Int::ToString(VideoDiskCache::_fileCount(), ::TYPES[14/*int*/])), ::STRINGS[1/*"."*/]), VideoDiskCache::GetFileExtension(fileSource->Name));
VideoDiskCache::_fileCount()++;
::g::Uno::IO::File::WriteAllBytes(path, bytes);
::g::Uno::Collections::Dictionary__Add_fn(uPtr(VideoDiskCache::_files()), fileSource->Name, path);
}
return (::g::Uno::Collections::Dictionary__get_Item_fn(uPtr(VideoDiskCache::_files()), uPtr(fileSource)->Name, &ret3), ret3);
}
// private static void OnTerminating(Fuse.Platform.ApplicationState newState) [static] :903
void VideoDiskCache::OnTerminating(int newState)
{
VideoDiskCache_typeof()->Init();
::g::Uno::Collections::Dictionary__Enumerator<uStrong<uString*>, uStrong<uString*> > ret4;
::g::Fuse::Platform::Lifecycle::remove_Terminating(uDelegate::New(::TYPES[12/*Uno.Action<Fuse.Platform.ApplicationState>*/], (void*)VideoDiskCache__OnTerminating_fn));
for (::g::Uno::Collections::Dictionary__Enumerator<uStrong<uString*>, uStrong<uString*> > enum1 = (::g::Uno::Collections::Dictionary__GetEnumerator_fn(uPtr(VideoDiskCache::_files()), &ret4), ret4); enum1.MoveNext(::TYPES[15/*Uno.Collections.Dictionary<string, string>.Enumerator*/]); )
{
::g::Uno::Collections::KeyValuePair<uStrong<uString*>, uStrong<uString*> > pair = enum1.Current(::TYPES[15/*Uno.Collections.Dictionary<string, string>.Enumerator*/]);
if (::g::Uno::IO::File::Exists(pair.Value(::TYPES[16/*Uno.Collections.KeyValuePair<string, string>*/])))
{
::g::Uno::Diagnostics::Debug::Log5(::g::Uno::String::op_Addition2(::STRINGS[2/*"Deleting te...*/], pair.Value(::TYPES[16/*Uno.Collections.KeyValuePair<string, string>*/])), 1, ::STRINGS[3/*"../../../.....*/], 910);
::g::Uno::IO::File::Delete(pair.Value(::TYPES[16/*Uno.Collections.KeyValuePair<string, string>*/]));
}
}
}
// }
// /Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno
// ---------------------------------------------------------------------------------------------------
// internal sealed class VideoDrawElement :1313
// {
// static VideoDrawElement() :1313
static void VideoDrawElement__cctor__fn(uType* __type)
{
VideoDrawElement::Impl_ = VideoDrawElement::New1();
}
static void VideoDrawElement_build(uType* type)
{
::TYPES[8] = ::g::Fuse::IRenderViewport_typeof();
::TYPES[17] = ::g::Uno::Float2_typeof()->Array();
type->SetFields(0,
::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLDrawCall_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoDrawElement, _draw_46004d37), 0,
::g::Uno::Float4x4_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoDrawElement, Draw_LocalTransform_46004d37_3_9_2), 0,
::g::Uno::Float4x4_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoDrawElement, Draw_LocalTransform_46004d37_3_9_3), 0,
::g::Uno::Graphics::VertexBuffer_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoDrawElement, Draw_VertexData_46004d37_6_2_1), 0,
type, (uintptr_t)&::g::Fuse::Controls::VideoImpl::VideoDrawElement::Impl_, uFieldFlagsStatic);
}
uType* VideoDrawElement_typeof()
{
static uSStrong<uType*> type;
if (type != NULL) return type;
uTypeOptions options;
options.FieldCount = 5;
options.ObjectSize = sizeof(VideoDrawElement);
options.TypeSize = sizeof(uType);
type = uClassType::New("Fuse.Controls.VideoImpl.VideoDrawElement", options);
type->fp_build_ = VideoDrawElement_build;
type->fp_ctor_ = (void*)VideoDrawElement__New1_fn;
type->fp_cctor_ = VideoDrawElement__cctor__fn;
return type;
}
// public generated VideoDrawElement() :1313
void VideoDrawElement__ctor__fn(VideoDrawElement* __this)
{
__this->ctor_();
}
// public void Draw(Fuse.DrawContext dc, Fuse.Visual element, float2 offset, float2 size, float2 uvPosition, float2 uvSize, Uno.Graphics.VideoTexture tex, int rotation) :1317
void VideoDrawElement__Draw_fn(VideoDrawElement* __this, ::g::Fuse::DrawContext* dc, ::g::Fuse::Visual* element, ::g::Uno::Float2* offset, ::g::Uno::Float2* size, ::g::Uno::Float2* uvPosition, ::g::Uno::Float2* uvSize, ::g::Uno::Graphics::VideoTexture* tex, int* rotation)
{
__this->Draw(dc, element, *offset, *size, *uvPosition, *uvSize, tex, *rotation);
}
// private generated void init_DrawCalls() :1313
void VideoDrawElement__init_DrawCalls_fn(VideoDrawElement* __this)
{
__this->init_DrawCalls();
}
// public generated VideoDrawElement New() :1313
void VideoDrawElement__New1_fn(VideoDrawElement** __retval)
{
*__retval = VideoDrawElement::New1();
}
uSStrong<VideoDrawElement*> VideoDrawElement::Impl_;
// public generated VideoDrawElement() [instance] :1313
void VideoDrawElement::ctor_()
{
init_DrawCalls();
}
// public void Draw(Fuse.DrawContext dc, Fuse.Visual element, float2 offset, float2 size, float2 uvPosition, float2 uvSize, Uno.Graphics.VideoTexture tex, int rotation) [instance] :1317
void VideoDrawElement::Draw(::g::Fuse::DrawContext* dc, ::g::Fuse::Visual* element, ::g::Uno::Float2 offset, ::g::Uno::Float2 size, ::g::Uno::Float2 uvPosition, ::g::Uno::Float2 uvSize, ::g::Uno::Graphics::VideoTexture* tex, int rotation)
{
::g::Uno::Float4x4 LocalTransform_46004d37_3_9_4 = ::g::Uno::Matrix::Mul10(Draw_LocalTransform_46004d37_3_9_2, ::g::Uno::Matrix::Scaling1(size.X, size.Y, 1.0f), Draw_LocalTransform_46004d37_3_9_3, ::g::Uno::Matrix::Translation(offset.X, offset.Y, 0.0f));
_draw_46004d37.BlendEnabled(true);
_draw_46004d37.DepthTestEnabled(false);
_draw_46004d37.CullFace(uPtr(dc)->CullFace());
_draw_46004d37.BlendSrcRgb(2);
_draw_46004d37.BlendDstRgb(3);
_draw_46004d37.BlendDstAlpha(3);
_draw_46004d37.Const1(0, rotation);
_draw_46004d37.Use();
_draw_46004d37.Attrib1(1, 2, Draw_VertexData_46004d37_6_2_1, 8, 0);
_draw_46004d37.Uniform12(2, ::g::Fuse::IRenderViewport::ViewProjectionTransform(uInterface(uPtr(dc->Viewport()), ::TYPES[8/*Fuse.IRenderViewport*/])));
_draw_46004d37.Uniform2(3, uvSize);
_draw_46004d37.Uniform2(4, uvPosition);
_draw_46004d37.Uniform12(5, (element != NULL) ? ::g::Uno::Matrix::Mul8(LocalTransform_46004d37_3_9_4, uPtr(element)->WorldTransform()) : LocalTransform_46004d37_3_9_4);
_draw_46004d37.Sampler7(6, tex, ::g::Uno::Graphics::SamplerState__LinearClamp());
_draw_46004d37.DrawArrays(6);
}
// private generated void init_DrawCalls() [instance] :1313
void VideoDrawElement::init_DrawCalls()
{
Draw_VertexData_46004d37_6_2_1 = ::g::Uno::Graphics::VertexBuffer::New2(::g::Uno::Runtime::Implementation::Internal::BufferConverters::ToBuffer3(uArray::Init< ::g::Uno::Float2>(::TYPES[17/*float2[]*/], 6, ::g::Uno::Float2__New2(0.0f, 0.0f), ::g::Uno::Float2__New2(0.0f, 1.0f), ::g::Uno::Float2__New2(1.0f, 1.0f), ::g::Uno::Float2__New2(0.0f, 0.0f), ::g::Uno::Float2__New2(1.0f, 1.0f), ::g::Uno::Float2__New2(1.0f, 0.0f))), 0);
Draw_LocalTransform_46004d37_3_9_2 = ::g::Uno::Matrix::Translation(-::g::Uno::Float2__New1(0.0f).X, -::g::Uno::Float2__New1(0.0f).Y, 0.0f);
Draw_LocalTransform_46004d37_3_9_3 = ::g::Uno::Matrix::RotationZ(0.0f);
_draw_46004d37 = ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLDrawCall__New1(::g::FuseControlsVideo_bundle::VideoDrawElement5c829975());
}
// public generated VideoDrawElement New() [static] :1313
VideoDrawElement* VideoDrawElement::New1()
{
VideoDrawElement* obj1 = (VideoDrawElement*)uNew(VideoDrawElement_typeof());
obj1->ctor_();
return obj1;
}
// }
// /Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno
// ---------------------------------------------------------------------------------------------------
// internal static class VideoLoader :953
// {
static void VideoLoader_build(uType* type)
{
::STRINGS[4] = uString::Const("Video not supported on this platform");
}
uClassType* VideoLoader_typeof()
{
static uSStrong<uClassType*> type;
if (type != NULL) return type;
uTypeOptions options;
options.TypeSize = sizeof(uClassType);
type = uClassType::New("Fuse.Controls.VideoImpl.VideoLoader", options);
type->fp_build_ = VideoLoader_build;
return type;
}
// public static Uno.Threading.Future<Fuse.Controls.VideoImpl.IVideoPlayer> Load(string url) :955
void VideoLoader__Load_fn(uString* url, ::g::Uno::Threading::Future1** __retval)
{
*__retval = VideoLoader::Load(url);
}
// public static Uno.Threading.Future<Fuse.Controls.VideoImpl.IVideoPlayer> Load(Uno.UX.FileSource file) :964
void VideoLoader__Load1_fn(::g::Uno::UX::FileSource* file, ::g::Uno::Threading::Future1** __retval)
{
*__retval = VideoLoader::Load1(file);
}
// public static Uno.Threading.Future<Fuse.Controls.VideoImpl.IVideoPlayer> Load(string url) [static] :955
::g::Uno::Threading::Future1* VideoLoader::Load(uString* url)
{
return ::g::Fuse::Controls::VideoImpl::iOS::VideoLoader::Load(url);
U_THROW(::g::Uno::Exception::New2(::STRINGS[4/*"Video not s...*/]));
}
// public static Uno.Threading.Future<Fuse.Controls.VideoImpl.IVideoPlayer> Load(Uno.UX.FileSource file) [static] :964
::g::Uno::Threading::Future1* VideoLoader::Load1(::g::Uno::UX::FileSource* file)
{
return ::g::Fuse::Controls::VideoImpl::iOS::VideoLoader::Load2(file);
U_THROW(::g::Uno::Exception::New2(::STRINGS[4/*"Video not s...*/]));
}
// }
// /Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno
// ---------------------------------------------------------------------------------------------------
// internal sealed extern class VideoVisual :1028
// {
static void VideoVisual_build(uType* type)
{
::STRINGS[5] = uString::Const("Video error");
::STRINGS[6] = uString::Const("/Users/paulsutcliffe/Library/Application Support/Fusetools/Packages/Fuse.Controls.Video/1.0.2/$.uno");
::STRINGS[7] = uString::Const("Fuse.Controls.VideoImpl.IVideoCallbacks.OnError");
::STRINGS[8] = uString::Const("");
::STRINGS[9] = uString::Const("IPlayback.PlayTo(double) not supported in Fuse.Controls.Video");
::STRINGS[10] = uString::Const("Fuse.Triggers.IPlayback.PlayTo");
::TYPES[5] = ::g::Uno::EventHandler_typeof();
::TYPES[18] = ::g::Uno::Action_typeof();
::TYPES[19] = ::g::Fuse::Controls::VideoImpl::IVideoService_typeof();
::TYPES[20] = ::g::Fuse::Triggers::IPlayback_typeof();
::TYPES[21] = ::g::Fuse::Triggers::IMediaPlayback_typeof();
::TYPES[22] = ::g::Uno::UX::ValueChangedArgs_typeof()->MakeType(::g::Uno::Double_typeof(), NULL);
::TYPES[23] = ::g::Uno::UX::ValueChangedHandler_typeof()->MakeType(::g::Uno::Double_typeof(), NULL);
type->SetBase(::g::Fuse::Controls::Graphics::ControlVisual_typeof()->MakeType(::g::Fuse::Controls::Video_typeof(), NULL));
type->SetInterfaces(
::g::Uno::Collections::IList_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL), offsetof(VideoVisual_type, interface0),
::g::Fuse::Scripting::IScriptObject_typeof(), offsetof(VideoVisual_type, interface1),
::g::Fuse::IProperties_typeof(), offsetof(VideoVisual_type, interface2),
::g::Fuse::INotifyUnrooted_typeof(), offsetof(VideoVisual_type, interface3),
::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL), offsetof(VideoVisual_type, interface4),
::g::Uno::Collections::IEnumerable_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL), offsetof(VideoVisual_type, interface5),
::g::Uno::Collections::IList_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL), offsetof(VideoVisual_type, interface6),
::g::Uno::UX::IPropertyListener_typeof(), offsetof(VideoVisual_type, interface7),
::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL), offsetof(VideoVisual_type, interface8),
::g::Uno::Collections::IEnumerable_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL), offsetof(VideoVisual_type, interface9),
::g::Fuse::Controls::VideoImpl::IVideoCallbacks_typeof(), offsetof(VideoVisual_type, interface10),
::TYPES[21/*Fuse.Triggers.IMediaPlayback*/], offsetof(VideoVisual_type, interface11),
::TYPES[20/*Fuse.Triggers.IPlayback*/], offsetof(VideoVisual_type, interface12),
::g::Fuse::Triggers::IProgress_typeof(), offsetof(VideoVisual_type, interface13));
type->SetFields(57,
::g::Fuse::Triggers::BusyTask_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoVisual, _busyTask), 0,
::g::Uno::Float2_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoVisual, _drawOrigin), 0,
::g::Uno::Float2_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoVisual, _drawSize), 0,
::g::Uno::Float2_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoVisual, _origin), 0,
::g::Uno::Float2_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoVisual, _scale), 0,
::g::Uno::Int2_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoVisual, _sizeCache), 0,
::g::Fuse::Internal::SizingContainer_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoVisual, _sizing), 0,
::g::Uno::Float4_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoVisual, _uvClip), 0,
::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/], offsetof(::g::Fuse::Controls::VideoImpl::VideoVisual, _videoService), 0,
::g::Uno::Float_typeof(), offsetof(::g::Fuse::Controls::VideoImpl::VideoVisual, _volume), 0,
::TYPES[23/*Uno.UX.ValueChangedHandler<double>*/], offsetof(::g::Fuse::Controls::VideoImpl::VideoVisual, ProgressChanged1), 0);
}
VideoVisual_type* VideoVisual_typeof()
{
static uSStrong<VideoVisual_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.BaseDefinition = ::g::Fuse::Controls::Graphics::ControlVisual_typeof();
options.FieldCount = 68;
options.InterfaceCount = 14;
options.ObjectSize = sizeof(VideoVisual);
options.TypeSize = sizeof(VideoVisual_type);
type = (VideoVisual_type*)uClassType::New("Fuse.Controls.VideoImpl.VideoVisual", options);
type->fp_build_ = VideoVisual_build;
type->fp_ctor_ = (void*)VideoVisual__New2_fn;
type->fp_Attach = (void(*)(::g::Fuse::Controls::Graphics::ControlVisual*))VideoVisual__Attach_fn;
type->fp_Detach = (void(*)(::g::Fuse::Controls::Graphics::ControlVisual*))VideoVisual__Detach_fn;
type->fp_Draw = (void(*)(::g::Fuse::Visual*, ::g::Fuse::DrawContext*))VideoVisual__Draw_fn;
type->fp_GetMarginSize = (void(*)(::g::Fuse::Visual*, ::g::Fuse::LayoutParams*, ::g::Uno::Float2*))VideoVisual__GetMarginSize_fn;
type->fp_OnArrangeMarginBox = (void(*)(::g::Fuse::Visual*, ::g::Uno::Float2*, ::g::Fuse::LayoutParams*, ::g::Uno::Float2*))VideoVisual__OnArrangeMarginBox_fn;
type->fp_OnHitTest = (void(*)(::g::Fuse::Visual*, ::g::Fuse::HitTestContext*))VideoVisual__OnHitTest_fn;
type->interface10.fp_OnFrameAvailable = (void(*)(uObject*))VideoVisual__FuseControlsVideoImplIVideoCallbacksOnFrameAvailable_fn;
type->interface10.fp_OnError = (void(*)(uObject*, ::g::Uno::Exception*))VideoVisual__FuseControlsVideoImplIVideoCallbacksOnError_fn;
type->interface10.fp_OnLoading = (void(*)(uObject*))VideoVisual__FuseControlsVideoImplIVideoCallbacksOnLoading_fn;
type->interface10.fp_OnReady = (void(*)(uObject*))VideoVisual__FuseControlsVideoImplIVideoCallbacksOnReady_fn;
type->interface10.fp_OnCompleted = (void(*)(uObject*))VideoVisual__FuseControlsVideoImplIVideoCallbacksOnCompleted_fn;
type->interface12.fp_Stop = (void(*)(uObject*))VideoVisual__FuseTriggersIPlaybackStop_fn;
type->interface12.fp_PlayTo = (void(*)(uObject*, double*))VideoVisual__FuseTriggersIPlaybackPlayTo_fn;
type->interface12.fp_Pause = (void(*)(uObject*))VideoVisual__FuseTriggersIPlaybackPause_fn;
type->interface12.fp_Resume = (void(*)(uObject*))VideoVisual__FuseTriggersIPlaybackResume_fn;
type->interface11.fp_get_Position = (void(*)(uObject*, double*))VideoVisual__FuseTriggersIMediaPlaybackget_Position_fn;
type->interface11.fp_set_Position = (void(*)(uObject*, double*))VideoVisual__FuseTriggersIMediaPlaybackset_Position_fn;
type->interface13.fp_get_Progress = (void(*)(uObject*, double*))VideoVisual__FuseTriggersIProgressget_Progress_fn;
type->interface12.fp_get_Progress = (void(*)(uObject*, double*))VideoVisual__FuseTriggersIPlaybackget_Progress_fn;
type->interface12.fp_set_Progress = (void(*)(uObject*, double*))VideoVisual__FuseTriggersIPlaybackset_Progress_fn;
type->interface13.fp_add_ProgressChanged = (void(*)(uObject*, uDelegate*))VideoVisual__FuseTriggersIProgressadd_ProgressChanged_fn;
type->interface13.fp_remove_ProgressChanged = (void(*)(uObject*, uDelegate*))VideoVisual__FuseTriggersIProgressremove_ProgressChanged_fn;
type->interface8.fp_Clear = (void(*)(uObject*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeClear_fn;
type->interface8.fp_Contains = (void(*)(uObject*, void*, bool*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeContains_fn;
type->interface6.fp_RemoveAt = (void(*)(uObject*, int*))::g::Fuse::Visual__UnoCollectionsIListFuseNodeRemoveAt_fn;
type->interface9.fp_GetEnumerator = (void(*)(uObject*, uObject**))::g::Fuse::Visual__UnoCollectionsIEnumerableFuseNodeGetEnumerator_fn;
type->interface8.fp_get_Count = (void(*)(uObject*, int*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeget_Count_fn;
type->interface6.fp_get_Item = (void(*)(uObject*, int*, uTRef))::g::Fuse::Visual__UnoCollectionsIListFuseNodeget_Item_fn;
type->interface6.fp_Insert = (void(*)(uObject*, int*, void*))::g::Fuse::Visual__Insert1_fn;
type->interface7.fp_OnPropertyChanged = (void(*)(uObject*, ::g::Uno::UX::PropertyObject*, ::g::Uno::UX::Selector*))::g::Fuse::Visual__OnPropertyChanged2_fn;
type->interface8.fp_Add = (void(*)(uObject*, void*))::g::Fuse::Visual__Add1_fn;
type->interface8.fp_Remove = (void(*)(uObject*, void*, bool*))::g::Fuse::Visual__Remove1_fn;
type->interface4.fp_Clear = (void(*)(uObject*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingClear_fn;
type->interface4.fp_Contains = (void(*)(uObject*, void*, bool*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingContains_fn;
type->interface0.fp_RemoveAt = (void(*)(uObject*, int*))::g::Fuse::Node__UnoCollectionsIListFuseBindingRemoveAt_fn;
type->interface5.fp_GetEnumerator = (void(*)(uObject*, uObject**))::g::Fuse::Node__UnoCollectionsIEnumerableFuseBindingGetEnumerator_fn;
type->interface1.fp_SetScriptObject = (void(*)(uObject*, uObject*, ::g::Fuse::Scripting::Context*))::g::Fuse::Node__FuseScriptingIScriptObjectSetScriptObject_fn;
type->interface4.fp_get_Count = (void(*)(uObject*, int*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingget_Count_fn;
type->interface0.fp_get_Item = (void(*)(uObject*, int*, uTRef))::g::Fuse::Node__UnoCollectionsIListFuseBindingget_Item_fn;
type->interface1.fp_get_ScriptObject = (void(*)(uObject*, uObject**))::g::Fuse::Node__FuseScriptingIScriptObjectget_ScriptObject_fn;
type->interface1.fp_get_ScriptContext = (void(*)(uObject*, ::g::Fuse::Scripting::Context**))::g::Fuse::Node__FuseScriptingIScriptObjectget_ScriptContext_fn;
type->interface3.fp_add_Unrooted = (void(*)(uObject*, uDelegate*))::g::Fuse::Node__FuseINotifyUnrootedadd_Unrooted_fn;
type->interface3.fp_remove_Unrooted = (void(*)(uObject*, uDelegate*))::g::Fuse::Node__FuseINotifyUnrootedremove_Unrooted_fn;
type->interface0.fp_Insert = (void(*)(uObject*, int*, void*))::g::Fuse::Node__Insert_fn;
type->interface2.fp_get_Properties = (void(*)(uObject*, ::g::Fuse::Properties**))::g::Fuse::Node__get_Properties_fn;
type->interface4.fp_Add = (void(*)(uObject*, void*))::g::Fuse::Node__Add_fn;
type->interface4.fp_Remove = (void(*)(uObject*, void*, bool*))::g::Fuse::Node__Remove_fn;
return type;
}
// public VideoVisual() :1060
void VideoVisual__ctor_5_fn(VideoVisual* __this)
{
__this->ctor_5();
}
// protected override sealed void Attach() :1033
void VideoVisual__Attach_fn(VideoVisual* __this)
{
::g::Fuse::Controls::Video* ret5;
::g::Fuse::Controls::Video* ret6;
::g::Fuse::Controls::Video* ret7;
::g::Fuse::Controls::Video* ret8;
uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret5), ret5))->add_RenderParamChanged(uDelegate::New(::TYPES[5/*Uno.EventHandler*/], (void*)VideoVisual__OnRenderParamChanged_fn, __this));
uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret6), ret6))->add_ParamChanged(uDelegate::New(::TYPES[5/*Uno.EventHandler*/], (void*)VideoVisual__OnParamChanged_fn, __this));
uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret7), ret7))->add_SourceChanged(uDelegate::New(::TYPES[5/*Uno.EventHandler*/], (void*)VideoVisual__OnSourceChanged_fn, __this));
::g::Fuse::UpdateManager::AddAction1(uDelegate::New(::TYPES[18/*Uno.Action*/], (void*)VideoVisual__OnUpdate_fn, __this), 0);
uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret8), ret8))->SetPlayback((uObject*)__this);
__this->OnRenderParamChanged(NULL, NULL);
__this->OnParamChanged(NULL, NULL);
__this->OnSourceChanged(NULL, NULL);
}
// protected override sealed void Detach() :1047
void VideoVisual__Detach_fn(VideoVisual* __this)
{
::g::Fuse::Controls::Video* ret9;
::g::Fuse::Controls::Video* ret10;
::g::Fuse::Controls::Video* ret11;
::g::Fuse::Controls::Video* ret12;
::g::Fuse::Controls::VideoImpl::IVideoService::Unload(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]));
uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret9), ret9))->SetPlayback(NULL);
uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret10), ret10))->remove_RenderParamChanged(uDelegate::New(::TYPES[5/*Uno.EventHandler*/], (void*)VideoVisual__OnRenderParamChanged_fn, __this));
uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret11), ret11))->remove_ParamChanged(uDelegate::New(::TYPES[5/*Uno.EventHandler*/], (void*)VideoVisual__OnParamChanged_fn, __this));
uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret12), ret12))->remove_SourceChanged(uDelegate::New(::TYPES[5/*Uno.EventHandler*/], (void*)VideoVisual__OnSourceChanged_fn, __this));
::g::Fuse::UpdateManager::RemoveAction1(uDelegate::New(::TYPES[18/*Uno.Action*/], (void*)VideoVisual__OnUpdate_fn, __this), 0);
}
// public override sealed void Draw(Fuse.DrawContext dc) :1282
void VideoVisual__Draw_fn(VideoVisual* __this, ::g::Fuse::DrawContext* dc)
{
::g::Uno::Float4 ind1;
::g::Uno::Float4 ind2;
::g::Uno::Float4 ind3;
::g::Fuse::Controls::Video* ret13;
::g::Fuse::Controls::Video* ret14;
::g::Uno::Graphics::VideoTexture* texture = ::g::Fuse::Controls::VideoImpl::IVideoService::VideoTexture(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]));
if (texture == NULL)
return;
if (uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret13), ret13))->StretchMode() == 4)
uPtr(::g::Fuse::Controls::VideoImpl::Scale9Rectangle::Impl())->Draw(dc, __this, __this->ActualSize(), __this->GetSize(), texture, uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret14), ret14))->Scale9Margin());
else
{
int rotation = ::g::Fuse::Controls::VideoImpl::IVideoService::RotationDegrees(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])) / 90;
uPtr(::g::Fuse::Controls::VideoImpl::VideoDrawElement::Impl())->Draw(dc, __this, __this->_drawOrigin, __this->_drawSize, (ind1 = __this->_uvClip, ::g::Uno::Float2__New2(ind1.X, ind1.Y)), ::g::Uno::Float2__op_Subtraction2((ind2 = __this->_uvClip, ::g::Uno::Float2__New2(ind2.Z, ind2.W)), (ind3 = __this->_uvClip, ::g::Uno::Float2__New2(ind3.X, ind3.Y))), texture, rotation);
}
}
// private bool get_FlipSize() :1235
void VideoVisual__get_FlipSize_fn(VideoVisual* __this, bool* __retval)
{
*__retval = __this->FlipSize();
}
// private void Fuse.Controls.VideoImpl.IVideoCallbacks.OnCompleted() :1097
void VideoVisual__FuseControlsVideoImplIVideoCallbacksOnCompleted_fn(VideoVisual* __this)
{
::g::Fuse::Controls::Video* ret15;
__this->ResetTriggers();
::g::Fuse::Triggers::WhileCompleted::SetState((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret15), ret15), true);
}
// private void Fuse.Controls.VideoImpl.IVideoCallbacks.OnError(Uno.Exception e) :1077
void VideoVisual__FuseControlsVideoImplIVideoCallbacksOnError_fn(VideoVisual* __this, ::g::Uno::Exception* e)
{
::g::Fuse::Controls::Video* ret16;
__this->ResetTriggers();
::g::Fuse::Triggers::BusyTask::SetBusy((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret16), ret16), &__this->_busyTask, 16, uPtr(e)->Message());
::g::Fuse::Diagnostics::UnknownException(::STRINGS[5/*"Video error"*/], e, __this, ::STRINGS[6/*"/Users/paul...*/], 1081, ::STRINGS[7/*"Fuse.Contro...*/]);
}
// private void Fuse.Controls.VideoImpl.IVideoCallbacks.OnFrameAvailable() :1067
void VideoVisual__FuseControlsVideoImplIVideoCallbacksOnFrameAvailable_fn(VideoVisual* __this)
{
if (::g::Uno::Int2__op_Inequality(::g::Fuse::Controls::VideoImpl::IVideoService::Size(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])), __this->_sizeCache))
{
__this->_sizeCache = ::g::Fuse::Controls::VideoImpl::IVideoService::Size(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]));
__this->InvalidateLayout(2);
}
__this->InvalidateVisual();
}
// private void Fuse.Controls.VideoImpl.IVideoCallbacks.OnLoading() :1085
void VideoVisual__FuseControlsVideoImplIVideoCallbacksOnLoading_fn(VideoVisual* __this)
{
::g::Fuse::Controls::Video* ret17;
__this->ResetTriggers();
::g::Fuse::Triggers::BusyTask::SetBusy((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret17), ret17), &__this->_busyTask, 1, ::STRINGS[8/*""*/]);
}
// private void Fuse.Controls.VideoImpl.IVideoCallbacks.OnReady() :1091
void VideoVisual__FuseControlsVideoImplIVideoCallbacksOnReady_fn(VideoVisual* __this)
{
::g::Fuse::Controls::Video* ret18;
__this->ResetTriggers();
::g::Fuse::Triggers::BusyTask::SetBusy((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret18), ret18), &__this->_busyTask, 0, ::STRINGS[8/*""*/]);
}
// private double Fuse.Triggers.IMediaPlayback.get_Position() :1112
void VideoVisual__FuseTriggersIMediaPlaybackget_Position_fn(VideoVisual* __this, double* __retval)
{
return *__retval = ::g::Fuse::Controls::VideoImpl::IVideoService::Position(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])), void();
}
// private void Fuse.Triggers.IMediaPlayback.set_Position(double value) :1113
void VideoVisual__FuseTriggersIMediaPlaybackset_Position_fn(VideoVisual* __this, double* value)
{
double value_ = *value;
::g::Fuse::Controls::VideoImpl::IVideoService::Position(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]), value_);
}
// private void Fuse.Triggers.IPlayback.Pause() :1136
void VideoVisual__FuseTriggersIPlaybackPause_fn(VideoVisual* __this)
{
::g::Fuse::Controls::Video* ret19;
if (::g::Fuse::Controls::VideoImpl::IVideoService::IsValid(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])))
{
::g::Fuse::Controls::VideoImpl::IVideoService::Pause(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]));
__this->ResetTriggers();
::g::Fuse::Triggers::WhilePaused::SetState((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret19), ret19), true);
}
}
// private void Fuse.Triggers.IPlayback.PlayTo(double progress) :1128
void VideoVisual__FuseTriggersIPlaybackPlayTo_fn(VideoVisual* __this, double* progress)
{
::g::Fuse::Diagnostics::Unsupported(::STRINGS[9/*"IPlayback.P...*/], __this, ::STRINGS[6/*"/Users/paul...*/], 1130, ::STRINGS[10/*"Fuse.Trigge...*/]);
}
// private double Fuse.Triggers.IPlayback.get_Progress() :1163
void VideoVisual__FuseTriggersIPlaybackget_Progress_fn(VideoVisual* __this, double* __retval)
{
return *__retval = (::g::Fuse::Controls::VideoImpl::IVideoService::Duration(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])) > 1e-05) ? ::g::Fuse::Controls::VideoImpl::IVideoService::Position(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])) / ::g::Fuse::Controls::VideoImpl::IVideoService::Duration(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])) : 0.0, void();
}
// private void Fuse.Triggers.IPlayback.set_Progress(double value) :1164
void VideoVisual__FuseTriggersIPlaybackset_Progress_fn(VideoVisual* __this, double* value)
{
double value_ = *value;
::g::Fuse::Controls::VideoImpl::IVideoService::Position(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]), ::g::Fuse::Controls::VideoImpl::IVideoService::Duration(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])) * value_);
}
// private void Fuse.Triggers.IPlayback.Resume() :1146
void VideoVisual__FuseTriggersIPlaybackResume_fn(VideoVisual* __this)
{
::g::Fuse::Controls::Video* ret20;
if (::g::Fuse::Controls::VideoImpl::IVideoService::IsValid(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])))
{
__this->ResetTriggers();
::g::Fuse::Triggers::WhilePlaying::SetState((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret20), ret20), true);
::g::Fuse::Controls::VideoImpl::IVideoService::Play(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]));
}
}
// private void Fuse.Triggers.IPlayback.Stop() :1121
void VideoVisual__FuseTriggersIPlaybackStop_fn(VideoVisual* __this)
{
::g::Fuse::Triggers::IPlayback::Pause(uInterface((uObject*)__this, ::TYPES[20/*Fuse.Triggers.IPlayback*/]));
::g::Fuse::Triggers::IMediaPlayback::Position(uInterface((uObject*)__this, ::TYPES[21/*Fuse.Triggers.IMediaPlayback*/]), 0.0);
}
// private double Fuse.Triggers.IProgress.get_Progress() :1158
void VideoVisual__FuseTriggersIProgressget_Progress_fn(VideoVisual* __this, double* __retval)
{
return *__retval = (::g::Fuse::Controls::VideoImpl::IVideoService::Duration(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])) > 1e-05) ? ::g::Fuse::Controls::VideoImpl::IVideoService::Position(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])) / ::g::Fuse::Controls::VideoImpl::IVideoService::Duration(uInterface(uPtr(__this->_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])) : 0.0, void();
}
// private void Fuse.Triggers.IProgress.add_ProgressChanged(Uno.UX.ValueChangedHandler<double> value) :1173
void VideoVisual__FuseTriggersIProgressadd_ProgressChanged_fn(VideoVisual* __this, uDelegate* value)
{
__this->add_ProgressChanged(value);
}
// private void Fuse.Triggers.IProgress.remove_ProgressChanged(Uno.UX.ValueChangedHandler<double> value) :1174
void VideoVisual__FuseTriggersIProgressremove_ProgressChanged_fn(VideoVisual* __this, uDelegate* value)
{
__this->remove_ProgressChanged(value);
}
// public override sealed float2 GetMarginSize(Fuse.LayoutParams lp) :1242
void VideoVisual__GetMarginSize_fn(VideoVisual* __this, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval)
{
::g::Fuse::Controls::Video* ret21;
::g::Fuse::Controls::Video* ret22;
::g::Fuse::LayoutParams lp_ = *lp;
uPtr(__this->_sizing)->snapToPixels = uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret21), ret21))->SnapToPixels();
uPtr(__this->_sizing)->absoluteZoom = uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret22), ret22))->AbsoluteZoom();
return *__retval = uPtr(__this->_sizing)->ExpandFillSize(__this->GetSize(), lp_), void();
}
// private float2 GetSize() :1250
void VideoVisual__GetSize_fn(VideoVisual* __this, ::g::Uno::Float2* __retval)
{
*__retval = __this->GetSize();
}
// public VideoVisual New() :1060
void VideoVisual__New2_fn(VideoVisual** __retval)
{
*__retval = VideoVisual::New2();
}
// protected override sealed float2 OnArrangeMarginBox(float2 position, Fuse.LayoutParams lp) :1263
void VideoVisual__OnArrangeMarginBox_fn(VideoVisual* __this, ::g::Uno::Float2* position, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval)
{
::g::Uno::Float2 ret23;
::g::Uno::Float2 position_ = *position;
::g::Fuse::LayoutParams lp_ = *lp;
::g::Fuse::Controls::Video* ret24;
::g::Fuse::Controls::Video* ret25;
::g::Uno::Float2 size = (::g::Fuse::Controls::Graphics::Visual__OnArrangeMarginBox_fn(__this, uCRef(position_), uCRef(lp_), &ret23), ret23);
uPtr(__this->_sizing)->snapToPixels = uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret24), ret24))->SnapToPixels();
uPtr(__this->_sizing)->absoluteZoom = uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(__this, &ret25), ret25))->AbsoluteZoom();
::g::Uno::Float2 contentDesiredSize = __this->GetSize();
__this->_scale = uPtr(__this->_sizing)->CalcScale(size, contentDesiredSize);
__this->_origin = uPtr(__this->_sizing)->CalcOrigin(size, ::g::Uno::Float2__op_Multiply2(contentDesiredSize, __this->_scale));
__this->_drawOrigin = __this->_origin;
__this->_drawSize = ::g::Uno::Float2__op_Multiply2(contentDesiredSize, __this->_scale);
__this->_uvClip = uPtr(__this->_sizing)->CalcClip(size, &__this->_drawOrigin, &__this->_drawSize);
return *__retval = size, void();
}
// protected override sealed void OnHitTest(Fuse.HitTestContext htc) :1300
void VideoVisual__OnHitTest_fn(VideoVisual* __this, ::g::Fuse::HitTestContext* htc)
{
::g::Uno::Float2 lp = uPtr(htc)->LocalPoint();
if ((((lp.X >= __this->_drawOrigin.X) && (lp.X <= (__this->_drawOrigin.X + __this->_drawSize.X))) && (lp.Y >= __this->_drawOrigin.Y)) && (lp.Y <= (__this->_drawOrigin.Y + __this->_drawSize.Y)))
uPtr(htc)->Hit(__this);
::g::Fuse::Visual__OnHitTest_fn(__this, htc);
}
// private void OnParamChanged(object sender, Uno.EventArgs args) :1203
void VideoVisual__OnParamChanged_fn(VideoVisual* __this, uObject* sender, ::g::Uno::EventArgs* args)
{
__this->OnParamChanged(sender, args);
}
// private void OnProgressChanged() :1178
void VideoVisual__OnProgressChanged_fn(VideoVisual* __this)
{
__this->OnProgressChanged();
}
// private void OnRenderParamChanged(object sender, Uno.EventArgs args) :1194
void VideoVisual__OnRenderParamChanged_fn(VideoVisual* __this, uObject* sender, ::g::Uno::EventArgs* args)
{
__this->OnRenderParamChanged(sender, args);
}
// private void OnSourceChanged(object sender, Uno.EventArgs args) :1210
void VideoVisual__OnSourceChanged_fn(VideoVisual* __this, uObject* sender, ::g::Uno::EventArgs* args)
{
__this->OnSourceChanged(sender, args);
}
// private void OnUpdate() :1187
void VideoVisual__OnUpdate_fn(VideoVisual* __this)
{
__this->OnUpdate();
}
// private generated void add_ProgressChanged(Uno.UX.ValueChangedHandler<double> value) :1177
void VideoVisual__add_ProgressChanged_fn(VideoVisual* __this, uDelegate* value)
{
__this->add_ProgressChanged(value);
}
// private generated void remove_ProgressChanged(Uno.UX.ValueChangedHandler<double> value) :1177
void VideoVisual__remove_ProgressChanged_fn(VideoVisual* __this, uDelegate* value)
{
__this->remove_ProgressChanged(value);
}
// private void ResetTriggers() :1225
void VideoVisual__ResetTriggers_fn(VideoVisual* __this)
{
__this->ResetTriggers();
}
// public VideoVisual() [instance] :1060
void VideoVisual::ctor_5()
{
_sizeCache = ::g::Uno::Int2__New2(0, 0);
_volume = 1.0f;
ctor_4();
_sizing = ::g::Fuse::Internal::SizingContainer::New1();
_videoService = (uObject*)::g::Fuse::Controls::VideoImpl::GraphicsVideoService::New1((uObject*)this);
}
// private bool get_FlipSize() [instance] :1235
bool VideoVisual::FlipSize()
{
int degrees = ::g::Fuse::Controls::VideoImpl::IVideoService::RotationDegrees(uInterface(uPtr(_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]));
return (degrees == 90) || (degrees == 270);
}
// private float2 GetSize() [instance] :1250
::g::Uno::Float2 VideoVisual::GetSize()
{
::g::Uno::Float2 size = ::g::Uno::Float2__op_Implicit1(::g::Fuse::Controls::VideoImpl::IVideoService::Size(uInterface(uPtr(_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])));
if (FlipSize())
size = ::g::Uno::Float2__New2(size.Y, size.X);
return size;
}
// private void OnParamChanged(object sender, Uno.EventArgs args) [instance] :1203
void VideoVisual::OnParamChanged(uObject* sender, ::g::Uno::EventArgs* args)
{
::g::Fuse::Controls::Video* ret26;
::g::Fuse::Controls::Video* ret27;
::g::Fuse::Controls::Video* ret28;
::g::Fuse::Controls::VideoImpl::IVideoService::IsLooping(uInterface(uPtr(_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]), uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret26), ret26))->IsLooping());
::g::Fuse::Controls::VideoImpl::IVideoService::AutoPlay(uInterface(uPtr(_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]), uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret27), ret27))->AutoPlay());
::g::Fuse::Controls::VideoImpl::IVideoService::Volume(uInterface(uPtr(_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]), uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret28), ret28))->Volume());
}
// private void OnProgressChanged() [instance] :1178
void VideoVisual::OnProgressChanged()
{
::g::Uno::UX::ValueChangedArgs* ret29;
if (::g::Uno::Delegate::op_Inequality(ProgressChanged1, NULL))
{
double progress = ::g::Fuse::Triggers::IPlayback::Progress(uInterface((uObject*)this, ::TYPES[20/*Fuse.Triggers.IPlayback*/]));
uPtr(ProgressChanged1)->Invoke(2, this, (::g::Uno::UX::ValueChangedArgs__New2_fn(::TYPES[22/*Uno.UX.ValueChangedArgs<double>*/], uCRef(progress), &ret29), ret29));
}
}
// private void OnRenderParamChanged(object sender, Uno.EventArgs args) [instance] :1194
void VideoVisual::OnRenderParamChanged(uObject* sender, ::g::Uno::EventArgs* args)
{
::g::Fuse::Controls::Video* ret30;
::g::Fuse::Controls::Video* ret31;
::g::Fuse::Controls::Video* ret32;
::g::Fuse::Controls::Video* ret33;
uPtr(_sizing)->SetStretchMode(uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret30), ret30))->StretchMode());
uPtr(_sizing)->SetStretchDirection(uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret31), ret31))->StretchDirection());
uPtr(_sizing)->SetStretchSizing(uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret32), ret32))->StretchSizing());
uPtr(_sizing)->SetAlignment(uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret33), ret33))->ContentAlignment());
InvalidateVisual();
}
// private void OnSourceChanged(object sender, Uno.EventArgs args) [instance] :1210
void VideoVisual::OnSourceChanged(uObject* sender, ::g::Uno::EventArgs* args)
{
::g::Fuse::Controls::Video* ret34;
::g::Fuse::Controls::Video* ret35;
::g::Fuse::Controls::Video* ret36;
::g::Fuse::Controls::Video* ret37;
if (uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret34), ret34))->File() != NULL)
{
::g::Fuse::Controls::VideoImpl::IVideoService::Load1(uInterface(uPtr(_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]), uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret35), ret35))->File());
return;
}
if (::g::Uno::String::op_Inequality(uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret36), ret36))->Url(), NULL))
{
::g::Fuse::Controls::VideoImpl::IVideoService::Load(uInterface(uPtr(_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]), uPtr((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret37), ret37))->Url());
return;
}
}
// private void OnUpdate() [instance] :1187
void VideoVisual::OnUpdate()
{
::g::Fuse::Controls::VideoImpl::IVideoService::Update(uInterface(uPtr(_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/]));
if (::g::Fuse::Controls::VideoImpl::IVideoService::IsValid(uInterface(uPtr(_videoService), ::TYPES[19/*Fuse.Controls.VideoImpl.IVideoService*/])))
OnProgressChanged();
}
// private generated void add_ProgressChanged(Uno.UX.ValueChangedHandler<double> value) [instance] :1177
void VideoVisual::add_ProgressChanged(uDelegate* value)
{
ProgressChanged1 = uCast<uDelegate*>(::g::Uno::Delegate::Combine(ProgressChanged1, value), ::TYPES[23/*Uno.UX.ValueChangedHandler<double>*/]);
}
// private generated void remove_ProgressChanged(Uno.UX.ValueChangedHandler<double> value) [instance] :1177
void VideoVisual::remove_ProgressChanged(uDelegate* value)
{
ProgressChanged1 = uCast<uDelegate*>(::g::Uno::Delegate::Remove(ProgressChanged1, value), ::TYPES[23/*Uno.UX.ValueChangedHandler<double>*/]);
}
// private void ResetTriggers() [instance] :1225
void VideoVisual::ResetTriggers()
{
::g::Fuse::Controls::Video* ret38;
::g::Fuse::Controls::Video* ret39;
::g::Fuse::Controls::Video* ret40;
::g::Fuse::Controls::Video* ret41;
::g::Fuse::Triggers::BusyTask::SetBusy((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret38), ret38), &_busyTask, 0, ::STRINGS[8/*""*/]);
::g::Fuse::Triggers::WhileCompleted::SetState((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret39), ret39), false);
::g::Fuse::Triggers::WhilePlaying::SetState((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret40), ret40), false);
::g::Fuse::Triggers::WhilePaused::SetState((::g::Fuse::Controls::Graphics::ControlVisual__get_Control_fn(this, &ret41), ret41), false);
}
// public VideoVisual New() [static] :1060
VideoVisual* VideoVisual::New2()
{
VideoVisual* obj4 = (VideoVisual*)uNew(VideoVisual_typeof());
obj4->ctor_5();
return obj4;
}
// }
}}}} // ::g::Fuse::Controls::VideoImpl
| [
"frpaulas@gmail.com"
] | frpaulas@gmail.com |
fbc721c1d42a1f64f84a517fa13aa3cd2303fa81 | 0a5ba12251ff6fc2c7090121b91f1aebee513219 | /src/Engine/HotSpotEventReceiverInterface.h | 4238e3b3e0c7fed1c5c54747e170229008ae3c1b | [] | no_license | AlexKLWS/Mengine | 0bfa0b7556ba0b0dd0e3606425bce0a6d04d0c37 | b4a93363f70f4f1b83720b9432e0919a89f6bdb1 | refs/heads/master | 2020-03-21T13:57:20.378867 | 2019-07-16T17:54:58 | 2019-07-16T17:54:58 | 138,633,973 | 0 | 0 | null | 2018-06-25T18:22:53 | 2018-06-25T18:22:52 | null | UTF-8 | C++ | false | false | 1,828 | h | #pragma once
#include "Interface/EventationInterface.h"
#include "Interface/InputHandlerInterface.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
enum HotSpotEventFlag
{
EVENT_KEY = 0,
EVENT_TEXT,
EVENT_MOUSE_BUTTON,
EVENT_MOUSE_BUTTON_BEGIN,
EVENT_MOUSE_BUTTON_END,
EVENT_MOUSE_WHEEL,
EVENT_MOUSE_MOVE,
EVENT_MOUSE_ENTER,
EVENT_MOUSE_LEAVE,
EVENT_MOUSE_OVER_DESTROY,
EVENT_ACTIVATE,
EVENT_DEACTIVATE
};
//////////////////////////////////////////////////////////////////////////
class HotSpotEventReceiverInterface
: public EventReceiverInterface
{
public:
virtual void onHotSpotActivate() = 0;
virtual void onHotSpotDeactivate() = 0;
virtual bool onHotSpotMouseEnter( const InputMouseEnterEvent & _event ) = 0;
virtual void onHotSpotMouseLeave( const InputMouseLeaveEvent & _event ) = 0;
virtual bool onHotSpotKey( const InputKeyEvent & _event ) = 0;
virtual bool onHotSpotText( const InputTextEvent & _event ) = 0;
virtual bool onHotSpotMouseButton( const InputMouseButtonEvent & _event ) = 0;
virtual bool onHotSpotMouseButtonBegin( const InputMouseButtonEvent & _event ) = 0;
virtual bool onHotSpotMouseButtonEnd( const InputMouseButtonEvent & _event ) = 0;
virtual bool onHotSpotMouseMove( const InputMouseMoveEvent & _event ) = 0;
virtual bool onHotSpotMouseWheel( const InputMouseWheelEvent & _event ) = 0;
virtual void onHotSpotMouseOverDestroy() = 0;
virtual void onHotSpotMouseButtonBegin( uint32_t _enumerator, bool _isEnd ) = 0;
virtual void onHotSpotMouseButtonEnd( uint32_t _enumerator, bool _isEnd ) = 0;
};
} | [
"irov13@mail.ru"
] | irov13@mail.ru |
4153a16e3168e241e2dcf7fbef619bd664de420a | 7d132eae1c4d1e572f42869bf1da5b094c53c25b | /Assignments/hw5/stack.h | 13a641e936a5057490668e768d11fd79f2c18e28 | [] | no_license | afreet220/CSCI104_DataStructure | bf8c83c3b61814daa3fbc550b152a2093ed5af35 | fb05514608489a858ff36b33cfeec7e531c22b5c | refs/heads/master | 2021-01-10T14:54:38.028428 | 2015-10-15T10:47:03 | 2015-10-15T10:47:03 | 44,303,931 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,222 | h | #ifndef STACK_H_
#define STACK_H_
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <exception>
#include <cstddef>
#include <stdexcept>
#include "ilist.h"
#include "arraylist.h"
using namespace std;
template <class T>
class Stack : private ArrayList<T>
{
public:
// add appropriate constructors and destructors
Stack();
virtual ~Stack();
bool isEmpty() const;
/* returns whether the stack contains any elements */
void push(const T& val);
/* adds a value to the top of the stack */
void pop();
/* deletes the top value from the stack */
T const & top() const;
/* returns the top value on the stack */
};
template <class T>
Stack<T>::Stack()
{
}
template <class T>
Stack<T>::~Stack()
{
}
template <class T>
bool Stack<T>::isEmpty() const
{
if (ArrayList<T>::size() == 0)
{
return true;
}
else {
return false;
}
}
template <class T>
void Stack<T>::push(const T& val)
{
ArrayList<T>::insert(ArrayList<T>::size(),val);
}
template <class T>
void Stack<T>::pop()
{
ArrayList<T>::remove(ArrayList<T>::size()-1);
}
template <class T>
T const & Stack<T>::top() const
{
return ArrayList<T>::get(ArrayList<T>::size()-1);
}
#endif /* STACK_H_ */
| [
"hcui@usc.edu"
] | hcui@usc.edu |
580f6eb09f1765365a03a394a50c4169eda25062 | bfd9c1b6f4d29ea6fac7ca42af9ef9053610fb73 | /gcm4-eve3.ino | 50c0325d46ca9640d640543f1e9010e7f18610ca | [
"ISC"
] | permissive | Chase-san/GCM4-BT81X-EVE3 | 5bc935c5be988f99ff65073a3e26a95e56e9667d | 13790b6301d58d73bd90630bc5b505730aa91301 | refs/heads/master | 2023-01-29T09:13:02.513099 | 2020-12-06T08:44:45 | 2020-12-06T08:44:45 | 318,928,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,373 | ino | /**
* Copyright (c) 2020, Robert Maupin
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "bt81x.h"
#include "device.h"
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
device_init();
delay(1000);
Serial.println("Starting Eve3.");
bt81x_init(&rvt70eve3);
Serial.printf("Chip ID %08x\n", bt81x_read_chipid());
Serial.printf("Freq %08d Hz\n", bt81x_read_frequency());
digitalWrite(LED_BUILTIN, LOW);
}
uint32_t cycles = 0;
uint64_t lastTime = 0;
void loop() {
uint64_t time = millis();
if (time - lastTime >= 1000) {
bt81x_demo_cps(cycles);
cycles = 0;
lastTime = time;
}
++cycles;
bt81x_demo_loop();
}
| [
"chasesan@gmail.com"
] | chasesan@gmail.com |
3b53a71e83e8aff20c9c85813bb61bdf80b45290 | b92769dda6c8b7e9bf79c48df810a702bfdf872f | /8.AdventuresInFunctions/8.7.strquote.cpp | 1aaea317d81ddd6683b42ee20c5fd67256ade4bb | [
"MIT"
] | permissive | HuangStomach/Cpp-primer-plus | 4276e0a24887ef6d48f202107b7b4c448230cd20 | c8b2b90f10057e72da3ab570da7cc39220c88f70 | refs/heads/master | 2021-06-25T07:22:15.405581 | 2021-02-28T06:55:23 | 2021-02-28T06:55:23 | 209,192,905 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,273 | cpp | #include <iostream>
#include <string>
using namespace std;
string version1(const string & s1, const string & s2);
const string & version2(const string & s1, const string & s2);
const string & version3(const string & s1, const string & s2);
int main(int argc, char const *argv[]) {
string input;
string copy;
string result;
cout << "Enter a string: ";
getline(cin, input);
copy = input;
cout << "Your string: " << input << endl;
result = version1(input, "***");
cout << "Your result: " << result << endl;
cout << "Your string: " << input << endl;
result = version2(input, "###");
cout << "Your result: " << result << endl;
cout << "Your string: " << input << endl;
cout << "Resetting original string." << endl;
input = copy;
result = version3(input, "@@@");
cout << "Your result: " << result << endl;
cout << "Your string: " << input << endl;
return 0;
}
string version1(const string & s1, const string & s2) {
string temp;
temp = s2 + s1 + s2;
return temp;
}
const string & version2(string & s1, const string & s2) {
s1 = s2 + s1 + s2;
return s1;
}
const string & version3(string & s1, const string & s2) {
string temp;
temp = s2 + s1 + s2;
return temp;
}
| [
"nxmbest@qq.com"
] | nxmbest@qq.com |
44d68cd67e19a445aedc8d5ef47f423710e325ec | 4184532108d8514ae215d59b4dad6b7502ed0264 | /kernel.cpp | b5ea513eb48c8f7388a1c6af80262ef69b0231a7 | [] | no_license | rzel/s-os | 2868ea4a7cbada8ff6f8db750ce8156760604673 | d19a73cd1f76a22ea5051b7c16836d15a53e8a77 | refs/heads/master | 2016-08-03T10:50:25.374235 | 2008-09-30T07:40:41 | 2008-09-30T07:40:41 | 40,682,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,095 | cpp | // This is the kernel object
#include "include/kernel.h"
using namespace std;
kernel * kernel_i;
kernel::kernel()
{
vid = new video();
vid->write("Starting SoS...\n\n", 14);
init();
}
kernel::~kernel()
{
vid->write("\n\nShutting Down...\n\n", 14);
terminate();
}
void kernel::init()
{
#ifdef PLATFORM_x86_64
enable_long_mode();
#endif
gdt_i = new gdt();
idt_i = new idt();
paging_i = new paging();
// Virtual File System
vfs_i = new vfs();
// Device Drivers
keyboard_i = new keyboard();
timer_i = new timer();
seashell_i = new seashell();
}
#ifdef PLATFORM_x86_64
void kernel::enable_long_mode()
{
// This function will only be called if the platform is defined as
// X86_64 in common.h.
vid->write("Jumping to Long Mode");
// First we check the CPUID information to see if the processor can
// support 64 bit code
if(!cpuid_check_flag(CPUID_FLAG_IA64))
{
vid->write("\t\t\t[FAIL]\n\n", 4);
panic("This processor does not support 64 bit long mode,\nand is unable to run this version of SoS.\n\nFor more information, please cousult the user manual");
halt();
}
// Will be if PAE bit is set (because we are already in long mode.s
if(1 == 0)
{
vid->write("\t\t\t[DONE]\n", 11);
return; // Exit
}
vid->write("\t\t\t[OK]\n", 2);
fixme("Jump to Long mode here");
}
#endif
void kernel::terminate()
{
delete seashell_i;
delete paging_i;
delete gdt_i;
delete idt_i;
delete vfs_i;
delete keyboard_i;
delete timer_i;
delete vid;
destruct();
__cxa_finalize(0);
// Restart for now
restart();
}
void kernel::restart()
{
u32int i;
disable();
do
{
i = inb(0x64);
if(i & 0x01)
{
(void)inb(0x60);
continue;
}
} while(i & 0x02);
outb(0x64, 0xFE);
halt();
}
void kernel::calculate_memory(struct multiboot * mboot_ptr)
{
u32int upper = mboot_ptr->mem_upper;
u32int lower = mboot_ptr->mem_lower;
vid->write("Calculating Memory\t\t\t");
total_memory = upper + lower;
vid->putint((u32int) total_memory / 1024, 2);
vid->write("MB detected\n", 2);
}
| [
"stephen.13@39fd31e7-933e-0410-a28a-1bbd0007c3db"
] | stephen.13@39fd31e7-933e-0410-a28a-1bbd0007c3db |
fc6e9ee31b002f1787cf1f5ae5107a6431f0a36e | 57d1d62e1a10282e8d4faa42e937c486102ebf04 | /judges/codeforces/done/381a.cpp | 821790ba3df07586961d9f05881f4c715a07bc92 | [] | no_license | diegoximenes/icpc | 91a32a599824241247a8cc57a2618563f433d6ea | 8c7ee69cc4a1f3514dddc0e7ae37e9fba0be8401 | refs/heads/master | 2022-10-12T11:47:10.706794 | 2022-09-24T04:03:31 | 2022-09-24T04:03:31 | 178,573,955 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 416 | cpp | #include<cstdio>
using namespace std;
int main()
{
int n, v[1010], sereja = 0, dima = 0;
scanf("%d", &n);
for(int i=0; i<n; ++i) scanf("%d", &v[i]);
int i = 0, j = n-1;
bool isSereja = 1;
while(i <= j)
{
int aux;
if(v[i] > v[j]) aux = v[i], ++i;
else aux = v[j], --j;
if(isSereja) sereja += aux, isSereja = 0;
else dima += aux, isSereja = 1;
}
printf("%d %d\n", sereja, dima);
return 0;
}
| [
"dxmendes1@gmail.com"
] | dxmendes1@gmail.com |
51720eea7a05e34240fc445fbccfb474f074599e | 5988ea61f0a5b61fef8550601b983b46beba9c5d | /3rd/ACE-5.7.0/ACE_wrappers/ace/DLL_Manager.cpp | 63d956b078d3ca63efb76c21a23fec9b0fbb270c | [
"MIT"
] | permissive | binghuo365/BaseLab | e2fd1278ee149d8819b29feaa97240dec7c8b293 | 2b7720f6173672efd9178e45c3c5a9283257732a | refs/heads/master | 2016-09-15T07:50:48.426709 | 2016-05-04T09:46:51 | 2016-05-04T09:46:51 | 38,291,364 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 25,144 | cpp | // $Id: DLL_Manager.cpp 85321 2009-05-12 08:31:31Z johnnyw $
#include "ace/DLL_Manager.h"
#include "ace/Log_Msg.h"
#include "ace/ACE.h"
#include "ace/Framework_Component.h"
#include "ace/Lib_Find.h"
#include "ace/Object_Manager.h"
#include "ace/SString.h"
#include "ace/Recursive_Thread_Mutex.h"
#include "ace/Guard_T.h"
#include "ace/OS_NS_dlfcn.h"
#include "ace/OS_NS_string.h"
ACE_RCSID (ace,
DLL_Manager,
"DLL_Manager.cpp,v 4.23 2003/11/05 23:30:46 shuston Exp")
/******************************************************************/
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
sig_atomic_t ACE_DLL_Handle::open_called_ = 0;
ACE_DLL_Handle::ACE_DLL_Handle (void)
: refcount_ (0),
dll_name_ (0),
handle_ (ACE_SHLIB_INVALID_HANDLE)
{
ACE_TRACE ("ACE_DLL_Handle::ACE_DLL_Handle");
}
ACE_DLL_Handle::~ACE_DLL_Handle (void)
{
ACE_TRACE ("ACE_DLL_Handle::~ACE_DLL_Handle");
this->close (1);
delete[] this->dll_name_;
}
const ACE_TCHAR *
ACE_DLL_Handle::dll_name (void) const
{
ACE_TRACE ("ACE_DLL_Handle::dll_name");
return this->dll_name_;
}
int
ACE_DLL_Handle::open (const ACE_TCHAR *dll_name,
int open_mode,
ACE_SHLIB_HANDLE handle)
{
ACE_TRACE ("ACE_DLL_Handle::open");
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0));
if (this->dll_name_)
{
// Once dll_name_ has been set, it can't be changed..
if (ACE_OS::strcmp (this->dll_name_, dll_name) != 0)
{
if (ACE::debug ())
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("(%P|%t) DLL_Handle::open: error, ")
ACE_TEXT ("tried to reopen %s with name %s\n"),
this->dll_name_,
dll_name));
return -1;
}
}
else
this->dll_name_ = ACE::strnew (dll_name);
if (!this->open_called_)
this->open_called_ = 1;
// If it hasn't been loaded yet, go ahead and do that now.
if (this->handle_ == ACE_SHLIB_INVALID_HANDLE)
{
if (handle)
this->handle_ = handle;
else
{
/*
** Get the set of names to try loading. We need to do this to
** properly support the ability for a user to specify a simple,
** unadorned name (for example, "ACE") that will work across
** platforms. We apply platform specifics to get a name that will
** work (e.g. libACE, ACEd.dll, ACE.dll, etc.) We rely on the
** underlying dlopen() implementation to "Do The Right Thing" in
** terms of using relative paths, LD_LIBRARY_PATH, system security
** rules, etc. except when ACE_MUST_HELP_DLOPEN_SEARCH_PATH is set.
** If it is set, then ACE::ldfind() scans the configured path
** looking for a match on the name and prefix/suffix applications.
** NOTE: having ACE scan for a file and then pass a fully-qualified
** pathname to dlopen() is a potential security hole; therefore,
** do not use ACE_MUST_HELP_DLOPEN_SEARCH_PATH unless necessary
** and only after considering the risks.
*/
ACE_Array<ACE_TString> dll_names;
dll_names.max_size (10); // Decent guess to avoid realloc later
#if defined (ACE_MUST_HELP_DLOPEN_SEARCH_PATH)
// Find out where the library is
ACE_TCHAR dll_pathname[MAXPATHLEN + 1];
// Transform the pathname into the appropriate dynamic link library
// by searching the ACE_LD_SEARCH_PATH.
ACE::ldfind (dll_name,
dll_pathname,
(sizeof dll_pathname / sizeof (ACE_TCHAR)));
ACE_TString dll_str (dll_pathname);
dll_names.size (1);
dll_names.set (dll_str, 0);
#else
this->get_dll_names (dll_name, dll_names);
#endif
ACE_Array_Iterator<ACE_TString> name_iter (dll_names);
ACE_TString *name = 0;
while (name_iter.next (name))
{
// The ACE_SHLIB_HANDLE object is obtained.
this->handle_ = ACE_OS::dlopen (name->c_str (),
open_mode);
if (ACE::debug ())
{
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ")
ACE_TEXT ("(\"%s\", 0x%x) -> %s: %s\n"),
name->c_str (),
open_mode,
((this->handle_ != ACE_SHLIB_INVALID_HANDLE)
? ACE_TEXT ("succeeded")
: ACE_TEXT ("failed")),
this->error()->c_str()));
}
if (this->handle_ != ACE_SHLIB_INVALID_HANDLE) // Good one?
break;
// If errno is ENOENT we just skip over this one,
// anything else - like an undefined symbol, for
// instance must be flagged here or the next error will
// mask it.
// @TODO: If we've found our DLL _and_ it's
// broken, should we continue at all?
if ((errno != 0) && (errno != ENOENT) && ACE::debug ())
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ")
ACE_TEXT ("(\'%s\') failed, errno=")
ACE_TEXT ("%d: %s\n"),
name->c_str (),
ACE_ERRNO_GET,
this->error ()->c_str ()));
#if defined (AIX)
// AIX often puts the shared library file (most often named
// shr.o) inside an archive library. If this is an archive
// library name, then try appending [shr.o] and retry.
if (ACE_TString::npos != name->strstr (ACE_TEXT (".a")))
{
ACE_TCHAR aix_pathname[MAXPATHLEN + 1];
ACE_OS::strncpy (aix_pathname,
name->c_str (),
name->length ());
aix_pathname[name->length ()] = '\0';
ACE_OS::strcat (aix_pathname, ACE_TEXT ("(shr.o)"));
open_mode |= RTLD_MEMBER;
if (ACE::debug ())
{
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ")
ACE_TEXT ("(\"%s\", 0x%x) -> %s: %s\n"),
aix_pathname,
open_mode,
(this->handle_ != ACE_SHLIB_INVALID_HANDLE
? ACE_TEXT ("succeeded")
: ACE_TEXT ("failed")),
this->error()->c_str()));
}
this->handle_ = ACE_OS::dlopen (aix_pathname, open_mode);
if (this->handle_ != ACE_SHLIB_INVALID_HANDLE)
break;
// If errno is ENOENT we just skip over this one, anything
// else - like an undefined symbol, for instance
// must be flagged here or the next error will mask it.
//
// @TODO: If we've found our DLL _and_ it's broken,
// should we continue at all?
if (ACE::debug () && (errno != 0) && (errno != ENOENT))
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ACE (%P|%t) DLL_Handle::open ")
ACE_TEXT ("(\'%s\') failed, errno=")
ACE_TEXT ("%d: %s\n"),
name->c_str (),
errno,
this->error ()->c_str ()));
}
#endif /* AIX */
name_iter.advance ();
}
if (this->handle_ == ACE_SHLIB_INVALID_HANDLE)
{
if (ACE::debug ())
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ACE (%P|%t) DLL_Handle::open (\"%s\"): ")
ACE_TEXT ("Invalid handle error: %s\n"),
this->dll_name_,
this->error ()->c_str ()));
return -1;
}
}
}
++this->refcount_;
if (ACE::debug ())
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("ACE (%P|%t) DLL_Handle::open - %s (%d), refcount=%d\n"),
this->dll_name_,
this->handle_,
this->refcount_));
return 0;
}
int
ACE_DLL_Handle::close (int unload)
{
ACE_TRACE ("ACE_DLL_Handle::close");
int retval = 0;
ACE_SHLIB_HANDLE h = ACE_SHLIB_INVALID_HANDLE;
// Only hold the lock until it comes time to dlclose() the DLL. Closing
// the DLL can cause further shutdowns as DLLs and their dependents are
// unloaded.
{
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0));
// Since we don't actually unload the dll as soon as the refcount
// reaches zero, we need to make sure we don't decrement it below
// zero.
if (this->refcount_ > 0)
--this->refcount_;
else
this->refcount_ = 0;
if (ACE::debug ())
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("ACE (%P|%t) DLL_Handle::close - ")
ACE_TEXT ("%s (handle=%d, refcount=%d)\n"),
this->dll_name_,
this->handle_,
this->refcount_));
if (this->refcount_ == 0 &&
this->handle_ != ACE_SHLIB_INVALID_HANDLE &&
unload == 1)
{
if (ACE::debug ())
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("ACE (%P|%t) DLL_Handle::close: ")
ACE_TEXT ("Unloading %s (handle=%d)\n"),
this->dll_name_,
this->handle_));
// First remove any associated Framework Components.
ACE_Framework_Repository *frPtr= ACE_Framework_Repository::instance ();
if (frPtr)
{
frPtr->remove_dll_components (this->dll_name_);
}
h = this->handle_;
this->handle_ = ACE_SHLIB_INVALID_HANDLE;
}
} // Release lock_ here
if (h != ACE_SHLIB_INVALID_HANDLE)
{
retval = ACE_OS::dlclose (h);
if (retval != 0 && ACE::debug ())
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ACE (%P|%t) DLL_Handle::close - ")
ACE_TEXT ("Failed with: \"%s\".\n"),
this->error ()->c_str ()));
}
return retval;
}
sig_atomic_t
ACE_DLL_Handle::refcount (void) const
{
return this->refcount_;
}
void *
ACE_DLL_Handle::symbol (const ACE_TCHAR *sym_name, int ignore_errors)
{
ACE_TRACE ("ACE_DLL_Handle::symbol");
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0));
ACE_Auto_Array_Ptr <ACE_TCHAR> auto_name (ACE::ldname (sym_name));
// handle_ can be invalid especially when ACE_DLL_Handle resigned ownership
// BTW. Handle lifecycle management is a little crazy in ACE
if (this->handle_ != ACE_SHLIB_INVALID_HANDLE)
{
#if defined (ACE_OPENVMS)
void *sym = ACE::ldsymbol (this->handle_, auto_name.get ());
#else
void *sym = ACE_OS::dlsym (this->handle_, auto_name.get ());
#endif
// Linux says that the symbol could be null and that it isn't an
// error. So you should check the error message also, but since
// null symbols won't do us much good anyway, let's still report
// an error.
if (!sym && ignore_errors != 1)
{
if (ACE::debug ())
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ACE (%P|%t) DLL_Handle::symbol (\"%s\") ")
ACE_TEXT (" failed with \"%s\".\n"),
auto_name.get (),
this->error ()->c_str ()));
return 0;
}
return sym;
}
return 0;
}
ACE_SHLIB_HANDLE
ACE_DLL_Handle::get_handle (int become_owner)
{
ACE_TRACE ("ACE_DLL_Handle::get_handle");
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0));
if (this->refcount_ == 0 && become_owner != 0)
{
if (ACE::debug ())
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ACE (%P|%t) DLL_Handle::get_handle: ")
ACE_TEXT ("cannot become owner, refcount == 0.\n")));
return ACE_SHLIB_INVALID_HANDLE;
}
ACE_SHLIB_HANDLE handle = this->handle_;
if (become_owner != 0)
{
if (--this->refcount_ == 0)
this->handle_ = ACE_SHLIB_INVALID_HANDLE;
}
if (ACE::debug ())
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("ACE (%P|%t) ACE_DLL_Handle::get_handle: ")
ACE_TEXT ("post call: handle %s, refcount %d\n"),
this->handle_ == ACE_SHLIB_INVALID_HANDLE ?
ACE_TEXT ("invalid") : ACE_TEXT ("valid"),
this->refcount_));
return handle;
}
// This method is used return the last error of a library operation.
auto_ptr <ACE_TString>
ACE_DLL_Handle::error (void)
{
ACE_TRACE ("ACE_DLL_Handle::error");
const ACE_TCHAR *error = ACE_OS::dlerror ();
auto_ptr<ACE_TString> str
(new ACE_TString (error ? error : ACE_TEXT ("no error")));
return str;
}
void
ACE_DLL_Handle::get_dll_names (const ACE_TCHAR *dll_name,
ACE_Array<ACE_TString> &try_names)
{
// Build the array of DLL names to try on this platform by applying the
// proper prefixes and/or suffixes to the specified dll_name.
ACE_TString base (dll_name);
ACE_TString base_dir, base_file, base_suffix;
// 1. Separate the dll_name into the dir part and the file part. We
// only decorate the file part to determine the names to try loading.
ACE_TString::size_type pos = base.rfind (ACE_DIRECTORY_SEPARATOR_CHAR);
if (pos != ACE_TString::npos)
{
base_dir = base.substr (0, pos + 1);
base_file = base.substr (pos + 1);
}
else
base_file = base;
// 2. Locate the file suffix, if there is one. Move the '.' and the
// suffix to base_suffix.
if ((pos = base_file.rfind (ACE_TEXT ('.'))) != ACE_TString::npos)
{
base_suffix = base_file.substr (pos);
base_file = base_file.substr (0, pos);
}
// 3. Build the combinations to try for this platform.
// Try these combinations:
// - name with decorator and platform's suffix appended (if not supplied)
// - name with platform's suffix appended (if not supplied)
// - name with platform's dll prefix (if it has one) and suffix
// - name with platform's dll prefix, decorator, and suffix.
// - name as originally given
// We first try to find the file using the decorator so that when a
// filename with and without decorator is used, we get the file with
// the same decorator as the ACE dll has and then as last resort
// the one without. For example with msvc, the debug build has a "d"
// decorator, but the release build has none and we really want to get
// the debug version of the library in a debug application instead
// of the release one.
// So we need room for 5 entries in try_names.
try_names.size (0);
if ((try_names.max_size () - try_names.size ()) < 5)
try_names.max_size (try_names.max_size () + 5);
#if defined (ACE_LD_DECORATOR_STR) && !defined (ACE_DISABLE_DEBUG_DLL_CHECK)
ACE_TString decorator (ACE_LD_DECORATOR_STR);
#endif
ACE_TString suffix (ACE_DLL_SUFFIX);
ACE_TString prefix (ACE_DLL_PREFIX);
for (size_t i = 0; i < 5 && try_names.size () < try_names.max_size (); ++i)
{
ACE_TString try_this;
size_t const j = try_names.size ();
switch (i)
{
case 0: // Name + decorator + suffix
case 1: // Name + suffix
case 2: // Prefix + name + decorator + suffix
case 3: // Prefix + name + suffix
if (
base_suffix.length () > 0
#if !(defined (ACE_LD_DECORATOR_STR) && !defined (ACE_DISABLE_DEBUG_DLL_CHECK))
|| (i == 1 || i == 3) // No decorator desired; skip
#endif
)
break;
try_this = base_dir;
if (i > 1)
try_this += prefix;
try_this += base_file;
if (base_suffix.length () > 0)
try_this += base_suffix;
else
{
#if defined (ACE_LD_DECORATOR_STR) && !defined (ACE_DISABLE_DEBUG_DLL_CHECK)
try_this += decorator;
#endif
try_this += suffix;
}
break;
case 4:
try_this = dll_name;
break;
}
if (try_this.length ())
{
try_names.size (j + 1);
try_names.set (try_this, j);
}
}
return;
}
/******************************************************************/
// Pointer to the Singleton instance.
ACE_DLL_Manager *ACE_DLL_Manager::instance_ = 0;
ACE_DLL_Manager *
ACE_DLL_Manager::instance (int size)
{
ACE_TRACE ("ACE_DLL_Manager::instance");
if (ACE_DLL_Manager::instance_ == 0)
{
// Perform Double-Checked Locking Optimization.
ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon,
*ACE_Static_Object_Lock::instance (), 0));
if (ACE_DLL_Manager::instance_ == 0)
{
ACE_NEW_RETURN (ACE_DLL_Manager::instance_,
ACE_DLL_Manager (size),
0);
}
}
return ACE_DLL_Manager::instance_;
}
void
ACE_DLL_Manager::close_singleton (void)
{
ACE_TRACE ("ACE_DLL_Manager::close_singleton");
ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon,
*ACE_Static_Object_Lock::instance ()));
delete ACE_DLL_Manager::instance_;
ACE_DLL_Manager::instance_ = 0;
}
ACE_DLL_Manager::ACE_DLL_Manager (int size)
: handle_vector_ (0),
current_size_ (0),
total_size_ (0),
unload_policy_ (ACE_DLL_UNLOAD_POLICY_PER_DLL)
{
ACE_TRACE ("ACE_DLL_Manager::ACE_DLL_Manager");
if (this->open (size) != 0 && ACE::debug ())
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ACE_DLL_Manager ctor failed to allocate ")
ACE_TEXT ("handle_vector_.\n")));
}
ACE_DLL_Manager::~ACE_DLL_Manager (void)
{
ACE_TRACE ("ACE_DLL_Manager::~ACE_DLL_Manager");
if (this->close () != 0 && ACE::debug ())
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ACE_DLL_Manager dtor failed to close ")
ACE_TEXT ("properly.\n")));
}
ACE_DLL_Handle *
ACE_DLL_Manager::open_dll (const ACE_TCHAR *dll_name,
int open_mode,
ACE_SHLIB_HANDLE handle)
{
ACE_TRACE ("ACE_DLL_Manager::open_dll");
ACE_DLL_Handle *temp_handle = 0;
ACE_DLL_Handle *dll_handle = 0;
{
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0));
dll_handle = this->find_dll (dll_name);
if (!dll_handle)
{
if (this->current_size_ < this->total_size_)
{
ACE_NEW_RETURN (temp_handle,
ACE_DLL_Handle,
0);
dll_handle = temp_handle;
}
}
}
if (dll_handle)
{
if (dll_handle->open (dll_name, open_mode, handle) != 0)
{
// Error while opening dll. Free temp handle
if (ACE::debug ())
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ACE_DLL_Manager::open_dll: Could not ")
ACE_TEXT ("open dll %s.\n"),
dll_name));
delete temp_handle;
return 0;
}
// Add the handle to the vector only if the dll is successfully
// opened.
if (temp_handle != 0)
{
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0));
this->handle_vector_[this->current_size_] = dll_handle;
++this->current_size_;
}
}
return dll_handle;
}
int
ACE_DLL_Manager::close_dll (const ACE_TCHAR *dll_name)
{
ACE_TRACE ("ACE_DLL_Manager::close_dll");
ACE_DLL_Handle *handle = 0;
{
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, this->lock_, 0));
handle = this->find_dll (dll_name);
}
if (handle)
{
return this->unload_dll (handle, 0);
}
return -1;
}
u_long
ACE_DLL_Manager::unload_policy (void) const
{
ACE_TRACE ("ACE_DLL_Manager::unload_policy");
return this->unload_policy_;
}
void
ACE_DLL_Manager::unload_policy (u_long unload_policy)
{
ACE_TRACE ("ACE_DLL_Manager::unload_policy");
ACE_MT (ACE_GUARD (ACE_Thread_Mutex, ace_mon, this->lock_));
u_long old_policy = this->unload_policy_;
this->unload_policy_ = unload_policy;
// If going from LAZY to EAGER or from PER_DLL to PER_PROCESS|EAGER,
// call close(1) on all the ACE_DLL_Handle objects with refcount == 0
// which will force those that are still loaded to be unloaded.
if (this->handle_vector_)
if (( ACE_BIT_ENABLED (old_policy, ACE_DLL_UNLOAD_POLICY_LAZY) &&
ACE_BIT_DISABLED (this->unload_policy_, ACE_DLL_UNLOAD_POLICY_LAZY) ) ||
( ACE_BIT_DISABLED (this->unload_policy_, ACE_DLL_UNLOAD_POLICY_LAZY) &&
ACE_BIT_ENABLED (old_policy, ACE_DLL_UNLOAD_POLICY_PER_DLL) &&
ACE_BIT_DISABLED (this->unload_policy_, ACE_DLL_UNLOAD_POLICY_PER_DLL) ))
{
for (int i = this->current_size_ - 1; i >= 0; i--)
{
if (this->handle_vector_[i] &&
this->handle_vector_[i]->refcount () == 0)
this->handle_vector_[i]->close (1);
}
}
}
int
ACE_DLL_Manager::open (int size)
{
ACE_TRACE ("ACE_DLL_Manager::open");
ACE_DLL_Handle **temp = 0;
ACE_NEW_RETURN (temp,
ACE_DLL_Handle *[size],
-1);
this->handle_vector_ = temp;
this->total_size_ = size;
return 0;
}
int
ACE_DLL_Manager::close (void)
{
ACE_TRACE ("ACE_DLL_Manager::close");
int force_close = 1;
if (this->handle_vector_ != 0)
{
// Delete components in reverse order.
for (int i = this->current_size_ - 1; i >= 0; i--)
{
if (this->handle_vector_[i])
{
ACE_DLL_Handle *s =
const_cast<ACE_DLL_Handle *> (this->handle_vector_[i]);
this->handle_vector_[i] = 0;
this->unload_dll (s, force_close);
delete s;
}
}
delete [] this->handle_vector_;
this->handle_vector_ = 0;
this->current_size_ = 0;
}
return 0;
}
ACE_DLL_Handle *
ACE_DLL_Manager::find_dll (const ACE_TCHAR *dll_name) const
{
ACE_TRACE ("ACE_DLL_Manager::find_dll");
for (int i = 0; i < this->current_size_; i++)
if (this->handle_vector_[i] &&
ACE_OS::strcmp (this->handle_vector_[i]->dll_name (), dll_name) == 0)
{
return this->handle_vector_[i];
}
return 0;
}
int
ACE_DLL_Manager::unload_dll (ACE_DLL_Handle *dll_handle, int force_unload)
{
ACE_TRACE ("ACE_DLL_Manager::unload_dll");
if (dll_handle)
{
int unload = force_unload;
if (unload == 0)
{
// apply strategy
if (ACE_BIT_DISABLED (this->unload_policy_,
ACE_DLL_UNLOAD_POLICY_PER_DLL))
{
unload = ACE_BIT_DISABLED (this->unload_policy_,
ACE_DLL_UNLOAD_POLICY_LAZY);
}
else
{
// Declare the type of the symbol:
typedef int (*dll_unload_policy)(void);
void * const unload_policy_ptr =
dll_handle->symbol (ACE_TEXT ("_get_dll_unload_policy"), 1);
#if defined (ACE_OPENVMS) && (!defined (__INITIAL_POINTER_SIZE) || (__INITIAL_POINTER_SIZE < 64))
int const temp_p =
reinterpret_cast<int> (unload_policy_ptr);
#else
intptr_t const temp_p =
reinterpret_cast<intptr_t> (unload_policy_ptr);
#endif
dll_unload_policy const the_policy =
reinterpret_cast<dll_unload_policy> (temp_p);
if (the_policy != 0)
unload = ACE_BIT_DISABLED (the_policy (),
ACE_DLL_UNLOAD_POLICY_LAZY);
else
unload = ACE_BIT_DISABLED (this->unload_policy_,
ACE_DLL_UNLOAD_POLICY_LAZY);
}
}
if (dll_handle->close (unload) != 0)
{
if (ACE::debug ())
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ACE_DLL_Manager::unload error.\n")));
return -1;
}
}
else
{
if (ACE::debug ())
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("ACE_DLL_Manager::unload_dll called with ")
ACE_TEXT ("null pointer.\n")));
return -1;
}
return 0;
}
ACE_END_VERSIONED_NAMESPACE_DECL
| [
"binghuo365@hotmail.com"
] | binghuo365@hotmail.com |
f4770312983ea59475b24da1646b41936f6e8cc0 | 5eba2be3fd80fd26f2c8a6ff51e6be4f8153732b | /main.ino | 26456fa867976b886197f8651bf34997dcb86059 | [] | no_license | juliamzdias/EA076_carrinho | f6e845ae7c784beb9c5a90458cede1cb13e25887 | e081aae27809697d1e94dd09e05beeb7db7056e6 | refs/heads/master | 2020-05-31T18:27:15.248407 | 2017-06-12T02:19:35 | 2017-06-12T02:19:35 | 94,044,305 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,318 | ino | /* EA076 - Projeto 3: Robô com detector de obstáculo
Isabella Bigatto 138537
Júlia Dias 156019
Objetivo: implementar um robô autônomo que detecta obstáculos através de um sensor infravermelho
e controla a velocidade das rodas via PWM.
*/
#include <stdio.h>
#include <TimerOne.h>
//Atribuição das portas do Arduino às variáveis utilizadas para o controle do carrinho
#define receptor A0
#define velocidadeA 3
#define motorA_hor 5
#define motorA_anti 6
#define motorB_hor 11
#define motorB_anti 10
#define velocidadeB 9
int sensor, contador = 0, flag = 0;
/* Inicialização da interrupção de tempo, da porta serial e definição dos pinos como entrada ou saída */
void setup() {
pinMode(receptor, INPUT);
pinMode(motorA_hor, INPUT);
pinMode(motorA_anti, INPUT);
pinMode(motorB_hor, INPUT);
pinMode(motorB_anti, INPUT);
pinMode(velocidadeA, INPUT);
pinMode(velocidadeB, INPUT);
Timer1.initialize(500000); //Interrupção a cada 0,5s
Timer1.attachInterrupt(tempo);
Serial.begin(9600);
}
/* Função atribuída à interrupção */
void tempo() {
sensor = analogRead(A0); // Leitura dos valores do sensor
if (flag == 1) { // Contagem de tempo usada quando o robô encontra um obstáculo para fazer a manobra de desvio
contador++;
}
}
void loop() {
/* Bloco que faz o robô andar para frente */
if (sensor > 650) {
analogWrite(velocidadeA, 200);
analogWrite(velocidadeB, 255);
digitalWrite(motorA_hor, HIGH);
digitalWrite(motorA_anti, LOW);
digitalWrite(motorB_anti, HIGH);
digitalWrite(motorB_hor, LOW);
}
/* Quando um obstáculo é detectado */
if ((sensor <= 650)) {
// os dois motores param
analogWrite(velocidadeA, 0);
analogWrite(velocidadeB, 0);
digitalWrite(motorA_hor, LOW);
digitalWrite(motorB_anti, LOW);
delay(1000);
flag = 1; // aciona uma flag para começar a contagem do contador, que determina por quanto tempo o robô vai dar ré
while (contador < 10) {
analogWrite(velocidadeA, 200);
analogWrite(velocidadeB, 0);
digitalWrite(motorA_anti, HIGH);
digitalWrite(motorA_hor, LOW);
digitalWrite(motorB_anti, HIGH);
digitalWrite(motorB_hor, LOW);
}
contador = 0;
flag = 0;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
cebf8a5ccb44eadf96ff28801ebee4c4a5c5bdea | 05a1353f62fdc7a0bf879f85f7b1175b39d69bc7 | /451_finalproject/sudoku_mpi.cpp | 7f5c34cf84b8f6e9a9367d2291faffc5ca8d42ee | [] | no_license | chen4089/451_finalproject | fcc9a860d52afcf95fa79b3ad24000ef55b9482d | 4d1dfb5d1361bfbdb03925ba5d8f5426343a894f | refs/heads/master | 2020-09-17T11:01:19.821348 | 2019-12-07T06:47:28 | 2019-12-07T06:47:28 | 224,081,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 886 | cpp | #include<iostream>
#include<fstream>
#include <mpi.h>
#include<stdlib>
#
#define size 9
using namespace std;
int solution[size][size] = { 0 };
int isGiven[size][size] = { 0 };
void printTable(int table[size][size])
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
cout << table[i][j] <<" ";
}
cout << endl;
}
}
void loadTable(const char* fileName, int table[size][size])
{
ifstream in;
in.open(fileName);
if (!in)
{
cout << "file load fail!" << endl;
return;
}
char temp;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
in >> temp;
table[i][j] = temp-'0';
if (temp != '0') isGiven[i][j] = 1;
}
}
in.close();
}
int main(int argc, char* argv[])
{
int sudoku[size][size] = { 0 };
string file = "problem.txt";
string result = "result.txt";
loadTable(file.c_str(), sudoku);
printTable(sudoku);
}
| [
"quiterie85@hotmail.com"
] | quiterie85@hotmail.com |
590fdea969aa4ea3dc0bd01d59a0bdab94b1ccf8 | e372f07caaaa40606033a60088e8fb5d10af7c44 | /HW6-Pencil-Interfaces/Graphite_TFT_Text_function/Graphite_TFT_Text_function.ino | 963055e8fdb6b601909766c809b735129fa1a0e5 | [] | no_license | jreus/componto2017 | e6409f3a9e318dc70d0695b94e60a6df9597734a | 84457400e223a3f145d3fb20d18bcae74c6d5905 | refs/heads/master | 2021-01-19T20:40:16.066643 | 2017-06-30T11:33:16 | 2017-06-30T11:33:16 | 88,528,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,402 | ino | /*
* Graphite Interface
*
* This program visualizes the values coming in from the two
* graphite electrodes as text on the TFT screen.
*
* Hardware:
* Four electrodes dividing up a graphite drawing.
* The outermost electrodes go to +5V and Ground
* The inner two to A0 and A1
*
* Digital Pins connect to the TFT display
* as shown in this guide: https://www.arduino.cc/en/Guide/TFTtoBoards
*
* LCD Arduino
* +5V +5V
* MISO pin 12
* SCK pin 13
* MOSI pin 11
* LCD CS pin 10
* SD CS pin 4
* D/C pin 9
* RESET pin 8
* BL +5V
* GND GND
*
* Reference for the TFT library:
* https://www.arduino.cc/en/Reference/TFTLibrary
*
* And in case you're wondering how itoa() works
* https://playground.arduino.cc/Code/PrintingNumbers
* http://www.cplusplus.com/reference/cstdlib/itoa/
* http://www.geeksforgeeks.org/implement-itoa/
*
*
* Inspired by "Ground", by Dewi de Vree and Jeroen Uyttendaele
*
*
* This example code is in the public domain.
* Created 15 March 2017 by Jonathan Reus
*/
#include <arduino.h>
#include <SD.h>
#include <SPI.h>
#include <TFT.h>
#include <stdlib.h>
// SPI pins and other necessary pins to control the TFT screen.
#define SD_CS 4 // SD chip select
#define LCD_CS 10
#define DC 9
#define RST 8
// Graphite electrode pins, use macros in case we want to change them
#define E1 A0
#define E2 A1
int main() {
init();
TFT myscreen = TFT(LCD_CS, DC, RST);
myscreen.begin();
myscreen.background(0,0,0); // black background
myscreen.stroke(255,255,255); // white text
myscreen.setTextSize(1);
myscreen.text("E1 Value :\n", 0, 0);
myscreen.text("E2 Value :\n", 0, 60);
myscreen.setTextSize(4);
int e1, e2;
while(true) {
e1 = analogRead(E1);
delay(1); // delay for stability
e2 = analogRead(E2);
delay(1);
drawText(e1, e2, myscreen);
}
return 0;
}
void drawText(int e1val, int e2val, TFT &myscreen) {
char e1str[10];
char e2str[10];
itoa(e1val, e1str, 10);
myscreen.text(e1str, 0, 20);
itoa(e2val, e2str, 10);
myscreen.text(e2str, 0, 80);
delay(100); // wait a moment before erasing the text
// "erase" the text by redrawing it in black
myscreen.stroke(0,0,0);
myscreen.text(e1str, 0, 20);
myscreen.text(e2str, 0, 80);
myscreen.stroke(255,255,255);
}
| [
"info@jonathanreus.com"
] | info@jonathanreus.com |
df1607dad8d451b1655a2b131997e0053b653e6d | 61418f2d5ad2a04ac6dfa585d2407c5ae218a836 | /include/vsg/core/Auxiliary.h | 01cc86408f9a030cfa248d34023fd6c389533695 | [
"MIT",
"Apache-2.0"
] | permissive | vsg-dev/VulkanSceneGraph | e6840572c6b141671f64525c37cf6929ed9fceb7 | 62b2e8e5b6886be486d5d5002b8ff7f89be089e8 | refs/heads/master | 2023-09-04T09:41:54.342443 | 2023-09-03T09:22:09 | 2023-09-03T09:22:09 | 148,609,004 | 962 | 190 | MIT | 2023-09-10T15:38:12 | 2018-09-13T08:43:58 | C++ | UTF-8 | C++ | false | false | 3,758 | h | #pragma once
/* <editor-fold desc="MIT License">
Copyright(c) 2018 Robert Osfield
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.
</editor-fold> */
#include <vsg/core/Object.h>
#include <vsg/core/ref_ptr.h>
#include <map>
#include <mutex>
namespace vsg
{
/** Auxiliary provides extra Object data that is rarely used, and hooks for observers.*/
class VSG_DECLSPEC Auxiliary
{
public:
std::mutex& getMutex() const { return _mutex; }
Object* getConnectedObject() { return _connectedObject; }
const Object* getConnectedObject() const { return _connectedObject; }
virtual std::size_t getSizeOf() const { return sizeof(Auxiliary); }
void ref() const;
void unref() const;
void unref_nodelete() const;
inline unsigned int referenceCount() const { return _referenceCount.load(); }
virtual int compare(const Auxiliary& rhs) const;
void setObject(const std::string& key, ref_ptr<Object> object)
{
userObjects[key] = object;
}
Object* getObject(const std::string& key)
{
if (auto itr = userObjects.find(key); itr != userObjects.end())
return itr->second.get();
else
return nullptr;
}
const Object* getObject(const std::string& key) const
{
if (auto itr = userObjects.find(key); itr != userObjects.end())
return itr->second.get();
else
return nullptr;
}
ref_ptr<Object> getRefObject(const std::string& key)
{
if (auto itr = userObjects.find(key); itr != userObjects.end())
return itr->second;
else
return {};
}
ref_ptr<const Object> getRefObject(const std::string& key) const
{
if (auto itr = userObjects.find(key); itr != userObjects.end())
return itr->second;
else
return {};
}
using ObjectMap = std::map<std::string, vsg::ref_ptr<Object>>;
/// container for all user objects
ObjectMap userObjects;
protected:
explicit Auxiliary(Object* object);
virtual ~Auxiliary();
/// reset the ConnectedObject pointer to 0 unless the ConnectedObject referenceCount goes back above 0,
/// return true if ConnectedObject should still be deleted, or false if the object should be kept.
bool signalConnectedObjectToBeDeleted();
void resetConnectedObject();
friend class Object;
friend class Allocator;
mutable std::atomic_uint _referenceCount;
mutable std::mutex _mutex;
Object* _connectedObject;
};
} // namespace vsg
| [
"robert@openscenegraph.com"
] | robert@openscenegraph.com |
2bc7e19d71dbcdf0fe059d688ff12c3b53f38baf | de5e012c16454f2f9f3929f0a21adf39baf9c717 | /ex01/PlasmaRifle.hpp | 63ce2a1d58609899957e517e175ab59c05c7936d | [] | no_license | Ovoda/Piscine_CPP_04 | 3d1a6e5cce517e035ae3df612d077ad1d68b6f36 | e1eca64ef78433357c900c851393470dfc12cc02 | refs/heads/master | 2023-06-14T21:06:04.393801 | 2021-07-07T04:38:02 | 2021-07-07T04:38:02 | 381,120,307 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 490 | hpp | #ifndef PLASMARIFLE_HPP
# define PLASMARIFLE_HPP
# include <iostream>
# include <string>
# include "AWeapon.hpp"
class PlasmaRifle : public AWeapon
{
public:
PlasmaRifle( void );
PlasmaRifle( PlasmaRifle const & src );
~PlasmaRifle();
PlasmaRifle & operator=( PlasmaRifle const & rhs );
void attack( void ) const;
};
std::ostream & operator<<( std::ostream & o, PlasmaRifle const & i );
#endif /* ***************************************************** PLASMARIFLE_H */ | [
"cdetourrispro@gmail.com"
] | cdetourrispro@gmail.com |
3ebbfbea2bf64ce1b2762c748b7cdf5e1be102f7 | b599dfef0aa22dcc8bdc06f894232d263a578308 | /EUI/include/native/NativeEditBox.h | 74d3786b63058a2873aa351c96b422263164292d | [] | no_license | ENgineE777/EditorSteps | 531c963d5786f50abf2859690d8e04db2bb47ca1 | cd15c8f6c72c2c0c3af2db34e9e89b99deac288f | refs/heads/master | 2021-01-01T16:57:39.905228 | 2017-08-06T12:10:01 | 2017-08-06T12:12:14 | 97,959,463 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | h |
#pragma once
#ifdef PLATFORM_WIN
#include "native/win/WinWidget.h"
#else
#include "NativeWidget.h"
#define WinWidget NativeWidget
#endif
class NativeEditBox : public WinWidget
{
public:
NativeEditBox(EUIWidget* owner) : WinWidget(owner) {};
virtual const char* GetText() = 0;
};
| [
"enginee777@gmail.com"
] | enginee777@gmail.com |
3df1b4a2d3b41c620d4613e9f8e3f8a4972c85e3 | 94c415aed3d5a6dcf9f13fc69f85e3db09d42bad | /cell/main.cpp | e57d18c9175026ba634a7ccd8ed955e32435a034 | [] | no_license | if1live/gotoamc | 68168614f8d7f3a216ede8dccd20801a2ee96d3c | a4e398cff458ff4d1cb350ca84be04d733dbe353 | refs/heads/master | 2016-09-06T07:36:18.120297 | 2014-03-07T14:05:00 | 2014-03-07T14:05:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | cpp | #include <stdio.h>
#include "videoIO.h"
#include "textFrame2PPM.h"
#include "frame2TextFrame.h"
#include "context.h"
int main(int argc, char *argv[])
{
Context *context = Context::instance(); //create global data
VideoIO *videoIO = new VideoIO();
Frame2TextFrame *frame2TextFrame = new Frame2TextFrame();
TextFrame2PPM *textFrame2PPM = new TextFrame2PPM();
videoIO->init(argc, argv);
// while(videoIO->isReadingComplete() == false)
for(int i = 0 ; i < context->getFrameLimit() ; i++)
{
try
{
videoIO->readFrame();
frame2TextFrame->convertFrame();
textFrame2PPM->convert();
videoIO->writeFrame();
}
catch(const char *msg)
{
fprintf(stderr, "Except : %s\n");
delete context;
return 1;
}
}
delete context; //delete context data
return 0;
}
| [
"bluewizard"
] | bluewizard |
1ae822497c6c9638b9b41067aa14d1dc244cfdfe | 68645254255985aaa8b40caacf655debc57be3d9 | /copy_files_background_windows/copy_files_background_windows.ino | 6bd8c9811ac80d2ba595d2dd316ccc5d211bb887 | [] | no_license | ricardojoserf/arduino-rubber-ducky-scripts | bc2977b255ab9ce79598e03b064005c96ae50ca2 | eea6d17993cc03a0d7b83ba832dc14046c4cc8f8 | refs/heads/master | 2021-06-12T13:13:27.901827 | 2020-11-18T19:33:07 | 2020-11-18T19:33:07 | 128,639,102 | 4 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,196 | ino | #include "Keyboard.h"
void typeKey(int key)
{
Keyboard.press(key);
delay(50);
Keyboard.release(key);
}
void esp_print(String text){
for (int i = 0; i<=text.length(); i++)
{
char val = text[i];
if (val == ':'){
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.print(".");
Keyboard.releaseAll();
}
else if (val == '/'){
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.print("7");
Keyboard.releaseAll();
}
else if (val == '('){
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.print("8");
Keyboard.releaseAll();
}
else if (val == ')'){
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.print("9");
Keyboard.releaseAll();
}
else if (val == '='){
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.print("0");
Keyboard.releaseAll();
}
else if (val == ';'){
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.print(",");
Keyboard.releaseAll();
}
else if (val == '"'){
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.print("2");
Keyboard.releaseAll();
}
else if (val == '-'){
Keyboard.print("/");
}
else if (val == '&'){
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.print("6");
Keyboard.releaseAll();
}
else if (val == '\\'){
Keyboard.press(KEY_RIGHT_ALT);
Keyboard.print("`");
Keyboard.releaseAll();
}
else{
Keyboard.print(val);
}
}
}
void opencmd(){
typeKey(KEY_ESC);
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_ESC);
Keyboard.releaseAll();
delay(400);
Keyboard.print("cmd");
delay(200);
typeKey(KEY_RETURN);
delay(500);
}
void exit(){
Keyboard.print("exit");
typeKey(KEY_RETURN);
}
void setup()
{
Keyboard.begin();
String orig = "D:\\Escritorio";
String dest = "E:\\test";
delay(500);
opencmd();
esp_print("START /MIN xcopy "+orig+" "+dest+" /e");
typeKey(KEY_RETURN);
delay(50);
exit();
Keyboard.end();
}
/* Unused endless loop */
void loop() {}
| [
"noreply@github.com"
] | noreply@github.com |
d2dfbb14fd9759426108bedc1459d14d651da2fa | 45e3eb85ad842e22efefad6d3c1af327998eb297 | /AtCoder/ABC/165/b.cpp | bd22ef8d65b9c1c3d2afbca20c4e2278f5aa002c | [] | no_license | sawamotokai/competitive-programming | 6b5e18217c765184acfb2613b681d0ac9ec3f762 | 9659124def45447be5fccada6e835cd7e09d8f79 | refs/heads/master | 2023-06-12T06:56:01.985876 | 2021-07-05T16:55:56 | 2021-07-05T16:55:56 | 241,240,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 796 | cpp | #include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define ok() puts(ok?"Yes":"No");
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<vi> vvi;
typedef vector<ii> vii;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef set<int> si;
typedef map<string, int> msi;
typedef greater<int> gt;
typedef priority_queue<int, vector<int>, gt> minq;
typedef long long ll;
typedef pair<ll,ll> pll;
const ll LINF = 1e18L + 1;
const int INF = 1e9 + 1;
//clang++ -std=c++11 -stdlib=libc++
int main() {
ll x; cin >> x;
double up = log(x) - log(100);
double down = log(101) - log(100);
ll ans = ceil((double) (log(x)-log(100)) / (double) (log(101) - log(100)));
ans += ans/100;
printf("%lld\n", ans);
return 0;
} | [
"kaisawamoto@gmail.com"
] | kaisawamoto@gmail.com |
f30b4bc5451e5af0934c68067a73c394a7f4d767 | 1804140c399ab9165e98ad2ddbed87112230ac85 | /wyrazenia-arytmetyczne/cosinus.cpp | 59709cf28fe52fb091f46f5c2e08c02f64b7ebb6 | [] | no_license | agnpawicka/cpp | 0c85c6af29ed58a2f6e85688c6a1a01bf471d911 | d9496a7be73ea19213fab3bb8e12002fe9520f3e | refs/heads/master | 2020-03-06T23:20:18.002703 | 2018-05-30T15:56:47 | 2018-05-30T15:56:47 | 127,129,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 365 | cpp |
#include "cosinus.hpp"
#include <cmath>
double Cos::oblicz() {
return std::cos (fstArg->oblicz());
}
Cos::Cos(Wyrazenie* fstArg) {
this->fstArg=fstArg;
Nazwa="cos";
if(fstArg== nullptr)
throw std::invalid_argument("nie podano argumentu cosinusa\n");
priorytet=4;
}
std::string Cos::opis() {
return nazwa()+'('+fstArg->opis()+')';
} | [
"agapawicka@gmail.com"
] | agapawicka@gmail.com |
8797d7f790f6f232049560862afe5e262b2739dc | 040caac5aacb3e878d0bee5963d936bae4b7ff28 | /12 may class/question2(gcd)/gcd.cpp | 81ab0f35b674160a32abca0ad3b34870f8f29a13 | [] | no_license | SakshiRathore982/CST_JIET_Assignments | e6eba68527b56d797e84dded4eee87cb4e21471b | d5576c9b73f3cf2f005e9b8a84f4f8f0a654bd1f | refs/heads/master | 2022-06-29T08:06:22.852128 | 2020-05-13T09:49:09 | 2020-05-13T09:49:09 | 263,273,356 | 0 | 0 | null | 2020-05-12T08:08:58 | 2020-05-12T08:08:57 | null | UTF-8 | C++ | false | false | 361 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int a,b,i,D,ran;
cout<<"Enter the input:"<<endl;
cin>>a;
cin>>b;
if(a<=b)
ran = a;
else
ran=b;
if (a==1 && b==1)
D=1;
else
{
for(i=ran;i>=1;i--)
{
if(a%i==0 && b%i==0)
{
D=i;
break;
}
}
}
cout<<"ouput: GCD : "<<D<<endl;
}
| [
"noreply@github.com"
] | noreply@github.com |
0834eeaabbd18a02c4696c95b7d31d5da943f321 | dc83b33921d46d97e5ef30e4a8e599a8182f9039 | /src/simulators/tableau_simulator.pybind.cc | 2d30f3c99bfd49e563926ec4f5561ea640dadc45 | [
"Apache-2.0"
] | permissive | dstrain115/Stim | 5189bedfc6e0c56c1d3a1844d81804b499e031ae | 82a161741c05d637fe16ea20b1d99a48b4ca4750 | refs/heads/main | 2023-07-07T09:40:28.762254 | 2021-08-06T04:34:05 | 2021-08-06T04:34:05 | 396,943,952 | 0 | 0 | Apache-2.0 | 2021-08-16T19:35:38 | 2021-08-16T19:35:37 | null | UTF-8 | C++ | false | false | 34,317 | cc | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "tableau_simulator.pybind.h"
#include "../py/base.pybind.h"
#include "../simulators/tableau_simulator.h"
#include "../stabilizers/pauli_string.pybind.h"
#include "../stabilizers/tableau.h"
using namespace stim_internal;
struct TempViewableData {
std::vector<GateTarget> targets;
TempViewableData(std::vector<GateTarget> targets) : targets(std::move(targets)) {
}
operator OperationData() {
return {{}, targets};
}
};
TableauSimulator create_tableau_simulator() {
return TableauSimulator(PYBIND_SHARED_RNG(), 0);
}
TempViewableData args_to_targets(TableauSimulator &self, const pybind11::args &args) {
std::vector<GateTarget> arguments;
uint32_t max_q = 0;
try {
for (const auto &e : args) {
uint32_t q = e.cast<uint32_t>();
max_q = std::max(max_q, q & TARGET_VALUE_MASK);
arguments.push_back(GateTarget{q});
}
} catch (const pybind11::cast_error &) {
throw std::out_of_range("Target qubits must be non-negative integers.");
}
// Note: quadratic behavior.
self.ensure_large_enough_for_qubits(max_q + 1);
return TempViewableData(arguments);
}
TempViewableData args_to_target_pairs(TableauSimulator &self, const pybind11::args &args) {
if (pybind11::len(args) & 1) {
throw std::invalid_argument("Two qubit operation requires an even number of targets.");
}
auto result = args_to_targets(self, args);
for (size_t k = 0; k < result.targets.size(); k += 2) {
if (result.targets[k] == result.targets[k + 1]) {
throw std::invalid_argument("Two qubit operation can't target the same qubit twice.");
}
}
return result;
}
void pybind_tableau_simulator(pybind11::module &m) {
auto &&c = pybind11::class_<TableauSimulator>(
m,
"TableauSimulator",
clean_doc_string(u8R"DOC(
A quantum stabilizer circuit simulator whose internal state is an inverse stabilizer tableau.
Supports interactive usage, where gates and measurements are applied on demand.
Examples:
>>> import stim
>>> s = stim.TableauSimulator()
>>> s.h(0)
>>> if s.measure(0):
... s.h(1)
... s.cnot(1, 2)
>>> s.measure(1) == s.measure(2)
True
>>> s = stim.TableauSimulator()
>>> s.h(0)
>>> s.cnot(0, 1)
>>> s.current_inverse_tableau()
stim.Tableau.from_conjugated_generators(
xs=[
stim.PauliString("+ZX"),
stim.PauliString("+_X"),
],
zs=[
stim.PauliString("+X_"),
stim.PauliString("+XZ"),
],
)
)DOC")
.data());
c.def(pybind11::init(&create_tableau_simulator));
c.def(
"current_inverse_tableau",
[](TableauSimulator &self) {
return self.inv_state;
},
clean_doc_string(u8R"DOC(
Returns a copy of the internal state of the simulator as a stim.Tableau.
Returns:
A stim.Tableau copy of the simulator's state.
Examples:
>>> import stim
>>> s = stim.TableauSimulator()
>>> s.h(0)
>>> s.current_inverse_tableau()
stim.Tableau.from_conjugated_generators(
xs=[
stim.PauliString("+Z"),
],
zs=[
stim.PauliString("+X"),
],
)
>>> s.cnot(0, 1)
>>> s.current_inverse_tableau()
stim.Tableau.from_conjugated_generators(
xs=[
stim.PauliString("+ZX"),
stim.PauliString("+_X"),
],
zs=[
stim.PauliString("+X_"),
stim.PauliString("+XZ"),
],
)
)DOC")
.data());
c.def(
"state_vector",
[](const TableauSimulator &self) {
auto complex_vec = self.to_state_vector();
std::vector<float> float_vec;
float_vec.reserve(complex_vec.size() * 2);
for (const auto &e : complex_vec) {
float_vec.push_back(e.real());
float_vec.push_back(e.imag());
}
void *ptr = float_vec.data();
ssize_t itemsize = sizeof(float) * 2;
std::vector<ssize_t> shape{(ssize_t)complex_vec.size()};
std::vector<ssize_t> stride{itemsize};
const std::string &format = pybind11::format_descriptor<std::complex<float>>::value;
bool readonly = true;
return pybind11::array_t<float>(
pybind11::buffer_info(ptr, itemsize, format, shape.size(), shape, stride, readonly));
},
clean_doc_string(u8R"DOC(
Returns a wavefunction that satisfies the stabilizers of the simulator's current state.
This function takes O(n * 2**n) time and O(2**n) space, where n is the number of qubits. The computation is
done by initialization a random state vector and iteratively projecting it into the +1 eigenspace of each
stabilizer of the state. The global phase of the result is arbitrary (and will vary from call to call).
The result is in little endian order. The amplitude at offset b_0 + b_1*2 + b_2*4 + ... + b_{n-1}*2^{n-1} is
the amplitude for the computational basis state where the qubit with index 0 is storing the bit b_0, the
qubit with index 1 is storing the bit b_1, etc.
Returns:
A `numpy.ndarray[numpy.complex64]` of computational basis amplitudes in little endian order.
Examples:
>>> import stim
>>> import numpy as np
>>> # Check that the qubit-to-amplitude-index ordering is little-endian.
>>> s = stim.TableauSimulator()
>>> s.x(1)
>>> s.x(4)
>>> vector = s.state_vector()
>>> np.abs(vector[0b_10010]).round(2)
1.0
>>> tensor = vector.reshape((2, 2, 2, 2, 2))
>>> np.abs(tensor[1, 0, 0, 1, 0]).round(2)
1.0
)DOC")
.data());
c.def(
"canonical_stabilizers",
[](const TableauSimulator &self) {
auto stabilizers = self.canonical_stabilizers();
std::vector<PyPauliString> result;
result.reserve(stabilizers.size());
for (auto &s : stabilizers) {
result.emplace_back(std::move(s), false);
}
return result;
},
clean_doc_string(u8R"DOC(
Returns a list of the stabilizers of the simulator's current state in a standard form.
Two simulators have the same canonical stabilizers if and only if their current quantum state is equal
(and tracking the same number of qubits).
The canonical form is computed as follows:
1. Get a list of stabilizers using the `z_output`s of `simulator.current_inverse_tableau()**-1`.
2. Perform Gaussian elimination on each generator g (ordered X0, Z0, X1, Z1, X2, Z2, etc).
2a) Pick any stabilizer that uses the generator g. If there are none, go to the next g.
2b) Multiply that stabilizer into all other stabilizers that use the generator g.
2c) Swap that stabilizer with the stabilizer at position `next_output` then increment `next_output`.
Returns:
A List[stim.PauliString] of the simulator's state's stabilizers.
Examples:
>>> import stim
>>> s = stim.TableauSimulator()
>>> s.h(0)
>>> s.cnot(0, 1)
>>> s.x(2)
>>> s.canonical_stabilizers()
[stim.PauliString("+XX_"), stim.PauliString("+ZZ_"), stim.PauliString("-__Z")]
>>> # Scramble the stabilizers then check that the canonical form is unchanged.
>>> s.set_inverse_tableau(s.current_inverse_tableau()**-1)
>>> s.cnot(0, 1)
>>> s.cz(0, 2)
>>> s.s(0, 2)
>>> s.cy(2, 1)
>>> s.set_inverse_tableau(s.current_inverse_tableau()**-1)
>>> s.canonical_stabilizers()
[stim.PauliString("+XX_"), stim.PauliString("+ZZ_"), stim.PauliString("-__Z")]
)DOC")
.data());
c.def(
"current_measurement_record",
[](TableauSimulator &self) {
return self.measurement_record.storage;
},
clean_doc_string(u8R"DOC(
Returns a copy of the record of all measurements performed by the simulator.
Examples:
>>> import stim
>>> s = stim.TableauSimulator()
>>> s.current_measurement_record()
[]
>>> s.measure(0)
False
>>> s.x(0)
>>> s.measure(0)
True
>>> s.current_measurement_record()
[False, True]
>>> s.do(stim.Circuit("M 0"))
>>> s.current_measurement_record()
[False, True, True]
Returns:
A list of booleans containing the result of every measurement performed by the simulator so far.
)DOC")
.data());
c.def(
"do",
&TableauSimulator::expand_do_circuit,
pybind11::arg("circuit"),
clean_doc_string(u8R"DOC(
Applies all the operations in the given stim.Circuit to the simulator's state.
Examples:
>>> import stim
>>> s = stim.TableauSimulator()
>>> s.do(stim.Circuit('''
... X 0
... M 0
... '''))
>>> s.current_measurement_record()
[True]
Args:
circuit: A stim.Circuit containing operations to apply.
)DOC")
.data());
c.def(
"do",
[](TableauSimulator &self, const PyPauliString &pauli_string) {
self.ensure_large_enough_for_qubits(pauli_string.value.num_qubits);
self.paulis(pauli_string.value);
},
pybind11::arg("pauli_string"),
clean_doc_string(u8R"DOC(
Applies all the Pauli operations in the given stim.PauliString to the simulator's state.
The Pauli at offset k is applied to the qubit with index k.
Examples:
>>> import stim
>>> s = stim.TableauSimulator()
>>> s.do(stim.PauliString("IXYZ"))
>>> s.measure_many(0, 1, 2, 3)
[False, True, True, False]
Args:
pauli_string: A stim.PauliString containing Pauli operations to apply.
)DOC")
.data());
c.def(
"h",
[](TableauSimulator &self, pybind11::args args) {
self.H_XZ(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a Hadamard gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"h_xy",
[](TableauSimulator &self, pybind11::args args) {
self.H_XY(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a variant of the Hadamard gate that swaps the X and Y axes to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"h_yz",
[](TableauSimulator &self, pybind11::args args) {
self.H_YZ(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a variant of the Hadamard gate that swaps the Y and Z axes to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"x",
[](TableauSimulator &self, pybind11::args args) {
self.X(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a Pauli X gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"y",
[](TableauSimulator &self, pybind11::args args) {
self.Y(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a Pauli Y gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"z",
[](TableauSimulator &self, pybind11::args args) {
self.Z(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a Pauli Z gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"s",
[](TableauSimulator &self, pybind11::args args) {
self.SQRT_Z(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a SQRT_Z gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"s_dag",
[](TableauSimulator &self, pybind11::args args) {
self.SQRT_Z_DAG(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a SQRT_Z_DAG gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"sqrt_x",
[](TableauSimulator &self, pybind11::args args) {
self.SQRT_X(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a SQRT_X gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"sqrt_x_dag",
[](TableauSimulator &self, pybind11::args args) {
self.SQRT_X_DAG(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a SQRT_X_DAG gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"sqrt_y",
[](TableauSimulator &self, pybind11::args args) {
self.SQRT_Y(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a SQRT_Y gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"sqrt_y_dag",
[](TableauSimulator &self, pybind11::args args) {
self.SQRT_Y_DAG(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Applies a SQRT_Y_DAG gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
)DOC")
.data());
c.def(
"swap",
[](TableauSimulator &self, pybind11::args args) {
self.SWAP(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies a swap gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"iswap",
[](TableauSimulator &self, pybind11::args args) {
self.ISWAP(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies an ISWAP gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"iswap_dag",
[](TableauSimulator &self, pybind11::args args) {
self.ISWAP_DAG(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies an ISWAP_DAG gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"cnot",
[](TableauSimulator &self, pybind11::args args) {
self.ZCX(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies a controlled X gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"cz",
[](TableauSimulator &self, pybind11::args args) {
self.ZCZ(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies a controlled Z gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"cy",
[](TableauSimulator &self, pybind11::args args) {
self.ZCY(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies a controlled Y gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"xcx",
[](TableauSimulator &self, pybind11::args args) {
self.XCX(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies an X-controlled X gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"xcy",
[](TableauSimulator &self, pybind11::args args) {
self.XCY(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies an X-controlled Y gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"xcz",
[](TableauSimulator &self, pybind11::args args) {
self.XCZ(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies an X-controlled Z gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"ycx",
[](TableauSimulator &self, pybind11::args args) {
self.YCX(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies a Y-controlled X gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"ycy",
[](TableauSimulator &self, pybind11::args args) {
self.YCY(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies a Y-controlled Y gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"ycz",
[](TableauSimulator &self, pybind11::args args) {
self.YCZ(args_to_target_pairs(self, args));
},
clean_doc_string(u8R"DOC(
Applies a Y-controlled Z gate to the simulator's state.
Args:
*targets: The indices of the qubits to target with the gate.
Applies the gate to the first two targets, then the next two targets, and so forth.
There must be an even number of targets.
)DOC")
.data());
c.def(
"reset",
[](TableauSimulator &self, pybind11::args args) {
self.reset_z(args_to_targets(self, args));
},
clean_doc_string(u8R"DOC(
Resets qubits to zero (e.g. by swapping them for zero'd qubit from the environment).
Args:
*targets: The indices of the qubits to reset.
)DOC")
.data());
c.def(
"peek_bloch",
[](TableauSimulator &self, size_t target) {
self.ensure_large_enough_for_qubits(target + 1);
return PyPauliString(self.peek_bloch(target));
},
pybind11::arg("target"),
clean_doc_string(u8R"DOC(
Returns the current bloch vector of the qubit, represented as a stim.PauliString.
This is a non-physical operation. It reports information about the qubit without disturbing it.
Args:
target: The qubit to peek at.
Returns:
stim.PauliString("I"): The qubit is entangled. Its bloch vector is x=y=z=0.
stim.PauliString("+Z"): The qubit is in the |0> state. Its bloch vector is z=+1, x=y=0.
stim.PauliString("-Z"): The qubit is in the |1> state. Its bloch vector is z=-1, x=y=0.
stim.PauliString("+Y"): The qubit is in the |i> state. Its bloch vector is y=+1, x=z=0.
stim.PauliString("-Y"): The qubit is in the |-i> state. Its bloch vector is y=-1, x=z=0.
stim.PauliString("+X"): The qubit is in the |+> state. Its bloch vector is x=+1, y=z=0.
stim.PauliString("-X"): The qubit is in the |-> state. Its bloch vector is x=-1, y=z=0.
Examples:
>>> import stim
>>> s = stim.TableauSimulator()
>>> s.peek_bloch(0)
stim.PauliString("+Z")
>>> s.x(0)
>>> s.peek_bloch(0)
stim.PauliString("-Z")
>>> s.h(0)
>>> s.peek_bloch(0)
stim.PauliString("-X")
>>> s.sqrt_x(1)
>>> s.peek_bloch(1)
stim.PauliString("-Y")
>>> s.cz(0, 1)
>>> s.peek_bloch(0)
stim.PauliString("+_")
)DOC")
.data());
c.def(
"measure",
[](TableauSimulator &self, uint32_t target) {
self.ensure_large_enough_for_qubits(target + 1);
self.measure_z(TempViewableData({GateTarget{target}}));
return (bool)self.measurement_record.storage.back();
},
pybind11::arg("target"),
clean_doc_string(u8R"DOC(
Measures a single qubit.
Unlike the other methods on TableauSimulator, this one does not broadcast
over multiple targets. This is to avoid returning a list, which would
create a pitfall where typing `if sim.measure(qubit)` would be a bug.
To measure multiple qubits, use `TableauSimulator.measure_many`.
Args:
target: The index of the qubit to measure.
Returns:
The measurement result as a bool.
)DOC")
.data());
c.def(
"measure_many",
[](TableauSimulator &self, pybind11::args args) {
auto converted_args = args_to_targets(self, args);
self.measure_z(converted_args);
auto e = self.measurement_record.storage.end();
return std::vector<bool>(e - converted_args.targets.size(), e);
},
clean_doc_string(u8R"DOC(
Measures multiple qubits.
Args:
*targets: The indices of the qubits to measure.
Returns:
The measurement results as a list of bools.
)DOC")
.data());
c.def(
"set_num_qubits",
[](TableauSimulator &self, uint32_t new_num_qubits) {
self.set_num_qubits(new_num_qubits);
},
clean_doc_string(u8R"DOC(
Forces the simulator's internal state to track exactly the qubits whose indices are in range(new_num_qubits).
Note that untracked qubits are always assumed to be in the |0> state. Therefore, calling this method
will effectively force any qubit whose index is outside range(new_num_qubits) to be reset to |0>.
Note that this method does not prevent future operations from implicitly expanding the size of the
tracked state (e.g. setting the number of qubits to 5 will not prevent a Hadamard from then being
applied to qubit 100, increasing the number of qubits to 101).
Args:
new_num_qubits: The length of the range of qubits the internal simulator should be tracking.
Examples:
>>> import stim
>>> s = stim.TableauSimulator()
>>> len(s.current_inverse_tableau())
0
>>> s.set_num_qubits(5)
>>> len(s.current_inverse_tableau())
5
>>> s.x(0, 1, 2, 3)
>>> s.set_num_qubits(2)
>>> s.measure_many(0, 1, 2, 3)
[True, True, False, False]
)DOC")
.data());
c.def(
"set_inverse_tableau",
[](TableauSimulator &self, const Tableau &new_inverse_tableau) {
self.inv_state = new_inverse_tableau;
},
clean_doc_string(u8R"DOC(
Overwrites the simulator's internal state with a copy of the given inverse tableau.
The inverse tableau specifies how Pauli product observables of qubits at the current time transform
into equivalent Pauli product observables at the beginning of time, when all qubits were in the
|0> state. For example, if the Z observable on qubit 5 maps to a product of Z observables at the
start of time then a Z basis measurement on qubit 5 will be deterministic and equal to the sign
of the product. Whereas if it mapped to a product of observables including an X or a Y then the Z
basis measurement would be random.
Any qubits not within the length of the tableau are implicitly in the |0> state.
Args:
new_inverse_tableau: The tableau to overwrite the internal state with.
Examples:
>>> import stim
>>> s = stim.TableauSimulator()
>>> t = stim.Tableau.random(4)
>>> s.set_inverse_tableau(t)
>>> s.current_inverse_tableau() == t
True
)DOC")
.data());
c.def(
"copy",
[](TableauSimulator &self) {
TableauSimulator copy = self;
return copy;
},
clean_doc_string(u8R"DOC(
Returns a copy of the simulator. A simulator with the same internal state.
Examples:
>>> import stim
>>> s1 = stim.TableauSimulator()
>>> s1.set_inverse_tableau(stim.Tableau.random(1))
>>> s2 = s1.copy()
>>> s2 is s1
False
>>> s2.current_inverse_tableau() == s1.current_inverse_tableau()
True
>>> s = stim.TableauSimulator()
>>> def brute_force_post_select(qubit, desired_result):
... global s
... while True:
... copy = s.copy()
... if copy.measure(qubit) == desired_result:
... s = copy
... break
>>> s.h(0)
>>> brute_force_post_select(qubit=0, desired_result=True)
>>> s.measure(0)
True
)DOC")
.data());
c.def(
"measure_kickback",
[](TableauSimulator &self, uint32_t target) {
self.ensure_large_enough_for_qubits(target + 1);
auto result = self.measure_kickback_z({target});
if (result.second.num_qubits == 0) {
return pybind11::make_tuple(result.first, pybind11::none());
}
return pybind11::make_tuple(result.first, PyPauliString(result.second));
},
pybind11::arg("target"),
clean_doc_string(u8R"DOC(
Measures a qubit and returns the result as well as its Pauli kickback (if any).
The "Pauli kickback" of a stabilizer circuit measurement is a set of Pauli operations that
flip the post-measurement system state between the two possible post-measurement states.
For example, consider measuring one of the qubits in the state |00>+|11> in the Z basis.
If the measurement result is False, then the system projects into the state |00>.
If the measurement result is True, then the system projects into the state |11>.
Applying a Pauli X operation to both qubits flips between |00> and |11>.
Therefore the Pauli kickback of the measurement is `stim.PauliString("XX")`.
Note that there are often many possible equivalent Pauli kickbacks. For example,
if in the previous example there was a third qubit in the |0> state, then both
`stim.PauliString("XX_")` and `stim.PauliString("XXZ")` are valid kickbacks.
Measurements with determinist results don't have a Pauli kickback.
Args:
target: The index of the qubit to measure.
Returns:
A (result, kickback) tuple.
The result is a bool containing the measurement's output.
The kickback is either None (meaning the measurement was deterministic) or a stim.PauliString
(meaning the measurement was random, and the operations in the Pauli string flip between the
two possible post-measurement states).
Examples:
>>> import stim
>>> s = stim.TableauSimulator()
>>> s.measure_kickback(0)
(False, None)
>>> s.h(0)
>>> s.measure_kickback(0)[1]
stim.PauliString("+X")
>>> def pseudo_post_select(qubit, desired_result):
... m, kick = s.measure_kickback(qubit)
... if m != desired_result:
... if kick is None:
... raise ValueError("Deterministic measurement differed from desired result.")
... s.do(kick)
>>> s = stim.TableauSimulator()
>>> s.h(0)
>>> s.cnot(0, 1)
>>> s.cnot(0, 2)
>>> pseudo_post_select(qubit=2, desired_result=True)
>>> s.measure_many(0, 1, 2)
[True, True, True]
)DOC")
.data());
}
| [
"noreply@github.com"
] | noreply@github.com |
34c46e77b96ecf942ec946d7ed1685941fbd214d | a726f810c3888fd764fd676a29a8e1f527e447fa | /src/Coord3.h | 00299acc5ade4726c70b1b316b3acce84c75ae8d | [] | no_license | adamwdennis/Frogger | c322e03c518ea4a8e4f7a5923f8431d4c9ac32a9 | 8aaea52152200b9d536206b41515be03833ce3c9 | refs/heads/master | 2021-01-25T07:08:33.351822 | 2012-05-17T18:39:45 | 2012-05-17T18:39:45 | 3,473,417 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,255 | h | #ifndef _COORD3_H_
#define _COORD3_H_
class Coord3
{
public:
Coord3(float p_rX = 0, float p_rY = 0, float p_rZ = 0)
{
m_rX = p_rX;
m_rY = p_rY;
m_rZ = p_rZ;
}
~Coord3() {}
//Overloaded operators
Coord3 operator+ (Coord3& rhs)
{
return Coord3(m_rX + rhs.GetX(), m_rY + rhs.GetY(), m_rZ + rhs.GetZ());
}
Coord3 operator- (Coord3& rhs)
{
return Coord3(m_rX - rhs.GetX(), m_rY - rhs.GetY(), m_rZ - rhs.GetZ());
}
float GetX() { return m_rX; }
float GetY() { return m_rY; }
float GetZ() { return m_rZ; }
void SetX(float p_iX) { m_rX = p_iX; }
void SetY(float p_iY) { m_rY = p_iY; }
void SetZ(float p_iZ) { m_rZ = p_iZ; }
float GetLength();
void Normalize();
void Scale(float scaler);
Coord3 CrossProduct(Coord3 val);
private:
float m_rX;
float m_rY;
float m_rZ;
};
void Coord3_copy(Coord3 src, Coord3* dst);
float Coord3_dotproduct(Coord3 v1, Coord3 v2);
//void Coord3_crossproduct(Coord3 v1, Coord3 v2, Coord3* cross);
void Coord3_add(Coord3 v1, Coord3 v2);
void Coord3_subtract(Coord3* v1, Coord3 v2);
void Coord3_rotateX(Coord3* v, float theta);
void Coord3_rotateY(Coord3* v, float theta);
void Coord3_rotateZ(Coord3* v, float theta);
void Coord3_rotate(Coord3* v, float x, float y, float z, float theta);
#endif | [
"adamd@adamd.hb-studios.com"
] | adamd@adamd.hb-studios.com |
2ef9cd2b70d5a1866b83256a8e54f314950eb75b | f4e3ce60f246c945efa51645fff79ba9b9a173f5 | /Dynamic programming/CoinChange/Ways(OrderDoesn'tMatter).cpp | f1d2473f26281804d5bceb179d1edf2f8b5d81d6 | [] | no_license | SinghVikram97/CompetitiveProgramming | dc205656ea620ca8fa4eaf00bdd4c145e5ff71ac | 6e6a3edf69e4fe40086b14ede97933a39d8739c2 | refs/heads/master | 2022-04-23T18:56:21.455721 | 2020-04-23T06:00:52 | 2020-04-23T06:00:52 | 105,851,223 | 19 | 9 | null | 2018-02-04T18:34:46 | 2017-10-05T05:01:39 | C++ | UTF-8 | C++ | false | false | 714 | cpp | /// Order doesn't matters
#include<bits/stdc++.h>
using namespace std;
int number_of_ways(int total_value,vector<int> coins,int index)
{
if(total_value<0) /// Imp condition
{
return 0;
}
else if(total_value==0)
{
return 1; /// Sucessful
}
else if(total_value>0 && index==coins.size()) /// Run out of coins but not money
{
return 0; /// Unsucessful
}
else
{
/// Le skte ho ya nhi le skte
return number_of_ways(total_value-coins[index],coins,index)+number_of_ways(total_value,coins,index+1);
}
}
int main()
{
int n,m;
cin>>n>>m;
vector<int> v(m);
for(int i=0;i<m;i++)
{
cin>>v[i];
}
cout<<number_of_ways(n,v,0);
}
| [
"noreply@github.com"
] | noreply@github.com |
be9f28c63039b3ec53bf5891a143eeaae97bafa0 | 3880ed9e62d9849e811b5de2d29522ddf0f8ad2c | /codeforces/913d.cpp | 720b28ebd4ea0181d465cb4bfa40cdcbbf0c02c5 | [] | no_license | Krythz43/CP-Archieve | 936b028f9f0f90e555dc7c19c11d3939f7532b2f | 36b5f7449bbd93135f4f09b7564b8ada94ef99e6 | refs/heads/master | 2020-08-31T18:42:47.954906 | 2020-05-12T05:18:00 | 2020-05-12T05:18:00 | 218,757,326 | 0 | 0 | null | 2020-05-12T05:18:02 | 2019-10-31T12:08:54 | C++ | UTF-8 | C++ | false | false | 1,223 | cpp | #include <cstdio>
#include <cmath>
#include <iostream>
#include <set>
#include <algorithm>
#include <vector>
#include <map>
#include <cassert>
#include <string>
#include <cstring>
#include <queue>
using namespace std;
#define rep(i,a,b) for(int i = a; i < b; i++)
#define S(x) scanf("%d",&x)
#define S2(x,y) scanf("%d%d",&x,&y)
#define P(x) printf("%d\n",x)
#define all(v) v.begin(),v.end()
#define FF first
#define SS second
#define pb push_back
#define mp make_pair
typedef long long int LL;
typedef pair<int, int > pii;
typedef vector<int > vi;
const int N = 200005;
int P[N], T[N];
vi v;
vector<pii > v1;
int n;
bool f(int x, int t) {
v.clear();
rep(i,0,n) if(P[i] >= x) {
v.pb(T[i]);
}
if(v.size() < x) return false;
sort(all(v));
rep(i,0,x) t -= v[i];
return t >= 0;
}
int main() {
int t;
S2(n,t);
rep(i,0,n) {
S2(P[i],T[i]);
}
int ans = 0;
int lo = 0, hi = n;
while(lo <= hi) {
int mi = (lo + hi) >> 1;
if(f(mi, t)) {
ans = mi;
lo = mi + 1;
} else {
hi = mi - 1;
}
}
P(ans);
P(ans);
rep(i,0,n) if(P[i] >= ans) {
v1.pb(mp(T[i],i+1));
}
sort(all(v1));
rep(i,0,ans) printf("%d ",v1[i].SS); printf("\n");
return 0;
} | [
"krithickrockz@gmail.com"
] | krithickrockz@gmail.com |
522885627addbd39d28bba8676e65db81630f0c6 | 93fbf65a76bbeb5d8e915c14e5601ae363b3057f | /Codechef/Feb 2021 Long Challenge/PrimeGame.cpp | 076ede115d60c1b0784f76131882facd1540ac5c | [] | no_license | sauravjaiswa/Coding-Problems | fd864a7678a961a422902eef42a29218cdd2367f | cb978f90d7dcaec75af84cba05d141fdf4f243a0 | refs/heads/master | 2023-04-14T11:34:03.138424 | 2021-03-25T17:46:47 | 2021-03-25T17:46:47 | 309,085,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | cpp | //Prime Game
#include<bits/stdc++.h>
#define lli long long int
using namespace std;
bool isprime(lli n)
{
lli i;
if(n<=1)
return false;
for(i=2;i<=sqrt(n);i++)
if(n%i==0)
return false;
return true;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
lli i;
lli primeCount[1000001];
primeCount[0]=primeCount[1]=0;
lli t;
cin>>t;
// cout<<primeCount[0]<<" "<<primeCount[1]<<" ";
for(i=2;i<1000001;i++){
if(isprime(i))
primeCount[i]=primeCount[i-1]+1;
else
primeCount[i]=primeCount[i-1];
// cout<<i<<" : "<<primeCount[i]<<" ";
}
// cout<<"\n";
while(t--){
lli x,y;
cin>>x>>y;
if(primeCount[x]>y)
cout<<"Divyam\n";
else
cout<<"Chef\n";
}
return 0;
}
| [
"41826172+sauravjaiswa@users.noreply.github.com"
] | 41826172+sauravjaiswa@users.noreply.github.com |
51bd2f04ca78481c1d4df48f0a5229a34d38aab0 | c2c8f2715607a59efdf69eb23d83a1e6690384d1 | /Week2_3-Data-Structure-I/templates/cpp-skiplist-template/dscl/skiplist.h | a8277ab6ffa27db5a6c5ca360e7a66bb5b658bfe | [
"MIT"
] | permissive | CDDSCL-Robot/training-plan | abe9ba19b9746ad0989a4a41ef6888d51eed45fc | b350717547abf6b715d686a765b8719a246d190b | refs/heads/template | 2023-08-03T23:55:35.636184 | 2021-09-24T02:12:10 | 2021-09-24T05:56:18 | 406,771,931 | 1 | 1 | MIT | 2021-09-24T11:29:27 | 2021-09-15T13:17:21 | C++ | UTF-8 | C++ | false | false | 3,563 | h | #ifndef SKIPLIST_H_
#define SKIPLIST_H_
#include <cassert>
#include <cstdlib>
#include <vector>
#include "util/random.h"
namespace skiplist {
template <typename Key, class Comparator>
class SkipList {
private:
struct Node;
public:
// Create a new SkipList object that will use "cmp" for comparing keys,
explicit SkipList(Comparator cmp);
SkipList(const SkipList&) = delete;
SkipList& operator=(const SkipList&) = delete;
// Insert key into the list.
// REQUIRES: nothing that compares equal to key is currently in the list.
void Insert(const Key& key);
// Remove key in the list iff the list contains the key
bool Remove(const Key& key);
// Returns true iff an entry that compares equal to key is in the list.
bool Contains(const Key& key) const;
// Iteration over the contents of a skip list
class Iterator {
public:
// Initialize an iterator over the specified list.
// The returned iterator is not valid.
explicit Iterator(const SkipList* list);
// Returns true iff the iterator is positioned at a valid node.
// valid indicates the iterator is not nullptr
bool Valid() const;
// Returns the key at the current position.
// REQUIRES: Valid()
const Key& key() const;
// Advances to the next position.
// REQUIRES: Valid()
void Next();
// Advances to the previous position.
// REQUIRES: Valid()
void Prev();
// Advance to the first entry with a key >= target
void Seek(const Key& target);
// Position at the first entry in list.
// Final state of iterator is Valid() iff list is not empty.
void SeekToFirst();
// Position at the last entry in list.
// Final state of iterator is Valid() iff list is not empty.
void SeekToLast();
private:
const SkipList* list_;
Node* node_;
};
private:
enum { kMaxHeight = 12 };
inline int GetMaxHeight() const { return max_height_; }
Node* NewNode(const Key& key, int height);
int RandomHeight();
bool Equal(const Key& a, const Key& b) const { return (compare_(a, b) == 0); }
// Return true if key is greater than the data stored in "n"
bool KeyIsAfterNode(const Key& key, Node* n) const;
// Return the earliest node that comes at or after key.
// Return nullptr if there is no such node.
//
// If prev is non-null, fills prev[level] with pointer to previous
// node at "level" for every level in [0..max_height_-1].
Node* FindGreaterOrEqual(const Key& key, Node** prev) const;
// Return the latest node with a key < key.
// Return head_ if there is no such node.
Node* FindLessThan(const Key& key) const;
// Return the last node in the list.
// Return head_ if list is empty.
Node* FindLast() const;
// Immutable after construction
Comparator const compare_;
Node* const head_;
// Modified only by Insert().
int max_height_; // Height of the entire list
// Read/written only by Insert().
Random rnd_;
};
// Implementation details follow
template <typename Key, class Comparator>
struct SkipList<Key, Comparator>::Node {
Node(const Key& k, int height) : key(k) {
// resize the next_ array of size height
}
explicit Node() : key(0) {}
Key const key;
// Accessors/mutators for links.
Node* Next(int n) {
// return the next level n of this Node
}
void SetNext(int n, Node* x) {
// set the next Node of level n
}
private:
// Array of length equal to the node height.
std::vector<Node*> next_;
};
// Implement your code
} // namespace skiplist
#endif // DSCL_SKIPLIST_H_
| [
"icepigzdb@gmail.com"
] | icepigzdb@gmail.com |
bdee1a8468da721423f90727fb498525f022ea9a | 387a1ee121d575ce173b24df048df7c781e0591d | /lab3/Header.h | ae6be266aca9d2e5e6a04a04208d1abf3c607b2c | [] | no_license | icekiborg/laba3 | d1a5fcc3d6e368dadf63ef158282f1bcbaf577c8 | 8fda8ee5b58dc52b2fcaf3fd9258442cbe5795aa | refs/heads/master | 2021-01-10T10:16:56.460853 | 2015-11-11T08:21:05 | 2015-11-11T08:21:05 | 45,964,983 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,498 | h | #pragma once
#include <iostream>
using namespace std;
class Land
{
protected:
int area;
public:
Land()
{
area = 0;
}
Land(int s)
{
area = s;
}
};
class Sea
{
protected:
int area1;
public:
Sea(int s1)
{
area1 = s1;
}
};
class Island : public Land, public Sea // множественное наследование
{
private:
char *name;
public:
Island(int s, int s1, const char *n) : Land(s), Sea(s1)
{
name = (char*)n;
}
void print()
{
cout << "Name: " << name << endl;
cout << "Area sea: " << area1 << endl;
cout << "Area land: " << area << endl;
}
};
class State : public Land // базовый Land
{
protected:
char *name;
int kolPeople;
public:
State()
{
name = "";
kolPeople = 0;
area = 0;
}
State(int s, const char *n, int kol) : Land(s)
{
name = (char*)n;
kolPeople = kol;
}
void setState(int s, const char *n, int kol)
{
area = s;
name = (char*)n;
kolPeople = kol;
}
void print()
{
cout << "Name: " << name << endl;
cout << "Area land: " << area << endl;
cout << "Number of people: " << kolPeople << endl;
}
};
class Continent
{
private:
int kolState;
public:
State *a[10]; // композиция
Continent(int kol)
{
kolState = kol;
for (int i = 0; i < kol; i++)
{
a[i] = new State();
}
}
void show()
{
for (int i = 0; i < kolState; i++)
{
cout << "State" << i+1 << endl;
a[i]->print();
}
}
}; | [
"q0770w@gmail.com"
] | q0770w@gmail.com |
e4f89fd1af3fc1ee9f51797326051ead683b36ab | e30f84c0b7ff276eb0cad55772a08659f6249764 | /Snooze.cpp | aa7e73b9e4710fb372ea788e5ab02e1e66504d38 | [
"MIT"
] | permissive | winocc/snooze | b1e4ce21459ea0c13daa7d59deeb38cfae40c91f | e62da81df2c713888f1548f0aa61318449764e72 | refs/heads/master | 2021-01-09T20:08:14.655891 | 2017-02-01T03:29:27 | 2017-02-01T03:29:27 | 81,229,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,433 | cpp | /******************************************************************************
* Low Power Library for Teensy LC/3.x
* Copyright (c) 2014, Colin Duffy https://github.com/duff2013
*
* 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, development funding 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.
*******************************************************************************
* Snooze.cpp
* Teensy 3.x/LC
*
* Purpose: Provides routines for configuring the Teensy for low power.
*
* NOTE: None
*******************************************************************************/
#include "Snooze.h"
#include "SnoozeBlock.h"
#include "utility/wake.h"
#include "utility/sleep.h"
#include "utility/clocks.h"
volatile uint32_t SnoozeClass::PCR3 = 0;
/**
* SnoozeClass Constructor
*/
SnoozeClass::SnoozeClass( void ) {
SIM_SOPT1CFG |= SIM_SOPT1CFG_USSWE;
SIM_SOPT1 &= ~SIM_SOPT1_USBSSTBY;
}
/*******************************************************************************
* source - returns the wakeup source.
*
* @return Digital pins return pin number, CMP - 34, RTC - 35, LPTMR - 36, TSI - 37.
*******************************************************************************/
int SnoozeClass::source( SNOOZE_BLOCK ) {
SnoozeBlock *p = &configuration;
return p->source;
}
/*******************************************************************************
* idle - puts processor into wait mode until next interrupt typically systick.
*******************************************************************************/
void SnoozeClass::idle( SNOOZE_BLOCK ) {
SnoozeBlock *p = &configuration;
p->mode = WAIT;
wait( );
p->mode = RUN;
}
/*******************************************************************************
* sleep - most versatile sleep mode. SnoozeBlock configuration or any interrupt
* can wake the processor.
*
* @param configuration SnoozeBlock class config.
*
* @return wakeup source
*******************************************************************************/
int SnoozeClass::sleep( SNOOZE_BLOCK ) {
SnoozeBlock *p = &configuration;
p->mode = VLPW;
//p->mode = VLPS;
p->enableDriver( );
pee_blpi( );
enter_vlpr( );
//vlps( );
vlpw( );
exit_vlpr( );
blpi_pee( );
p->disableDriver( );
p->mode = RUN;
return p->source;
}
/*******************************************************************************
* deepSleep - LLWU is used to handle interrupts that wake. USB regulator is
* enabled and 3.3V output pin can supply full current (100mA MAX).
*
* @param configuration SnoozeBlock class config.
* @param mode |LLS|VLLS3|VLLS2|VLLS1|
*
* @return wakeup source
*******************************************************************************/
int SnoozeClass::deepSleep( SNOOZE_BLOCK, SLEEP_MODE mode ) {
int priority = nvic_execution_priority( );// get current priority
priority = ( priority < 256 ) && ( ( priority - 16 ) > 0 ) ? priority - 16 : 128;
NVIC_SET_PRIORITY( IRQ_LLWU, priority );//set priority to new level
SnoozeBlock *p = &configuration;
p->mode = LLS;
p->enableDriver( );
llwu_set( );
switch ( mode ) {
case LLS:
lls( );
break;
case VLLS3:
vlls3( );
break;
case VLLS2:
vlls2( );
break;
case VLLS1:
vlls1( );
break;
case VLLS0:
vlls0( );
break;
default:
break;
}
//#if defined(__MK66FX1M0__) || defined(__MKL26Z64__)
p->source = llwu_disable( );
//#else
//llwu_disable( );
//#endif
p->disableDriver( );
p->mode = RUN;
return p->source;
}
/*******************************************************************************
* hibernate - LLWU is used to handle interrupts that wake. USB regulator is
* disabled and 3.3V output pin can only supply limited current and
* voltage drops to ~2.7V.
*
* @param configuration SnoozeBlock class config.
* @param mode |LLS|VLLS3|VLLS2|VLLS1|
*
* @return wakeup source
*******************************************************************************/
int SnoozeClass::hibernate( SNOOZE_BLOCK, SLEEP_MODE mode ) {
int priority = nvic_execution_priority( );// get current priority
priority = ( priority < 256 ) && ( ( priority - 16 ) > 0 ) ? priority - 16 : 128;
NVIC_SET_PRIORITY( IRQ_LLWU, priority );//set priority to new level
SIM_SOPT1CFG |= SIM_SOPT1CFG_USSWE;
SIM_SOPT1 |= SIM_SOPT1_USBSSTBY;
PCR3 = PORTA_PCR3;
PORTA_PCR3 = PORT_PCR_MUX( 0 );
SnoozeBlock *p = &configuration;
p->mode = mode;
p->enableDriver( );
llwu_set( );
switch ( mode ) {
case LLS:
lls( );
break;
case VLLS3:
vlls3( );
break;
case VLLS2:
vlls2( );
break;
case VLLS1:
vlls1( );
break;
case VLLS0:
vlls0( );
break;
default:
break;
}
//#if defined(__MK66FX1M0__) || defined(__MKL26Z64__)
p->source = llwu_disable( );
//#else
//llwu_disable( );
//#endif
p->disableDriver( );
p->mode = RUN;
SIM_SOPT1CFG |= SIM_SOPT1CFG_USSWE;
SIM_SOPT1 &= ~SIM_SOPT1_USBSSTBY;
PORTA_PCR3 = PCR3;
return p->source;
} | [
"cmduffy@engr.psu.edu"
] | cmduffy@engr.psu.edu |
98b2762e666ceef4a2d672230b52bd1f98835783 | 861e538595f39009f0b7a9dc7876737b5fea3675 | /test/unit/LAS.cpp | 00381fafb5b60ae65c4f61881116fac8d86df612 | [
"BSD-2-Clause"
] | permissive | jwend/p_points2grid | 4422445acd2192fe77b86d2fccc86ad8d6662015 | fdc021e9e0cc022331c8792d1a531aa81a0f64ad | refs/heads/master | 2020-04-06T18:21:35.050292 | 2018-02-12T23:26:15 | 2018-02-12T23:26:15 | 23,968,354 | 2 | 2 | null | 2017-06-08T17:11:15 | 2014-09-12T16:36:52 | C++ | UTF-8 | C++ | false | false | 2,126 | cpp | #include <points2grid/Global.hpp>
#include <points2grid/lasfile.hpp>
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdexcept>
#include <float.h>
#include "Point.hpp"
#include "Grid.hpp"
#include "DTypes.h"
int main(int argc, char **argv)
{
int buffer_size = 10000;
char inputFile[1024] = "/home/ncasler/app-dev/point-cloud-tree/data/1000_908.las";
char inputFile2[1024] = "/home/ncasler/app-dev/point-cloud-tree/data/998_988.las";
int epsg_code = 0;
int point_count = 0;
double min_x, min_y, min_z, max_x, max_y, max_z;
DType d_type = DT_Float32;
int np = 10;
min_x = DBL_MAX;
min_y = DBL_MAX;
min_z = DBL_MAX;
max_x = -DBL_MAX;
max_y = -DBL_MAX;
max_z = -DBL_MAX;
printf("Input file: %s\n", inputFile);
las_file las1;
las_file las2;
las1.open(inputFile);
las2.open(inputFile2);
double resX = 3.0;
double resY = 3.0;
min_x = fmin(las1.minimums()[0], las2.minimums()[0]);
min_y = fmin(las1.minimums()[1], las2.minimums()[1]);
min_z = fmin(las1.minimums()[2], las2.minimums()[2]);
max_x = fmax(las1.maximums()[0], las2.maximums()[0]);
max_y = fmax(las1.maximums()[1], las2.maximums()[1]);
max_z = fmax(las1.maximums()[2], las2.maximums()[2]);
printf("MIN:(%f, %f),Max (%f,%f)\n", min_x, min_y, max_x, max_y);
int cols = ceil((max_x - min_x) / resX);
int rows = ceil((max_y - min_y) / resY);
struct point origin(min_x, max_y, min_z);
struct grid *gridTest = new grid(&origin, cols, rows, d_type, resX, resY);
int size = gridTest->getSize() / 1000000;
printf("Grid will have %ix%i dims and will take %i GB\n", cols, rows, size);
las1.close();
las2.close();
// Optimize block size
double aspect_ratio = (float)cols / (float)rows;
int cellCount = cols * rows;
int blockMax = 2000000;
int b_dim = ceil(sqrt(blockMax));
int nb = ceil((float)cellCount/(float)blockMax);
int b_col = ceil((float)cols / (float)b_dim);
int b_row = ceil((float)rows / (float)b_dim);
printf("Block_dim: %i, b_col: %i, b_row: %i\n", b_dim, b_col, b_row);
printf("t_Cell: %i, Proportion: %f, Block Count: %i", cellCount, aspect_ratio, nb);
delete(gridTest);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
f0f7ea26df02497fafd63d2afc72f6c09bbaa110 | a0370090e044e2817842b90a9559be41282072c5 | /DevExpress VCL/ExpressPrinting System/Demos/CBuilder/ReportExplorer/Splash.cpp | 3ca35055ac58c34ef365eb95787142c868a75f5b | [] | no_license | bravesoftdz/MyVCL-7 | 600a1c1be2ea71b198859b39b6da53c6b65601b3 | 197c1e284f9ac0791c15376bcf12c243400e7bcd | refs/heads/master | 2022-01-11T17:18:00.430191 | 2018-12-20T08:23:02 | 2018-12-20T08:23:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,656 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Splash.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
//---------------------------------------------------------------------------
__fastcall TfmSplash::TfmSplash(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TfmSplash::FormCreate(TObject *Sender)
{
const String CRLF = "\n";
const String WarningText =
" If you do not own appropriate Control Libraries from Developer Express Inc., part of Reports " + CRLF +
"cannot be used, because last ones are needed specific ReportItems for rendering from these Libraries." + CRLF +
" Mentioned above ReportItems are the part of ReportLinks for these Libraries." + CRLF +
CRLF + CRLF +
" In case you own them, just uncomment directives placed top of Main.cpp and Main.h according " + CRLF +
"to the following explanation:" +
CRLF +
CRLF +
" - dxPScxSSLnk for ExpressSpreadSheet" + CRLF +
" - dxPSdxLCLnk for ExpressLayoutControl (Only available in Delphi5 and higher)" + CRLF +
" - dxPScxCommon for ExpressEditors" + CRLF +
" (also needed for ExpressQuantumGrid v4, ExpressQuantumTree v4 and ExpressVerticalGrid v3)" + CRLF +
" - dxPSExtCommon for ExpressExtendedEditors";
Caption = Application->Title;
lblText->Caption = WarningText;
}
//---------------------------------------------------------------------------
| [
"karaim@mail.ru"
] | karaim@mail.ru |
a35eaf5ab4fc4d9c3d15b9d441afffce8af14a97 | 587bb649a2ef7f5e82a16f751910116f32c94a50 | /09_DrawSingleTriangle/d3dUtility.cpp | af1ef62bd9311bde4003aac167b4ec1139585288 | [] | no_license | ImL1s/c-LearnDirectX | e6dc1d807cf601c10b060e5902bcd22dbccb7943 | 06e8baf41893be693768f48e314d4b53809e83fe | refs/heads/master | 2021-01-20T00:27:36.089136 | 2017-05-24T05:45:58 | 2017-05-24T05:45:58 | 89,131,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,892 | cpp | #include "d3dUtility.h"
//#pragma comment(lib,"d3d9.lib")
//#pragma comment(lib,"d3dx9.lib")
//#pragma comment(lib,"winmm.lib")
bool d3d::InitD3D(
HINSTANCE hInstance,
int width, int height,
bool windowed,
D3DDEVTYPE deviceType,
IDirect3DDevice9** device)
{
//
// Create the main application window.
//
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)d3d::WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(0, IDI_APPLICATION);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = "Direct3D9App";
if (!RegisterClass(&wc))
{
::MessageBox(0, "RegisterClass() - FAILED", 0, 0);
return false;
}
//HWND CreateWindow( LPCTSTR lpClassName,
// LPCTSTR lpWindowName,
// DWORD dwStyle,
// int x,
// int y,
// int nWidth,
// int nHeight,
// HWND hWndParent,
// HMENU hMenu,
// HINSTANCE hInstance,
// LPVOID lpParam
//);
HWND hwnd = 0;
hwnd = ::CreateWindow("Direct3D9App", "Direct3D9App",
WS_EX_TOPMOST,
0, 0, width, height,
0 /*parent hwnd*/, 0 /* menu */, hInstance, 0 /*extra*/);
if (!hwnd)
{
::MessageBox(0, "CreateWindow() - FAILED", 0, 0);
return false;
}
::ShowWindow(hwnd, SW_SHOW);
::UpdateWindow(hwnd);
//
// Init D3D:
//
HRESULT hr = 0;
// Step 1: Create the IDirect3D9 object.
//要初始化IDirect3D,首先必须获取指向接口IDrect3D9的指针。使得一个专门的Direct3D函数可以很容易做到
IDirect3D9* d3d9 = 0;
d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
if (!d3d9)
{
::MessageBox(0, "Direct3DCreate9() - FAILED", 0, 0);
return false;
}
// Step 2: Check for hardware vp.
//检验图形卡是否支持该硬件顶点运算
D3DCAPS9 caps;
d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, deviceType, &caps);
int vp = 0;
if (caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
vp = D3DCREATE_HARDWARE_VERTEXPROCESSING;
//硬件顶点运算
else
vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
//软件顶点运算
// Step 3: Fill out the D3DPRESENT_PARAMETERS structure.
D3DPRESENT_PARAMETERS d3dpp;
d3dpp.BackBufferWidth = width; //后台缓存中表面的宽度,单位为像素
d3dpp.BackBufferHeight = height;//高度
d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;//后台缓存的像素格式(如32位像素格式:D3DFMT_A8R8G8B8)
d3dpp.BackBufferCount = 1; //所需使用的后台缓存的个数,通常是1,需要一个后台缓存
d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; //多重采样类型
d3dpp.MultiSampleQuality = 0; //多重采样的质量水平
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; //枚举类型指定交换链中的缓存的页面设置方式。
d3dpp.hDeviceWindow = hwnd; //与设备相关的窗口句柄。指定了所有进行绘制的应用程序窗口
d3dpp.Windowed = windowed;//窗口模式
d3dpp.EnableAutoDepthStencil = true; //自动创建并维护深度缓存或模板缓存
d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;//深度缓存或模板缓存的像素格式
d3dpp.Flags = 0;//附加特性;刷新频率
d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
// Step 4: Create the device.
// 利用已经初始化的D3DPRESENT_PARAMETERS结构创建IDrect3Device9(一个C++对象,代表我们用来显示3D图形的物理硬件设备)
hr = d3d9->CreateDevice(
D3DADAPTER_DEFAULT, // primary adapter默认显卡
deviceType, // device type
hwnd, // window associated with device
vp, // vertex processing
&d3dpp, // present parameters
device); // return created device
if (FAILED(hr))
{
// try again using a 16-bit depth buffer
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
hr = d3d9->CreateDevice(
D3DADAPTER_DEFAULT,
deviceType,
hwnd,
vp,
&d3dpp,
device);//返回创建的设备
if (FAILED(hr))
{
d3d9->Release(); // done with d3d9 object
::MessageBox(0, "CreateDevice() - FAILED", 0, 0);
return false;
}
}
d3d9->Release(); // done with d3d9 object
return true;
}
//消息循环
int d3d::EnterMsgLoop(bool(*ptr_display)(float timeDelta))
{
MSG msg;
::ZeroMemory(&msg, sizeof(MSG));
static float lastTime = (float)timeGetTime();
while (msg.message != WM_QUIT)
{
if (::PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
else
{
float currTime = (float)timeGetTime();
float timeDelta = (currTime - lastTime)*0.001f;
//计算相邻两次调用ptr_display的时间间隔
ptr_display(timeDelta);//条用ptr_display()函数
lastTime = currTime;
}
}
return msg.wParam;
} | [
"aa22396584@gmail.com"
] | aa22396584@gmail.com |
042d9c46c2e839e52d9782308335e52b65d910c0 | 0dca3325c194509a48d0c4056909175d6c29f7bc | /vod/include/alibabacloud/vod/model/DeleteDetectionTemplateRequest.h | e08c1b91ae922525cc7fd950c4606184d53fb88e | [
"Apache-2.0"
] | permissive | dingshiyu/aliyun-openapi-cpp-sdk | 3eebd9149c2e6a2b835aba9d746ef9e6bef9ad62 | 4edd799a79f9b94330d5705bb0789105b6d0bb44 | refs/heads/master | 2023-07-31T10:11:20.446221 | 2021-09-26T10:08:42 | 2021-09-26T10:08:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,366 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_VOD_MODEL_DELETEDETECTIONTEMPLATEREQUEST_H_
#define ALIBABACLOUD_VOD_MODEL_DELETEDETECTIONTEMPLATEREQUEST_H_
#include <string>
#include <vector>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <alibabacloud/vod/VodExport.h>
namespace AlibabaCloud
{
namespace Vod
{
namespace Model
{
class ALIBABACLOUD_VOD_EXPORT DeleteDetectionTemplateRequest : public RpcServiceRequest
{
public:
DeleteDetectionTemplateRequest();
~DeleteDetectionTemplateRequest();
std::string getTemplateId()const;
void setTemplateId(const std::string& templateId);
private:
std::string templateId_;
};
}
}
}
#endif // !ALIBABACLOUD_VOD_MODEL_DELETEDETECTIONTEMPLATEREQUEST_H_ | [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
c9e0ad773f2300804925a6dd4fead96cdbf4f93d | edcec2b1e0416ca656eb3cb53d1bbf2f145ab7a5 | /GameEngine/include/Game/Modules/FunctionLoadMusic.h | 14aa158844b7a1d6cf7d11b5494f682ced9f2714 | [] | no_license | Niraka/ThirdYearEngine | e69e14af2adadb9ef1d5654535ae0ffef2463847 | f3ebdae2a727db642a4744c31c16c9d03eaee3a6 | refs/heads/master | 2021-01-11T23:32:49.222414 | 2017-01-13T22:57:45 | 2017-01-13T22:57:45 | 78,595,541 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 423 | h | /**
@author Nathan */
#ifndef FUNCTION_LOAD_MUSIC_H
#define FUNCTION_LOAD_MUSIC_H
#include "Game/Modules/Function.h"
#include "Game/Modules/ScriptParam.h"
class FunctionLoadMusic :
public Function
{
private:
ScriptParam m_fileName;
ScriptParam m_musicName;
protected:
public:
FunctionLoadMusic(std::vector<ScriptParam>& params);
~FunctionLoadMusic();
ScriptVar& execute(ScriptInfoPack& pack);
};
#endif | [
"nirakagames@hotmail.co.uk"
] | nirakagames@hotmail.co.uk |
43111e7cac899bc3a9aed30708e3d4b96bd09524 | ca4fe6ea9f61faf113d14db513ad6805a5d112b7 | /libamqpprox/amqpprox_methods_open.cpp | 15505c864bfb7263437151c62f234742cc5c29a2 | [
"Apache-2.0"
] | permissive | tokheim/amqpprox | 3613c9cad6b9cdeaf6be02886e083ed3d1821e8b | ff3e60372b24631739af8421ef62a9744917f607 | refs/heads/main | 2023-08-22T01:05:03.372402 | 2021-09-29T17:10:13 | 2021-09-29T17:10:13 | 423,238,449 | 0 | 0 | NOASSERTION | 2021-10-31T19:11:41 | 2021-10-31T19:11:40 | null | UTF-8 | C++ | false | false | 1,390 | cpp | /*
** Copyright 2020 Bloomberg Finance L.P.
**
** 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 <amqpprox_methods_open.h>
#include <amqpprox_buffer.h>
#include <amqpprox_types.h>
#include <boost/endian/arithmetic.hpp>
#include <iostream>
namespace Bloomberg {
namespace amqpprox {
namespace methods {
bool Open::decode(Open *open, Buffer &buffer)
{
// Here we do not decode the reserved slots
return Types::decodeShortString(&open->d_virtualHost, buffer);
}
bool Open::encode(Buffer &buffer, const Open &open)
{
return Types::encodeShortString(buffer, open.virtualHost()) &&
Types::encodeShortString(buffer, "") &&
buffer.writeIn<boost::endian::big_uint8_t>(0);
}
std::ostream &operator<<(std::ostream &os, const Open &openMethod)
{
os << "Open = [virtualHost: \"" << openMethod.virtualHost() << "\"]";
return os;
}
}
}
}
| [
"anightingale@bloomberg.net"
] | anightingale@bloomberg.net |
f4b3102c050ee275328f19c025603b0903123e46 | fdebf91f6cd8fb712e8db34e75826d23c6b7cac6 | /src/xray/xr_3da/xrGame/Actor_Network.cpp | 2a120cfd0a84677459a9e7029819093460e85104 | [
"Apache-2.0"
] | permissive | joye-ramone/OLR-3.0 | cc47af86d65974563fe13ea2f67aa18e5b01a31d | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | refs/heads/master | 2023-03-15T16:01:59.644050 | 2016-01-30T18:27:46 | 2016-01-30T18:27:46 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 57,729 | cpp | #include "pch_script.h"
#include "actor.h"
#include "Actor_Flags.h"
#include "inventory.h"
#include "xrserver_objects_alife_monsters.h"
#include "xrServer.h"
#include "CameraLook.h"
#include "CameraFirstEye.h"
#include "ActorEffector.h"
#include "PHWorld.h"
#include "level.h"
#include "xr_level_controller.h"
#include "game_cl_base.h"
#include "infoportion.h"
#include "alife_registry_wrappers.h"
#include "../skeletonanimated.h"
#include "client_spawn_manager.h"
#include "hit.h"
#include "PHDestroyable.h"
#include "CharacterPhysicsSupport.h"
#include "Grenade.h"
#include "WeaponMagazined.h"
#include "CustomOutfit.h"
#include "actor_anim_defs.h"
#include "map_manager.h"
#include "HUDManager.h"
#include "ui/UIArtefactPanel.h"
#include "ui/UIMainIngameWnd.h"
#include "gamepersistent.h"
#include "game_object_space.h"
#include "GameTaskManager.h"
#include "game_base_kill_type.h"
#include "holder_custom.h"
#include "actor_memory.h"
#include "actor_statistic_mgr.h"
#include "characterphysicssupport.h"
#include "game_cl_base_weapon_usage_statistic.h"
#include "clsid_game.h"
#include "../x_ray.h"
#ifdef DEBUG
# include "debug_renderer.h"
#endif
int g_cl_InterpolationType = 0;
u32 g_cl_InterpolationMaxPoints = 0;
int g_dwInputUpdateDelta = 20;
BOOL net_cl_inputguaranteed = FALSE;
CActor* g_actor = NULL;
CActor* Actor()
{
VERIFY (g_actor);
if (GameID() != GAME_SINGLE)
VERIFY (g_actor == Level().CurrentControlEntity());
return (g_actor);
};
//--------------------------------------------------------------------
void CActor::ConvState(u32 mstate_rl, string128 *buf)
{
strcpy(*buf,"");
if (isActorAccelerated(mstate_rl, IsZoomAimingMode())) strcat(*buf,"Accel ");
if (mstate_rl&mcCrouch) strcat(*buf,"Crouch ");
if (mstate_rl&mcFwd) strcat(*buf,"Fwd ");
if (mstate_rl&mcBack) strcat(*buf,"Back ");
if (mstate_rl&mcLStrafe) strcat(*buf,"LStrafe ");
if (mstate_rl&mcRStrafe) strcat(*buf,"RStrafe ");
if (mstate_rl&mcJump) strcat(*buf,"Jump ");
if (mstate_rl&mcFall) strcat(*buf,"Fall ");
if (mstate_rl&mcTurn) strcat(*buf,"Turn ");
if (mstate_rl&mcLanding) strcat(*buf,"Landing ");
if (mstate_rl&mcLLookout) strcat(*buf,"LLookout ");
if (mstate_rl&mcRLookout) strcat(*buf,"RLookout ");
if (m_bJumpKeyPressed) strcat(*buf,"+Jumping ");
};
//--------------------------------------------------------------------
void CActor::net_Export (NET_Packet& P) // export to server
{
//CSE_ALifeCreatureAbstract
u8 flags = 0;
P.w_float (GetfHealth());
P.w_u32 (Level().timeServer());
P.w_u8 (flags);
Fvector p = Position();
P.w_vec3 (p);//Position());
P.w_float /*w_angle8*/ (angle_normalize(r_model_yaw)); //Device.vCameraDirection.getH());//
P.w_float /*w_angle8*/ (angle_normalize(unaffected_r_torso.yaw));//(r_torso.yaw);
P.w_float /*w_angle8*/ (angle_normalize(unaffected_r_torso.pitch));//(r_torso.pitch);
P.w_float /*w_angle8*/ (angle_normalize(unaffected_r_torso.roll));//(r_torso.roll);
P.w_u8 (u8(g_Team()));
P.w_u8 (u8(g_Squad()));
P.w_u8 (u8(g_Group()));
//CSE_ALifeCreatureTrader
// P.w_float (inventory().TotalWeight());
// P.w_u32 (m_dwMoney);
//CSE_ALifeCreatureActor
u16 ms = (u16)(mstate_real & 0x0000ffff);
P.w_u16 (u16(ms));
P.w_sdir (NET_SavedAccel);
Fvector v = character_physics_support()->movement()->GetVelocity();
P.w_sdir (v);//m_PhysicMovementControl.GetVelocity());
// P.w_float_q16 (fArmor,-500,1000);
P.w_float (g_Radiation());
P.w_u8 (u8(inventory().GetActiveSlot()));
/////////////////////////////////////////////////
u16 NumItems = PHGetSyncItemsNumber();
if (H_Parent() || (GameID() == GAME_SINGLE) || ((NumItems > 1) && OnClient()))
NumItems = 0;
if (!g_Alive()) NumItems = 0;
P.w_u16 (NumItems);
if (!NumItems) return;
if (g_Alive())
{
SPHNetState State;
CPHSynchronize* pSyncObj = NULL;
pSyncObj = PHGetSyncItem(0);
pSyncObj->get_State(State);
P.w_u8 ( State.enabled );
P.w_vec3 ( State.angular_vel);
P.w_vec3 ( State.linear_vel);
P.w_vec3 ( State.force);
P.w_vec3 ( State.torque);
P.w_vec3 ( State.position);
P.w_float ( State.quaternion.x );
P.w_float ( State.quaternion.y );
P.w_float ( State.quaternion.z );
P.w_float ( State.quaternion.w );
}
else
{
net_ExportDeadBody(P);
};
};
static void w_vec_q8(NET_Packet& P,const Fvector& vec,const Fvector& min,const Fvector& max)
{
P.w_float_q8(vec.x,min.x,max.x);
P.w_float_q8(vec.y,min.y,max.y);
P.w_float_q8(vec.z,min.z,max.z);
}
static void r_vec_q8(NET_Packet& P,Fvector& vec,const Fvector& min,const Fvector& max)
{
P.r_float_q8(vec.x,min.x,max.x);
P.r_float_q8(vec.y,min.y,max.y);
P.r_float_q8(vec.z,min.z,max.z);
clamp(vec.x,min.x,max.x);
clamp(vec.y,min.y,max.y);
clamp(vec.z,min.z,max.z);
}
static void w_qt_q8(NET_Packet& P,const Fquaternion& q)
{
//Fvector Q;
//Q.set(q.x,q.y,q.z);
//if(q.w<0.f) Q.invert();
//P.w_float_q8(Q.x,-1.f,1.f);
//P.w_float_q8(Q.y,-1.f,1.f);
//P.w_float_q8(Q.z,-1.f,1.f);
///////////////////////////////////////////////////
P.w_float_q8(q.x,-1.f,1.f);
P.w_float_q8(q.y,-1.f,1.f);
P.w_float_q8(q.z,-1.f,1.f);
P.w_float_q8(q.w,-1.f,1.f);
///////////////////////////////////////////
//P.w_float_q8(q.x,-1.f,1.f);
//P.w_float_q8(q.y,-1.f,1.f);
//P.w_float_q8(q.z,-1.f,1.f);
//P.w(sign())
}
static void r_qt_q8(NET_Packet& P,Fquaternion& q)
{
//// x^2 + y^2 + z^2 + w^2 = 1
//P.r_float_q8(q.x,-1.f,1.f);
//P.r_float_q8(q.y,-1.f,1.f);
//P.r_float_q8(q.z,-1.f,1.f);
//float w2=1.f-q.x*q.x-q.y*q.y-q.z*q.z;
//w2=w2<0.f ? 0.f : w2;
//q.w=_sqrt(w2);
/////////////////////////////////////////////////////
///////////////////////////////////////////////////
P.r_float_q8(q.x,-1.f,1.f);
P.r_float_q8(q.y,-1.f,1.f);
P.r_float_q8(q.z,-1.f,1.f);
P.r_float_q8(q.w,-1.f,1.f);
clamp(q.x,-1.f,1.f);
clamp(q.y,-1.f,1.f);
clamp(q.z,-1.f,1.f);
clamp(q.w,-1.f,1.f);
}
#define F_MAX 3.402823466e+38F
static void UpdateLimits (Fvector &p, Fvector& min, Fvector& max)
{
if(p.x<min.x)min.x=p.x;
if(p.y<min.y)min.y=p.y;
if(p.z<min.z)min.z=p.z;
if(p.x>max.x)max.x=p.x;
if(p.y>max.y)max.y=p.y;
if(p.z>max.z)max.z=p.z;
for (int k=0; k<3; k++)
{
if (p[k]<min[k] || p[k]>max[k])
{
R_ASSERT2(0, "Fuck");
UpdateLimits(p, min, max);
}
}
};
void CActor::net_ExportDeadBody (NET_Packet &P)
{
/////////////////////////////
Fvector min,max;
min.set(F_MAX,F_MAX,F_MAX);
max.set(-F_MAX,-F_MAX,-F_MAX);
/////////////////////////////////////
u16 bones_number = PHGetSyncItemsNumber();
for(u16 i=0;i<bones_number;i++)
{
SPHNetState state;
PHGetSyncItem(i)->get_State(state);
Fvector& p=state.position;
UpdateLimits (p, min, max);
Fvector px =state.linear_vel;
px.div(10.0f);
px.add(state.position);
UpdateLimits (px, min, max);
};
P.w_u8(10);
P.w_vec3(min);
P.w_vec3(max);
for(u16 i=0;i<bones_number;i++)
{
SPHNetState state;
PHGetSyncItem(i)->get_State(state);
// state.net_Save(P,min,max);
w_vec_q8(P,state.position,min,max);
w_qt_q8(P,state.quaternion);
//---------------------------------
Fvector px =state.linear_vel;
px.div(10.0f);
px.add(state.position);
w_vec_q8(P,px,min,max);
};
};
void CActor::net_Import (NET_Packet& P) // import from server
{
//-----------------------------------------------
net_Import_Base(P);
//-----------------------------------------------
m_u16NumBones = P.r_u16();
if (m_u16NumBones == 0) return;
//-----------------------------------------------
net_Import_Physic(P);
//-----------------------------------------------
};
void CActor::net_Import_Base ( NET_Packet& P)
{
net_update N;
u8 flags;
u16 tmp;
//CSE_ALifeCreatureAbstract
float health;
P.r_float (health);
//----------- for E3 -----------------------------
if (OnClient())SetfHealth(health);
//------------------------------------------------
P.r_u32 (N.dwTimeStamp );
//---------------------------------------------
//---------------------------------------------
P.r_u8 (flags );
P.r_vec3 (N.p_pos );
P.r_float /*r_angle8*/ (N.o_model );
P.r_float /*r_angle8*/ (N.o_torso.yaw );
P.r_float /*r_angle8*/ (N.o_torso.pitch);
P.r_float /*r_angle8*/ (N.o_torso.roll ); if (N.o_torso.roll > PI) N.o_torso.roll -= PI_MUL_2;
id_Team = P.r_u8();
id_Squad = P.r_u8();
id_Group = P.r_u8();
//----------- for E3 -----------------------------
// if (OnClient())
//------------------------------------------------
{
// if (OnServer() || Remote())
if (Level().IsDemoPlay())
{
unaffected_r_torso.yaw = N.o_torso.yaw;
unaffected_r_torso.pitch = N.o_torso.pitch;
unaffected_r_torso.roll = N.o_torso.roll;
cam_Active()->yaw = -N.o_torso.yaw;
cam_Active()->pitch = N.o_torso.pitch;
};
};
//CSE_ALifeCreatureTrader
// P.r_float (fDummy);
// m_dwMoney = P.r_u32();
//CSE_ALifeCreatureActor
P.r_u16 (tmp ); N.mstate = u32(tmp);
P.r_sdir (N.p_accel );
P.r_sdir (N.p_velocity );
float fRRadiation;
P.r_float (fRRadiation);
//----------- for E3 -----------------------------
if (OnClient())
{
// fArmor = fRArmor;
SetfRadiation(fRRadiation);
};
//------------------------------------------------
u8 ActiveSlot;
P.r_u8 (ActiveSlot);
//----------- for E3 -----------------------------
if (OnClient())
//------------------------------------------------
{
if (ActiveSlot == 0xff) inventory().SetActiveSlot(NO_ACTIVE_SLOT);
else
{
if (inventory().GetActiveSlot() != u32(ActiveSlot))
inventory().Activate(u32(ActiveSlot));
};
}
//----------- for E3 -----------------------------
if (Local() && OnClient()) return;
//-------------------------------------------------
if (!NET.empty() && N.dwTimeStamp < NET.back().dwTimeStamp) return;
if (!NET.empty() && N.dwTimeStamp == NET.back().dwTimeStamp)
{
NET.back() = N;
}
else
{
NET.push_back (N);
if (NET.size()>5) NET.pop_front();
}
//-----------------------------------------------
net_Import_Base_proceed ();
//-----------------------------------------------
};
void CActor::net_Import_Base_proceed ( )
{
if (g_Alive())
{
setVisible ((BOOL)!HUDview ());
setEnabled (TRUE);
};
//---------------------------------------------
if (Remote()) return;
net_update N = NET.back();
};
void CActor::net_Import_Physic ( NET_Packet& P)
{
m_States.clear();
if (m_u16NumBones != 1)
{
Fvector min, max;
P.r_u8();
P.r_vec3(min);
P.r_vec3(max);
for (u16 i=0; i<m_u16NumBones; i++)
{
SPHNetState state, stateL;
PHGetSyncItem(i)->get_State(state);
// stateL.net_Load(P, min, max);
r_vec_q8(P, stateL.position, min, max);
r_qt_q8(P, stateL.quaternion);
//---------------------------------------
r_vec_q8(P, stateL.linear_vel, min, max);
stateL.linear_vel.sub(stateL.position);
stateL.linear_vel.mul(10.0f);
//---------------------------------------
state.position = stateL.position;
state.previous_position = stateL.position;
state.quaternion = stateL.quaternion;
state.previous_quaternion = stateL.quaternion;
state.linear_vel = stateL.linear_vel;
//---------------------------------------
m_States.push_back(state);
};
}
else
{
net_update_A N_A;
P.r_u8 ( *((u8*)&(N_A.State.enabled)) );
P.r_vec3 ( N_A.State.angular_vel);
P.r_vec3 ( N_A.State.linear_vel);
P.r_vec3 ( N_A.State.force);
P.r_vec3 ( N_A.State.torque);
P.r_vec3 ( N_A.State.position);
P.r_float ( N_A.State.quaternion.x );
P.r_float ( N_A.State.quaternion.y );
P.r_float ( N_A.State.quaternion.z );
P.r_float ( N_A.State.quaternion.w );
if (!NET.empty())
N_A.dwTimeStamp = NET.back().dwTimeStamp;
else
N_A.dwTimeStamp = Level().timeServer();
N_A.State.previous_position = N_A.State.position;
N_A.State.previous_quaternion = N_A.State.quaternion;
//----------- for E3 -----------------------------
if (Local() && OnClient() || !g_Alive()) return;
// if (g_Alive() && (Remote() || OnServer()))
{
//-----------------------------------------------
if (!NET_A.empty() && N_A.dwTimeStamp < NET_A.back().dwTimeStamp) return;
if (!NET_A.empty() && N_A.dwTimeStamp == NET_A.back().dwTimeStamp)
{
NET_A.back() = N_A;
}
else
{
NET_A.push_back (N_A);
if (NET_A.size()>5) NET_A.pop_front();
};
if (!NET_A.empty()) m_bInterpolate = true;
};
}
//-----------------------------------------------
net_Import_Physic_proceed();
//-----------------------------------------------
};
void CActor::net_Import_Physic_proceed ( )
{
Level().AddObject_To_Objects4CrPr(this);
CrPr_SetActivated(false);
CrPr_SetActivationStep(0);
};
BOOL CActor::net_Spawn (CSE_Abstract* DC)
{
g_pGamePersistent->LoadTitle ("st_actor_netspawn"); // alpet: для отображения дополнительной длительной фазы загрузки, после короткого этапа "Синхронизации"
pApp->LoadBegin();
m_holder_id = ALife::_OBJECT_ID(-1);
m_feel_touch_characters = 0;
m_snd_noise = 0.0f;
m_sndShockEffector = NULL;
/* m_followers = NULL;*/
if (m_pPhysicsShell)
{
m_pPhysicsShell->Deactivate();
xr_delete(m_pPhysicsShell);
};
//force actor to be local on server client
CSE_Abstract *e = (CSE_Abstract*)(DC);
CSE_ALifeCreatureActor *E = smart_cast<CSE_ALifeCreatureActor*>(e);
if (OnServer())
{
E->s_flags.set(M_SPAWN_OBJECT_LOCAL, TRUE);
}
if( TRUE == E->s_flags.test(M_SPAWN_OBJECT_LOCAL) && TRUE == E->s_flags.is(M_SPAWN_OBJECT_ASPLAYER))
g_actor = this;
VERIFY(m_pActorEffector == NULL);
m_pActorEffector = xr_new<CCameraManager>(false);
// motions
m_bAnimTorsoPlayed = false;
m_current_legs_blend = 0;
m_current_jump_blend = 0;
m_current_legs.invalidate ();
m_current_torso.invalidate ();
m_current_head.invalidate ();
//-------------------------------------
// инициализация реестров, используемых актером
encyclopedia_registry->registry().init(ID());
game_news_registry->registry().init(ID());
if (!CInventoryOwner::net_Spawn(DC)) return FALSE;
if (!inherited::net_Spawn(DC)) return FALSE;
CSE_ALifeTraderAbstract *pTA = smart_cast<CSE_ALifeTraderAbstract*>(e);
set_money (pTA->m_dwMoney, false);
//убрать все артефакты с пояса
m_ArtefactsOnBelt.clear();
//. if( TRUE == E->s_flags.test(M_SPAWN_OBJECT_LOCAL) && TRUE == E->s_flags.is(M_SPAWN_OBJECT_ASPLAYER))
//. HUD().GetUI()->UIMainIngameWnd->m_artefactPanel->InitIcons(m_ArtefactsOnBelt);
ROS()->force_mode (IRender_ObjectSpecific::TRACE_ALL);
m_pPhysics_support->in_NetSpawn (e);
character_physics_support()->movement()->ActivateBox (0);
if(E->m_holderID!=u16(-1))
{
character_physics_support()->movement()->DestroyCharacter();
}
if(m_bOutBorder)character_physics_support()->movement()->setOutBorder();
r_torso_tgt_roll = 0;
r_model_yaw = E->o_torso.yaw;
r_torso.yaw = E->o_torso.yaw;
r_torso.pitch = E->o_torso.pitch;
r_torso.roll = 0.0f;//E->o_Angle.z;
unaffected_r_torso.yaw = r_torso.yaw;
unaffected_r_torso.pitch= r_torso.pitch;
unaffected_r_torso.roll = r_torso.roll;
if( psActorFlags.test(AF_PSP) )
cam_Set (eacLookAt);
else
cam_Set (eacFirstEye);
cam_Active()->Set (-E->o_torso.yaw,E->o_torso.pitch,0);//E->o_Angle.z);
// *** movement state - respawn
mstate_wishful = 0;
mstate_real = 0;
mstate_old = 0;
m_bJumpKeyPressed = FALSE;
NET_SavedAccel.set (0,0,0);
NET_WasInterpolating = TRUE;
setEnabled (E->s_flags.is(M_SPAWN_OBJECT_LOCAL));
Engine.Sheduler.Register (this,TRUE);
if (!IsGameTypeSingle())
{
setEnabled(TRUE);
}
hit_slowmo = 0.f;
OnChangeVisual();
//----------------------------------
m_bAllowDeathRemove = false;
// m_bHasUpdate = false;
m_bInInterpolation = false;
m_bInterpolate = false;
// if (GameID() != GAME_SINGLE)
{
processing_activate();
}
#ifdef DEBUG
LastPosS.clear();
LastPosH.clear();
LastPosL.clear();
#endif
//*
// if (OnServer())// && E->s_flags.is(M_SPAWN_OBJECT_LOCAL))
/*
if (OnClient())
{
if (!pStatGraph)
{
static g_Y = 0;
pStatGraph = xr_new<CStatGraph>();
pStatGraph->SetRect(0, g_Y, Device.dwWidth, 100, 0xff000000, 0xff000000);
g_Y += 110;
if (g_Y > 700) g_Y = 100;
pStatGraph->SetGrid(0, 0.0f, 10, 1.0f, 0xff808080, 0xffffffff);
pStatGraph->SetMinMax(0, 10, 300);
pStatGraph->SetStyle(CStatGraph::stBar);
pStatGraph->AppendSubGraph(CStatGraph::stCurve);
pStatGraph->AppendSubGraph(CStatGraph::stCurve);
}
}
*/
SetDefaultVisualOutfit(cNameVisual());
smart_cast<CKinematics*>(Visual())->CalculateBones();
//--------------------------------------------------------------
inventory().SetPrevActiveSlot(NO_ACTIVE_SLOT);
//-------------------------------------
m_States.empty();
//-------------------------------------
if (!g_Alive())
{
mstate_wishful &= ~mcAnyMove;
mstate_real &= ~mcAnyMove;
CKinematicsAnimated* K= smart_cast<CKinematicsAnimated*>(Visual());
K->PlayCycle("death_init");
//остановить звук тяжелого дыхания
m_HeavyBreathSnd.stop();
}
typedef CClientSpawnManager::CALLBACK_TYPE CALLBACK_TYPE;
CALLBACK_TYPE callback;
callback.bind (this,&CActor::on_requested_spawn);
m_holder_id = E->m_holderID;
if (E->m_holderID != ALife::_OBJECT_ID(-1))
if(!g_dedicated_server)
Level().client_spawn_manager().add(E->m_holderID,ID(),callback);
//F
//-------------------------------------------------------------
m_iLastHitterID = u16(-1);
m_iLastHittingWeaponID = u16(-1);
m_s16LastHittedElement = -1;
m_bWasHitted = false;
m_dwILastUpdateTime = 0;
if (IsGameTypeSingle()){
Level().MapManager().AddMapLocation("actor_location",ID());
Level().MapManager().AddMapLocation("actor_location_p",ID());
m_game_task_manager = xr_new<CGameTaskManager>();
GameTaskManager().initialize(ID());
m_statistic_manager = xr_new<CActorStatisticMgr>();
}
spatial.type |=STYPE_REACTTOSOUND;
psHUD_Flags.set(HUD_WEAPON_RT,TRUE);
if (Level().IsDemoPlay() && OnClient())
{
setLocal(FALSE);
};
pApp->LoadEnd();
return TRUE;
}
void CActor::net_Destroy ()
{
inherited::net_Destroy ();
if (m_holder_id != ALife::_OBJECT_ID(-1))
if(!g_dedicated_server)
Level().client_spawn_manager().remove (m_holder_id,ID());
delete_data (m_game_task_manager);
delete_data (m_statistic_manager);
if(!g_dedicated_server)
Level().MapManager ().RemoveMapLocationByObjectID(ID());
#pragma todo("Dima to MadMax : do not comment inventory owner net_Destroy!!!")
CInventoryOwner::net_Destroy();
cam_UnsetLadder();
character_physics_support()->movement()->DestroyCharacter();
if(m_pPhysicsShell) {
m_pPhysicsShell->Deactivate();
xr_delete<CPhysicsShell>(m_pPhysicsShell);
};
m_pPhysics_support->in_NetDestroy ();
xr_delete (m_sndShockEffector);
xr_delete (pStatGraph);
xr_delete (m_pActorEffector);
pCamBobbing = NULL;
#ifdef DEBUG
LastPosS.clear();
LastPosH.clear();
LastPosL.clear();
#endif
processing_deactivate();
m_holder=NULL;
m_holderID=u16(-1);
m_ArtefactsOnBelt.clear();
if (Level().CurrentViewEntity() == this)
HUD().GetUI()->UIMainIngameWnd->m_artefactPanel->InitIcons(m_ArtefactsOnBelt);
SetDefaultVisualOutfit(NULL);
if(g_actor == this) g_actor= NULL;
Engine.Sheduler.Unregister (this);
}
void CActor::net_Relcase (CObject* O)
{
VERIFY(O);
CGameObject* GO = smart_cast<CGameObject*>(O);
if(GO&&m_pObjectWeLookingAt==GO){
m_pObjectWeLookingAt=NULL;
}
CHolderCustom* HC=smart_cast<CHolderCustom*>(GO);
if(HC&&HC==m_pVehicleWeLookingAt){
m_pVehicleWeLookingAt=NULL;
}
if(HC&&HC==m_holder)
{
m_holder->detach_Actor();
m_holder=NULL;
}
inherited::net_Relcase (O);
if (!g_dedicated_server)
memory().remove_links(O);
m_pPhysics_support->in_NetRelcase(O);
}
BOOL CActor::net_Relevant () // relevant for export to server
{
if (OnServer())
{
return getSVU() | getLocal();
}
else
{
return Local() & g_Alive();
};
};
void CActor::SetCallbacks()
{
CKinematics* V = smart_cast<CKinematics*>(Visual());
VERIFY (V);
u16 spine0_bone = V->LL_BoneID("bip01_spine");
u16 spine1_bone = V->LL_BoneID("bip01_spine1");
u16 shoulder_bone = V->LL_BoneID("bip01_spine2");
u16 head_bone = V->LL_BoneID("bip01_head");
V->LL_GetBoneInstance(u16(spine0_bone)).set_callback (bctCustom,Spin0Callback,this);
V->LL_GetBoneInstance(u16(spine1_bone)).set_callback (bctCustom,Spin1Callback,this);
V->LL_GetBoneInstance(u16(shoulder_bone)).set_callback (bctCustom,ShoulderCallback,this);
V->LL_GetBoneInstance(u16(head_bone)).set_callback (bctCustom,HeadCallback,this);
}
void CActor::ResetCallbacks()
{
CKinematics* V = smart_cast<CKinematics*>(Visual());
VERIFY (V);
u16 spine0_bone = V->LL_BoneID("bip01_spine");
u16 spine1_bone = V->LL_BoneID("bip01_spine1");
u16 shoulder_bone = V->LL_BoneID("bip01_spine2");
u16 head_bone = V->LL_BoneID("bip01_head");
V->LL_GetBoneInstance(u16(spine0_bone)).reset_callback ();
V->LL_GetBoneInstance(u16(spine1_bone)).reset_callback ();
V->LL_GetBoneInstance(u16(shoulder_bone)).reset_callback();
V->LL_GetBoneInstance(u16(head_bone)).reset_callback ();
}
void CActor::OnChangeVisual()
{
/// inherited::OnChangeVisual();
{
CPhysicsShell* tmp_shell=PPhysicsShell();
PPhysicsShell()=NULL;
inherited::OnChangeVisual();
PPhysicsShell()=tmp_shell;
tmp_shell=NULL;
}
CKinematicsAnimated* V = smart_cast<CKinematicsAnimated*>(Visual());
if (V){
SetCallbacks ();
m_anims->Create (V);
m_vehicle_anims->Create (V);
CDamageManager::reload(*cNameSect(),"damage",pSettings);
//-------------------------------------------------------------------------------
m_head = smart_cast<CKinematics*>(Visual())->LL_BoneID("bip01_head");
m_r_hand = smart_cast<CKinematics*>(Visual())->LL_BoneID(pSettings->r_string(*cNameSect(),"weapon_bone0"));
m_l_finger1 = smart_cast<CKinematics*>(Visual())->LL_BoneID(pSettings->r_string(*cNameSect(),"weapon_bone1"));
m_r_finger2 = smart_cast<CKinematics*>(Visual())->LL_BoneID(pSettings->r_string(*cNameSect(),"weapon_bone2"));
//-------------------------------------------------------------------------------
m_neck = smart_cast<CKinematics*>(Visual())->LL_BoneID("bip01_neck");
m_l_clavicle = smart_cast<CKinematics*>(Visual())->LL_BoneID("bip01_l_clavicle");
m_r_clavicle = smart_cast<CKinematics*>(Visual())->LL_BoneID("bip01_r_clavicle");
m_spine2 = smart_cast<CKinematics*>(Visual())->LL_BoneID("bip01_spine2");
m_spine1 = smart_cast<CKinematics*>(Visual())->LL_BoneID("bip01_spine1");
m_spine = smart_cast<CKinematics*>(Visual())->LL_BoneID("bip01_spine");
//-------------------------------------------------------------------------------
reattach_items();
//-------------------------------------------------------------------------------
m_pPhysics_support->in_ChangeVisual();
//-------------------------------------------------------------------------------
SetCallbacks ();
//-------------------------------------------------------------------------------
m_current_head.invalidate ();
m_current_legs.invalidate ();
m_current_torso.invalidate ();
m_current_legs_blend = NULL;
m_current_torso_blend = NULL;
m_current_jump_blend = NULL;
}
};
void CActor::ChangeVisual ( shared_str NewVisual )
{
if (!NewVisual.size()) return;
if (cNameVisual().size() )
{
if (cNameVisual() == NewVisual) return;
}
cNameVisual_set(NewVisual);
g_SetAnimation (mstate_real);
Visual()->dcast_PKinematics()->CalculateBones_Invalidate();
Visual()->dcast_PKinematics()->CalculateBones();
};
void ACTOR_DEFS::net_update::lerp(ACTOR_DEFS::net_update& A, ACTOR_DEFS::net_update& B, float f)
{
// float invf = 1.f-f;
// //
// o_model = angle_lerp (A.o_model,B.o_model, f);
// o_torso.yaw = angle_lerp (A.o_torso.yaw,B.o_torso.yaw,f);
// o_torso.pitch = angle_lerp (A.o_torso.pitch,B.o_torso.pitch,f);
// o_torso.roll = angle_lerp (A.o_torso.roll,B.o_torso.roll,f);
// p_pos.lerp (A.p_pos,B.p_pos,f);
// p_accel = (f<0.5f)?A.p_accel:B.p_accel;
// p_velocity.lerp (A.p_velocity,B.p_velocity,f);
// mstate = (f<0.5f)?A.mstate:B.mstate;
// weapon = (f<0.5f)?A.weapon:B.weapon;
// fHealth = invf*A.fHealth+f*B.fHealth;
// fArmor = invf*A.fArmor+f*B.fArmor;
// weapon = (f<0.5f)?A.weapon:B.weapon;
}
InterpData IStartT;
InterpData IRecT;
InterpData IEndT;
void CActor::PH_B_CrPr () // actions & operations before physic correction-prediction steps
{
//just set last update data for now
// if (!m_bHasUpdate) return;
if (CrPr_IsActivated()) return;
if (CrPr_GetActivationStep() > ph_world->m_steps_num) return;
if (g_Alive())
{
CrPr_SetActivated(true);
{
///////////////////////////////////////////////
InterpData* pIStart = &IStart;
pIStart->Pos = Position();
pIStart->Vel = character_physics_support()->movement()->GetVelocity();
pIStart->o_model = angle_normalize(r_model_yaw);
pIStart->o_torso.yaw = angle_normalize(unaffected_r_torso.yaw);
pIStart->o_torso.pitch = angle_normalize(unaffected_r_torso.pitch);
pIStart->o_torso.roll = angle_normalize(unaffected_r_torso.roll);
if (pIStart->o_torso.roll > PI)
pIStart->o_torso.roll -= PI_MUL_2;
}
///////////////////////////////////////////////
CPHSynchronize* pSyncObj = NULL;
pSyncObj = PHGetSyncItem(0);
if (!pSyncObj) return;
pSyncObj->get_State(LastState);
///////////////////////////////////////////////
//----------- for E3 -----------------------------
if (Local() && OnClient())
//------------------------------------------------
{
PHUnFreeze();
pSyncObj->set_State(NET_A.back().State);
}
else
{
net_update_A N_A = NET_A.back();
net_update N = NET.back();
NET_Last = N;
///////////////////////////////////////////////
cam_Active()->Set (-unaffected_r_torso.yaw,unaffected_r_torso.pitch, 0);//, unaffected_r_torso.roll); // set's camera orientation
if (!N_A.State.enabled)
{
pSyncObj->set_State(N_A.State);
}
else
{
PHUnFreeze();
pSyncObj->set_State(N_A.State);
g_Physics(N.p_accel, 0.0f, 0.0f);
Position().set(IStart.Pos);
};
};
}
else
{
if (PHGetSyncItemsNumber() != m_u16NumBones || m_States.empty()) return;
CrPr_SetActivated(true);
PHUnFreeze();
for (u16 i=0; i<m_u16NumBones; i++)
{
SPHNetState state, stateL;
PHGetSyncItem(i)->get_State(state);
stateL = m_States[i];
//---------------------------------------
state.position = stateL.position;
state.previous_position = stateL.previous_position;
state.quaternion = stateL.quaternion;
state.previous_quaternion = stateL.previous_quaternion;
state.linear_vel = stateL.linear_vel;
state.enabled = true;
//---------------------------------------
PHGetSyncItem(i)->set_State(state);
};
};
};
void CActor::PH_I_CrPr () // actions & operations between two phisic prediction steps
{
//store recalculated data, then we able to restore it after small future prediction
// if (!m_bHasUpdate) return;
if (!CrPr_IsActivated()) return;
if (g_Alive())
{
////////////////////////////////////
CPHSynchronize* pSyncObj = NULL;
pSyncObj = PHGetSyncItem(0);
if (!pSyncObj) return;
////////////////////////////////////
pSyncObj->get_State(RecalculatedState);
////////////////////////////////////
};
};
void CActor::PH_A_CrPr ()
{
//restore recalculated data and get data for interpolation
// if (!m_bHasUpdate) return;
// m_bHasUpdate = false;
if (!CrPr_IsActivated()) return;
if (!g_Alive()) return;
////////////////////////////////////
CPHSynchronize* pSyncObj = NULL;
pSyncObj = PHGetSyncItem(0);
if (!pSyncObj) return;
////////////////////////////////////
pSyncObj->get_State(PredictedState);
////////////////////////////////////
pSyncObj->set_State(RecalculatedState);
////////////////////////////////////
if (!m_bInterpolate) return;
////////////////////////////////////
mstate_wishful = mstate_real = NET_Last.mstate;
CalculateInterpolationParams();
};
extern float g_cl_lvInterp;
void CActor::CalculateInterpolationParams()
{
// Fmatrix xformX0, xformX1;
CPHSynchronize* pSyncObj = NULL;
pSyncObj = PHGetSyncItem(0);
///////////////////////////////////////////////
InterpData* pIStart = &IStart;
InterpData* pIRec = &IRec;
InterpData* pIEnd = &IEnd;
///////////////////////////////////////////////
/*
pIStart->Pos = Position();
pIStart->Vel = m_PhysicMovementControl->GetVelocity();
pIStart->o_model = r_model_yaw;
pIStart->o_torso.yaw = unaffected_r_torso.yaw;
pIStart->o_torso.pitch = unaffected_r_torso.pitch;
pIStart->o_torso.roll = unaffected_r_torso.roll;
*/
/////////////////////////////////////////////////////////////////////
pIRec->Pos = RecalculatedState.position;
pIRec->Vel = RecalculatedState.linear_vel;
pIRec->o_model = NET_Last.o_model;
pIRec->o_torso = NET_Last.o_torso;
/////////////////////////////////////////////////////////////////////
pIEnd->Pos = PredictedState.position;
pIEnd->Vel = PredictedState.linear_vel;
pIEnd->o_model = pIRec->o_model ;
pIEnd->o_torso.yaw = pIRec->o_torso.yaw ;
pIEnd->o_torso.pitch = pIRec->o_torso.pitch ;
pIEnd->o_torso.roll = pIRec->o_torso.roll ;
/////////////////////////////////////////////////////////////////////
// Msg("from %f, to %f", IStart.o_torso.yaw/PI*180.0f, IEnd.o_torso.yaw/PI*180.0f);
/////////////////////////////////////////////////////////////////////
Fvector SP0, SP1, SP2, SP3;
Fvector HP0, HP1, HP2, HP3;
SP0 = pIStart->Pos;
HP0 = pIStart->Pos;
if (m_bInInterpolation)
{
u32 CurTime = Level().timeServer();
float factor = float(CurTime - m_dwIStartTime)/(m_dwIEndTime - m_dwIStartTime);
if (factor > 1.0f) factor = 1.0f;
float c = factor;
for (u32 k=0; k<3; k++)
{
SP0[k] = c*(c*(c*SCoeff[k][0]+SCoeff[k][1])+SCoeff[k][2])+SCoeff[k][3];
SP1[k] = (c*c*SCoeff[k][0]*3+c*SCoeff[k][1]*2+SCoeff[k][2])/3; // сокрость из формулы в 3 раза превышает скорость при расчете коэффициентов !!!!
HP0[k] = c*(c*(c*HCoeff[k][0]+HCoeff[k][1])+HCoeff[k][2])+HCoeff[k][3];
HP1[k] = (c*c*HCoeff[k][0]*3+c*HCoeff[k][1]*2+HCoeff[k][2]); // сокрость из формулы в 3 раза превышает скорость при расчете коэффициентов !!!!
};
SP1.add(SP0);
}
else
{
if (LastState.linear_vel.x == 0 && LastState.linear_vel.y == 0 && LastState.linear_vel.z == 0)
{
HP1.sub(RecalculatedState.position, RecalculatedState.previous_position);
}
else
{
HP1.sub(LastState.position, LastState.previous_position);
};
HP1.mul(1.0f/fixed_step);
SP1.add(HP1, SP0);
}
HP2.sub(PredictedState.position, PredictedState.previous_position);
HP2.mul(1.0f/fixed_step);
SP2.sub(PredictedState.position, HP2);
SP3.set(PredictedState.position);
HP3.set(PredictedState.position);
/*
{
Fvector d0, d1;
d0.sub(SP1, SP0);
d1.sub(SP3, SP0);
float res = d0.dotproduct(d1);
if (res < 0)
{
Msg ("! %f", res);
}
else
Msg ("%f", res);
}
*/
/////////////////////////////////////////////////////////////////////////////
Fvector TotalPath;
TotalPath.sub(SP3, SP0);
float TotalLen = TotalPath.magnitude();
SPHNetState State0 = (NET_A.back()).State;
SPHNetState State1 = PredictedState;
float lV0 = State0.linear_vel.magnitude();
float lV1 = State1.linear_vel.magnitude();
u32 ConstTime = u32((fixed_step - ph_world->m_frame_time)*1000)+ Level().GetInterpolationSteps()*u32(fixed_step*1000);
m_dwIStartTime = m_dwILastUpdateTime;
// if (( lV0 + lV1) > 0.000001 && g_cl_lvInterp == 0)
{
// u32 CulcTime = iCeil(TotalLen*2000/( lV0 + lV1));
// m_dwIEndTime = m_dwIStartTime + min(CulcTime, ConstTime);
}
// else
m_dwIEndTime = m_dwIStartTime + ConstTime;
/////////////////////////////////////////////////////////////////////////////
Fvector V0, V1;
// V0.sub(SP1, SP0);
// V1.sub(SP3, SP2);
V0.set(HP1);
V1.set(HP2);
lV0 = V0.magnitude();
lV1 = V1.magnitude();
if (TotalLen != 0)
{
if (V0.x != 0 || V0.y != 0 || V0.z != 0)
{
if (lV0 > TotalLen/3)
{
HP1.normalize();
// V0.normalize();
// V0.mul(TotalLen/3);
HP1.normalize();
HP1.mul(TotalLen/3);
SP1.add(HP1, SP0);
}
}
if (V1.x != 0 || V1.y != 0 || V1.z != 0)
{
if (lV1 > TotalLen/3)
{
// V1.normalize();
// V1.mul(TotalLen/3);
HP2.normalize();
HP2.mul(TotalLen/3);
SP2.sub(SP3, HP2);
};
}
};
/////////////////////////////////////////////////////////////////////////////
for( u32 i =0; i<3; i++)
{
SCoeff[i][0] = SP3[i] - 3*SP2[i] + 3*SP1[i] - SP0[i];
SCoeff[i][1] = 3*SP2[i] - 6*SP1[i] + 3*SP0[i];
SCoeff[i][2] = 3*SP1[i] - 3*SP0[i];
SCoeff[i][3] = SP0[i];
HCoeff[i][0] = 2*HP0[i] - 2*HP3[i] + HP1[i] + HP2[i];
HCoeff[i][1] = -3*HP0[i] + 3*HP3[i] - 2*HP1[i] - HP2[i];
HCoeff[i][2] = HP1[i];
HCoeff[i][3] = HP0[i];
};
/////////////////////////////////////////////////////////////////////////////
m_bInInterpolation = true;
if (m_pPhysicsShell) m_pPhysicsShell->NetInterpolationModeON();
}
int actInterpType = 0;
void CActor::make_Interpolation ()
{
m_dwILastUpdateTime = Level().timeServer();
if(g_Alive() && m_bInInterpolation)
{
u32 CurTime = m_dwILastUpdateTime;
if (CurTime >= m_dwIEndTime)
{
m_bInInterpolation = false;
mstate_real = mstate_wishful = NET_Last.mstate;
NET_SavedAccel = NET_Last.p_accel;
CPHSynchronize* pSyncObj = NULL;
pSyncObj = PHGetSyncItem(0);
if (!pSyncObj) return;
pSyncObj->set_State(PredictedState);//, PredictedState.enabled);
VERIFY2 (_valid(renderable.xform),*cName());
}
else
{
float factor = 0.0f;
if (m_dwIEndTime != m_dwIStartTime)
factor = float(CurTime - m_dwIStartTime)/(m_dwIEndTime - m_dwIStartTime);
Fvector NewPos;
NewPos.lerp(IStart.Pos, IEnd.Pos, factor);
VERIFY2 (_valid(renderable.xform),*cName());
// r_model_yaw = angle_lerp (IStart.o_model,IEnd.o_model, factor);
unaffected_r_torso.yaw = angle_lerp (IStart.o_torso.yaw,IEnd.o_torso.yaw,factor);
unaffected_r_torso.pitch = angle_lerp (IStart.o_torso.pitch,IEnd.o_torso.pitch,factor);
unaffected_r_torso.roll = angle_lerp (IStart.o_torso.roll,IEnd.o_torso.roll,factor);
for (u32 k=0; k<3; k++)
{
IPosL[k] = NewPos[k];
IPosS[k] = factor*(factor*(factor*SCoeff[k][0]+SCoeff[k][1])+SCoeff[k][2])+SCoeff[k][3];
IPosH[k] = factor*(factor*(factor*HCoeff[k][0]+HCoeff[k][1])+HCoeff[k][2])+HCoeff[k][3];
};
Fvector SpeedVector, ResPosition;
switch (g_cl_InterpolationType)
{
case 0:
{
ResPosition.set(IPosL);
SpeedVector.sub(IEnd.Pos, IStart.Pos);
SpeedVector.div(float(m_dwIEndTime - m_dwIStartTime)/1000.0f);
}break;
case 1:
{
for (int k=0; k<3; k++)
SpeedVector[k] = (factor*factor*SCoeff[k][0]*3+factor*SCoeff[k][1]*2+SCoeff[k][2])/3; // сокрость из формулы в 3 раза превышает скорость при расчете коэффициентов !!!!
ResPosition.set(IPosS);
}break;
case 2:
{
for (int k=0; k<3; k++)
SpeedVector[k] = (factor*factor*HCoeff[k][0]*3+factor*HCoeff[k][1]*2+HCoeff[k][2]);
ResPosition.set(IPosH);
}break;
default:
{
R_ASSERT2(0, "Unknown interpolation curve type!");
}
}
character_physics_support()->movement()->SetPosition (ResPosition);
character_physics_support()->movement()->SetVelocity (SpeedVector);
cam_Active()->Set (-unaffected_r_torso.yaw,unaffected_r_torso.pitch, 0);//, unaffected_r_torso.roll);
};
}
else
{
m_bInInterpolation = false;
};
#ifdef DEBUG
if (getVisible() && g_Alive() && mstate_real)
{
LastPosS.push_back(IPosS); while (LastPosS.size()>g_cl_InterpolationMaxPoints) LastPosS.pop_front();
LastPosH.push_back(IPosH); while (LastPosH.size()>g_cl_InterpolationMaxPoints) LastPosH.pop_front();
LastPosL.push_back(IPosL); while (LastPosL.size()>g_cl_InterpolationMaxPoints) LastPosL.pop_front();
};
#endif
};
/*
void CActor::UpdatePosStack ( u32 Time0, u32 Time1 )
{
//******** Storing Last Position in stack ********
CPHSynchronize* pSyncObj = NULL;
pSyncObj = PHGetSyncItem(0);
if (!pSyncObj) return;
SPHNetState State;
pSyncObj->get_State(State);
if (!SMemoryPosStack.empty() && SMemoryPosStack.back().u64WorldStep >= ph_world->m_steps_num)
{
xr_deque<SMemoryPos>::iterator B = SMemoryPosStack.begin();
xr_deque<SMemoryPos>::iterator E = SMemoryPosStack.end();
xr_deque<SMemoryPos>::iterator I = std::lower_bound(B,E,u64(ph_world->m_steps_num-1));
if (I != E)
{
I->SState = State;
I->u64WorldStep = ph_world->m_steps_num;
};
}
else
{
SMemoryPosStack.push_back(SMemoryPos(Time0, Time1, ph_world->m_steps_num, State));
if (SMemoryPosStack.front().dwTime0 < (Level().timeServer() - 2000)) SMemoryPosStack.pop_front();
};
};
ACTOR_DEFS::SMemoryPos* CActor::FindMemoryPos (u32 Time)
{
if (SMemoryPosStack.empty()) return NULL;
if (Time > SMemoryPosStack.back().dwTime1) return NULL;
xr_deque<SMemoryPos>::iterator B = SMemoryPosStack.begin();
xr_deque<SMemoryPos>::iterator E = SMemoryPosStack.end();
xr_deque<SMemoryPos>::iterator I = std::lower_bound(B,E,Time);
if (I==E) return NULL;
return &(*I);
};
*/
void CActor::save(NET_Packet &output_packet)
{
inherited::save(output_packet);
CInventoryOwner::save(output_packet);
output_packet.w_u8(u8(m_bOutBorder));
}
void CActor::load(IReader &input_packet)
{
inherited::load(input_packet);
CInventoryOwner::load(input_packet);
m_bOutBorder=!!(input_packet.r_u8());
}
#ifdef DEBUG
extern Flags32 dbg_net_Draw_Flags;
void dbg_draw_piramid (Fvector pos, Fvector dir, float size, float xdir, u32 color)
{
Fvector p0, p1, p2, p3, p4;
p0.set(size, size, 0.0f);
p1.set(-size, size, 0.0f);
p2.set(-size, -size, 0.0f);
p3.set(size, -size, 0.0f);
p4.set(0, 0, size*4);
bool Double = false;
Fmatrix t; t.identity();
if (_valid(dir) && dir.square_magnitude()>0.01f)
{
t.k.normalize (dir);
Fvector::generate_orthonormal_basis(t.k, t.j, t.i);
}
else
{
t.rotateY(xdir);
Double = true;
}
t.c.set(pos);
// Level().debug_renderer().draw_line(t, p0, p1, color);
// Level().debug_renderer().draw_line(t, p1, p2, color);
// Level().debug_renderer().draw_line(t, p2, p3, color);
// Level().debug_renderer().draw_line(t, p3, p0, color);
// Level().debug_renderer().draw_line(t, p0, p4, color);
// Level().debug_renderer().draw_line(t, p1, p4, color);
// Level().debug_renderer().draw_line(t, p2, p4, color);
// Level().debug_renderer().draw_line(t, p3, p4, color);
if (!Double)
{
RCache.dbg_DrawTRI(t, p0, p1, p4, color);
RCache.dbg_DrawTRI(t, p1, p2, p4, color);
RCache.dbg_DrawTRI(t, p2, p3, p4, color);
RCache.dbg_DrawTRI(t, p3, p0, p4, color);
}
else
{
// Fmatrix scale;
// scale.scale(0.8f, 0.8f, 0.8f);
// t.mulA_44(scale);
// t.c.set(pos);
Level().debug_renderer().draw_line(t, p0, p1, color);
Level().debug_renderer().draw_line(t, p1, p2, color);
Level().debug_renderer().draw_line(t, p2, p3, color);
Level().debug_renderer().draw_line(t, p3, p0, color);
Level().debug_renderer().draw_line(t, p0, p4, color);
Level().debug_renderer().draw_line(t, p1, p4, color);
Level().debug_renderer().draw_line(t, p2, p4, color);
Level().debug_renderer().draw_line(t, p3, p4, color);
};
};
void CActor::OnRender_Network()
{
RCache.OnFrameEnd();
//-----------------------------------------------------------------------------------------------------
float size = 0.2f;
// dbg_draw_piramid(Position(), m_PhysicMovementControl->GetVelocity(), size/2, -r_model_yaw, color_rgba(255, 255, 255, 255));
//-----------------------------------------------------------------------------------------------------
if (g_Alive())
{
if (dbg_net_Draw_Flags.test(1<<8))
{
Fvector bc; bc.add(Position(), m_AutoPickUp_AABB_Offset);
Fvector bd = m_AutoPickUp_AABB;
Level().debug_renderer().draw_aabb (bc, bd.x, bd.y, bd.z, color_rgba(0, 255, 0, 255));
};
CKinematics* V = smart_cast<CKinematics*>(Visual());
if (dbg_net_Draw_Flags.test(1<<0) && V)
{
if (this != Level().CurrentViewEntity() || cam_active != eacFirstEye)
{
/*
u16 BoneCount = V->LL_BoneCount();
for (u16 i=0; i<BoneCount; i++)
{
Fobb BoneOBB = V->LL_GetBox(i);
Fmatrix BoneMatrix; BoneOBB.xform_get(BoneMatrix);
Fmatrix BoneMatrixRes; BoneMatrixRes.mul(V->LL_GetTransform(i), BoneMatrix);
BoneMatrix.mul(XFORM(), BoneMatrixRes);
Level().debug_renderer().draw_obb(BoneMatrix, BoneOBB.m_halfsize, color_rgba(0, 255, 0, 255));
};
*/
CCF_Skeleton* Skeleton = smart_cast<CCF_Skeleton*>(collidable.model);
if (Skeleton){
Skeleton->_dbg_refresh();
const CCF_Skeleton::ElementVec& Elements = Skeleton->_GetElements();
for (CCF_Skeleton::ElementVec::const_iterator I=Elements.begin(); I!=Elements.end(); I++){
if (!I->valid()) continue;
switch (I->type){
case SBoneShape::stBox:{
Fmatrix M;
M.invert (I->b_IM);
Fvector h_size = I->b_hsize;
Level().debug_renderer().draw_obb (M, h_size, color_rgba(0, 255, 0, 255));
}break;
case SBoneShape::stCylinder:{
Fmatrix M;
M.c.set (I->c_cylinder.m_center);
M.k.set (I->c_cylinder.m_direction);
Fvector h_size;
h_size.set (I->c_cylinder.m_radius,I->c_cylinder.m_radius,I->c_cylinder.m_height*0.5f);
Fvector::generate_orthonormal_basis(M.k,M.j,M.i);
Level().debug_renderer().draw_obb (M, h_size, color_rgba(0, 127, 255, 255));
}break;
case SBoneShape::stSphere:{
Fmatrix l_ball;
l_ball.scale (I->s_sphere.R, I->s_sphere.R, I->s_sphere.R);
l_ball.translate_add(I->s_sphere.P);
Level().debug_renderer().draw_ellipse(l_ball, color_rgba(0, 255, 0, 255));
}break;
};
};
}
};
};
if (!(dbg_net_Draw_Flags.is_any((1<<1)))) return;
dbg_draw_piramid(Position(), character_physics_support()->movement()->GetVelocity(), size, -r_model_yaw, color_rgba(128, 255, 128, 255));
dbg_draw_piramid(IStart.Pos, IStart.Vel, size, -IStart.o_model, color_rgba(255, 0, 0, 255));
// Fvector tmp, tmp1; tmp1.set(0, .1f, 0);
// dbg_draw_piramid(tmp.add(IStartT.Pos, tmp1), IStartT.Vel, size, -IStartT.o_model, color_rgba(155, 0, 0, 155));
dbg_draw_piramid(IRec.Pos, IRec.Vel, size, -IRec.o_model, color_rgba(0, 0, 255, 255));
// dbg_draw_piramid(tmp.add(IRecT.Pos, tmp1), IRecT.Vel, size, -IRecT.o_model, color_rgba(0, 0, 155, 155));
dbg_draw_piramid(IEnd.Pos, IEnd.Vel, size, -IEnd.o_model, color_rgba(0, 255, 0, 255));
// dbg_draw_piramid(tmp.add(IEndT.Pos, tmp1), IEndT.Vel, size, -IEndT.o_model, color_rgba(0, 155, 0, 155));
dbg_draw_piramid(NET_Last.p_pos, NET_Last.p_velocity, size*3/4, -NET_Last.o_model, color_rgba(255, 255, 255, 255));
Fmatrix MS, MH, ML, *pM = NULL;
ML.translate(0, 0.2f, 0);
MS.translate(0, 0.2f, 0);
MH.translate(0, 0.2f, 0);
Fvector point0S, point1S, point0H, point1H, point0L, point1L, *ppoint0 = NULL, *ppoint1 = NULL;
Fvector tS, tH;
u32 cColor = 0, sColor = 0;
VIS_POSITION* pLastPos = NULL;
switch (g_cl_InterpolationType)
{
case 0: ppoint0 = &point0L; ppoint1 = &point1L; cColor = color_rgba(0, 255, 0, 255); sColor = color_rgba(128, 255, 128, 255); pM = &ML; pLastPos = &LastPosL; break;
case 1: ppoint0 = &point0S; ppoint1 = &point1S; cColor = color_rgba(0, 0, 255, 255); sColor = color_rgba(128, 128, 255, 255); pM = &MS; pLastPos = &LastPosS; break;
case 2: ppoint0 = &point0H; ppoint1 = &point1H; cColor = color_rgba(255, 0, 0, 255); sColor = color_rgba(255, 128, 128, 255); pM = &MH; pLastPos = &LastPosH; break;
}
//drawing path trajectory
float c = 0;
for (int i=0; i<11; i++)
{
c = float(i) * 0.1f;
for (u32 k=0; k<3; k++)
{
point1S[k] = c*(c*(c*SCoeff[k][0]+SCoeff[k][1])+SCoeff[k][2])+SCoeff[k][3];
point1H[k] = c*(c*(c*HCoeff[k][0]+HCoeff[k][1])+HCoeff[k][2])+HCoeff[k][3];
point1L[k] = IStart.Pos[k] + c*(IEnd.Pos[k]-IStart.Pos[k]);
};
if (i!=0)
{
Level().debug_renderer().draw_line(*pM, *ppoint0, *ppoint1, cColor);
};
point0S.set(point1S);
point0H.set(point1H);
point0L.set(point1L);
};
//drawing speed vectors
for (int i=0; i<2; i++)
{
c = float(i);
for (u32 k=0; k<3; k++)
{
point1S[k] = c*(c*(c*SCoeff[k][0]+SCoeff[k][1])+SCoeff[k][2])+SCoeff[k][3];
point1H[k] = c*(c*(c*HCoeff[k][0]+HCoeff[k][1])+HCoeff[k][2])+HCoeff[k][3];
tS[k] = (c*c*SCoeff[k][0]*3+c*SCoeff[k][1]*2+SCoeff[k][2])/3; // сокрость из формулы в 3 раза превышает скорость при расчете коэффициентов !!!!
tH[k] = (c*c*HCoeff[k][0]*3+c*HCoeff[k][1]*2+HCoeff[k][2]);
};
point0S.add(tS, point1S);
point0H.add(tH, point1H);
if (g_cl_InterpolationType > 0)
{
Level().debug_renderer().draw_line(*pM, *ppoint0, *ppoint1, sColor);
}
}
//draw interpolation history curve
if (!pLastPos->empty())
{
Fvector Pos1, Pos2;
VIS_POSITION_it It = pLastPos->begin();
Pos1 = *It;
for (; It != pLastPos->end(); It++)
{
Pos2 = *It;
Level().debug_renderer().draw_line (*pM, Pos1, Pos2, cColor);
Level().debug_renderer().draw_aabb (Pos2, size/5, size/5, size/5, sColor);
Pos1 = *It;
};
};
Fvector PH, PS;
PH.set(IPosH); PH.y += 1;
PS.set(IPosS); PS.y += 1;
// Level().debug_renderer().draw_aabb (PS, size, size, size, color_rgba(128, 128, 255, 255));
// Level().debug_renderer().draw_aabb (PH, size, size, size, color_rgba(255, 128, 128, 255));
/////////////////////////////////////////////////////////////////////////////////
}
else
{
if (!(dbg_net_Draw_Flags.is_any((1<<1)))) return;
CKinematics* V = smart_cast<CKinematics*>(Visual());
if (dbg_net_Draw_Flags.test(1<<0) && V)
{
u16 BoneCount = V->LL_BoneCount();
for (u16 i=0; i<BoneCount; i++)
{
Fobb BoneOBB = V->LL_GetBox(i);
Fmatrix BoneMatrix; BoneOBB.xform_get(BoneMatrix);
Fmatrix BoneMatrixRes; BoneMatrixRes.mul(V->LL_GetTransform(i), BoneMatrix);
BoneMatrix.mul(XFORM(), BoneMatrixRes);
Level().debug_renderer().draw_obb(BoneMatrix, BoneOBB.m_halfsize, color_rgba(0, 255, 0, 255));
};
};
if (!m_States.empty())
{
u32 NumBones = m_States.size();
for (u32 i=0; i<NumBones; i++)
{
SPHNetState state = m_States[i];
Fvector half_dim;
half_dim.x = 0.2f;
half_dim.y = 0.1f;
half_dim.z = 0.1f;
u32 Color = color_rgba(255, 0, 0, 255);
Fmatrix M;
M = Fidentity;
M.rotation(state.quaternion);
M.translate_add(state.position);
Level().debug_renderer().draw_obb (M, half_dim, Color);
if (!PHGetSyncItem(u16(i))) continue;
PHGetSyncItem(u16(i))->get_State(state);
Color = color_rgba(0, 255, 0, 255);
M = Fidentity;
M.rotation(state.quaternion);
M.translate_add(state.position);
Level().debug_renderer().draw_obb (M, half_dim, Color);
};
}
else
{
if (!g_Alive() && PHGetSyncItemsNumber() > 2)
{
u16 NumBones = PHGetSyncItemsNumber();
for (u16 i=0; i<NumBones; i++)
{
SPHNetState state;// = m_States[i];
PHGetSyncItem(i)->get_State(state);
Fmatrix M;
M = Fidentity;
M.rotation(state.quaternion);
M.translate_add(state.position);
Fvector half_dim;
half_dim.x = 0.2f;
half_dim.y = 0.1f;
half_dim.z = 0.1f;
u32 Color = color_rgba(0, 255, 0, 255);
Level().debug_renderer().draw_obb (M, half_dim, Color);
};
//-----------------------------------------------------------------
Fvector min,max;
min.set(F_MAX,F_MAX,F_MAX);
max.set(-F_MAX,-F_MAX,-F_MAX);
/////////////////////////////////////
for(u16 i=0;i<NumBones;i++)
{
SPHNetState state;
PHGetSyncItem(i)->get_State(state);
Fvector& p=state.position;
UpdateLimits (p, min, max);
Fvector px =state.linear_vel;
px.div(10.0f);
px.add(state.position);
UpdateLimits (px, min, max);
};
NET_Packet PX;
for(u16 i=0;i<NumBones;i++)
{
SPHNetState state;
PHGetSyncItem(i)->get_State(state);
PX.B.count = 0;
w_vec_q8(PX,state.position,min,max);
w_qt_q8(PX,state.quaternion);
// w_vec_q8(PX,state.linear_vel,min,max);
PX.r_pos = 0;
r_vec_q8(PX,state.position,min,max);
r_qt_q8(PX,state.quaternion);
// r_vec_q8(PX,state.linear_vel,min,max);
//===============================================
Fmatrix M;
M = Fidentity;
M.rotation(state.quaternion);
M.translate_add(state.position);
Fvector half_dim;
half_dim.x = 0.2f;
half_dim.y = 0.1f;
half_dim.z = 0.1f;
u32 Color = color_rgba(255, 0, 0, 255);
Level().debug_renderer().draw_obb (M, half_dim, Color);
};
Fvector LC, LS;
LC.add(min, max); LC.div(2.0f);
LS.sub(max, min); LS.div(2.0f);
Level().debug_renderer().draw_aabb (LC, LS.x, LS.y, LS.z, color_rgba(255, 128, 128, 255));
//-----------------------------------------------------------------
};
}
}
};
#endif
void CActor::net_Save(NET_Packet& P)
{
#ifdef DEBUG
u32 pos;
Msg ("Actor net_Save");
pos = P.w_tell();
inherited::net_Save (P);
Msg ("inherited::net_Save() : %d",P.w_tell() - pos);
pos = P.w_tell();
m_pPhysics_support->in_NetSave(P);
P.w_u16(m_holderID);
Msg ("m_pPhysics_support->in_NetSave() : %d",P.w_tell() - pos);
#else
inherited::net_Save (P);
m_pPhysics_support->in_NetSave(P);
P.w_u16(m_holderID);
#endif
}
BOOL CActor::net_SaveRelevant()
{
return TRUE;
}
void CActor::Check_for_AutoPickUp()
{
if (!psActorFlags.test(AF_AUTOPICKUP)) return;
if (GameID() == GAME_SINGLE) return;
if (Level().CurrentControlEntity() != this) return;
if (!g_Alive()) return;
Fvector bc; bc.add(Position(), m_AutoPickUp_AABB_Offset);
Fbox APU_Box;
APU_Box.set(Fvector().sub(bc, m_AutoPickUp_AABB), Fvector().add(bc, m_AutoPickUp_AABB));
xr_vector<ISpatial*> ISpatialResult;
g_SpatialSpace->q_box (ISpatialResult,0,STYPE_COLLIDEABLE,bc,m_AutoPickUp_AABB);
// Determine visibility for dynamic part of scene
for (u32 o_it=0; o_it<ISpatialResult.size(); o_it++)
{
ISpatial* spatial = ISpatialResult[o_it];
CInventoryItem* pIItem = smart_cast<CInventoryItem*> (spatial->dcast_CObject ());
if (0 == pIItem) continue;
if (!pIItem->CanTake()) continue;
if (Level().m_feel_deny.is_object_denied(pIItem->cast_game_object()) ) continue;
CGrenade* pGrenade = smart_cast<CGrenade*> (pIItem);
if (pGrenade) continue;
if (APU_Box.Pick(pIItem->object().Position(), pIItem->object().Position()))
{
if (GameID() == GAME_DEATHMATCH || GameID() == GAME_TEAMDEATHMATCH)
{
if (pIItem->GetSlot() == PISTOL_SLOT || pIItem->GetSlot() == RIFLE_SLOT )
{
if (inventory().ItemFromSlot(pIItem->GetSlot()))
{
continue;
}
}
}
NET_Packet P;
u_EventGen(P,GE_OWNERSHIP_TAKE, ID());
P.w_u16(pIItem->object().ID());
u_EventSend(P);
}
}
}
void CActor::SetHitInfo (CObject* who, CObject* weapon, s16 element, Fvector Pos, Fvector Dir)
{
m_iLastHitterID = (who!= NULL) ? who->ID() : u16(-1);
m_iLastHittingWeaponID = (weapon != NULL) ? weapon->ID() : u16(-1);
m_s16LastHittedElement = element;
m_fLastHealth = GetfHealth();
m_bWasHitted = true;
m_vLastHitDir = Dir;
m_vLastHitPos = Pos;
};
void CActor::OnHitHealthLoss (float NewHealth)
{
if (!m_bWasHitted) return;
if (GameID() == GAME_SINGLE || !OnServer()) return;
float fNewHealth = NewHealth;
m_bWasHitted = false;
if (m_iLastHitterID != u16(-1))
{
NET_Packet P;
u_EventGen (P,GE_GAME_EVENT,ID());
P.w_u16(GAME_EVENT_PLAYER_HITTED);
P.w_u16(u16(ID()&0xffff));
P.w_u16 (u16(m_iLastHitterID&0xffff));
P.w_float(m_fLastHealth - fNewHealth);
u_EventSend(P);
}
};
void CActor::OnCriticalHitHealthLoss ()
{
if (GameID() == GAME_SINGLE || !OnServer()) return;
CObject* pLastHitter = Level().Objects.net_Find(m_iLastHitterID);
CObject* pLastHittingWeapon = Level().Objects.net_Find(m_iLastHittingWeaponID);
#ifdef DEBUG
Msg("%s killed by hit from %s %s",
*cName(),
(pLastHitter ? *(pLastHitter->cName()) : ""),
((pLastHittingWeapon && pLastHittingWeapon != pLastHitter) ? *(pLastHittingWeapon->cName()) : ""));
#endif
//-------------------------------------------------------------------
if (m_iLastHitterID != u16(-1))
{
NET_Packet P;
u_EventGen (P,GE_GAME_EVENT,ID());
P.w_u16(GAME_EVENT_PLAYER_HITTED);
P.w_u16(u16(ID()&0xffff));
P.w_u16 (u16(m_iLastHitterID&0xffff));
P.w_float(m_fLastHealth);
u_EventSend(P);
}
//-------------------------------------------------------------------
SPECIAL_KILL_TYPE SpecialHit = SKT_NONE;
if(pLastHittingWeapon)
{
if(pLastHittingWeapon->CLS_ID==CLSID_OBJECT_W_KNIFE)
SpecialHit = SKT_KNIFEKILL;
}
if (m_s16LastHittedElement > 0)
{
if (m_s16LastHittedElement == m_head)
{
CWeaponMagazined* pWeaponMagazined = smart_cast<CWeaponMagazined*>(pLastHittingWeapon);
if (pWeaponMagazined)
{
SpecialHit = SKT_HEADSHOT;
//-------------------------------
NET_Packet P;
u_EventGen(P, GEG_PLAYER_PLAY_HEADSHOT_PARTICLE, ID());
P.w_s16(m_s16LastHittedElement);
P.w_dir(m_vLastHitDir);
P.w_vec3(m_vLastHitPos);
u_EventSend(P);
//-------------------------------
}
}
else
{
CKinematics* pKinematics = smart_cast<CKinematics*>(Visual());
VERIFY (pKinematics);
u16 ParentBone = u16(m_s16LastHittedElement);
while (ParentBone)
{
ParentBone = pKinematics->LL_GetData(ParentBone).GetParentID();
if (ParentBone && ParentBone == m_head)
{
SpecialHit = SKT_HEADSHOT;
break;
};
}
};
};
//-------------------------------
if (m_bWasBackStabbed) SpecialHit = SKT_BACKSTAB;
//-------------------------------
NET_Packet P;
u_EventGen (P,GE_GAME_EVENT,ID());
P.w_u16(GAME_EVENT_PLAYER_KILLED);
P.w_u16(u16(ID()&0xffff));
P.w_u8 (KT_HIT);
P.w_u16 ((m_iLastHitterID) ? u16(m_iLastHitterID&0xffff) : 0);
P.w_u16 ((m_iLastHittingWeaponID && m_iLastHitterID != m_iLastHittingWeaponID) ? u16(m_iLastHittingWeaponID&0xffff) : 0);
P.w_u8 (u8(SpecialHit));
u_EventSend(P);
//-------------------------------------------
if (GameID() != GAME_SINGLE)
Game().m_WeaponUsageStatistic->OnBullet_Check_Result(true);
};
void CActor::OnPlayHeadShotParticle(NET_Packet P)
{
Fvector HitDir, HitPos;
s16 element = P.r_s16();
P.r_dir(HitDir); HitDir.invert();
P.r_vec3(HitPos);
//-----------------------------------
if (!m_sHeadShotParticle.size()) return;
Fmatrix pos;
CParticlesPlayer::MakeXFORM(this,element,HitDir,HitPos,pos);
// установить particles
CParticlesObject* ps = NULL;
ps = CParticlesObject::Create(m_sHeadShotParticle.c_str(),TRUE);
ps->UpdateParent(pos,Fvector().set(0.f,0.f,0.f));
GamePersistent().ps_needtoplay.push_back(ps);
};
void CActor::OnCriticalWoundHealthLoss ()
{
if (GameID() == GAME_SINGLE || !OnServer()) return;
#ifdef DEBUG
/// Msg("%s is bleed out, thanks to %s", *cName(), (m_pLastHitter ? *(m_pLastHitter->cName()) : ""));
#endif
//-------------------------------
NET_Packet P;
u_EventGen (P,GE_GAME_EVENT,ID());
P.w_u16(GAME_EVENT_PLAYER_KILLED);
P.w_u16(u16(ID()&0xffff));
P.w_u8 (KT_BLEEDING);
P.w_u16 ((m_iLastHitterID) ? u16(m_iLastHitterID&0xffff) : 0);
P.w_u16 ((m_iLastHittingWeaponID && m_iLastHitterID != m_iLastHittingWeaponID) ? u16(m_iLastHittingWeaponID&0xffff) : 0);
P.w_u8 (SKT_NONE);
u_EventSend(P);
};
void CActor::OnCriticalRadiationHealthLoss ()
{
if (GameID() == GAME_SINGLE || !OnServer()) return;
//-------------------------------
// Msg("%s killed by radiation", *cName());
NET_Packet P;
u_EventGen (P,GE_GAME_EVENT,ID());
P.w_u16(GAME_EVENT_PLAYER_KILLED);
P.w_u16(u16(ID()&0xffff));
P.w_u8 (KT_RADIATION);
P.w_u16 (0);
P.w_u16 (0);
P.w_u8 (SKT_NONE);
u_EventSend(P);
};
bool CActor::Check_for_BackStab_Bone (u16 element)
{
if (element == m_head) return true;
else
if (element == m_neck) return true;
else
if (element == m_spine2) return true;
else
if (element == m_l_clavicle) return true;
else
if (element == m_r_clavicle) return true;
else
if (element == m_spine1) return true;
else
if (element == m_spine) return true;
return false;
}
bool CActor::InventoryAllowSprint ()
{
PIItem pActiveItem = inventory().ActiveItem();
if (pActiveItem && !pActiveItem->IsSprintAllowed())
{
return false;
};
PIItem pOutfitItem = inventory().ItemFromSlot(OUTFIT_SLOT);
if (pOutfitItem && !pOutfitItem->IsSprintAllowed())
{
return false;
}
return true;
};
BOOL CActor::BonePassBullet (int boneID)
{
if (GameID() == GAME_SINGLE) return inherited::BonePassBullet(boneID);
CCustomOutfit* pOutfit = (CCustomOutfit*)inventory().m_slots[OUTFIT_SLOT].m_pIItem;
if(!pOutfit)
{
CKinematics* V = smart_cast<CKinematics*>(Visual()); VERIFY(V);
CBoneInstance &bone_instance = V->LL_GetBoneInstance(u16(boneID));
return (bone_instance.get_param(3)> 0.5f);
}
return pOutfit->BonePassBullet(boneID);
}
void CActor::On_B_NotCurrentEntity ()
{
inventory().Items_SetCurrentEntityHud(false);
}; | [
"vlad_tislenko@mail.ru"
] | vlad_tislenko@mail.ru |
91bc5ba5db3d4e542dc358409993ef24d5c299cd | 1fa13ef7cd6519ea4146f15f7b91e8691a34e90a | /myRTG/particle-system.cpp | f954e6e20cc6f8efa46f1326f99dd6f5dc291b58 | [] | no_license | TurtleTracks/Real-Time-Graphics | dd700dfac1f2e33950fd560dea7db0114671d85c | 55d5a407332cbf9402922e9d88c8d65538826927 | refs/heads/master | 2021-01-16T21:30:16.841769 | 2018-01-09T08:19:29 | 2018-01-09T08:19:29 | 100,235,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,054 | cpp | #include "particle-system.hpp"
#include "utilities.hpp"
#include <glm\glm.hpp>
#include <glm\common.hpp>
using namespace Utilities;
// constants ////
const double eps = 0.0001;
const double mass = 0.02;
const double restDensity = 2.773 * 1000;
const float separation = 0.0173f;
const float mOverRho = mass / restDensity;
const int gridsz = 32;
const float H = 1.0 / gridsz;
const float HH = H * H;
const double _poly6 = 315.0 / (64 * PI * glm::pow(H, 9));
const float _spiky = -45.0 / (PI * glm::pow(H, 6));
const double DT = 1.0 / 60.0;
const int maxZidx = 229377;
const glm::vec3 vec0 = glm::vec3(0);
const glm::vec3 maxAABB = glm::vec3(1);
// state ////
const int solverIterations = 4;
double time;
const int stepsPerFrame = 4;
int stepsTillSort = 0; // modulo 100
// data structures ////
struct Handle
{
unsigned int zidx;
Particle *particle;
};
struct Cell
{
bool empty;
int firstHandlePos;
};
std::vector<Cell> cells(maxZidx);
std::vector<std::vector<Particle*>> neighborhoods(maxZidx);
std::vector<Handle> handles;
std::vector<glm::vec3> ncellVector(27);
/* Initialize Particle System */
void ParticleSystem::init()
{
glm::vec3 g = glm::vec3(0, -9.8, 0);
forces.push_back(g);
ncellVector =
{
glm::vec3(0, 0, 0), glm::vec3(-1,0,0), glm::vec3(1,0,0),
glm::vec3(0, 0, -1), glm::vec3(-1,0,-1), glm::vec3(1,0,-1),
glm::vec3(0, 0, 1), glm::vec3(-1,0,1), glm::vec3(1,0,1),
glm::vec3(0, -1, 0), glm::vec3(-1,-1,0), glm::vec3(1,-1,0),
glm::vec3(0, -1, -1), glm::vec3(-1,-1,-1), glm::vec3(1,-1,-1),
glm::vec3(0, -1, 1), glm::vec3(-1,-1,1), glm::vec3(1,-1,1),
glm::vec3(0, 1, 0), glm::vec3(-1,1,0), glm::vec3(1,1,0),
glm::vec3(0, 1, -1), glm::vec3(-1,1,-1), glm::vec3(1,1,-1),
glm::vec3(0, 1, 1), glm::vec3(-1,1,1), glm::vec3(1,1,1),
};
for (int i = 0; i < ncellVector.size(); i++)
{
ncellVector[i] = ncellVector[i] * H;
}
}
/* get z-order index from position */
unsigned int ParticleSystem::getZidx(glm::vec3 pos)
{
pos /= H;
if (pos.x < 0) return -1;
if (pos.y < 0) return -1;
if (pos.z < 0) return -1;
unsigned char x = (unsigned int)pos.x;
unsigned char y = (unsigned int)pos.y;
unsigned char z = (unsigned int)pos.z;
unsigned int index = 0;
index = Morton[x] | Morton[y] << 1 | Morton[z] << 2;
return index;
}
glm::vec3 ParticleSystem::decodeIdx(unsigned int idx)
{
unsigned int x = Compact1By2(idx);
unsigned int y = Compact1By2(idx >> 1);
unsigned int z = Compact1By2(idx >> 2);
return glm::vec3(x, y, z) / (float)gridsz;
}
/* store all cell neighbors for each cell */
void ParticleSystem::fillNeighborhoods()
{
unsigned int idmax = maxZidx;
for (unsigned int id = 0; id < idmax; id++)
{
neighborhoods[id].clear();
glm::vec3 pos = glm::vec3(decodeIdx(id)) + 1.0f/(2*gridsz);
for (int i = 0; i < 27; i++)
{
glm::vec3 cellPos = pos + ncellVector[i];
unsigned int ind = getZidx(cellPos);
if (ind < cells.size() && !cells[ind].empty)
{
unsigned int ppos = cells[ind].firstHandlePos;
while ((ppos) < particles.size() && handles[ppos].zidx == ind)
{
neighborhoods[id].push_back(handles[ppos].particle);
ppos++;
}
}
}
}
}
/* Sort Handle vector (and update with correct index values) */
void updateHandles()
{
for (unsigned int i = 1; i < handles.size(); i++)
{
handles[i].zidx = handles[i].particle->zidx;
Handle handle = handles[i];
unsigned int ind = handles[i].particle->zidx;
unsigned int pos = i;
while (pos > 0 && handles[pos - 1].zidx > ind)
{
handles[pos] = handles[pos - 1];
pos -= 1;
}
if(pos != i) handles[pos] = handle;
}
}
/* regenerate handles (needed after particles sort) */
void ParticleSystem::resetHandles()
{
if (particles.size() > handles.size()) handles.resize(particles.size());
for (unsigned int i = 1; i < handles.size(); i++)
{
handles[i].particle = &particles[i];
handles[i].zidx = particles[i].zidx;
}
}
/* update cells with position to first Particle in particles vector */
void updateCells()
{
for (unsigned int i = 0; i < cells.size(); i++)
{
cells[i].empty = true;
cells[i].firstHandlePos = 0;
}
unsigned int ind = 0;
for (unsigned int i = 0; i < handles.size(); i++)
{
while (handles[i].zidx > ind && ind < cells.size())
{
ind++;
}
if (cells[ind].empty)
{
cells[ind].firstHandlePos = i; // order handles != order partcls
cells[ind].empty = false;
}
}
}
/* Index sort on particle vector */
void ParticleSystem::sortParticles()
{
for (unsigned int i = 1; i < particles.size(); i++)
{
Particle particle = particles[i];
unsigned int ind = particles[i].zidx;
unsigned int pos = i;
while (pos > 0 && particles[pos - 1].zidx > ind)
{
particles[pos] = particles[pos - 1];
pos -= 1;
}
if (pos != i) particles[pos] = particle;
}
}
double weightFunction(double rr)
{
double hhrr = HH - rr;
double hhrr3 = hhrr * hhrr * hhrr;
return (rr < HH && 0 < rr) ?_poly6 * hhrr3 : 0;
}
glm::vec3 weightGradient(const glm::vec3 &pipj)
{
float r = glm::length(pipj);
float hr2 = (H - r) * (H - r);
return (r < H && 0 < r) ? _spiky * hr2 * (pipj / r) : glm::vec3(0);
}
double densityConstraint(const Particle &pi, const std::vector<Particle*> &hood)
{
double estimator = 0;
for (auto &pj : hood)
{
glm::vec3 pipj = pi.pred - (*pj).pred;
estimator += weightFunction(glm::dot(pipj, pipj)) * mass;
}
return (estimator/ restDensity) - 1;
}
double gradientConstraintSums(const Particle &pi, const std::vector<Particle*> &hood)
{
glm::vec3 sum1 = vec0;
double sum2 = 0;
double sum1s = 0;
for (auto &pj : hood)
{
glm::vec3 val = weightGradient(pi.pred - (*pj).pred) * mOverRho;
sum1 += val;
sum2 += glm::dot(val, val);
}
sum1s = glm::dot(sum1, sum1);
return (sum1s + sum2);
}
void ParticleSystem::createParticle(glm::vec3 pos)
{
glm::vec3 o = glm::vec3(0); //empty
unsigned int ind = getZidx(pos);
Particle p = { pos, ind, o, 0, o, 0 };
particles.push_back(p);
Handle h = { ind, &particles.back() };
handles.push_back(h);
}
void ParticleSystem::createTower()
{
int x = int(0.2 * gridsz);
int y = int(0.7 * gridsz);
int z = int(0.9 * gridsz);
particles.reserve(x * y * z * 2);
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
for (int k = 0; k < z; k++)
{
createParticle(glm::vec3(i, j, k) * separation);
}
}
}
}
void ParticleSystem::reset()
{
time = 0;
particles.clear();
}
void ParticleSystem::advanceTime(double dt)
{
if (stepsTillSort == 0)
{
sortParticles();
resetHandles();
updateCells();
} else
{
updateHandles();
updateCells();
}
stepsTillSort = (stepsTillSort + 1) % 100;
for (Particle &p : particles)
{
// apply forces :
p.vel += (float)dt * forces[0]; // forces[0] is technically g accel.
// predict position :
p.pred = p.pos + (float)dt * p.vel;
}
fillNeighborhoods();
int iter = 0;
while (iter < solverIterations)
{
//int lastIDX = -1;
//double lastGC = 0;
for(Particle &p : particles)
{
std::vector<Particle*> &hood = neighborhoods[p.zidx];
// calculate lambda
double dc = -densityConstraint(p, hood);
//double gc = lastIDX == p.zidx ? lastGC : gradientConstraintSums(p, hood);
double gc = gradientConstraintSums(p, hood);
p.lambda = dc / (gc + 1000);
//lastIDX = p.zidx;
//lastGC = gc;
}
for (Particle &p : particles)
{
std::vector<Particle*> &hood = neighborhoods[p.zidx];
// calculate delta_p
p.delta = vec0;
for (Particle *pj : hood)
{
glm::vec3 pipj = p.pred - (*pj).pred;
double scale = weightFunction(glm::dot(pipj, pipj))
/ weightFunction(HH * 0.01);
scale = scale * scale;
double scorr = -0.00001 * scale * scale;
double multiplier = p.lambda + (*pj).lambda + scorr;
glm::vec3 wg = weightGradient(pipj);
p.delta += (float)multiplier * wg;
}
p.delta *= mass/restDensity;
p.pred += p.delta;
p.pred = glm::clamp(p.pred, vec0, maxAABB);
}
iter++;
}
for (Particle &p : particles)
{
// update velocity
p.vel = (float)(1.0 / dt) * (p.pred - p.pos);
// apply vorticity confinement and XSPHD viscosity
// update position
p.pos = p.pred;
p.zidx = getZidx(glm::vec3(p.pos));
}
}
void ParticleSystem::bufferParticles()
{
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, particles.size() * sizeof(Particle),
&particles[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Particle), nullptr);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Particle),
(const GLvoid*)(sizeof(float) * 4));
glEnableVertexAttribArray(0);
glPointSize(5);
}
void ParticleSystem::updateVBO()
{
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, particles.size() * sizeof(Particle),
&particles[0], GL_STATIC_DRAW);
}
void ParticleSystem::update()
{
for (int i = 0; i < stepsPerFrame; i++)
{
advanceTime(DT / stepsPerFrame);
}
}
void ParticleSystem::draw()
{
glBindVertexArray(VAO);
updateVBO();
glDrawArrays(GL_POINTS, 0, particles.size());
} | [
"FemiAdegunloye@live.com"
] | FemiAdegunloye@live.com |
f0bc453edf28ee0eecd8baa33ad7a0de0df965cd | e44620035d4d3ced29f50c48862b85c978415f42 | /Final.1/Final.1/Player.cpp | ca63d48f23ab736897a4f94101693aa458ad82b5 | [] | no_license | TuckerL-OSU/CS162 | 6338d34e10ae39f78cce7cb1aac94e72c2a589b9 | cab3d74fd643bf51accf65bdc9b2739a20c28c8f | refs/heads/master | 2020-09-05T09:08:16.289795 | 2019-11-06T17:23:47 | 2019-11-06T17:23:47 | 218,779,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 615 | cpp | /******************************************************************************
* Tucker Lavell
* CS162 Fall 2017
* Final Project
* Player.cpp
******************************************************************************/
#include "Player.hpp"
Player::Player() {
this->y = 0;
this->x = 0;
this->moonStones = 0;
bp = new Backpack();
}
Player::~Player() {
delete bp;
}
void Player::setLoc(int row, int col) {
this->y = row;
this->x = col;
}
void Player::setY(int row) {
this->y = row;
}
int Player::getY() {
return y;
}
void Player::setX(int col) {
this->x = col;
}
int Player::getX() {
return x;
}
| [
"38082010+TuckerL-OSU@users.noreply.github.com"
] | 38082010+TuckerL-OSU@users.noreply.github.com |
ce9405f595fff937147de211809c8525b9d5f4de | 53ee21ad91ead69687f7ff650f27da2eddf5b1ba | /Snake_game/Snake_game/Classes.cpp | 75eb3796e08a04192491a6ebb65263cb9b76bce7 | [] | no_license | chenjuntu/Projects | fc240e775c5a796c87a62f550721dec5ffdb4fbe | 95ba9b73dd81022f695282635d9fe0890b56a37e | refs/heads/master | 2020-05-24T22:50:13.523000 | 2017-05-03T21:03:45 | 2017-05-03T21:03:45 | 84,888,181 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,106 | cpp | /*
* File: Classes.cpp
* Author: Juntu
*
* Created on March 8, 2017, 10:16 AM
*/
#include "Class_header.h"
#include <iostream>
#include <cstdlib>
void Print_screen(char Board[][80]){
for(int i = 0; i < 15; i++){
for(int j = 0; j < 80; j++){
std::cout << Board[i][j];
}
std::cout << std::endl;
}
}
void Egg_generation(char Board[][80]){
int x, y;
do{
x = rand() % 78 + 1;
y = rand() % 13 + 1;
}while(Board[y][x] != ' ');
Board[y][x] = '$';
}
Snake::Snake(char (*Board)[80]){
Head = new Node;
//Head->Coordinate = &(Board[10][40]);
Head->x = 40;
Head->y = 10;
Head->Symbol = '@';
Head->Direction = 'w';
Board[10][40] = Head->Symbol;
Node *Current = Head;
for(int i = 0; i < 3; i++){
Current->Next = new Node;
Current->Next->x = Current->x - 1;
Current->Next->y = Current->y;
Current = Current->Next;
Board[Current->y][Current->x] = Current->Symbol;
Current->Next = NULL;
}
Tail = Current;
Length = 4;
}
Snake::~Snake(){
Node *Temp = Head;
for (int i = 0; i < Length; i++){
Head = Temp->Next;
delete Temp;
Temp = Head;
}
Tail = NULL;
}
void Snake::Turn(char Command){
switch(Command){
case 'w':
if(Head->Direction != 's')
Head->Direction = Command;
break;
case 's':
if(Head->Direction != 'w')
Head->Direction = Command;
break;
case 'a':
if(Head->Direction != 'd')
Head->Direction = Command;
break;
case 'd':
if(Head->Direction != 'a')
Head->Direction = Command;
break;
default:
break;
}
}
int Snake::Move(char (*Board)[80]){
int Result;
int old_x, temp_x;
int old_y, temp_y;
Node *Current = Head;
old_x = Head->x;
old_y = Head->y;
Result = 0;
switch(Head->Direction){
case 'w':
Head->y--;
if(Board[Head->y][Head->x] == '$')
Result = 1;
else if(Board[Head->y][Head->x] == '#' || Board[Head->y][Head->x] == '*')
return 2;
Board[Head->y][Head->x] = Head->Symbol;
break;
case 's':
Head->y++;
if(Board[Head->y][Head->x] == '$')
Result = 1;
else if(Board[Head->y][Head->x] == '#' || Board[Head->y][Head->x] == '*')
return 2;
Board[Head->y][Head->x] = Head->Symbol;
break;
case 'a':
Head->x--;
if(Board[Head->y][Head->x] == '$')
Result = 1;
else if(Board[Head->y][Head->x] == '#' || Board[Head->y][Head->x] == '*')
return 2;
Board[Head->y][Head->x] = Head->Symbol;
break;
case 'd':
Head->x++;
if(Board[Head->y][Head->x] == '$')
Result = 1;
else if(Board[Head->y][Head->x] == '#' || Board[Head->y][Head->x] == '*')
return 2;
Board[Head->y][Head->x] = Head->Symbol;
break;
default:
std::cout << "An unknown bug has been found, please contact author to fix it." << std::endl;
return 2;
break;
}
Board[Tail->y][Tail->x] = ' ';
for(int i = 1; i < Length; i++){
temp_x = Current->Next->x;
temp_y = Current->Next->y;
Current->Next->x = old_x;
Current->Next->y = old_y;
Board[old_y][old_x] = Current->Next->Symbol;
Current = Current->Next;
old_x = temp_x;
old_y = temp_y;
if(Current->Next == NULL)
Tail = Current;
}
return Result;
}
void Snake::Growth(void){
Tail->Next = new Node;
//Just copy the last one's coordinate, it will show up after next move()
Tail->Next->x = Tail->x;
Tail->Next->y = Tail->y;
Tail = Tail->Next;
Tail->Next = NULL;
Length++;
} | [
"owen.jt.chen@gmail.com"
] | owen.jt.chen@gmail.com |
19a4551eea711e4bc1281f12632daef2a8c78ca0 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/inetsrv/iis/svcs/staxcore/seo/testsrv/testsrv.h | a1f7e364999af81c840d921909ffa126c29aa443 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 897 | h | // TestSrv.h : main header file for the TESTSRV application
//
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CTestSrvApp:
// See TestSrv.cpp for the implementation of this class
//
class CTestSrvApp : public CWinApp
{
public:
CTestSrvApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTestSrvApp)
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CTestSrvApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
1f7ac14b450d151e1cf97c2a900c900d1b212fb5 | bdc02a328a21b053c4dc23392a1588f9af205b24 | /SCNU_SmartWard(D003)/jsonrpc-qt/error.h | ddc3b3313a7ac1b90520c9e02dec2c876a5cc177 | [] | no_license | Stefan-China/Keil_HomeControl | 64037219b0e7f046e550b4e5c6240818ddfdd402 | f4294af9f5df37e3f1a882dc487fe32040327a84 | refs/heads/master | 2023-06-19T05:36:30.771461 | 2021-07-19T00:23:40 | 2021-07-19T00:23:40 | 377,675,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,326 | h | // Copyright 2011 Luis Gustavo S. Barreto
#ifndef JSONRPC_ERROR_H
#define JSONRPC_ERROR_H
#include <QString>
#include <QByteArray>
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
using namespace rapidjson;
namespace JsonRPC {
enum ErrorCode
{
NO_ERROR,
PARSE_ERROR = -32700,
INVALID_REQUEST = -32600,
METHOD_NOT_FOUND = -32601,
INVALID_PARAMS = -32602,
INTERNAL_ERROR = -32603
};
class Error
{
/*!
@brief Constructs a Error object with \param code error code and
\param desc error message.
*/
Error(ErrorCode code, QString desc);
/*! Constructs a Error object with \param code error code.
It'll try to set the error message automatically for standard
error codes. If you pass a non-standard error code,
ErrorCode::NO_ERROR will be used.
*/
Error(ErrorCode code = NO_ERROR);
Error(const Error &);
/*! Generates the JSON object.
*/
operator QByteArray() const;
/*! Generates the QVariantMap object.
The generated QVariantMap can be parsed into a JSON Object.
*/
operator Value() const;
/*! Error code.
*/
ErrorCode code;
/*! Error message.
*/
QString desc;
};
} // namespace JsonRPC
#endif // JSONRPC_ERROR_H
| [
"309496562@qq.com"
] | 309496562@qq.com |
179c5d6641dd1662c3f10afe201bd1ca9abae3f6 | 66af69840a05d11f4abf68ca2a8d990c9d6eda2b | /cpp/szyfr_Cezara.cpp | df7955ec1bbf5525c0753ea9afdc4fef4c66e649 | [] | no_license | dobrawarog/gitrepo | 174c22b11ed322b0046e029c547ef3455a7400f1 | 20aab0ba54210e547f9c2ebe03b6d544bff4dc38 | refs/heads/master | 2021-06-27T23:08:01.440795 | 2020-10-06T10:36:00 | 2020-10-06T10:36:00 | 148,303,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,218 | cpp | /*
* szyfr_Cezara.cpp
*/
#include <iostream>
using namespace std;
int male_litery(char tekst[]){
int i = 0;
while (tekst[i] != '\0'){
if ((int)tekst[i] > 64 && (int)tekst[i] < 91) {
tekst[i] = (char)((int)tekst[i]+32);
}
i++;
}
return tekst[i];
}
void szyfruj(char tekst[], int klucz){
int i = 0;
int kod = 0;
while(tekst[i] != '\0'){
kod = (int)tekst[i] + klucz;
cout << kod << endl;
if (kod > 122){
kod = -26;
}
tekst[i] = (char)kod;
i ++;
}
}
void deszyfruj(char tekst[], int klucz){
int i = 0;
int kod = 0;
while(tekst[i] != '\0'){
kod = (int)tekst[i] - klucz;
if (kod < 97){
kod += 26;
}
tekst[i] = (char)kod;
i ++;
}
}
int main(int argc, char **argv)
{
char tekst[20];
cout << "Podaj tekst" << endl;
cin.getline(tekst, 20);
male_litery(tekst);
int klucz = 0;
cout << "Podaj klucz: ";
cin >> klucz ;
klucz = klucz % 26;
szyfruj(tekst, klucz);
cout << tekst << endl;
deszyfruj(tekst, klucz);
cout << tekst << endl;
return 0;
}
| [
"dobrawa.rog@lo1.sandomierz.pl"
] | dobrawa.rog@lo1.sandomierz.pl |
7e4406ec79064cde550d4bf2a170f22df13d13e3 | 7cc5183d0b36133330b6cd428435e6b64a46e051 | /tensorflow/core/profiler/rpc/client/capture_profile.cc | 0b467fefaadfa0d7ee63989f311db4bd3dfd261c | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | shizukanaskytree/tensorflow | cfd0f3c583d362c62111a56eec9da6f9e3e0ddf9 | 7356ce170e2b12961309f0bf163d4f0fcf230b74 | refs/heads/master | 2022-11-19T04:46:43.708649 | 2022-11-12T09:03:54 | 2022-11-12T09:10:12 | 177,024,714 | 2 | 1 | Apache-2.0 | 2021-11-10T19:53:04 | 2019-03-21T21:13:38 | C++ | UTF-8 | C++ | false | false | 10,104 | cc | /* Copyright 2017 The TensorFlow Authors All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/profiler/rpc/client/capture_profile.h"
#include <iostream>
#include <limits>
#include <memory>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/rpc/client/profiler_client.h"
#include "tensorflow/core/profiler/rpc/client/remote_profiler_session_manager.h"
#include "tensorflow/core/profiler/rpc/client/save_profile.h"
#include "tensorflow/tsl/profiler/protobuf/profiler_analysis.pb.h"
#include "tensorflow/tsl/profiler/protobuf/profiler_options.pb.h"
#include "tensorflow/tsl/profiler/protobuf/profiler_service.pb.h"
namespace tensorflow {
namespace profiler {
namespace {
using ::tensorflow::profiler::RemoteProfilerSessionManager;
using Response = ::tensorflow::profiler::RemoteProfilerSessionManager::Response;
constexpr uint64 kMaxEvents = 1000000;
const absl::string_view kXPlanePb = "xplane.pb";
MonitorRequest PopulateMonitorRequest(int duration_ms, int monitoring_level,
bool timestamp) {
MonitorRequest request;
request.set_duration_ms(duration_ms);
request.set_monitoring_level(monitoring_level);
request.set_timestamp(timestamp);
return request;
}
ProfileRequest PopulateProfileRequest(
absl::string_view repository_root, absl::string_view session_id,
absl::string_view host_name,
const RemoteProfilerSessionManagerOptions& options) {
ProfileRequest request;
// TODO(b/169976117) Remove duration from request.
request.set_duration_ms(options.profiler_options().duration_ms());
request.set_max_events(kMaxEvents);
request.set_repository_root(repository_root.data(), repository_root.size());
request.set_session_id(session_id.data(), session_id.size());
request.set_host_name(host_name.data(), host_name.size());
// These tools are only used by TPU profiler.
request.add_tools("trace_viewer");
request.add_tools("op_profile");
request.add_tools("input_pipeline");
request.add_tools("kernel_stats");
request.add_tools("memory_viewer");
request.add_tools("memory_profile");
request.add_tools("overview_page");
request.add_tools("pod_viewer");
request.add_tools("tensorflow_stats");
// XPlane tool is only used by OSS profiler and safely ignored by TPU
// profiler.
request.add_tools(kXPlanePb.data(), kXPlanePb.size());
*request.mutable_opts() = options.profiler_options();
return request;
}
NewProfileSessionRequest PopulateNewProfileSessionRequest(
absl::string_view repository_root, absl::string_view session_id,
const RemoteProfilerSessionManagerOptions& opts) {
NewProfileSessionRequest request;
std::vector<absl::string_view> parts =
absl::StrSplit(opts.service_addresses(0), ':');
DCHECK(!parts.empty());
*request.mutable_request() =
PopulateProfileRequest(repository_root, session_id, parts[0], opts);
request.set_repository_root(repository_root.data(), repository_root.size());
request.set_session_id(session_id.data(), session_id.size());
for (const auto& hostname : opts.service_addresses()) {
request.add_hosts(hostname);
}
return request;
}
inline bool ShouldRetryTracing(Status status) {
return status.code() == error::Code::UNAVAILABLE ||
status.code() == error::Code::ALREADY_EXISTS ||
// When auto-reconnecting to a remote TensorFlow worker after it
// restarts, gRPC can return an UNKNOWN error code with a "Stream
// removed" error message. This should not be treated as an
// unrecoverable error.
(status.code() == error::Code::UNKNOWN &&
status.error_message() == "Stream removed");
}
Status Profile(const std::string& repository_root,
const std::string& session_id,
const RemoteProfilerSessionManagerOptions& opts) {
Status status;
// Host name will be overwritten by RemoteProfilerSessionManager later.
ProfileRequest request = PopulateProfileRequest(repository_root, session_id,
/*host_name=*/"", opts);
auto session = RemoteProfilerSessionManager::Create(opts, request, status);
TF_RETURN_IF_ERROR(status);
// Expect one or more service addresses.
DCHECK_GT(opts.service_addresses_size(), 0);
std::vector<Response> responses = session->WaitForCompletion();
// Expect responses to have the same size as clients.
DCHECK_EQ(responses.size(), opts.service_addresses_size());
bool has_trace_data = false;
for (const auto& client_response : responses) {
ProfileResponse& response = *client_response.profile_response;
if (response.empty_trace()) {
LOG(WARNING) << "No trace event is collected from "
<< client_response.service_address;
} else {
has_trace_data = true;
// If server side returns tool data in the response, saves that into the
// repository. This improves backward compatibility by reducing assumption
// of what server side does.
TF_RETURN_IF_ERROR(SaveProfile(repository_root, session_id,
client_response.service_address, response,
&std::cout));
}
if (!client_response.status.ok()) {
LOG(WARNING) << client_response.service_address << " returned "
<< client_response.status;
}
}
if (!has_trace_data) {
return Status(error::Code::UNAVAILABLE,
"No trace event was collected because there were no responses"
" from clients or the responses did not have trace data.");
}
return OkStatus();
}
// Start a new profiling session that include all the hosts included in
// hostnames, for the time interval of duration_ms. Possibly save the profiling
// result in the directory specified by repository_root and session_id.
Status NewSession(absl::string_view repository_root,
absl::string_view session_id,
const RemoteProfilerSessionManagerOptions& opts) {
NewProfileSessionRequest request =
PopulateNewProfileSessionRequest(repository_root, session_id, opts);
NewProfileSessionResponse response;
TF_RETURN_IF_ERROR(
NewSessionGrpc(opts.service_addresses(0), request, &response));
std::cout << "Profile session succeed for host(s):"
<< absl::StrJoin(opts.service_addresses(), ",") << std::endl;
if (response.empty_trace()) {
return errors::Unavailable("No trace event is collected");
}
return OkStatus();
}
} // namespace
Status Trace(const std::string& logdir, int num_tracing_attempts,
RemoteProfilerSessionManagerOptions& opts,
bool is_cloud_tpu_session) {
DCHECK_GT(opts.profiler_options().duration_ms(), 0);
DCHECK(!opts.service_addresses().empty());
// Use the current timestamp as the run name.
std::string session_id = GetCurrentTimeStampAsString();
std::string repository_root = GetTensorBoardProfilePluginDir(logdir);
auto duration_ms = opts.profiler_options().duration_ms();
TF_RETURN_IF_ERROR(MaybeCreateEmptyEventFile(logdir));
Status status;
int remaining_attempts = num_tracing_attempts;
while (true) {
auto start_timestamp = absl::Now() + absl::Milliseconds(opts.delay_ms());
opts.mutable_profiler_options()->set_start_timestamp_ns(
absl::ToUnixNanos(start_timestamp));
LOG(INFO) << "Profiler delay_ms was " << opts.delay_ms()
<< ", start_timestamp_ns set to "
<< opts.profiler_options().start_timestamp_ns() << " ["
<< start_timestamp << "]";
std::cout << "Starting to trace for " << duration_ms << " ms. "
<< "Remaining attempt(s): " << --remaining_attempts << std::endl;
if (is_cloud_tpu_session) {
status = NewSession(repository_root, session_id, opts);
} else {
status = Profile(repository_root, session_id, opts);
}
if (remaining_attempts <= 0 || status.ok() || !ShouldRetryTracing(status))
break;
std::cout << "No trace event is collected. Automatically retrying.\n"
<< std::endl;
}
if (ShouldRetryTracing(status)) {
std::cout << "No trace event is collected after " << num_tracing_attempts
<< " attempt(s). "
<< "Perhaps, you want to try again (with more attempts?).\n"
<< "Tip: increase number of attempts with --num_tracing_attempts."
<< std::endl;
}
return status;
}
Status Monitor(const std::string& service_addr, int duration_ms,
int monitoring_level, bool display_timestamp,
std::string* result) {
MonitorRequest request =
PopulateMonitorRequest(duration_ms, monitoring_level, display_timestamp);
MonitorResponse response;
TF_RETURN_IF_ERROR(MonitorGrpc(service_addr, request, &response));
*result = response.data();
return OkStatus();
}
Status ExportToTensorBoard(const XSpace& xspace, const std::string& logdir) {
TF_RETURN_IF_ERROR(MaybeCreateEmptyEventFile(logdir));
return SaveXSpace(GetTensorBoardProfilePluginDir(logdir),
GetCurrentTimeStampAsString(), port::Hostname(), xspace);
}
} // namespace profiler
} // namespace tensorflow
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
15c3cfd90cf107a4326d6a904827e1f57d0b4924 | c21c8cba94f4f73aa23de98e555ef77bcab494f0 | /GeeksforGeeks/Random-problems/BIT 1D.cpp | a6f382b6deeb64b9a82223b199b55423d7d3bfcf | [] | no_license | hoatd/Ds-Algos- | fc3ed0c8c1b285fb558f53eeeaea2632e0ed03ae | 1e74995433685f32ce75a036cd82460605024c49 | refs/heads/master | 2023-03-19T05:48:42.595330 | 2019-04-29T06:20:43 | 2019-04-29T06:20:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,908 | cpp |
/** 1d BIT: binary indexed tree gives us sum in range and update value effieciently with less memory usage in comparision with the segment tree **/
/** we give one extra index to the BITree in comp to the initial array an every time the getsum(index) function is called
we have to return the sum of the array upto that index.
algo: for get sum:
we increase index by 1 i.e, index=index+1
then we go to parent index until the index is greter than 0
we get the parent index by removing the last set bit i.e, by formula index = index-(index & (-index))
similarly for update operation
we increase the index by 1 and then we update until the parent index is less equal to n
parent is obtained in update using index=index+(index&(-index))
**/
#include<bits/stdc++.h>
#include<cstdio>
#include<cstdlib>
#define read(val) scanf("%d",&val);
#define print(val) printf("%d ",val);
#define scan(val) scanf("%lld",&val);
#define show(val) printf("%lld ",val);
#define rr(val) for(int i=0; i<val; i++)
#define ret return 0;
#define ll long long
using namespace std;
#define n 12
// set bit[0] to 0
int arr[n];
int BIT[n+1];
void initialise_bit()
{
for(int i=0; i<=n; i++)
{
BIT[i]=0;
}
}
int getsum(int index)
{
index++;
int sum=0;
while(index > 0)
{
sum += BIT[index];
index=index-(index&(-index));
}
return sum;
}
void update_bit(int index,int val)
{
index++;
while(index<=n)
{
BIT[index]+=val;
index=index+(index&(-index));
}
}
void solve()
{
for(int i=0; i<n; i++)
{
update_bit(i,arr[i]);
}
}
int main()
{
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
initialise_bit();
solve();
int query;cin>>query;
int l,r;
// for get sum up to index i from start use l as 0
while(query--)
{
cin>>l>>r;
int val = getsum(r)-getsum(l-1);
cout<<val<<endl;
}
return 0;
}
| [
"shivakp2111@gmail.com"
] | shivakp2111@gmail.com |
34b00ae3d33a69a0f0dab036dc93357f2cc36af3 | a07fb51d7d4a9faf30ed7fb7ef811334befd67ba | /06.프로그래밍언어(C++)/8주차/3교시_함수와배열_구조체/struct3.cpp | f708fe4a2b22d2a55949b104ce6968ae43c385ca | [] | no_license | Jnkim/CPP | d90955aa0fa42146bc3ad97351e3cfcd5dac517a | af39850190d119cc5ff6eda1ab13aaab1129f7d5 | refs/heads/master | 2023-02-04T15:15:21.902451 | 2020-12-29T18:28:47 | 2020-12-29T18:28:47 | 325,350,916 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,171 | cpp | #include <iostream>
#include <cstring>
using namespace std;
void showData(struct Address &st); // 구조체 참조변수 형식 (Call by Refrence )
struct Address{
char name[20];
char phone[20];
char address[80];
};
int main(){
/* strcpy를 사용하려면 #include <cstring> 라이브러리 선언 필수 */
struct Address adr;
strcpy(adr.name , "천사표" );
strcpy(adr.phone , "010-6578-1463" );
strcpy(adr.address , "전남 나주시 빛가람로 블라블라.. 123" );
//struct Address adr = {"천사표" , "010-6578-1463" , "전남 나주시 빛가람로 블라블라.. 123" };
showData(adr); // 구조체 포인터주소값을 전달 (Call By Value와 같다. )
return 0;
}
void showData(struct Address &st){ // 구조체 참조 포인터값을 전달받는 변수 "&변수"
// 값을 수정하면 원본(struct)의 값도 변경된다.
cout << "이름 : " <<st.name<< endl; // 구조체 값참조 방식 ( Refrence로 받을경우 일반 구조체로 변경된다. 일반 구초제일경우: "구조체명.속성")
cout << "전화 : " <<st.phone<< endl;
cout << "주소 : " <<st.address<< endl;
}
| [
"jnkim0117@gmail.com"
] | jnkim0117@gmail.com |
f147cfec6ba508d21e1968998f79b1f82a34ec9f | f8ce41ccb99154c646756bf0223d8e7d15f470c9 | /ServoTest.ino | c0e10afb47fc4bb8a1b26bc967639f40d080eb20 | [] | no_license | AidenKunkler-Peck/ServoTest | a138e9297a9fb09471654a1fdb512cb9f69c859d | d05099add5fce1d188bfaa1948c2822ee2c1c04e | refs/heads/master | 2020-03-26T06:16:34.814612 | 2018-08-13T15:13:44 | 2018-08-13T15:13:44 | 144,597,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,768 | ino | #include <Servo.h>//provides the library for the servo
//int angle = 0;//establishes variable
Servo servo;//builds a servo object and calls it "servo"
void setup() {
Serial.begin(9600);//only needed for Serial.print
servo.attach(8);//connects servo to the 8th port on the Arduino
servo.write(0);//resets the servo at 0
delay(1000);//delay of 1 second
}
void loop() {
//servo.write(360); //base code to test your device
//delay(1000);
//servo.write(0);
//delay(1000);
//for(angle = 180; angle <= 160; angle++){//moves servo from 180 to 160 degrees
//servo.write(angle);//writes the angle provided above
//delay(15);
//}
//for(angle = 180; angle > 160; angle--){//moves servo back to 180 from 160
// servo.write(angle);//^
// delay(15);
//}
//for(angle = 180; angle <= 140; angle++){//^
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle >= 140; angle--){
// servo.write(angle);
// delay(15);
//}
//for(angle = 180; angle < 120; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 120; angle--){
// servo.write(angle);
// delay(15);
//}
//for(angle = 180; angle < 100; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 100; angle--){
// servo.write(angle);
// delay(15);
//}
//for(angle = 180; angle < 80; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 80; angle--){
// servo.write(angle);
// delay(15);
//}
//for(angle = 180; angle < 60; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 60; angle--){
// servo.write(angle);
// delay(15);
//}
//for(angle = 180; angle < 40; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 40; angle--){
// servo.write(angle);
// delay(15);
//}
//for(angle = 180; angle < 20; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 20; angle--){
// servo.write(angle);
// delay(15);
//}
//for(angle = 180; angle < 40; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 40; angle--){
// servo.write(angle);
// delay(15);
//}for(angle = 180; angle < 60; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 60; angle--){
// servo.write(angle);
// delay(15);
//}for(angle = 180; angle < 80; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 80; angle--){
// servo.write(angle);
// delay(15);
//}for(angle = 180; angle < 100; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 100; angle--){
// servo.write(angle);
// delay(15);
//}for(angle = 180; angle < 120; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 120; angle--){
// servo.write(angle);
// delay(15);
//}for(angle = 180; angle < 140; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 140; angle--){
// servo.write(angle);
// delay(15);
//}for(angle = 180; angle < 160; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 160; angle--){
// servo.write(angle);
// delay(15);
//}for(angle = 180; angle < 360; angle++){
//
//servo.write(angle);
//delay(15);
//}
//for(angle = 180; angle > 360; angle--){
// servo.write(angle);
// delay(15);
int forward = 20;//set these numbers to whatever you want
int backward = 1;
for(int p = 180; p >= 0; p-=forward){//this for loop does the same thing as all of the code above
for(int angle = 180; angle >= p; angle-=backward){
servo.write(angle);
delay(10);//adjust speed
// Serial.print("angle: ");//look in Serial monitor to see the angles
// Serial.println(angle);//you can comment this to see the numbers
// Serial.print("P :");
// Serial.println(p);
}
}
}
| [
"42150635+AidenKunkler-Peck@users.noreply.github.com"
] | 42150635+AidenKunkler-Peck@users.noreply.github.com |
a4ced84567f8735499df360f8013a8ec0a225f67 | 25e99a0af5751865bce1702ee85cc5c080b0715c | /ds_algo/src/leetcode_v2/algorithms/LongestCommonPrefix/solve.cpp | ad6df4ff5a3b2dff47b42e436b4fedeed4c0990b | [
"MIT"
] | permissive | jasonblog/note | 215837f6a08d07abe3e3d2be2e1f183e14aa4a30 | 4471f95736c60969a718d854cab929f06726280a | refs/heads/master | 2023-05-31T13:02:27.451743 | 2022-04-04T11:28:06 | 2022-04-04T11:28:06 | 35,311,001 | 130 | 67 | null | 2023-02-10T21:26:36 | 2015-05-09T02:04:40 | C | UTF-8 | C++ | false | false | 743 | cpp | #include <string>
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
class Solution
{
public:
string longestCommonPrefix(vector<string>& strs)
{
int n = strs.size();
if (n < 1) {
return "";
}
int m = strs[0].size();
int i, j;
for (i = 0; i < m; ++i) {
for (auto s : strs) {
if (i >= s.size() || s[i] != strs[0][i]) {
return strs[0].substr(0, i);
}
}
}
return strs[0];
}
};
int main(int argc, char** argv)
{
Solution solution;
vector<string> s = {"abcd", "abc", "abedefg", "abcdefgh"};
cout << solution.longestCommonPrefix(s) << endl;
}
| [
"jason_yao@htc.com"
] | jason_yao@htc.com |
ec936c0067df6c4334de3a46594df6f7e695c9db | 8ed7b2cb70c6e33b01679c17d0e340f11c733520 | /drum-machine-test/test/testjsonserializer.cpp | a734c93ef6de39e970f251af13d5caff9f6e318d | [] | no_license | saibi/qt | 6528b727bd73da82f513f2f54c067a669f394c9a | a3066b90cbc1ac6b9c82af5c75c40ce9e845f9a2 | refs/heads/master | 2022-06-26T20:08:07.960786 | 2022-06-10T06:49:28 | 2022-06-10T06:49:28 | 88,221,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,712 | cpp | #include "testjsonserializer.h"
#include "dummyserializable.h"
#include "track.h"
const QString FILENAME = "test.json";
const QString DUMMY_FILE_CONTENT = "{\n \"myBool\": true,\n \"myDouble\": 5.2,\n \"myInt\": 1,\n \"myString\": \"hello\"\n}\n";
TestJsonSerializer::TestJsonSerializer(QObject *parent) :
QObject(parent),
mSerializer()
{
}
void TestJsonSerializer::saveDummy()
{
DummySerializable dummy;
dummy.myInt = 1;
dummy.myDouble = 5.2;
dummy.myString = "hello";
dummy.myBool = true;
mSerializer.save(dummy, FILENAME);
QString data = loadFileContent();
QVERIFY(data == DUMMY_FILE_CONTENT);
}
QString TestJsonSerializer::loadFileContent()
{
QFile file(FILENAME);
file.open(QFile::ReadOnly);
QString content = file.readAll();
file.close();
return content;
}
void TestJsonSerializer::loadDummy()
{
QFile file(FILENAME);
file.open(QFile::WriteOnly | QIODevice::Text);
QTextStream out(&file);
out << DUMMY_FILE_CONTENT;
file.close();
DummySerializable dummy;
mSerializer.load(dummy, FILENAME);
QCOMPARE(dummy.myInt, 1);
QCOMPARE(dummy.myDouble, 5.2);
QCOMPARE(dummy.myString, QString("hello"));
QCOMPARE(dummy.myBool, true);
}
void TestJsonSerializer::cleanup()
{
QFile(FILENAME).remove();
}
void TestJsonSerializer::saveTrack_data()
{
QTest::addColumn<int>("soundEventCount");
QTest::newRow("1") << 1;
QTest::newRow("100") << 100;
QTest::newRow("1000") << 1000;
}
void TestJsonSerializer::saveTrack()
{
QFETCH(int, soundEventCount);
Track track;
track.record();
for (int i = 0; i < soundEventCount; ++i)
track.addSoundEvent(i % 4);
track.stop();
QBENCHMARK {
mSerializer.save(track, FILENAME);
}
}
//QTEST_MAIN(TestJsonSerializer)
| [
"ymkim@huvitz.com"
] | ymkim@huvitz.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.