blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
10586808e3689a1dcebc4504a423a1c5b9ce242c
deb8ef49795452ff607023c6bce8c3e8ed4c8360
/Projects/UAlbertaBot/Source/starcraftsearch/StarcraftState.hpp
8fc167779ba68287860733364c8a55862716c046
[]
no_license
timburr1/ou-skynet
f36ed7996c21f788a69e3ae643b629da7d917144
299a95fae4419429be1d04286ea754459a9be2d6
refs/heads/master
2020-04-19T22:58:46.259980
2011-12-06T20:10:34
2011-12-06T20:10:34
34,360,542
0
0
null
null
null
null
UTF-8
C++
false
false
42,901
hpp
#ifndef STARCRAFT_STATE_H #define STARCRAFT_STATE_H #define GSN_DEBUG 0 #define MAX_ACTIONS 30 #define BUILDING_PLACEMENT 24 * 5 #define DATA (StarcraftData::getInstance()) #include <string.h> #include <queue> #include <algorithm> #include <fstream> #include "BWAPI.h" #include <limits.h> #include "ActionSet.hpp" #include "StarcraftAction.hpp" #include "StarcraftData.hpp" #include "ActionInProgress.hpp" #include "BuildingData.hpp" #include "StarcraftSearchGoal.hpp" #include "StarcraftSearchConstraint.hpp" #include <math.h> // #define DEBUG_LEGAL class StarcraftState { protected: /********************************************************************* * DATA **********************************************************************/ StarcraftState * parent; // the state that generated this state ActionsInProgress progress; BuildingData<unsigned short> buildings; ActionSet completedUnitSet, // ActionSet of completed units progressUnitSet; // ActionSet bitmask of units in progress char mineralWorkers, // number of workers currently mining gasWorkers; // number of workers currently getting gas unsigned char actionPerformed, // the action which generated this state actionPerformedK; int maxSupply, // our maximum allowed supply currentSupply; // our current allocated supply char padding[2]; unsigned short currentFrame; // the current frame of the game int minerals, // current mineral count gas; // current gas count unsigned char numUnits[MAX_ACTIONS]; // how many of each unit are completed /********************************************************************* * VIRTUAL FUNCTIONS *********************************************************************/ virtual ~StarcraftState() {} virtual bool specificIsLegal(Action a) = 0; virtual int specificWhenReady(Action a) = 0; virtual void specificDoAction(const Action action, const int ffTime) = 0; virtual void specificFastForward(const int toFrame) = 0; virtual void specificFinishAction(const Action action) = 0; virtual void setGameStartData() = 0; public: /********************************************************************************** * * Action Performing Functions - Changes State * **********************************************************************************/ // do an action, action must be legal for this not to break void doAction(const Action action, const int ffTime) { if (GSN_DEBUG) printf("Do Action - %s\n", DATA[action].getName().c_str()); // set the actionPerformed actionPerformed = (unsigned char)action; actionPerformedK = 1; // fast forward to when this action can be performed if (ffTime != -1) { fastForward(ffTime); } else { fastForward(resourcesReady(action)); } // create the struct unsigned int tempTime = currentFrame + DATA[action].buildTime(); // if building, add a constant amount of time to find a building placement if (DATA[action].isBuilding()) { // add 2 seconds tempTime += BUILDING_PLACEMENT; } // add it to the actions in progress progress.addAction(action, tempTime); // update the progress bitmask progressUnitSet.add(action); // if what builds this unit is a building if (DATA[action].whatBuildsIsBuilding()) { // add it to a free building, which MUST be free since it's called from doAction // which must be already fastForwarded to the correct time buildings.queueAction(action); } // modify our resources minerals -= DATA[action].mineralPrice(); gas -= DATA[action].gasPrice(); currentSupply += DATA[action].supplyRequired(); if (minerals < 0 || gas < 0) { printf("Resource Error: m:%d g:%d\n", minerals, gas); } // do race specific things here, like subtract a larva specificDoAction(action, ffTime); if (GSN_DEBUG) printf("Do Action End\n"); } // fast forwards the current state to time toFrame void fastForward(const int toFrame) { if (GSN_DEBUG) printf("\tFast Forward to %d from %d progress size %d\n", toFrame, currentFrame, progress.size()); // do specific things here, like figure out how many larva we will have specificFastForward(toFrame); // fast forward the building timers to the current frame buildings.fastForwardBuildings(toFrame - currentFrame); // update resources & finish each action int lastActionFinished(currentFrame), totalTime(0); double moreGas = 0, moreMinerals = 0; while (!progress.isEmpty() && progress.nextActionFinishTime() <= (unsigned int)toFrame) { // figure out how long since the last action was finished int timeElapsed = progress.nextActionFinishTime() - lastActionFinished; totalTime += timeElapsed; // update our mineral and gas count for that period moreMinerals += timeElapsed * getMineralsPerFrame(); moreGas += timeElapsed * getGasPerFrame(); // update when the last action was finished lastActionFinished = progress.nextActionFinishTime(); // finish the action, which updates mineral and gas rates if required finishNextActionInProgress(); } // update resources from the last action finished to toFrame int elapsed = toFrame - lastActionFinished; moreMinerals += elapsed * getMineralsPerFrame(); moreGas += elapsed * getGasPerFrame(); totalTime += elapsed; minerals += (int)(ceil(moreMinerals)); gas += (int)(ceil(moreGas)); // we are now in the FUTURE... "the future, conan?" currentFrame = toFrame; if (GSN_DEBUG) printf("\tFast Forward End\n"); } // when we want to 'complete' an action (its time is up) do this void finishNextActionInProgress() { if (GSN_DEBUG) printf("\t\tFinishing Action %s\n", DATA[progress.nextAction()].getName().c_str()); // get the actionUnit from the progress data int actionUnit = progress.nextAction(); // add the unit to the unit counter addNumUnits(actionUnit, DATA[actionUnit].numProduced()); // add to the max supply if it's a supplying unit maxSupply += DATA[actionUnit].supplyProvided(); // if it's a worker, put it on minerals if (DATA[actionUnit].isWorker()) { mineralWorkers++; } // if it's an extractor if (DATA[actionUnit].isRefinery()) { // take those workers from minerals and put them into it mineralWorkers -= 3; gasWorkers += 3; } // if it's a building that can produce units, add it to the building data if (DATA[actionUnit].isBuilding() && !DATA[actionUnit].isSupplyProvider()) { buildings.addBuilding(actionUnit); } // pop it from the progress vector progress.popNextAction(); // we need to re-set the whole progress mask again :( setProgressMask(); // do race specific action finishings specificFinishAction(actionUnit); if (GSN_DEBUG) printf("\t\tFinish Action End\n"); } /********************************************************************************** * * When Resources Ready Function + Sub Functions * **********************************************************************************/ // returns the time at which all resources to perform an action will be available int resourcesReady(const int action) { if (GSN_DEBUG) printf(">\n>\n> NEW ACTION: %s\n>\n> Progress Size %d\n>\n\nResource Calculation - %s\n", DATA[action].getName().c_str(), progress.size(), DATA[action].getName().c_str()); // the resource times we care about int m(currentFrame), // minerals g(currentFrame), // gas l(currentFrame), // class-specific s(currentFrame), // supply p(currentFrame), // prerequisites maxVal(currentFrame); // figure out when prerequisites will be ready p = whenPrerequisitesReady(action); // check minerals m = whenMineralsReady(action); // check gas g = whenGasReady(action); // race specific timings (Zerg Larva) l = specificWhenReady(action); // set when we will have enough supply for this unit s = whenSupplyReady(action); // figure out the max of all these times maxVal = (m > maxVal) ? m : maxVal; maxVal = (g > maxVal) ? g : maxVal; maxVal = (l > maxVal) ? l : maxVal; maxVal = (s > maxVal) ? s : maxVal; maxVal = (p > maxVal) ? p : maxVal; if (GSN_DEBUG) { printf("\tMinerals \t%d\n\tGas \t\t%d\n\tSpecific \t%d\n\tSupply \t%d\n\tPreReq \t%d\n", m, g, l, s, p); printf("Resource Calculation End (return %d)\n\n", maxVal); } // return the time return maxVal + 1; } int whenSupplyReady(const Action action) const { if (GSN_DEBUG) printf("\tWhen Supply Ready\n"); int s = currentFrame; // set when we will have enough supply for this unit int supplyNeeded = DATA[action].supplyRequired() + currentSupply - maxSupply; if (supplyNeeded > 0) { //if (GSN_DEBUG) printf("\t\tSupply Is Needed: %d\n", supplyNeeded); // placeholder for minimum olord time int min = 9999999; // if we don't have the resources, this action would only be legal if there is an // overlord in progress, so check to see when the first overlord will finish for (int i(0); i<progress.size(); ++i) { if (GSN_DEBUG) printf("\t\tSupply Check: %s %d Progress Size %d\n", DATA[progress.getAction(i)].getName().c_str(), DATA[progress.getAction(i)].supplyProvided(), progress.size()); // so, if the unit provides the supply we need if (DATA[progress.getAction(i)].supplyProvided() > supplyNeeded) { // set 'min' to the min of these times min = (progress.getTime(i) < min) ? progress.getTime(i) : min; //if (GSN_DEBUG) printf("\t\tSupply Found: %s %d\n", DATA[progress.getAction(i)].getName().c_str(), min); } // then set supply time to min s = min; } } return s; } int whenPrerequisitesReady(const Action action) const { if (GSN_DEBUG) printf("\tCalculating Prerequisites\n"); int p = currentFrame; // if a building builds this action if (DATA[action].whatBuildsIsBuilding()) { if (GSN_DEBUG) printf("\t\tAction Needs Building\n"); // get when the building / prereqs will be ready p = whenBuildingPrereqReady(action); } // otherwise something else builds this action so we don't worry about buildings else { // if requirement in progress (and not already made), set when it will be finished ActionSet reqInProgress = (DATA[action].getPrerequisites() & progressUnitSet) - completedUnitSet; if (GSN_DEBUG) printf("\t\tAction Does Not Need Building\n"); // if it's not empty, check when they will be done if (!reqInProgress.isEmpty()) { if (GSN_DEBUG) printf("\t\tAction Has Prerequisites In Progress\n"); p = progress.whenActionsFinished(reqInProgress); } } if (GSN_DEBUG) printf("\tCalculating Prerequisites End (return %d)\n", p); return p ; } int whenBuildingPrereqReady(const Action action) const { if (GSN_DEBUG) printf("\t\tWhen Building Prereq Ready\n"); Action builder = DATA[action].whatBuildsAction(); assert(DATA[builder].isBuilding()); // is the building currently constructed bool buildingConstructed = numUnits[builder] > 0; // is the building currently in progress bool buildingProgress = progress.numInProgress(builder) > 0; // when the building will be available int buildingAvailableTime; // if the building is both finished and in progress if (buildingConstructed && buildingProgress) { if (GSN_DEBUG) printf("\t\t\tBuilding Constructed %d and In Progress %d\n", numUnits[builder], progress.numInProgress(builder)); // get the time the constructed version will be free int A = whenConstructedBuildingReady(builder); // get the time the progress version will be free int B = progress.nextActionFinishTime(builder); // take the buildingAvailableTime = (A < B) ? A : B; } // otherwise if the constructed version is all we have else if (buildingConstructed) { if (GSN_DEBUG) printf("\t\t\tBuilding Constructed Only\n"); // set the time accordingly buildingAvailableTime = whenConstructedBuildingReady(builder); } // otherwise the progress version is all we have else { if (GSN_DEBUG) printf("\t\t\tBuilding In Progress Only\n"); // set the time accordingly buildingAvailableTime = progress.nextActionFinishTime(builder); } // get all prerequisites currently in progress but do not have any completed ActionSet prereqInProgress = (DATA[action].getPrerequisites() & progressUnitSet) - completedUnitSet; // remove the specific builder from this list since we calculated that earlier prereqInProgress.subtract(builder); // if we actually have some prerequisites in progress other than the building if (!prereqInProgress.isEmpty()) { // get the max time the earliest of each type will be finished in int C = progress.whenActionsFinished(prereqInProgress); // take the maximum of this value and when the building was available buildingAvailableTime = (C > buildingAvailableTime) ? C : buildingAvailableTime; } if (GSN_DEBUG) printf("\t\tWhen Building Prereq Ready End (return %d)\n", buildingAvailableTime); return buildingAvailableTime; } int whenConstructedBuildingReady(const Action builder) const { if (GSN_DEBUG) printf("\t\t\tWhen Constructed Building Ready\n"); // if what builds a is a building and we have at least one of them completed so far if (DATA[builder].isBuilding() && numUnits[builder] > 0 ) { int returnTime = currentFrame + buildings.timeUntilFree(builder); if (GSN_DEBUG) printf("\t\t\tWhen Constructed Building Ready End (return %d)\n", returnTime); // get when the next building is available return returnTime; } return currentFrame; } // when will minerals be ready int whenMineralsReady(const int action) const { int difference = DATA[action].mineralPrice() - minerals; double m = currentFrame; double addMinerals = 0, addTime = 0; if (difference > 0) { int lastAction = currentFrame; int tmw = mineralWorkers, tgw = gasWorkers; for (int i(0); i<progress.size(); ++i) { // the vector is sorted in descending order int ri = progress.size() - i - 1; // the time elapsed and the current minerals per frame int elapsed = progress.getTime(ri) - lastAction; double mpf = (tmw * DATA.mpwpf); // the amount of minerals that would be added this time step double tempAdd = elapsed * mpf, tempTime = elapsed; // if this amount is enough to push us over what we need if (addMinerals + tempAdd >= difference) { // figure out when we go over tempTime = (difference - addMinerals) / mpf; // add the minerals and time addMinerals += tempTime * mpf; addTime += tempTime; //if (GSN_DEBUG) printf("Necessary Minerals Acquired Mid-Iteration: %lf\n", addMinerals); // break out of the loop break; // otherwise, add the whole interval } else { addMinerals += tempAdd; addTime += elapsed; //if (GSN_DEBUG) printf("Another Mineral Iteration Necessary: %lf\n", addMinerals); } // if it was a drone or extractor update the temp variables if (DATA[progress.getAction(ri)].isWorker()) { tmw++; } else if (DATA[progress.getAction(ri)].isRefinery()) { tmw -= 3; tgw += 3; } // update the last action lastAction = progress.getTime(ri); } // if we still haven't added enough minerals, add more time if (addMinerals < difference) { addTime += (difference - addMinerals) / (tmw * DATA.mpwpf); //if (GSN_DEBUG) printf("\t\tNot Enough Minerals, Adding: minerals(%lf) time(%lf)\n", (difference - addMinerals), addTime); } m += addTime; } //if (GSN_DEBUG) printf("\tMinerals Needs Adding: Minerals(%d, %lf) Frames(%lf, %d > %d)\n", difference, addMinerals, addTime, currentFrame, (int)ceil(m)); // for some reason if i don't return +1, i mine 1 less mineral in the interval return (int)(ceil(m) + 1); } int whenGasReady(const int action) const { double g = currentFrame; int difference = DATA[action].gasPrice() - gas; double addGas = 0, addTime = 0; if (difference > 0) { int lastAction = currentFrame; int tmw = mineralWorkers, tgw = gasWorkers; for (int i(0); i<progress.size(); ++i) { // the vector is sorted in descending order int ri = progress.size() - i - 1; // the time elapsed and the current minerals per frame int elapsed = progress.getTime(ri) - lastAction; double gpf = (tgw * DATA.gpwpf); // the amount of minerals that would be added this time step double tempAdd = elapsed * gpf, tempTime = elapsed; // if this amount is enough to push us over what we need if (addGas + tempAdd >= difference) { // figure out when we go over tempTime = (difference - addGas) / gpf; // add the minerals and time addGas += tempTime * gpf; addTime += tempTime; // break out of the loop break; // otherwise, add the whole interval } else { addGas += tempAdd; addTime += elapsed; } // if it was a drone or extractor update temp variables if (DATA[progress.getAction(ri)].isWorker()) { tmw++; } else if (DATA[progress.getAction(ri)].isRefinery()) { tmw -= 3; tgw += 3; } // update the last action lastAction = progress.getTime(ri); } // if we still haven't added enough minerals, add more time if (addGas < difference) { addTime += (difference - addGas) / (tgw * DATA.gpwpf); } g += addTime; } //if (GSN_DEBUG) printf("\tGas Needs Adding: Gas(%d, %lf) Frames(%lf, %d > %d)\n", difference, addGas, addTime, currentFrame, (int)ceil(g)); return (int)(ceil(g) + 1); } /********************************************************************************** * * Heuristic Search + Pruning + Evaluation Functions * **********************************************************************************/ // Gets an upper bound on the time it will take to complete goal: // Sum the following: // calculateGoalResourceLowerBound() // calculateDependencyTimeRemaining() // sum the build time of everything in the goal int calculateUpperBoundHeuristic(const StarcraftSearchGoal & goal) const { // the upper bound int upperBound(0); // dependency chain build time heuristic upperBound += calculateDependencyHeuristic(goal); // resources ready heuristic upperBound += calculateResourcesReadyHeuristic(goal); // add build time for everything in the goal for (int a = 0; a<DATA.size(); ++a) { // how many of this action we still need to build int need = goal[a] - numUnits[a]; // if this action is in the goal if (need > 0) { upperBound += need * DATA[a].buildTime(); } } return currentFrame + upperBound; } int workerUpperBound(const StarcraftSearchGoal & goal) const { std::pair<short,short> grlb = calculateGoalResourceLowerBound(goal); std::pair<int, int> resourceReadyPair = resourceReadyLowerBound(grlb.first, grlb.second); return resourceReadyPair.second; } // heuristic evaluation function for this state int eval(const StarcraftSearchGoal & goal, const bool useLandmark = true) const { // dependency chain build time heuristic int dependencyHeuristic = calculateDependencyHeuristic(goal); if (useLandmark) { return dependencyHeuristic; } else { return 1; } } int calculateResourcesReadyHeuristic(const StarcraftSearchGoal & goal) const { // resources ready heuristic std::pair<short,short> grlb = calculateGoalResourceLowerBound(goal); std::pair<int, int> resourceReadyPair = resourceReadyLowerBound(grlb.first, grlb.second); int resourceReadyLowerBoundVal = resourceReadyPair.first - currentFrame; return resourceReadyLowerBoundVal; } int calculateDependencyHeuristic(const StarcraftSearchGoal & goal) const { // the maximum dependency time for all actions in the goal int max = 0; // for each action which exists for (int a = 0; a<DATA.size(); ++a) { // if this action is in the goal if (goal[a] > numUnits[a]) { // calculate the time remaining for this action's dependencies int actionDTR = calculateDependencyTimeRemaining(a); // set the maximum value max = (actionDTR > max) ? actionDTR : max; } } // return the maximum value return max; } // calculates a lower bound on the amount of time it would take us to // reach the resources necessary to reach our goal std::pair<short,short> calculateGoalResourceLowerBound(const StarcraftSearchGoal & goal) const { std::pair<short,short> totalResources(0,0); // first calculate the resources needed directly by goal actions for (int a(0); a < MAX_ACTIONS; ++a) { // if this action is in the goal if (goal.get(a)) { // calculate how many we still need of this action int stillNeed(goal[a] - (numUnits[a] + progress[a])); // if it is greater than zero, add it to the total if (stillNeed > 0) { //printf("Adding price of %d %s (%d,%d)\n", stillNeed, DATA[a].getName().c_str(), DATA[a].mineralPrice(), DATA[a].gasPrice()); totalResources.first += stillNeed * DATA[a].mineralPrice(); totalResources.second += stillNeed * DATA[a].gasPrice(); } } } // calculate how many resources are still needed by dependencies remaining // for all actions in the goal // an actionset of what we've added so far // this will prevent shared dependencies from adding resources twice ActionSet addedSoFar(0); // for each action in the goal for (int a(0); a < MAX_ACTIONS; ++a) { // if we need some of this action // and we don't have any already (since this would always return time zero if (goal[a]) { //printf("Calculating Dependency Resources For %s\n", DATA[a].getName().c_str()); // calculate how many resources we would need for these dependencies calculateDependencyResourcesRemaining(a, totalResources, addedSoFar); } } // if the total resources requires gas and we do not have a refinery, add the price of one if (totalResources.second > 0 && !numUnits[DATA.getRefinery()] && !progress[DATA.getRefinery()]) { //printf("Goal requires gas, adding refinery price\n"); totalResources.first += DATA[DATA.getRefinery()].mineralPrice(); totalResources.second += DATA[DATA.getRefinery()].gasPrice(); } // return the total return totalResources; } void calculateDependencyResourcesRemaining(const int action, std::pair<short,short> & totalResources, ActionSet & addedSoFar) const { // get the strict dependencies of this action ActionSet strictDependencies = DATA.getStrictDependency(action); // for each of the top level dependencies this action has while (!strictDependencies.isEmpty()) { // get the next action from this dependency int nextStrictDependency = strictDependencies.popAction(); // if we have already started, completed, or added this action already, continue if (completedUnitSet.contains(nextStrictDependency) || progressUnitSet.contains(nextStrictDependency)) { continue; } // otherwise we haven't seen it yet else { // if we haven't added it yet, add it if (!addedSoFar.contains(nextStrictDependency)) { //printf("\tAdding resources for dependency %s, (%d,%d)\n", DATA[nextStrictDependency].getName().c_str(), DATA[nextStrictDependency].mineralPrice(), DATA[nextStrictDependency].gasPrice()); // add the resources totalResources.first += DATA[nextStrictDependency].mineralPrice(); totalResources.second += DATA[nextStrictDependency].gasPrice(); // mark the action as added addedSoFar.add(nextStrictDependency); } else { //printf("\tPreviously added price of %s, skipping\n",DATA[nextStrictDependency].getName().c_str()); } // recurse down the line calculateDependencyResourcesRemaining(nextStrictDependency, totalResources, addedSoFar); } } } // calculates the time remaining in the chain of dependencies of action given 'have' already completed int calculateDependencyTimeRemaining(const int action) const { // get the strict dependencies of this action ActionSet strictDependencies = DATA.getStrictDependency(action); //bool actionCompleted = completedUnitSet.contains(action); bool actionInProgress = progressUnitSet.contains(action); // this will hold the max return time of all dependencies int max = 0; // if one of the unit is in progress, get the remaining time on it if (actionInProgress) { max += progress.nextActionFinishTime(action) - currentFrame; } // otherwise get the build time of the unit else { max += DATA[action].buildTime(); } // for each of the top level dependencies this action has while (!strictDependencies.isEmpty()) { // get the next action from this dependency int nextStrictDependency = strictDependencies.popAction(); // if we have this dependency completed, break out of the loop if (completedUnitSet.contains(nextStrictDependency)) { //if (1) printf("DEPCALC: Have %s, stop\n", DATA[nextStrictDependency].getName().c_str()); continue; } // if we have this dependency in progress else if (progressUnitSet.contains(nextStrictDependency)) { // return the time left on this action int timeRemaining = progress.nextActionFinishTime(nextStrictDependency) - currentFrame; //if (1) printf("DEPCALC: Prog %s, %d\n", DATA[nextStrictDependency].getName().c_str(), timeRemaining); max = (timeRemaining > max) ? timeRemaining : max; } // we do not have this dependency at all else { //if (1) printf("DEPCALC: Need %s\n", DATA[nextStrictDependency].getName().c_str()); // sum the current build time as well as that of the next strict dependency int sum = DATA[nextStrictDependency].buildTime() + calculateDependencyTimeRemaining(nextStrictDependency); // set the maximum max = (sum > max) ? sum : max; } } // return the maxium over all strict dependencies recursively // if this action had no dependencies max will be zero if (max == 0) { printf("WTF\n"); } return max; } std::pair<int, int> resourceReadyLowerBound(const int goalMinerals, const int goalGas) const { double currentMinerals = minerals; double currentGas = gas; double currentWorkers = mineralWorkers; double mineralTimeElapsed = 0; double remainingMinerals, mineralTimeRemaining; while (true) { remainingMinerals = goalMinerals - currentMinerals; mineralTimeRemaining = remainingMinerals / (currentWorkers * DATA.mpwpf); //printf("%lf remaining, %lf frames, %lf\n", remainingMinerals, mineralTimeRemaining, (mineralTimeRemaining - DATA[DATA.getWorker()].buildTime()) * DATA.mpwpf); // if we were to build another worker, would it make its resources back? if ( (mineralTimeRemaining - DATA[DATA.getWorker()].buildTime()) * DATA.mpwpf >= DATA[DATA.getWorker()].mineralPrice() ) { currentMinerals += currentWorkers * DATA.mpwpf * DATA[DATA.getWorker()].buildTime() - DATA[DATA.getWorker()].mineralPrice(); currentWorkers++; mineralTimeElapsed += DATA[DATA.getWorker()].buildTime(); } else { break; } } remainingMinerals = goalMinerals - currentMinerals; if (remainingMinerals >= 0) { mineralTimeRemaining = remainingMinerals / (currentWorkers * DATA.mpwpf); mineralTimeElapsed += mineralTimeRemaining; } //if (goalMinerals) printf("%d minerals gathered in %lf frames with %d workers.\n", goalMinerals, mineralTimeElapsed, (int)currentWorkers); double gasRemaining = goalGas - currentGas; double gasTimeRemaining = gasRemaining / (3 * DATA.gpwpf); if (goalGas && !numUnits[DATA.getRefinery()] && !progress[DATA.getRefinery()]) { gasTimeRemaining += DATA[DATA.getRefinery()].buildTime(); } //if (goalGas) printf("%d gas gathered in %lf frames with %d workers.\n", goalGas, gasTimeRemaining, 3); int workers = (int)(currentWorkers + (goalGas ? 3 : 0)); return std::pair<int, int>((int)ceil(currentFrame + (gasTimeRemaining > mineralTimeElapsed ? gasTimeRemaining : mineralTimeElapsed)), workers); } int hash(const std::vector<int> & random) const { int hash = 0; int * p = (int *)(this); for (size_t i=1; i<sizeof(*this)/4; ++i) { int randData = (*(p+i)) ^ random[i]; hash ^= randData; } return hash; } /********************************************************************************** * * Action Legality Functions * **********************************************************************************/ ActionSet getLegalActions(const StarcraftSearchGoal & goal) const { // initially empty bitmask ActionSet legal; // for each possible action, check for legality for (int i = 0; i < DATA.size(); ++i) { // if we have the prerequisite units if (isLegal(i, goal)) { // set the bitmask bit to a 1 legal.add(i); } } // return the bitmask return legal; } // given the goal, is this action legal bool isLegal(const Action a, const StarcraftSearchGoal & goal) const { if (currentSupply > maxSupply) { printData(); } if (!goal.get(a) && !goal.getMax(a)) { #ifdef DEBUG_LEGAL printf("NONE IN GOAL %d\n", a); #endif return false; } // if we have enough of this thing don't make any more if (goal.get(a) && (getNumUnits(a) >= goal.get(a))) { #ifdef DEBUG_LEGAL printf("HAVE ALREADY %d\n", a); #endif return false; } // if we have more than the max we want, return false if (goal.getMax(a) && (getNumUnits(a) >= goal.getMax(a))) { #ifdef DEBUG_LEGAL printf("HAVE MAX ALREADY %d\n", a); #endif return false; } // check if the tech requirements are met if (!hasRequirements(DATA[a].getPrerequisites())) { #ifdef DEBUG_LEGAL printf("PREREQ %d\n", a); #endif return false; } // if it's a unit and we are out of supply and aren't making an overlord, it's not legal int supplyInProgress = progress[DATA.getSupplyProvider()]*DATA[DATA.getSupplyProvider()].supplyProvided() + progress[DATA.getResourceDepot()]*DATA[DATA.getResourceDepot()].supplyProvided(); if ( (currentSupply + DATA[a].supplyRequired()) > maxSupply + supplyInProgress) { #ifdef DEBUG_LEGAL printf("NO SUPPLY %d\n", a); #endif //printData(); return false; } // specific rule for never leaving 0 workers on minerals if (DATA[a].isRefinery() && (mineralWorkers <= 4 + 3*getNumUnits(DATA.getRefinery()))) { #ifdef DEBUG_LEGAL printf("REFINERY 1 %d\n", a); #endif return false; } // if it's a new building and no drones are available, it's not legal if (DATA[a].isBuilding() && (mineralWorkers <= 1)) { #ifdef DEBUG_LEGAL printf("NO MINERAL WORKERS %d\n", a); #endif return false; } // we can't build a building with our last worker if (DATA[a].isBuilding() && (mineralWorkers <= 1 + 3*getNumUnits(DATA.getRefinery()))) { #ifdef DEBUG_LEGAL printf("NO MINERAL WORKERS - (%d, %d) %d\n", mineralWorkers, getNumUnits(DATA.getRefinery()), a); #endif return false; } // if we have no gas income we can't make a gas unit bool noGas = (gasWorkers == 0) && (getNumUnits(DATA.getRefinery()) == 0); if (((DATA[a].gasPrice() - gas) > 0) && noGas) { #ifdef DEBUG_LEGAL printf("NO GAS %d\n", a); #endif return false; } // if we have no mineral income we'll never have a minerla unit bool noMoney = (mineralWorkers == 0) && (progress.numInProgress(DATA.getWorker()) == 0); if (((DATA[a].mineralPrice() - minerals) > 0) && noMoney) { #ifdef DEBUG_LEGAL printf("NO MONEY %d\n", a); #endif return false; } // don't build more refineries than resource depots if (DATA[a].isRefinery() && (getNumUnits(DATA.getRefinery()) >= getNumUnits(DATA.getResourceDepot()))) { #ifdef DEBUG_LEGAL printf("NOT ENOUGH DEPOTS FOR REFINERY %d", a); #endif return false; } // we don't need to go over the maximum supply limit with supply providers if (DATA[a].isSupplyProvider() && (maxSupply + getSupplyInProgress() >= 400)) { #ifdef DEBUG_LEGAL printf("TOO MUCH SUPPLY FOR PROVIDER %d\n", a); #endif return false; } #ifdef DEBUG_LEGAL printf("Action Legal %d\n", a); #endif return true; } // does the current state meet the goal requirements bool meetsGoal(const StarcraftSearchGoal & goal) const { // for each unit in the array for (int i=0; i<MAX_ACTIONS; ++i) { // if we don't have enough of them, no good if (getNumUnits(i) < goal.get(i)) { return false; } } // otherwise it's fine return true; } bool meetsGoalCompleted(const StarcraftSearchGoal & goal) const { if (minerals < goal.getMineralGoal() || gas < goal.getGasGoal()) { return false; } // for each unit in the array for (int i=0; i<MAX_ACTIONS; ++i) { // if we don't have enough of them, no good if (numUnits[i] < goal.get(i)) return false; } // otherwise it's fine return true; } bool meetsConstraints(const StarcraftSearchConstraints & ssc) const { for (int i=0; i<ssc.size(); ++i) { StarcraftSearchConstraint & c = ssc.getConstraint(i); if (currentFrame > c.frame && numUnits[c.action] < c.actionCount) { return false; } } return true; } /********************************************************************************** * * Getter + Setter Functions * **********************************************************************************/ int getCurrentFrame() const { return currentFrame; } ActionSet getCompletedUnitSet() const { return completedUnitSet; } ActionSet getProgressUnitSet() const { return progressUnitSet; } Action getActionPerformed() const { return actionPerformed; } void setParent(StarcraftState * p) { parent = p; } StarcraftState * getParent() const { return parent; } ActionSet getUnitsCompleteAndProgress() const { return completedUnitSet + progressUnitSet; } int getLastFinishTime() const { return progress.getLastFinishTime(); } int getWorkerCount() const { return getNumUnits(DATA.getWorker()); } int getNumResourceDepots() const { return getNumUnits(DATA.getResourceDepot()); } // sets a bitmask of units we have based on the unit count array void setUnitMask() { // reset the bits completedUnitSet = 0; // for each possible action for (int i=0; i<DATA.size(); ++i) { // if we have more than 0 of the unit, set the bit to 1 if (numUnits[i] > 0) completedUnitSet.add(i); } } // sets the progress mask based on the progress vector inline void setProgressMask() { // reset the bits progressUnitSet = ActionSet(__ZERO); // for each unit in the inProgress vector for (int i(0); i<progress.size(); ++i) { // set the bit of the progress mask appropriately progressUnitSet.add(progress.getAction(i)); } } void addBuilding(const int action, const int timeUntilFree) { buildings.addBuilding(action, timeUntilFree); } void addActionInProgress(const int action, const int completionFrame) { // add it to the actions in progress progress.addAction(action, completionFrame); // update the progress bitmask progressUnitSet.add(action); } // add a number of a unit type void addNumUnits(const int t, const char d) { // set the unit amount appropriately numUnits[t] += d; // if the new number is more than zero, set the bit in the unitMask if (numUnits[t] > 0) { completedUnitSet.add(t); } // otherwise, clear the bit in the unitMask else { completedUnitSet.subtract(t); } } // set the number of a particular unit type void setNumUnits(const int t, const unsigned char n) { // set the unit amount appropriately numUnits[t] = n; // if the new number is more than zero, set the bit in the unitMask if (numUnits[t] > 0) { completedUnitSet.add(t); } // otherwise, clear the bit in the unitMask else { completedUnitSet.subtract(t); } } void setFrame(const int frame) { currentFrame = frame; } void setSupply(const int cSupply, const int mSupply) { currentSupply = cSupply; maxSupply = mSupply; } void setResources(const int m, const int g) { minerals = m; gas = g; } int getNumUnits(const int t) const { return numUnits[t] + (progress[t] * DATA[t].numProduced()); } void setActionPerformedK(const unsigned char k) { actionPerformedK = k; } int getActionPerformedK() const { return actionPerformedK; } int getSupplyInProgress() const { int supplyInProgress = progress[DATA.getSupplyProvider()]*DATA[DATA.getSupplyProvider()].supplyProvided() + progress[DATA.getResourceDepot()]*DATA[DATA.getResourceDepot()].supplyProvided(); return supplyInProgress; } bool hasEnoughSupplyForGoal(const StarcraftSearchGoal & goal) const { int goalSupplyNeeded = 0; for (int a=0; a<DATA.size(); ++a) { int unitsNeeded = (getNumUnits(a)) - goal[a]; if (unitsNeeded > 0) { goalSupplyNeeded += DATA[a].supplyRequired(); } } return (maxSupply - currentSupply) >= goalSupplyNeeded; } bool meetsActionGoal(const StarcraftSearchGoal & goal, const Action a) const { return getNumUnits(a) >= goal[a]; } // determines if an action has prerequisites met via bitmask operations bool hasRequirements(const ActionSet required) const { return (completedUnitSet + progressUnitSet).contains(required); } // setters void setMineralWorkers (const unsigned char mw) { mineralWorkers = mw; } void setGasWorkers (const unsigned char gw) { gasWorkers = gw; } void addMineralWorkers (const int d) { mineralWorkers = mineralWorkers+d; } void addGasWorkers (const int d) { gasWorkers = gasWorkers+d;} // getter methods for the internal variables double getMineralsPerFrame() const { return DATA.mpwpf * mineralWorkers; } double getGasPerFrame() const { return DATA.gpwpf * gasWorkers; } int getMaxSupply() const { return maxSupply; } int getCurrentSupply() const { return currentSupply; } unsigned char getMineralWorkers() const { return mineralWorkers; } unsigned char getGasWorkers() const { return gasWorkers; } int getMinerals() const { return minerals; } int getGas() const { return gas; } int getMinerals(const int frame) const { //assert(frame >= currentFrame); return minerals + (int)(getMineralsPerFrame() * (frame-currentFrame)); } int getGas(const int frame) const { //assert(frame >= currentFrame); return gas + (int)(getGasPerFrame() * (frame-currentFrame)); } int getFinishTimeMinerals() const { return getMinerals(getLastFinishTime()); } int getFinishTimeGas() const { return getGas(getLastFinishTime()); } void printData() const { printf("\n-----------------------------------------------------------\n"); printf("TEST %d\n", minerals); printf("Current Frame: %d (%dm %ds)\n\n", currentFrame, (currentFrame / 24) / 60, (currentFrame / 24) % 60); printf("Completed:\n\n"); for (int i=0; i<MAX_ACTIONS; i++) if (numUnits[i] > 0) { printf("\t%d\t%s\n", numUnits[i], DATA[i].getName().c_str()); } printf("\nIn Progress:\n\n"); for (int i(0); i<progress.size(); i++) { printf("\t%d\t%s\n", progress.getTime(i), DATA[progress.getAction(i)].getName().c_str()); } //printf("\nLegal Actions:\n\n"); //LOOP_BITS (getLegalActions(), action) { // // printf("\t%s\n", data->action_strings[action].c_str()); //} printf("\n%6d Minerals\n%6d Gas\n%6d Max Supply\n%6d Current Supply\n", minerals, gas, maxSupply, currentSupply); printf("\n%6d Mineral Drones\n%6d Gas Drones\n", mineralWorkers, gasWorkers); printf("\n-----------------------------------------------------------\n"); //printPath(); } /*void printDataToFile(std::string fileName) { FILE * fout = fopen(fileName.c_s1tr(), "w"); fprintf(fout, "\n-----------------------------------------------------------\n"); fprintf(fout, "TEST %d\n", minerals); fprintf(fout, "Current Frame: %d (%dm %ds)\n\n", currentFrame, (currentFrame / 24) / 60, (currentFrame / 24) % 60); fprintf(fout, "Completed:\n\n"); for (int i=0; i<MAX_ACTIONS; i++) if (numUnits[i] > 0) { fprintf(fout, "\t%d\t%s\n", numUnits[i], DATA[i].getName().c_str()); } fprintf(fout, "\nIn Progress:\n\n"); for (int i(0); i<progress.size(); i++) { fprintf(fout, "\t%d\t%s\n", progress.getTime(i), DATA[progress.getAction(i)].getName().c_str()); } fprintf(fout, "\n%6d Minerals\n%6d Gas\n%6d Max Supply\n%6d Current Supply\n", minerals, gas, maxSupply, currentSupply); fprintf(fout, "\n%6d Mineral Drones\n%6d Gas Drones\n", mineralWorkers, gasWorkers); fprintf(fout, "\n-----------------------------------------------------------\n"); //printPath(); }*/ }; #endif
[ "[email protected]@ce23f72d-95c0-fd94-fabd-fc6dce850bd1" ]
[ [ [ 1, 1424 ] ] ]
b435bd2da98d81f3a1cf5018c1f6e81435232412
48b240bc1b62cd94a34197f74beaceddb410f657
/src/socketbuffermanager.cpp
5699625260f5e7f0ce1e05dbdf65cb64073728f4
[]
no_license
sctnightcore/SocketBuffer
fd1073a483128cd64d72bc3a6f0250077058244e
917f82f8e410ea24e74dd0e06dd265d7779cdbb8
refs/heads/master
2021-01-19T18:24:15.226631
2011-09-10T06:07:46
2011-09-10T06:07:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,396
cpp
#include "socketbuffermanager.h" #include <iostream> using namespace std; SocketBufferManager::SocketBufferManager(QString target, bool server, int inPort, int outPort, bool debug) : QObject(0) { this->debug = debug; this->outHost = target; this->outPort = outPort; this->connect(&this->listener, SIGNAL(newConnection()), this, SLOT(gotConnection())); this->listener.listen(server ? QHostAddress::Any : QHostAddress::LocalHost, inPort); if (this->debug) { cout << "DEBUG ENABLED" << endl; } } void SocketBufferManager::gotConnection() { while (this->listener.hasPendingConnections()) { QTcpSocket* incoming = this->listener.nextPendingConnection(); QTcpSocket* outgoing = new QTcpSocket(); outgoing->connectToHost(this->outHost, this->outPort); ServerPair* s = new ServerPair(incoming, outgoing); this->connect(s, SIGNAL(selfDestruct(ServerPair*)), this, SLOT(disconnected(ServerPair*))); this->sockets.append(s); if (this->debug) { cout << "Got Connection: " << incoming->peerAddress().toString().toAscii().data() << endl; } } } void SocketBufferManager::disconnected(ServerPair *pair) { this->sockets.removeAll(pair); if (this->debug) { cout << "Disconnected" << endl; } }
[ [ [ 1, 50 ] ] ]
d44a577506f8edc3042befcfbb5c711f3c85f083
2e49d76d75832667626f69bf7271f9076cef6dd7
/TableProcessor/TableProcessor/TableProcessor.cpp
d8c572aea25c04e8084e426125730e7c2a1bfdf7
[]
no_license
plastiv/simple-table-processor
c91d722465386976e4921ecc0e7666c4f725327b
d7211631177119aabacd3cd19132d6c481a165ef
refs/heads/master
2021-01-17T04:32:38.182917
2011-11-09T14:15:46
2011-11-09T14:15:46
34,895,455
0
0
null
null
null
null
UTF-8
C++
false
false
1,180
cpp
// TableProcessor.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Table.h" #include <fstream> #include <cstdlib> #include <iterator> #include <string> #include <sstream> #include <stdexcept> // Error message function for TableProcessor void error(const char* why, const char* what="") { std::cerr << why << ' ' << what << endl; cout << "The program has terminated!" << endl; exit(1); } int main(int argc, char* argv[]) { // Expected 2 parameters inputFileName.txt outputFileName.txt if (argc != 3 ) error ("wrong number of arguments"); std::cout << "Read table from file " << argv[1]<< endl; std::ifstream inputFile(argv[1]); //open input file stream if (!inputFile) error ("cannot open input file", argv[1]); Table table; inputFile >> table; std::cout << table << endl; table.processAllCells(); std::cout << "Processed table" << endl << table << endl; std::cout << "Write table to file " << argv[2] << endl; std::ofstream outputFile(argv[2]); //open output file stream if (!outputFile) error ("cannot open output file", argv[2]); outputFile << table; return 0; }
[ "plastiv@fb4b1917-370a-0c84-de19-b6e0e16a7844" ]
[ [ [ 1, 44 ] ] ]
c0ab45be93d3ae4362ee31f96de2623658b2158b
3970f1a70df104f46443480d1ba86e246d8f3b22
/imebra/src/base/include/thread.h
92cd21d64144960ac334a12230bbcdcb1a284760
[]
no_license
zhan2016/vimrid
9f8ea8a6eb98153300e6f8c1264b2c042c23ee22
28ae31d57b77df883be3b869f6b64695df441edb
refs/heads/master
2021-01-20T16:24:36.247136
2009-07-28T18:32:31
2009-07-28T18:32:31
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
7,857
h
/* 0.0.46 Imebra: a C++ dicom library. Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 by Paolo Brandoli This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 for more details. You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 along with this program; If not, see http://www.gnu.org/licenses/ ------------------- If you want to use Imebra commercially then you have to buy the commercial license available at http://puntoexe.com After you buy the commercial license then you can use Imebra according to the terms described in the Imebra Commercial License Version 1. A copy of the Imebra Commercial License Version 1 is available in the documentation pages. Imebra is available at http://puntoexe.com The author can be contacted by email at [email protected] or by mail at the following address: Paolo Brandoli Preglov trg 6 1000 Ljubljana Slovenia */ /*! \file thread.h \brief Declaration of a class that represents the threads. The class in this file hide the platform specific features and supply a common interface to the threads. */ #if !defined(CImbxThread_F1BAF067_21DE_466b_AEA1_6CC4F006FAFA__INCLUDED_) #define CImbxThread_F1BAF067_21DE_466b_AEA1_6CC4F006FAFA__INCLUDED_ #include "baseObject.h" #ifdef PUNTOEXE_WINDOWS #include "windows.h" #else #include <pthread.h> // this must be the first included file #endif #include <exception> #include <stdexcept> #include <list> #include <typeinfo> namespace puntoexe { /// \brief This class represents a thread. /// /// The thread can be started with thread::start(). /// Once the thread is started, the virtual functionů /// threadFunction() is executed in a separate thread. /// /// The code in threadFunction() can call shouldTerminate() /// to know when the thread should be terminated /// gracefully as soon as possible. /// /// The function terminate() can be called to inform the /// thread that it should terminate. /// terminate() is called automatically by the thread /// destructor which also waits for the thread termination /// before deallocating it and returning. /// /////////////////////////////////////////////////////////// class thread: public baseObject { public: /// \brief Construct the thread. /// /// Your application has to call start() in order to start /// the thread function. /// /////////////////////////////////////////////////////////// thread(); /// \internal /// \brief Called when the thread's reference counter /// reaches zero. /// /// Calls terminate() in order to signal to the thread that /// it has to terminate as soon as possible, then wait /// for the thread termination before returning. /// /// @return always true /// /////////////////////////////////////////////////////////// virtual bool preDelete(); /// \brief This function is executed in another thread when /// start() is called. /// /// The code in this function can call shouldTerminate() /// to know when another thread has requested its /// termination. /// /// This function has to be implemented in a derived class. /// /////////////////////////////////////////////////////////// virtual void threadFunction()=0; /// \brief Execute the function threadFunction() in a /// separate thread. /// /////////////////////////////////////////////////////////// void start(); /// \brief Communicates to the thread that it should /// terminate as soon as possible. /// /// A call to shouldTerminate() returns true after this /// function has been called. /// /////////////////////////////////////////////////////////// void terminate(); /// \brief Returns true if the function threadFunction() /// should return as soon as possible. /// /// @return true if the function threadFunction() should /// return as soon as possible /// /////////////////////////////////////////////////////////// bool shouldTerminate(); /// \brief Return true if the function threadFunction() is /// running in its own thread. /// /// @return true if the function threadFunction() is /// running in its own thread /// /////////////////////////////////////////////////////////// bool isRunning(); #ifdef PUNTOEXE_WINDOWS typedef DWORD tThreadId; #else typedef void* tThreadId; #endif /// \brief Return a number that identifies the active /// thread. /// /// Please note that this isn't the thread handle, but a /// number that is different for each running thread. /// /// When a thread terminates the number could be used to /// identify another thread. /// /// @return an id for the currently active thread /// /////////////////////////////////////////////////////////// static tThreadId getThreadId(); /// \brief Switch to another thread. /// /// The current thread is stopped and the following thrad /// scheduled to be executed on the processor is started. /// /////////////////////////////////////////////////////////// static void yield(); private: #ifdef PUNTOEXE_WINDOWS static unsigned int __stdcall privateThreadFunction(void* pParameter); #else static void* privateThreadFunction(void* pParameter); #endif // This is the thread handle. Is used to join the thread /////////////////////////////////////////////////////////// #ifdef PUNTOEXE_WINDOWS HANDLE m_threadHandle; #else pthread_t m_threadHandle; #endif bool m_bThreadHandleValid; criticalSection m_lockThreadHandle; // true if the thread should terminate /////////////////////////////////////////////////////////// bool m_bTerminate; criticalSection m_lockTerminateFlag; // true if the thread's function is running /////////////////////////////////////////////////////////// bool m_bIsRunning; criticalSection m_lockRunningFlag; #ifdef PUNTOEXE_POSIX public: static pthread_key_t* getSharedKey(); static void* getNextId(); // Force the construction of the creation of a shared // key for all the threads (pthread_key_create) /////////////////////////////////////////////////////////// class forceKeyConstruction { public: forceKeyConstruction() { thread::getSharedKey(); thread::getNextId(); } }; private: class sharedKey { public: pthread_key_t m_key; sharedKey() { pthread_key_create(&m_key, 0); } }; #endif }; /// \brief This is used as the base class for the /// exceptions thrown by the class thread. /// /////////////////////////////////////////////////////////// class threadException: public std::runtime_error { public: threadException(std::string message): std::runtime_error(message){} }; /// \brief Exception thrown by thread when an attempt to /// run an already running thread is made. /// /////////////////////////////////////////////////////////// class threadExceptionAlreadyRunning: public threadException { public: threadExceptionAlreadyRunning(std::string message): threadException(message){} }; class threadExceptionFailedToLaunch: public threadException { public: threadExceptionFailedToLaunch(std::string message): threadException(message){} }; } // namespace puntoexe #endif // !defined(CImbxThread_F1BAF067_21DE_466b_AEA1_6CC4F006FAFA__INCLUDED_)
[ [ [ 1, 274 ] ] ]
14dc8d86a6335044b0831eaa006a471d5e0ab382
011359e589f99ae5fe8271962d447165e9ff7768
/src/burner/misc.cpp
43843135f336e4ebc470a5d7f0dbfc92374239e4
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
2,846
cpp
// Misc functions module #include <math.h> #include "burner.h" // ---------------------------------------------------------------------------- // Software gamma, brightness and contrast adjust, added by regret // ref: bsnes int bcolorAdjust = 0; int color_gamma = 0; int color_brightness = 0; int color_contrast = 0; int color_grayscale = 0; int color_invert = 0; static unsigned char contrast_adjust(unsigned char input) { signed result = input - color_contrast + (2 * color_contrast * input + 127) / 255; return max(0, min(255, result)); } static unsigned char brightness_adjust(unsigned char input) { signed result = input + color_brightness; return max(0, min(255, result)); } static unsigned char gamma_adjust(unsigned char input) { signed result = (signed)(pow(((double)input / 255.0), (double)(100 + color_gamma) / 100.0) * 255.0 + 0.5); return max(0, min(255, result)); } void colorAdjust(int& r, int& g, int& b) { if (!bcolorAdjust) return; double kr = 0.2126, kb = 0.0722, kg = (1.0 - kr - kb); //luminance weights if (color_contrast != 0) { r = contrast_adjust(r); g = contrast_adjust(g); b = contrast_adjust(b); } if (color_brightness != 0) { r = brightness_adjust(r); g = brightness_adjust(g); b = brightness_adjust(b); } if (color_gamma != 0) { r = gamma_adjust(r); g = gamma_adjust(g); b = gamma_adjust(b); } if (color_grayscale) { signed l = (signed)((double)r * kr + (double)g * kg + (double)b * kb); l = max(0, min(255, l)); r = g = b = l; } if (color_invert) { r ^= 0xff; g ^= 0xff; b ^= 0xff; } } // Standard callbacks for 16/24/32 bit color: static unsigned int __cdecl HighCol15(int r, int g, int b, int /* i */) { colorAdjust(r, g, b); unsigned int t; t = (r << 7) & 0x7c00; // 0rrr rr00 0000 0000 t |= (g << 2) & 0x03e0; // 0000 00gg ggg0 0000 t |= (b >> 3) & 0x001f; // 0000 0000 000b bbbb return t; } static unsigned int __cdecl HighCol16(int r, int g, int b, int /* i */) { colorAdjust(r, g, b); unsigned int t; t = (r << 8) & 0xf800; // rrrr r000 0000 0000 t |= (g << 3) & 0x07e0; // 0000 0ggg ggg0 0000 t |= (b >> 3) & 0x001f; // 0000 0000 000b bbbb return t; } // 24-bit/32-bit static unsigned int __cdecl HighCol24(int r, int g, int b, int /* i */) { colorAdjust(r, g, b); unsigned int t; t = (r << 16) & 0xff0000; t |= (g << 8 ) & 0x00ff00; t |= (b ) & 0x0000ff; return t; } int SetBurnHighCol(int nDepth) { VidRecalcPal(); if (nDepth == 15) VidHighCol = HighCol15; else if (nDepth == 16) VidHighCol = HighCol16; else if (nDepth > 16) VidHighCol = HighCol24; if (bDrvOkay && !(BurnDrvGetFlags() & BDF_16BIT_ONLY) || nDepth <= 16) BurnHighCol = VidHighCol; return 0; }
[ [ [ 1, 122 ] ] ]
a32a1dcc0efa52980a890ab0ae14e961658c8dbb
53ee90fbc1011cb17ba013d0a49812697d4e6130
/Arduino/RobinProcessor01/CMotorBoard.h
84f5651d863cd14e925c0a574d160aebb85ed58a
[]
no_license
janoschtraumstunde/Robin
c3f68667c37c44e19473119b4b9b9be0fe2fb57f
bd691cbd2a0091e5100df5dfe1268d27c99b39f6
refs/heads/master
2021-01-12T14:06:44.095094
2010-12-09T14:34:27
2010-12-09T14:34:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,169
h
#include <WProgram.h> #include <Wire.h> #include "CommandData.h" class MotorBoard { static CommandData cmdData; static union CommandUnion cmdUnion; public: static void sendCommand(char command) { sendCommand(command, 0, 0, 0, 1); } static void sendCommand(char command, int first) { sendCommand(command, first, 0, 0, 3); } static void sendCommand(char command, int first, int second) { sendCommand(command, first, second, 0, 5); } static void sendCommand(char command, int first, int second, int third) { sendCommand(command, first, second, third, 7); } private: static void sendCommand(char command, int first, int second, int third, int byteCount) { cmdData.command = command; cmdData.first = first; cmdData.second = second; cmdData.third = third; sendCommand(cmdData, byteCount); } static void sendCommand(struct CommandData &cmd, int byteCount) { Wire.beginTransmission(1); cmdUnion.command = cmd; for (int i = 0; i < byteCount; i++) { Wire.send(cmdUnion.bytes[i]); } Wire.endTransmission(); } }; CommandData MotorBoard::cmdData; CommandUnion MotorBoard::cmdUnion;
[ [ [ 1, 47 ] ] ]
a4a51789febf5317f13c2610c37727fdb153e87d
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestpopups/inc/bctestheadingpanecase.h
53f5e2c62f6d67f1fa9d2324fbffc05626f0ae8c
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,783
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Declares test bc for heading pane testcase. * */ #ifndef C_CBCTESTHEADINGPANECASE_H #define C_CBCTESTHEADINGPANECASE_H #include "bctestcase.h" class CBCTestPopupsContainer; class CCoeControl; /** * test case for various popups classes */ class CBCTestHeadingPaneCase: public CBCTestCase { public: // constructor and destructor /** * Symbian 2nd static constructor */ static CBCTestHeadingPaneCase* NewL( CBCTestPopupsContainer* aContainer ); /** * Destructor */ virtual ~CBCTestHeadingPaneCase(); // from CBCTestCase /** * Execute corresponding test functions for UI command * @param aCmd, UI command */ void RunL( TInt aCmd ); protected: // new functions /** * Build autotest script */ void BuildScriptL(); /** * TestHeadingPaneL function */ void TestHeadingPaneL(); private: // constructor /** * C++ default constructor */ CBCTestHeadingPaneCase( CBCTestPopupsContainer* aContainer ); /** * Symbian 2nd constructor */ void ConstructL(); private: // data /** * Pointer to container. * not own */ CBCTestPopupsContainer* iContainer; }; #endif // C_CBCTESTHEADINGPANECASE_H
[ "none@none" ]
[ [ [ 1, 86 ] ] ]
ea6b062de42299e52000b252cc5837ef9656c0f5
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D10/D3D10Include.h
542e3d07340211fd6426637b2993c93168dd4715
[]
no_license
midnite8177/phever
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
45529e80ebf707e7299887165821ca360aa1907d
refs/heads/master
2020-05-16T21:59:24.201346
2010-07-12T23:51:53
2010-07-12T23:51:53
34,965,829
3
2
null
null
null
null
UTF-8
C++
false
false
2,194
h
//Copyright (c) Microsoft Corporation. All rights reserved. #pragma once #include "DirectObject.h" namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct3D10 { using namespace System; using namespace Microsoft::WindowsAPICodePack::DirectX; /// <summary> /// An include interface allows an application to create user-overridable methods for opening and closing files when loading an effect from memory. This class does not inherit from anything, but does declare the following methods: /// <para>(Also see DirectX SDK: ID3D10Include)</para> /// </summary> public ref class Include : public DirectObject { public: /// <summary> /// A user-implemented method for closing a shader #include file. /// <para>(Also see DirectX SDK: ID3D10Include::Close)</para> /// </summary> /// <param name="data">Pointer to the returned buffer that contains the include directives. This is the pointer that was returned by the corresponding Include.Open call.</param> void Close(IntPtr data); /// <summary> /// A user-implemented method for opening and reading the contents of a shader #include file. /// <para>(Also see DirectX SDK: ID3D10Include::Open)</para> /// </summary> /// <param name="includeType">The location of the #include file. See IncludeType.</param> /// <param name="fileName">Name of the #include file.</param> /// <param name="parentData">Pointer to the container that includes the #include file.</param> /// <param name="bytes">Number of bytes returned.</param> /// <returns>Pointer to the returned buffer that contains the include directives. This pointer remains valid until Include.Close() is called.</returns> IntPtr Open(IncludeType includeType, String^ fileName, IntPtr parentData, [System::Runtime::InteropServices::Out] UInt32 % bytes); internal: Include() { } Include(ID3D10Include* pNativeID3D10Include) : DirectObject(pNativeID3D10Include) { } }; } } } }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 48 ] ] ]
2537f86d1a6b7ced2fa0de14695633fc64eb2388
216398e30aca5f7874edfb8b72a13f95c22fbb5a
/Healthcare/Common/CommonType.h
38f47cf505f15baa8b1805679a10195b19e06b46
[]
no_license
markisme/healthcare
791813ac6ac811870f3f28d1d31c3d5a07fb2fa2
7ab5a959deba02e7637da02a3f3c681548871520
refs/heads/master
2021-01-10T07:18:42.195610
2009-09-09T13:00:10
2009-09-09T13:00:10
35,987,767
0
0
null
null
null
null
UTF-8
C++
false
false
705
h
#pragma once #include <vector> struct PacketData { PacketData( int x = 0, int y = 0 ) : _x( x ), _y( y ) {}; ~PacketData() {}; int _x; int _y; int _temp; }; typedef std::vector<PacketData> DataList; struct UserInfo { std::string _userNo; std::string _userName; std::string _age; std::string _sex; std::string _tall; std::string _weight; std::string _blood; std::string _tel; std::string _pic; }; typedef std::vector<UserInfo> UserList; struct UserData { std::string _year; std::string _month; std::string _day; std::string _hour; std::string _min; std::string _value; std::string _temp; }; typedef std::vector<UserData> UserDataList;
[ "naidzzang@cc586c1e-b153-0410-8069-cfc9d6f95ec9" ]
[ [ [ 1, 43 ] ] ]
ba787404be5f585192cdb70a71d65dfdb7196e58
c0c44b30d6a9fd5896fd3dce703c98764c0c447f
/cpp/Targets/MapLib/Shared/include/InfoBoxInterface.h
6daf0795a77e68468192cd258d5dd98742508f8e
[ "BSD-3-Clause" ]
permissive
wayfinder/Wayfinder-CppCore-v2
59d703b3a9fdf4a67f9b75fbbf4474933aeda7bf
f1d41905bf7523351bc0a1a6b08d04b06c533bd4
refs/heads/master
2020-05-19T15:54:41.035880
2010-06-29T11:56:03
2010-06-29T11:56:03
744,294
1
0
null
null
null
null
UTF-8
C++
false
false
1,871
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef INFO_BOX_INTERFACE_H #define INFO_BOX_INTERFACE_H class InfoBoxInterface { public: /** * Virtual destructor. */ virtual ~InfoBoxInterface() {} /** * Set the text for the info box in utf8. */ virtual void setText( const char* utf8Text ) const = 0; }; #endif
[ [ [ 1, 31 ] ] ]
b6a1654b9eb5d1ed1f56e3b2ff1eb38da3d0a29c
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/terralib/drivers/qt/TeQtGraph.h
5844a706ad7553300de90d56813da17999aafc15
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,078
h
/************************************************************************************ TerraView - visualization and exploration of geographical databases using TerraLib. Copyright © 2001-2004 INPE and Tecgraf/PUC-Rio. This file is part of TerraView. TerraView is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with TerraView. The authors reassure the license terms regarding the warranties. They specifically disclaim any warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The software provided hereunder is on an "as is" basis, and the authors have no obligation to provide maintenance, support, updates, enhancements, or modifications. In no event shall INPE and Tecgraf / PUC-Rio be held liable to any party for direct, indirect, special, incidental, or consequential damages arising out of the use of this program and its documentation. *************************************************************************************/ #ifndef __TERRALIB_INTERNAL_QTGRAPH_H #define __TERRALIB_INTERNAL_QTGRAPH_H #include <qwidget.h> #include <qpainter.h> #include <qpixmap.h> #include "TeGraph.h" class TeQtGraphPlot : public TeGraphPlot { public : TeQtGraphPlot (QWidget *parent=0, const char *name=0); ~TeQtGraphPlot (); virtual void plot (); void plotRectangle (int x, int y, int dx, int dy); void value_to_pixel(double px, double py, int* x, int* y); int pwidth_; int pheight_; int getWidth (); int getHeight (); QPixmap* getPixmap() {return pixmap_;} QWidget* widget_; void plotOnWindow(); void plotOnPixmap(); void copyPixmapToWindow(); void copyPixmapToWindow(int, int, int, int); void copyPixmapToPrinter(); void setLineAttributes (TeColor c, int , int ); void setFillAreaColor (TeColor c); void setTextColor (TeColor c); void fillRectangle (int x, int y, int dx, int dy); void drawRectangle (int x, int y, int dx, int dy); void drawLine (int sx, int sy, int dx, int dy); void drawText (int x, int y, char*t, double angle = 0); void fillArc (int xc, int yc, int w, int h, double a1, double a2, TeColor c); void drawArc (int xc, int yc, int w, int h, double a1, double a2, TeColor c); void textExtent ( string &str, int &w, int &h, double angle = 0.); void resize(int, int); private : QPainter painter_; QPixmap* pixmap_; QPen linePen_; QColor lineColor_; QBrush polygonBrush_; QColor polygonColor_; QPen textPen_; map<TePolyBasicType, Qt::BrushStyle> brushStyleMap_; map<TeLnBasicType, Qt::PenStyle> penStyleMap_; }; class TePlotWidget : public TeQtGraphPlot { public: // Initialization TePlotWidget(QWidget *parent=0, const char *name=0); ~TePlotWidget() {} void erase (int order = 0); void plot (); }; #endif
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 83 ] ] ]
abf195412ece23626660751f02d68a0d1bb83feb
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Source/Intersection/WmlIntrLin3Cyl3.cpp
a4896b65c63e807d89ef12ee0e575703d222b0ab
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
13,431
cpp
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. #include "WmlIntrLin3Cyl3.h" #include "WmlDistLin3Lin3.h" using namespace Wml; //---------------------------------------------------------------------------- template <class Real> static int Find (const Vector3<Real>& rkOrigin, const Vector3<Real>& rkDirection, const Cylinder3<Real>& rkCylinder, Real afT[2]) { // set up quadratic Q(t) = a*t^2 + 2*b*t + c Vector3<Real> kU, kV, kW = rkCylinder.Direction(); Vector3<Real>::GenerateOrthonormalBasis(kU,kV,kW,true); Vector3<Real> kD(kU.Dot(rkDirection),kV.Dot(rkDirection), kW.Dot(rkDirection)); Real fDLength = kD.Normalize(); Real fInvDLength = ((Real)1.0)/fDLength; Vector3<Real> kDiff = rkOrigin - rkCylinder.Center(); Vector3<Real> kP(kU.Dot(kDiff),kV.Dot(kDiff),kW.Dot(kDiff)); Real fHalfHeight = ((Real)0.5)*rkCylinder.Height(); Real fRadiusSqr = rkCylinder.Radius()*rkCylinder.Radius(); Real fInv, fA, fB, fC, fDiscr, fRoot, fT, fT0, fT1, fTmp0, fTmp1; if ( Math<Real>::FAbs(kD.Z()) >= (Real)1.0 - Math<Real>::EPSILON ) { // line is parallel to cylinder axis if ( kP.X()*kP.X()+kP.Y()*kP.Y() <= fRadiusSqr ) { fTmp0 = fInvDLength/kD.Z(); afT[0] = (+fHalfHeight - kP.Z())*fTmp0; afT[1] = (-fHalfHeight - kP.Z())*fTmp0; return 2; } else { return 0; } } if ( Math<Real>::FAbs(kD.Z()) <= Math<Real>::EPSILON ) { // line is perpendicular to axis of cylinder if ( Math<Real>::FAbs(kP.Z()) > fHalfHeight ) { // line is outside the planar caps of cylinder return 0; } fA = kD.X()*kD.X() + kD.Y()*kD.Y(); fB = kP.X()*kD.X() + kP.Y()*kD.Y(); fC = kP.X()*kP.X() + kP.Y()*kP.Y() - fRadiusSqr; fDiscr = fB*fB - fA*fC; if ( fDiscr < (Real)0.0 ) { // line does not intersect cylinder wall return 0; } else if ( fDiscr > (Real)0.0 ) { fRoot = Math<Real>::Sqrt(fDiscr); fTmp0 = fInvDLength/fA; afT[0] = (-fB - fRoot)*fTmp0; afT[1] = (-fB + fRoot)*fTmp0; return 2; } else { afT[0] = -fB*fInvDLength/fA; return 1; } } // test plane intersections first int iQuantity = 0; fInv = ((Real)1.0)/kD.Z(); fT0 = (+fHalfHeight - kP.Z())*fInv; fTmp0 = kP.X() + fT0*kD.X(); fTmp1 = kP.Y() + fT0*kD.Y(); if ( fTmp0*fTmp0 + fTmp1*fTmp1 <= fRadiusSqr ) afT[iQuantity++] = fT0*fInvDLength; fT1 = (-fHalfHeight - kP.Z())*fInv; fTmp0 = kP.X() + fT1*kD.X(); fTmp1 = kP.Y() + fT1*kD.Y(); if ( fTmp0*fTmp0 + fTmp1*fTmp1 <= fRadiusSqr ) afT[iQuantity++] = fT1*fInvDLength; if ( iQuantity == 2 ) { // line intersects both top and bottom return 2; } // If iQuantity == 1, then line must intersect cylinder wall // somewhere between caps in a single point. This case is detected // in the following code that tests for intersection between line and // cylinder wall. fA = kD.X()*kD.X() + kD.Y()*kD.Y(); fB = kP.X()*kD.X() + kP.Y()*kD.Y(); fC = kP.X()*kP.X() + kP.Y()*kP.Y() - fRadiusSqr; fDiscr = fB*fB - fA*fC; if ( fDiscr < (Real)0.0 ) { // line does not intersect cylinder wall assert( iQuantity == 0 ); return 0; } else if ( fDiscr > (Real)0.0 ) { fRoot = Math<Real>::Sqrt(fDiscr); fInv = ((Real)1.0)/fA; fT = (-fB - fRoot)*fInv; if ( fT0 <= fT1 ) { if ( fT0 <= fT && fT <= fT1 ) afT[iQuantity++] = fT*fInvDLength; } else { if ( fT1 <= fT && fT <= fT0 ) afT[iQuantity++] = fT*fInvDLength; } if ( iQuantity == 2 ) { // Line intersects one of top/bottom of cylinder and once on // cylinder wall. return 2; } fT = (-fB + fRoot)*fInv; if ( fT0 <= fT1 ) { if ( fT0 <= fT && fT <= fT1 ) afT[iQuantity++] = fT*fInvDLength; } else { if ( fT1 <= fT && fT <= fT0 ) afT[iQuantity++] = fT*fInvDLength; } } else { fT = -fB/fA; if ( fT0 <= fT1 ) { if ( fT0 <= fT && fT <= fT1 ) afT[iQuantity++] = fT*fInvDLength; } else { if ( fT1 <= fT && fT <= fT0 ) afT[iQuantity++] = fT*fInvDLength; } } return iQuantity; } //---------------------------------------------------------------------------- template <class Real> static int FindHollow (const Vector3<Real>& rkOrigin, const Vector3<Real>& rkDirection, const Cylinder3<Real>& rkCylinder, Real afT[2]) { // set up quadratic Q(t) = a*t^2 + 2*b*t + c Vector3<Real> kU, kV, kW = rkCylinder.Direction(); Vector3<Real>::GenerateOrthonormalBasis(kU,kV,kW,true); Vector3<Real> kD(kU.Dot(rkDirection),kV.Dot(rkDirection), kW.Dot(rkDirection)); Real fDLength = kD.Normalize(); Real fInvDLength = ((Real)1.0)/fDLength; Vector3<Real> kDiff = rkOrigin - rkCylinder.Center(); Vector3<Real> kP(kU.Dot(kDiff),kV.Dot(kDiff),kW.Dot(kDiff)); Real fHalfHeight = ((Real)0.5)*rkCylinder.Height(); Real fRadiusSqr = rkCylinder.Radius()*rkCylinder.Radius(); Real fA, fB, fC, fDiscr, fRoot, fT; if ( Math<Real>::FAbs(kD.Z()) >= (Real)1.0 - Math<Real>::EPSILON ) { // line is parallel to cylinder axis if ( kP.X()*kP.X() + kP.Y()*kP.Y() != fRadiusSqr ) { // line inside or outside the cylinder return 0; } else { // The line intersects the cylinder along a line segment on the // cylinder wall. Compute the line parameters for the end points // of the segment. fT = fInvDLength/kD.Z(); afT[0] = (+fHalfHeight - kP.Z())*fT; afT[1] = (-fHalfHeight - kP.Z())*fT; return 2; } } if ( Math<Real>::FAbs(kD.Z()) <= Math<Real>::EPSILON ) { // line is perpendicular to axis of cylinder if ( Math<Real>::FAbs(kP.Z()) > fHalfHeight ) { // line is outside the planar caps of cylinder return 0; } fA = kD.X()*kD.X() + kD.Y()*kD.Y(); fB = kP.X()*kD.X() + kP.Y()*kD.Y(); fC = kP.X()*kP.X() + kP.Y()*kP.Y() - fRadiusSqr; fDiscr = fB*fB - fA*fC; if ( fDiscr < (Real)0.0 ) { // line does not intersect cylinder wall return 0; } else if ( fDiscr > (Real)0.0 ) { fRoot = Math<Real>::Sqrt(fDiscr); fT = fInvDLength/fA; afT[0] = (-fB - fRoot)*fT; afT[1] = (-fB + fRoot)*fT; return 2; } else { afT[0] = -fB*fInvDLength/fA; return 1; } } // Clip line to a segment that is between the two planes of the cylinder // end disks. Real fInv = ((Real)1.0)/kD.Z(); Real fT0 = (+fHalfHeight - kP.Z())*fInv; Real fT1 = (-fHalfHeight - kP.Z())*fInv; // Compute the intersections (if any) between the line and the infinite // cylinder. int iQuantity = 0; fA = kD.X()*kD.X() + kD.Y()*kD.Y(); fB = kP.X()*kD.X() + kP.Y()*kD.Y(); fC = kP.X()*kP.X() + kP.Y()*kP.Y() - fRadiusSqr; fDiscr = fB*fB - fA*fC; if ( fDiscr < (Real)0.0 ) { // line does not intersect infinite cylinder return 0; } else if ( fDiscr > (Real)0.0 ) { // Line intersects infinite cylinder in two points. Only save the // line-parameters of intersection if those parameters are within the // clipped line. fRoot = Math<Real>::Sqrt(fDiscr); fInv = ((Real)1.0)/fA; fT = (-fB - fRoot)*fInv; if ( fT0 <= fT1 ) { if ( fT0 <= fT && fT <= fT1 ) afT[iQuantity++] = fT*fInvDLength; } else { if ( fT1 <= fT && fT <= fT0 ) afT[iQuantity++] = fT*fInvDLength; } fT = (-fB + fRoot)*fInv; if ( fT0 <= fT1 ) { if ( fT0 <= fT && fT <= fT1 ) afT[iQuantity++] = fT*fInvDLength; } else { if ( fT1 <= fT && fT <= fT0 ) afT[iQuantity++] = fT*fInvDLength; } } else { // Line intersects infinite cylinder in one point (line is tangent to // cylinder). Only save the line-parameter of intersection if that // parameter is within the clipped line. fT = -fB/fA; if ( fT0 <= fT1 ) { if ( fT0 <= fT && fT <= fT1 ) afT[iQuantity++] = fT*fInvDLength; } else { if ( fT1 <= fT && fT <= fT0 ) afT[iQuantity++] = fT*fInvDLength; } } return iQuantity; } //---------------------------------------------------------------------------- template <class Real> bool Wml::FindIntersection (const Segment3<Real>& rkSegment, const Cylinder3<Real>& rkCylinder, int& riQuantity, Vector3<Real> akPoint[2]) { Real afT[2]; if ( rkCylinder.Capped() ) { riQuantity = Find(rkSegment.Origin(),rkSegment.Direction(), rkCylinder,afT); } else { riQuantity = FindHollow(rkSegment.Origin(),rkSegment.Direction(), rkCylinder,afT); } int iClipQuantity = 0; for (int i = 0; i < riQuantity; i++) { if ( (Real)0.0 <= afT[i] && afT[i] <= (Real)1.0 ) { akPoint[iClipQuantity++] = rkSegment.Origin() + afT[i]*rkSegment.Direction(); } } riQuantity = iClipQuantity; return riQuantity > 0; } //---------------------------------------------------------------------------- template <class Real> bool Wml::FindIntersection (const Ray3<Real>& rkRay, const Cylinder3<Real>& rkCylinder, int& riQuantity, Vector3<Real> akPoint[2]) { Real afT[2]; if ( rkCylinder.Capped() ) { riQuantity = Find(rkRay.Origin(),rkRay.Direction(),rkCylinder,afT); } else { riQuantity = FindHollow(rkRay.Origin(),rkRay.Direction(), rkCylinder,afT); } int iClipQuantity = 0; for (int i = 0; i < riQuantity; i++) { if ( afT[i] >= (Real)0.0 ) { akPoint[iClipQuantity++] = rkRay.Origin() + afT[i]*rkRay.Direction(); } } riQuantity = iClipQuantity; return riQuantity > 0; } //---------------------------------------------------------------------------- template <class Real> bool Wml::FindIntersection (const Line3<Real>& rkLine, const Cylinder3<Real>& rkCylinder, int& riQuantity, Vector3<Real> akPoint[2]) { Real afT[2]; if ( rkCylinder.Capped() ) { riQuantity = Find(rkLine.Origin(),rkLine.Direction(),rkCylinder,afT); } else { riQuantity = FindHollow(rkLine.Origin(),rkLine.Direction(), rkCylinder,afT); } for (int i = 0; i < riQuantity; i++) akPoint[i] = rkLine.Origin() + afT[i]*rkLine.Direction(); return riQuantity > 0; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- namespace Wml { template WML_ITEM bool FindIntersection<float> ( const Segment3<float>&, const Cylinder3<float>&, int&, Vector3<float>[2]); template WML_ITEM bool FindIntersection<float> ( const Ray3<float>&, const Cylinder3<float>&, int&, Vector3<float>[2]); template WML_ITEM bool FindIntersection<float> ( const Line3<float>&, const Cylinder3<float>&, int&, Vector3<float>[2]); template WML_ITEM bool FindIntersection<double> ( const Segment3<double>&, const Cylinder3<double>&, int&, Vector3<double>[2]); template WML_ITEM bool FindIntersection<double> ( const Ray3<double>&, const Cylinder3<double>&, int&, Vector3<double>[2]); template WML_ITEM bool FindIntersection<double> ( const Line3<double>&, const Cylinder3<double>&, int&, Vector3<double>[2]); } //----------------------------------------------------------------------------
[ [ [ 1, 428 ] ] ]
fe84bacaabf570143113020ddf5c0f88ae9a7c8b
252e638cde99ab2aa84922a2e230511f8f0c84be
/reflib/src/RegionProcessForm.cpp
4d83d7aa08586f4f1396d684749faacdb4cca3e6
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,758
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "StdTool.h" #include "TourTool.h" #include "RegionProcessForm.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "TableGridProcessForm" #pragma link "VStringStorage" #pragma resource "*.dfm" TTourRefBookRegionProcessForm *TourRefBookRegionProcessForm; enum TourRefBookRegionProcessStringTypes { TourRefBookRegionIdStr = TourRefBookProcessStringTypesEnumCount }; #define GetTranslatedStr(Index) VStringStorage->Lines->Strings[Index] //--------------------------------------------------------------------------- __fastcall TTourRefBookRegionProcessForm::TTourRefBookRegionProcessForm(TComponent* Owner) : TTourRefBookTableGridProcessForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TTourRefBookRegionProcessForm::FormCloseQuery( TObject *Sender, bool &CanClose) { Boolean ResultFlag; ResultFlag = true; CanClose = false; FunctionArgUsedSkip(Sender); if (ModalResult == mrOk) { if (RegionIdDBEdit->Text.IsEmpty()) { ResultFlag = false; TourShowDialogError (AnsiString(GetTranslatedStr(TourRefBookInputFieldMessageStr) + GetTranslatedStr(TourRefBookRegionIdStr)).c_str()); RegionIdDBEdit->SetFocus(); } if (ResultFlag) { CanClose = true; } } else { CanClose = true; } } //--------------------------------------------------------------------------- #undef GetTranslatedStr(Index)
[ [ [ 1, 64 ] ] ]
b81f24b28ea85b3f1eb9a301cb1a92c1990a7b7c
cc336f796b029620d6828804a866824daa6cc2e0
/cximage/CxImage/ximatif.h
6eaebef334febe8a3ec8f164b6ab2c2a58820ffb
[]
no_license
tokyovigilante/xbmc-sources-fork
84fa1a4b6fec5570ce37a69d667e9b48974e3dc3
ac3c6ef8c567f1eeb750ce6e74c63c2d53fcde11
refs/heads/master
2021-01-19T10:11:37.336476
2009-03-09T20:33:58
2009-03-09T20:33:58
29,232
2
0
null
null
null
null
WINDOWS-1250
C++
false
false
3,068
h
/* * File: ximatif.h * Purpose: TIFF Image Class Loader and Writer */ /* === C R E D I T S & D I S C L A I M E R S ============== * CxImageTIF (c) 07/Aug/2001 <[email protected]> * Permission is given by the author to freely redistribute and include * this code in any program as long as this credit is given where due. * * CxImage version 5.80 29/Sep/2003 * See the file history.htm for the complete bugfix and news report. * * Special thanks to Troels Knakkergaard for new features, enhancements and bugfixes * * Special thanks to Abe <God(dot)bless(at)marihuana(dot)com> for MultiPageTIFF code. * * Parts of the code come from FreeImage 2 * Design and implementation by * - Floris van den Berg ([email protected]) * - Hervé Drolon ([email protected]) * - Markus Loibl ([email protected]) * - Luca Piergentili ([email protected]) * * LibTIFF is: * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE * OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED * CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT * THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY * SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL * PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. * * Use at your own risk! * ========================================================== */ #if !defined(__ximatif_h) #define __ximatif_h #include "ximage.h" #if CXIMAGE_SUPPORT_TIF #include "../tiff/tiffio.h" class DLL_EXP CxImageTIF: public CxImage { public: CxImageTIF(): CxImage(CXIMAGE_FORMAT_TIF) {m_tif2=NULL; m_multipage=false; m_pages=0;} ~CxImageTIF(); // bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_TIF);} // bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_TIF);} bool Decode(CxFile * hFile); bool Encode(CxFile * hFile, bool bAppend=false); bool Encode(CxFile * hFile, CxImage ** pImages, int pagecount); bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } bool Encode(FILE *hFile, bool bAppend=false) { CxIOFile file(hFile); return Encode(&file,bAppend); } bool Encode(FILE *hFile, CxImage ** pImages, int pagecount) { CxIOFile file(hFile); return Encode(&file, pImages, pagecount); } protected: void TileToStrip(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew); bool EncodeBody(TIFF *m_tif, bool multipage=false, int page=0, int pagecount=0); TIFF *m_tif2; bool m_multipage; int m_pages; }; #endif #endif
[ "jmarshallnz@568bbfeb-2a22-0410-94d2-cc84cf5bfa90" ]
[ [ [ 1, 80 ] ] ]
54dae7e01cf9f0bc1efd35f953459cda44ed5814
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Wrappers/MyGUI.Managed/Generate/MyGUI.Managed_ScrollView.h
a4c16f3777c8b1d70cd182f3f2ebe872e2183895
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
3,708
h
/*! @file @author Generate utility by Albert Semenov @date 01/2009 @module */ #pragma once #include "MyGUI.Managed_Widget.h" namespace MyGUI { namespace Managed { public ref class ScrollView : public Widget { private: typedef MyGUI::ScrollView ThisType; public: ScrollView() : Widget() { } internal: ScrollView( MyGUI::ScrollView* _native ) : Widget(_native) { } ScrollView( BaseWidget^ _parent, MyGUI::WidgetStyle _style, const std::string& _skin, const MyGUI::IntCoord& _coord, MyGUI::Align _align, const std::string& _layer, const std::string& _name ) { CreateWidget(_parent, _style, _skin, _coord, _align, _layer, _name); } virtual const std::string& getClassTypeName() override { return ThisType::getClassTypeName(); } static BaseWidget^ WidgetCreator(BaseWidget^ _parent, MyGUI::WidgetStyle _style, const std::string& _skin, const MyGUI::IntCoord& _coord, MyGUI::Align _align, const std::string& _layer, const std::string& _name) { return gcnew ScrollView(_parent, _style, _skin, _coord, _align, _layer, _name); } //InsertPoint public: void SetProperty( Convert<const std::string &>::Type _key , Convert<const std::string &>::Type _value ) { MMYGUI_CHECK_NATIVE(mNative); static_cast<ThisType*>(mNative)->setProperty( Convert<const std::string &>::From(_key) , Convert<const std::string &>::From(_value) ); } public: void SetCanvasSize( Convert<int>::Type _width , Convert<int>::Type _height ) { MMYGUI_CHECK_NATIVE(mNative); static_cast<ThisType*>(mNative)->setCanvasSize( Convert<int>::From(_width) , Convert<int>::From(_height) ); } public: property Convert<MyGUI::types::TSize< int >>::Type CanvasSize { Convert<MyGUI::types::TSize< int >>::Type get( ) { MMYGUI_CHECK_NATIVE(mNative); return Convert<MyGUI::types::TSize< int >>::To( static_cast<ThisType*>(mNative)->getCanvasSize() ); } void set(Convert<const MyGUI::types::TSize< int > &>::Type _value) { MMYGUI_CHECK_NATIVE(mNative); static_cast<ThisType*>(mNative)->setCanvasSize( Convert<const MyGUI::types::TSize< int > &>::From(_value) ); } } public: property Convert<MyGUI::Align>::Type CanvasAlign { Convert<MyGUI::Align>::Type get( ) { MMYGUI_CHECK_NATIVE(mNative); return Convert<MyGUI::Align>::To( static_cast<ThisType*>(mNative)->getCanvasAlign() ); } void set(Convert<MyGUI::Align>::Type _value) { MMYGUI_CHECK_NATIVE(mNative); static_cast<ThisType*>(mNative)->setCanvasAlign( Convert<MyGUI::Align>::From(_value) ); } } public: property Convert<bool>::Type VisibleHScroll { Convert<bool>::Type get( ) { MMYGUI_CHECK_NATIVE(mNative); return Convert<bool>::To( static_cast<ThisType*>(mNative)->isVisibleHScroll() ); } void set(Convert<bool>::Type _value) { MMYGUI_CHECK_NATIVE(mNative); static_cast<ThisType*>(mNative)->setVisibleHScroll( Convert<bool>::From(_value) ); } } public: property Convert<bool>::Type VisibleVScroll { Convert<bool>::Type get( ) { MMYGUI_CHECK_NATIVE(mNative); return Convert<bool>::To( static_cast<ThisType*>(mNative)->isVisibleVScroll() ); } void set(Convert<bool>::Type _value) { MMYGUI_CHECK_NATIVE(mNative); static_cast<ThisType*>(mNative)->setVisibleVScroll( Convert<bool>::From(_value) ); } } }; } // namespace Managed } // namespace MyGUI
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 169 ] ] ]
bf8657286afaf0534fa6af83f36073abff583c9d
99d3989754840d95b316a36759097646916a15ea
/trunk/2011_09_07_to_baoxin_gpd/ferrylibs/test/Test_GeneratePatch.h
90c3f4b04f3cacf8d3fcf1d10fb39b2871a070e4
[]
no_license
svn2github/ferryzhouprojects
5d75b3421a9cb8065a2de424c6c45d194aeee09c
482ef1e6070c75f7b2c230617afe8a8df6936f30
refs/heads/master
2021-01-02T09:20:01.983370
2011-10-20T11:39:38
2011-10-20T11:39:38
11,786,263
1
0
null
null
null
null
UTF-8
C++
false
false
1,611
h
#pragma once #include <iostream> #include <fstream> #include "highgui.h" #include <ferry/cv_geometry/IOUtil.h> using namespace std; using namespace ferry::cv_geometry; using namespace ferry::cv_geometry::io_util; namespace ferry { namespace cv_geometry { namespace test { class Test_GeneratePatch { public: void test() { char* infile = "C:/zj/vcprojects/cv_3d_reconstruction/test_cv_geometry/data/urban_map/scene_1/small/im_db/full_t0_k0.jpg"; char* outfile = "C:/zj/vcprojects/cv_3d_reconstruction/test_cv_geometry/data/urban_map/scene_1/small/im_db/seg_t0_k0_s7.jpg"; char* polygonfile = "C:/zj/vcprojects/cv_3d_reconstruction/test_cv_geometry/data/urban_map/scene_1/small/im_db/seg_t0_k0_s7.txt"; gen(infile, outfile, polygonfile); } void gen(const char* infile, const char* outfile, const char* polygonfile) { IplImage* src = cvLoadImage(infile, 1); IplImage* dst = cvCreateImage(cvGetSize(src), 8, 3); vector<CvPoint> xs; ifstream ifs(polygonfile); ifs>>xs; ifs.close(); CvPoint* polygon = new CvPoint[xs.size()]; for (int i = 0; i < xs.size(); i++) { polygon[i] = xs[i]; } cout<<xs<<endl; IplImage* pim = cvCreateImage(cvGetSize(src), 8, 1); cvZero(pim); int size[] = {xs.size()}; cvFillPoly(pim, &polygon, size, 1, CV_RGB(255, 255, 255)); cvNamedWindow("src", 1); cvShowImage("src", src); cvNamedWindow("poly", 1); cvShowImage("poly", pim); cvCopy(src, dst, pim); cvNamedWindow("dst", 1); cvShowImage("dst", dst); cvSaveImage(outfile, dst); } }; } } }
[ "ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2" ]
[ [ [ 1, 68 ] ] ]
097280ccb3afe556323cb7881d6fbbbc6a2f2721
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_6_002.cpp
dce3ac2a0dd8a0e4b0ce53bf7094617012d2ddbe
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
2,370
cpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2006 Hartmut Kaiser. 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) The tests included in this file were initially taken from the mcpp V2.5 preprocessor validation suite and were modified to fit into the Boost.Wave unit test requirements. The original files of the mcpp preprocessor are distributed under the license reproduced at the end of this file. =============================================================================*/ // Tests error reporting: illegal #if expressions. // 14.1: String literal is not allowed in #if expression. //E t_6_002.cpp(20): error: ill formed preprocessor expression: "string" #if "string" #endif /*- * Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 48 ] ] ]
ebc001bdde47595be5b2f2ef4f8a1fc14ce65b5a
4b51d32f40ef5a36c98a53d2a1eab7e6f362cb00
/CapaIndices/Common/Codigo.h
f736a4d53cdf5cce9e714a012e31e3772af4de96
[]
no_license
damian-pisaturo/datos7506
bcff7f1e9e69af8051ebf464107b92f91be560e4
a67aac89eccd619cdc02a7e6940980f346981895
refs/heads/master
2016-09-06T16:48:18.612868
2007-12-10T22:12:28
2007-12-10T22:12:28
32,679,551
0
0
null
null
null
null
UTF-8
C++
false
false
246
h
#ifndef CODIGO_H_ #define CODIGO_H_ class Codigo { public: const static char NO_MODIFICADO = 0; const static char UNDERFLOW = 1; const static char OVERFLOW = 2; const static char MODIFICADO = 3; }; #endif /*CODIGO_H_*/
[ "manugarciacab@4ef8b2a0-b237-0410-b753-5dc98fa25004", "ecaravatti@4ef8b2a0-b237-0410-b753-5dc98fa25004", "nfantone@4ef8b2a0-b237-0410-b753-5dc98fa25004" ]
[ [ [ 1, 3 ], [ 12, 14 ] ], [ [ 4, 4 ], [ 7, 11 ] ], [ [ 5, 6 ] ] ]
26210b46ff039f982a7c9d05a56951862184b761
777399eafeb952743fcb973fbba392842c2e9b14
/CyberneticWarrior/CyberneticWarrior/source/CRocket.h
856253b38df1f6b88208b984b8bf68871ecbe112
[]
no_license
Warbeleth/cyberneticwarrior
7c0af33ada4d461b90dc843c6a25cd5dc2ba056a
21959c93d638b5bc8a881f75119d33d5708a3ea9
refs/heads/master
2021-01-10T14:31:27.017284
2010-11-23T23:16:28
2010-11-23T23:16:28
53,352,209
0
0
null
null
null
null
UTF-8
C++
false
false
377
h
#ifndef _CROCKET_H_ #define _CROCKET_H_ #include "CBaseProjectile.h" class CRocket : public CBaseProjectile { private: int m_nRocketState; protected: enum RocketStates { ROCKET_DIRECTIONAL, ROCKET_HOMING, ROCKET_MAX }; public: CRocket( void ); ~CRocket( void ); void Update( float fElapsedTime); bool CheckCollision( CBase* pBase ); }; #endif
[ "atmuccio@d49f6b0b-9fae-41b6-31ce-67b77e794db9", "[email protected]" ]
[ [ [ 1, 8 ], [ 10, 22 ] ], [ [ 9, 9 ] ] ]
f01df984869b588f53693be158431b58ac0cb1d7
096a82f2a4c8dfe4444467b3f55efba278e88022
/Calibrator/Calibrator.cpp
6644f8775b487e09359c2577251bce3f5aa0e5cb
[]
no_license
pulse-cc/Metrology
88d9b0140f7fa73f113a6cad26ddf63a94a7350c
ca242c465b7a2ddf58e9fb607a66196ca1bdedcb
refs/heads/master
2021-01-17T05:24:58.113444
2011-08-17T12:10:49
2011-08-17T12:10:49
2,143,670
1
1
null
null
null
null
UTF-8
C++
false
false
739
cpp
#include "stdafx.h" #include "Calibrator.h" static Calibrator *pC = new Calibrator(); CALIBRATOR_API Calibrator *getCalibrator(void) { return pC; } Calibrator::Calibrator() { printf("Creating VIRTUAL calibrator\n"); setBarrier(0); setVoltage(0); setFrequency(0); } Calibrator::~Calibrator() { } double Calibrator::setVoltage(double Volt) { m_U = Volt; LSleep(100); return m_U; } uint Calibrator::setFrequency(uint Hz) { m_F = Hz; LSleep(100); return m_F; } bool Calibrator::setOutput(bool State) { m_state = State; LSleep(100); return m_state; } void Calibrator::setBarrier(double Umax) { if (Umax > 1000.) { fprintf(stderr, "Too high voltage %lf\n", Umax); exit(1); } }
[ [ [ 1, 5 ], [ 7, 7 ], [ 9, 10 ], [ 12, 13 ], [ 17, 17 ], [ 21, 42 ] ], [ [ 6, 6 ], [ 8, 8 ], [ 11, 11 ], [ 14, 16 ], [ 18, 20 ], [ 43, 49 ] ] ]
b08fe506a1516df9b7feae7250ba868a5e887f65
50f94444677eb6363f2965bc2a29c09f8da7e20d
/Src/EmptyProject/Npc.h
9de5763df20d8fce57af7a6959f06b00e3e63353
[]
no_license
gasbank/poolg
efd426db847150536eaa176d17dcddcf35e74e5d
e73221494c4a9fd29c3d75fb823c6fb1983d30e5
refs/heads/master
2020-04-10T11:56:52.033568
2010-11-04T19:31:00
2010-11-04T19:31:00
1,051,621
1
0
null
null
null
null
UTF-8
C++
false
false
226
h
#pragma once #include "Character.h" /** @brief NPC 를 나타내는 클래스 (미구현) */ class Npc : public Character { public: ~Npc() {} protected: Npc( UnitType type ) : Character( type ) {} };
[ [ [ 1, 16 ] ] ]
151a3b4e14e2b381d969d55b7ec4584302ec7664
cf579692f2e289563160b6a218fa5f1b6335d813
/XBtool/ColorDlg/ColorDialog.cpp
763641e5d84b9e9b0a5cd8921af1026397e6d1e6
[]
no_license
opcow/XBtool
a7451971de3296e1ce5632b0c9d95430f6d3b223
718a7fbf87e08c12c0c829dd2e2c0d6cee967cbe
refs/heads/master
2021-01-16T21:02:17.759102
2011-03-09T23:36:54
2011-03-09T23:36:54
1,461,420
8
2
null
null
null
null
UTF-8
C++
false
false
2,287
cpp
/////////////////////////////////////////////////////////////////////////// // ColorDialog.cpp - auto load/save of custom colors CColorDialog extension // (c) 1997 Roger Onslow #include "stdafx.h" #include "ColorDialog.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////// // // CMyColorDialog property page IMPLEMENT_DYNCREATE(CMyColorDialog, CColorDialog) bool CMyColorDialog::c_NeedToInitCustColors = true; COLORREF CMyColorDialog::c_CustColors[]; COLORREF CMyColorDialog::c_LastCustColors[]; #define SECTION _T("Custom Colors") void CMyColorDialog::InitCustColors() { for (int i = 0; i < NCUSTCOLORS; i++) { CString entry; entry.Format("%d",i); c_LastCustColors[i] = c_CustColors[i] = ::AfxGetApp()->GetProfileInt(SECTION,entry,RGB(255,255,255)); } c_NeedToInitCustColors= false; } void CMyColorDialog::SaveCustColors() { for (int i = 0; i < NCUSTCOLORS; i++) { if (c_LastCustColors[i] != c_CustColors[i]) { CString entry; entry.Format("%d",i); if (c_CustColors[i] == RGB(255,255,255)) { ::AfxGetApp()->WriteProfileString(SECTION,entry,NULL); } else { ::AfxGetApp()->WriteProfileInt(SECTION, entry,c_CustColors[i]); } c_LastCustColors[i] = c_CustColors[i]; } } } CMyColorDialog::CMyColorDialog( COLORREF clrInit, DWORD dwFlags, CWnd* pParentWnd) : CColorDialog(clrInit,dwFlags,pParentWnd) { //{{AFX_DATA_INIT(CMyColorDialog) //}}AFX_DATA_INIT if (c_NeedToInitCustColors) { InitCustColors(); } m_cc.lpCustColors = c_CustColors; } int CMyColorDialog::DoModal() { int code = (int) CColorDialog::DoModal(); SaveCustColors(); return code; } void CMyColorDialog::DoDataExchange(CDataExchange* pDX) { // overridden (calls this base class) CColorDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMyColorDialog) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMyColorDialog, CColorDialog) //{{AFX_MSG_MAP(CMyColorDialog) //}}AFX_MSG_MAP END_MESSAGE_MAP()
[ [ [ 1, 75 ] ] ]
e6b4815c60d6fe373102fca7680661e6fb949a82
85712cdcdf41f80dbe027af584fcc71767318192
/branches/BeNet/Audio/Encode.cpp
88d44f635a46f925640f98a5f8f99a7c17f89484
[ "MIT" ]
permissive
BackupTheBerlios/dengon-svn
85661945f45b3f2e341fca2ef4d4680073b9d69e
bcffcb641594219bc564be865c9bf181b96b4e3c
refs/heads/master
2016-09-05T19:31:57.896502
2010-09-18T19:18:45
2010-09-18T19:18:45
40,664,766
0
0
null
null
null
null
UTF-8
C++
false
false
2,492
cpp
/* Encode.cpp */ #ifndef _Encode_h #include "Encode.h" #endif #include <math.h> #include <stdio.h> Encode::Encode(){ g72x_init_state(&state); enc_bits = 4; in_size = sizeof (short); out_buffer = 0; out_bits = 0; code = 0; } //Pack output codes into bytes and write them to stdout. //Returns 1 if there is residual output, else returns 0. int Encode::pack_output(unsigned code, int bits, char* buffer) { unsigned char out_byte; out_buffer |= (code << out_bits); out_bits += bits; if (out_bits >= 8) { out_byte = out_buffer & 0xff; out_bits -= 8; out_buffer >>= 8; buffer[out_buffer_pos++] = out_byte; } return (out_bits > 0); } void Encode::reset_pack(){ out_buffer = 0; out_bits = 0; out_buffer_pos = 0; } static short abs(short i) { if (i<0) return -i; else return i; } char* Encode::createBuffer(size_t size, int &size_of_buf, int no_of_trame_to_skip) { size_of_buf = size / 4 / (no_of_trame_to_skip*2); return new char[size_of_buf]; } bool Encode::decisionToEncode(void *data, size_t size, int no_of_trame_to_skip, float volume) { short *data_short = (short*)data; long data_decision = 0; for (unsigned int i = 0; i < size / 2; i += no_of_trame_to_skip*2) { //to control the volume of mic data_short[i] = (short)((float)data_short[i] * volume); //to avoid some "affreux" peak if (data_short[i] > 30500 || data_short[i] < -30500) data_short[i] = (short)((float)data_short[i] / 1.2); data_decision += abs(data_short[i]); } data = (void*)data_short; // printf("%d\n",(data_decision / (size/(no_of_trame_to_skip * 2)))); return ((data_decision / (size/(no_of_trame_to_skip * 2))) >= (20) && (size == 32768)); // return ((data_decision / (size/(no_of_trame_to_skip * 2))) >= (120) /*&& (size == 32768) */); } void Encode::encodeBuffer(void *data, size_t size, char *buffer, int no_of_trame_to_skip) { reset_pack(); short *data_short = (short*)data; /* Read input buffer and process */ for(unsigned int i = 0; i < size / 2; i += no_of_trame_to_skip*2){ sample_short = data_short [i]; code = g721_encoder(sample_short, AUDIO_ENCODING_LINEAR, &state); //code = g723_40_encoder(sample_short, AUDIO_ENCODING_LINEAR, &state); resid = pack_output(code, enc_bits, buffer); } /* Fill with zero codes until all residual codes are written out */ while (resid) { resid = pack_output(0, enc_bits, buffer); } }
[ "lemon@c14d4bca-7b17-0410-87b9-834895956487" ]
[ [ [ 1, 103 ] ] ]
da4244a82935e080053756a46faf918f496f6dfc
f744f8897adce6654cdfe6466eaf4d0fad4ba661
/src/data/VBOMesh.h
e6c3e414c2af7f0aa8546fd782eaacb08deef43f
[]
no_license
pizibing/bones-animation
37919ab3750683a5da0cc849f80d1e0f5b37c89c
92ce438e28e3020c0e8987299c11c4b74ff98ed5
refs/heads/master
2016-08-03T05:34:19.294712
2009-09-16T14:59:32
2009-09-16T14:59:32
33,969,248
0
0
null
null
null
null
UTF-8
C++
false
false
6,362
h
#pragma once #include "gl/glut.h" #include <gl/glext.h> //a VBOMesh is all the information of a mesh include position of //every vertices, normals, textures, material and matrix //position, normal, texture information are stored in VBO class VBOMesh { public: //constructors VBOMesh(void); //generate a VBOMesh whose vertices are defined by the given //vertex and usage. hasNormal, hasTexture, hasMaterial will be set false. //matrix will be set to identity 4*4 matrix //size will be set to the size of vertex divided by 3 //if vertex's size can not be divided exactly by 3, vertices will be set to 0 // By default, usage mode is set as GL_STATIC_DRAW_ARB. // Other usages are GL_STREAM_DRAW_ARB, GL_STREAM_READ_ARB, GL_STREAM_COPY_ARB, // GL_STATIC_DRAW_ARB, GL_STATIC_READ_ARB, GL_STATIC_COPY_ARB, // GL_DYNAMIC_DRAW_ARB, GL_DYNAMIC_READ_ARB, GL_DYNAMIC_COPY_ARB. VBOMesh(const GLfloat* vertex, int size, GLenum usage); //destructor ~VBOMesh(void); //functions //if vertices of this VBOMesh is 0 (no VBO is generated for vertices) //then generate a VBO using vertex and usage //size will be set to the size of vertex divided by 3 //if vertex's size can not be divided exactly by 3, nothing happen //else nothing will happen // By default, usage mode is set as GL_STATIC_DRAW_ARB. // Other usages are GL_STREAM_DRAW_ARB, GL_STREAM_READ_ARB, GL_STREAM_COPY_ARB, // GL_STATIC_DRAW_ARB, GL_STATIC_READ_ARB, GL_STATIC_COPY_ARB, // GL_DYNAMIC_DRAW_ARB, GL_DYNAMIC_READ_ARB, GL_DYNAMIC_COPY_ARB. void setVertices(const GLfloat* vertex, int size, GLenum usage); //if normals of this VBOMesh is 0 (no VBO is generated for normals) //then generate a VBO using normal and usage, hasNormal will be set to true //else nothing will happen //if normal's size doesn't equal to size*3, nothing will happen // By default, usage mode is set as GL_STATIC_DRAW_ARB. // Other usages are GL_STREAM_DRAW_ARB, GL_STREAM_READ_ARB, GL_STREAM_COPY_ARB, // GL_STATIC_DRAW_ARB, GL_STATIC_READ_ARB, GL_STATIC_COPY_ARB, // GL_DYNAMIC_DRAW_ARB, GL_DYNAMIC_READ_ARB, GL_DYNAMIC_COPY_ARB. void setNormals(const GLfloat* normal, int size, GLenum usage); //if textures of this VBOMesh is 0 (no VBO is generated for textures) //then generate a VBO using texture and usage, hasTexture will be set to true //texID will be set to texid //else nothing will happen //if texture's size doesn't equal to size*2, nothing will happen // By default, usage mode is set as GL_STATIC_DRAW_ARB. // Other usages are GL_STREAM_DRAW_ARB, GL_STREAM_READ_ARB, GL_STREAM_COPY_ARB, // GL_STATIC_DRAW_ARB, GL_STATIC_READ_ARB, GL_STATIC_COPY_ARB, // GL_DYNAMIC_DRAW_ARB, GL_DYNAMIC_READ_ARB, GL_DYNAMIC_COPY_ARB. void setTextures(const GLfloat* texture, int size, GLenum usage, GLuint texid); //set the material of this VBOMesh. //hasMaterial will be set to true and //ambient,diffuse,specular,emission,shininess will be set void setMaterial(const GLfloat am[4], const GLfloat di[4], const GLfloat sp[4], const GLfloat em[4], GLfloat sh); //set matrix of this VBOMesh to the given ma void setMatrix(const float ma[16]); //update vertices VBO to the version of vertex //GL_WRITE_ONLY_ARB will be set as the map state //if vertices equals 0, nothing will happen //if vertex's size doesn't equal to size*3, nothing will happen void updateVertices(const GLfloat* vertex, int size); //update normals VBO to the version of normal //GL_WRITE_ONLY_ARB will be set as the map state //if normals equals 0, nothing will happen //if normal's size doesn't equal to size*3, nothing will happen void updateNormals(const GLfloat* normal, int size); //update textures VBO to the version of texture //GL_WRITE_ONLY_ARB will be set as the map state //if textures equals 0, nothing will happen //if texture's size doesn't equal to size*2, nothing will happen void updateTextures(const GLfloat* texture, int size); //get functions // return hasNormal bool getHasNormal(); // return normals GLuint getNormals(); // return hasTexture bool getHasTexture(); // return textures GLuint getTextures(); // return texID GLuint getTexID(); // return vertices GLuint getVertices(); // return hasMaterial bool getHasMaterial(); // return ambient[4] GLfloat* getAmbient(); // return diffuse[4] GLfloat* getDiffuse(); // return specular[4] GLfloat* getSpecular(); // return emission[4] GLfloat* getEmission(); // return shininess GLfloat getShininess(); // return matrix[16] float* getMatrix(); // return size int getSize(); private: // generate vertex buffer object and bind it with its data // You must give 2 hints about data usage; target and mode, so that OpenGL can // decide which data should be stored and its location. // VBO works with 2 different targets; GL_ARRAY_BUFFER_ARB for vertex arrays // and GL_ELEMENT_ARRAY_BUFFER_ARB for index array in glDrawElements(). // The default target is GL_ARRAY_BUFFER_ARB. // By default, usage mode is set as GL_STATIC_DRAW_ARB. // Other usages are GL_STREAM_DRAW_ARB, GL_STREAM_READ_ARB, GL_STREAM_COPY_ARB, // GL_STATIC_DRAW_ARB, GL_STATIC_READ_ARB, GL_STATIC_COPY_ARB, // GL_DYNAMIC_DRAW_ARB, GL_DYNAMIC_READ_ARB, GL_DYNAMIC_COPY_ARB. GLuint createVBO(const void* data, int dataSize, GLenum target, GLenum usage); //update the first 'count' elements of vbo to the version of src //i.e. every element of vbo equals corresponding element of src void updateVBO(float* vbo, float* src, int count); //the size of vertices and should be the size of normals //textures //size of vertices doesn't mean its length or sizeof, but the number //of dots it represent, i.e. length/3 int size; //whether this VBOMesh has normals bool hasNormal; //VBO id of normals GLuint normals; //whether this VBOMesh has texture bool hasTexture; //VBO id of texture coordinates GLuint textures; //texture id of the texture GLuint texID; //VBO id of vertices GLuint vertices; //whether this VBOMesh has material bool hasMaterial; GLfloat ambient[4]; GLfloat diffuse[4]; GLfloat specular[4]; GLfloat emission[4]; GLfloat shininess; //a matrix record the position of the VBOMesh in the world space float matrix[16]; };
[ [ [ 1, 162 ] ] ]
76a8f037721266925af306113bc722c1370fb0c7
90825f9cb7d1688f0970d952572123b2bb207721
/Excellent_Adventure_Master/Canvas.h
425419369a15c262fd69b023a9f232ac2273b612
[]
no_license
quilime/Excellent-Adventure
8bf06d7284e1f3f5800ea697f1643d8a377a12d9
8994cc61d61e84a48e4cb8dee0f19fa0def4a480
refs/heads/master
2021-01-16T22:41:52.139397
2010-08-14T04:57:01
2010-08-14T04:57:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,343
h
#ifndef _CANVAS_H #define _CANVAS_H // Enable for Simulator #define USE_UART //#define BENCHMARK // Assumes [0, 255] // Yes, the compiler IS stupid enough to not properly perform shifts without // corrupting the upper bytes. //#define COLOR(R,G,B) (uint32_t)(((uint32_t)(B) << 16) | ((uint32_t)(G) << 8) | (uint32_t)(R)) // Broken: // #define COLOR(R,G,B) (uint32_t)(((B) << 16) | ((G) << 8) | (R)) //Produce a byte-packed 15-bit color. Channels are from [0:31] #define COLOR(R,G,B) (Color_t)( ((B) << 10) | ((G) << 5) | ((R))) #define COLOR_B(R,G,B) (Color_t)((1 << 15) | ((B) << 10) | ((G) << 5) | ((R))) // The bright bit is bit-16 #define SETBRIGHT(C) ((C) |= (1 << 15)) #define UNSETBRIGHT(C) ((C) &= ~(1 << 15)) // 0b01111100 --> 0x7C // Color to scaled RGB 256 values #define RED256(C) (uint8_t)((((C) << 2) & 0x7C)) #define GREEN256(C) (uint8_t)((((C) >> 3) & 0x7C)) #define BLUE256(C) (uint8_t)((((C) >> 8) & 0x7C)) // Bright versions: // 0b11111000 --> 0xF8 #define RED256_B(C) (uint8_t)(((C) << 3) & 0xF8) #define GREEN256_B(C) (uint8_t)(((C) >> 2) & 0xF8) #define BLUE256_B(C) (uint8_t)(((C) >> 7) & 0xF8) // Raw 5-bit values #define RED(C) (uint8_t)(((C)) & 0x1F) #define GREEN(C) (uint8_t)(((C) >> 5) & 0x1F) #define BLUE(C) (uint8_t)(((C) >> 10) & 0x1F) #define IS_BRIGHT(C) (((C) >> 15) & 0x1) #define CANVAS_WIDTH 6 #define CANVAS_HEIGHT 10 #define CANVAS_WM1 (CANVAS_WIDTH - 1) #define CANVAS_HM1 (CANVAS_HEIGHT - 1) #define CANVAS_WIDTH2 8 #define CANVAS_WIDTH2_BITS 3 #define XY_TO_LINEAR(X,Y) (((Y) << CANVAS_WIDTH2_BITS) + (X)) #define CANVAS_MEMORY_SIZE (CANVAS_WIDTH2 * CANVAS_HEIGHT) #define ADDR_ALL_PIXELS 0 typedef unsigned int Color_t; class Canvas { // Internally we use a canvas with a height a power of 2 Color_t *m_canvas; public: Canvas(); ~Canvas(); void Destroy(); // The firstID is the ID of the first pixel in the panels. void InitPanels(); void BlitToPanels(); void Clear(Color_t color = 0); void PutPixel(char x, char y, Color_t color); Color_t GetPixel(char x, char y); Color_t * GetCanvas(); }; #endif
[ "[email protected]", "chris@.(none)" ]
[ [ [ 1, 18 ], [ 21, 23 ], [ 26, 29 ], [ 32, 34 ], [ 40, 42 ], [ 45, 48 ], [ 50, 50 ], [ 52, 58 ], [ 60, 74 ], [ 76, 89 ], [ 91, 98 ] ], [ [ 19, 20 ], [ 24, 25 ], [ 30, 31 ], [ 35, 39 ], [ 43, 44 ], [ 49, 49 ], [ 51, 51 ], [ 59, 59 ], [ 75, 75 ], [ 90, 90 ] ] ]
ad24912d2ba563a01c50f155733c6adb07f7e9b2
906e87b1936397339734770be45317f06fe66e6e
/include/TGConsole.h
c2067c5b80b541501fab1c438c40a7fc16ae6020
[]
no_license
kcmohanprasad/tgui
03c1ab47e9058bc763b7e6ffc21a37b4358369bf
9f9cf391fa86b99c7d606c4d196e512a7b06be95
refs/heads/master
2021-01-10T08:52:18.629088
2007-05-17T04:42:58
2007-05-17T04:42:58
52,069,498
0
0
null
null
null
null
UTF-8
C++
false
false
2,049
h
//----------------------------------------------------------------------------- // This source file is part of TGUI (Tiny GUI) // // Copyright (c) 2006-2007 Tubras Software, Ltd // Also see acknowledgements in Readme.html // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to // do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //----------------------------------------------------------------------------- #ifndef __TGCONSOLE_H__ #define __TGCONSOLE_H__ namespace TGUI { class _TGUIExport TGConsole : public TGWindow { TGListBox* m_list; TGEditBox* m_input; protected: bool acceptText(const TGEventArgs& args); bool escapeText(const TGEventArgs& args); public: TGConsole(TGString caption="Console"); virtual ~TGConsole(); virtual void setBounds(int x1, int y1, int x2, int y2); virtual void addItem(TGString item); virtual void addText(TGString text) {addItem(text);}; virtual void toggle(); }; } #endif
[ "pc0der@a5263bde-0223-0410-8bbb-1954fdd97a2f" ]
[ [ [ 1, 50 ] ] ]
5a7195eddd468035c9bfdd42d01192b61411f2b2
d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189
/pygccxml_dev/unittests/data/remove_template_defaults.hpp
d1aabcaf01eeead32d310e2872bbf17724acc926
[ "BSL-1.0" ]
permissive
gatoatigrado/pyplusplusclone
30af9065fb6ac3dcce527c79ed5151aade6a742f
a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede
refs/heads/master
2016-09-05T23:32:08.595261
2010-05-16T10:53:45
2010-05-16T10:53:45
700,369
4
2
null
null
null
null
UTF-8
C++
false
false
3,075
hpp
// Copyright 2004-2008 Roman Yakovenko. // 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) #ifndef __remove_template_defaults_hpp__ #define __remove_template_defaults_hpp__ #if defined( __GNUC__ ) #include <ext/hash_set> #include <ext/hash_map> #define HASH_XXX_NS __gnu_cxx #else #include <hash_set> #include <hash_map> #if defined( __GCCXML__ ) && !defined( __PYGCCXML_MSVC9__ ) #define HASH_XXX_NS std #else #define HASH_XXX_NS stdext #endif//GCCXML #endif #include <string> #include <vector> #include <deque> #include <queue> #include <list> #include <set> #include <map> namespace rtd{ template <class T> struct type {}; namespace vectors{ typedef std::vector< int > v_int; typedef std::vector< std::string > v_string; typedef std::vector< v_int > v_v_int; } namespace lists{ typedef std::list< int > l_int; typedef std::list< std::wstring > l_wstring; } namespace deques{ typedef std::deque< std::vector< int > > d_v_int; typedef std::deque< std::list< std::string > > d_l_string; } namespace queues{ typedef std::queue< int > q_int; typedef std::queue< std::string > q_string; } namespace priority_queues{ typedef std::priority_queue< int > pq_int; typedef std::priority_queue< std::string > pq_string; } namespace sets{ typedef std::set< std::vector< int > > s_v_int; typedef std::set< std::string > s_string; } namespace multiset_sets{ typedef std::multiset< std::vector< int > > ms_v_int; typedef std::multiset< std::string > ms_string; } namespace maps{ typedef std::map< int, double > m_i2d; typedef std::map< std::wstring, double > m_wstr2d; typedef std::map< const std::vector< int >, m_wstr2d > m_v_i2m_wstr2d; inline std::map<std::string, int> f2(){} } namespace multimaps{ typedef std::multimap< int, double > mm_i2d; typedef std::multimap< std::wstring const, double > mm_wstr2d; typedef std::multimap< std::vector< int > const, mm_wstr2d const > mm_v_i2mm_wstr2d; } namespace hash_sets{ typedef HASH_XXX_NS::hash_set< std::vector< int > > hs_v_int; typedef HASH_XXX_NS::hash_set< std::string > hs_string; } namespace hash_multisets{ typedef HASH_XXX_NS::hash_multiset< std::vector< int > > mhs_v_int; typedef HASH_XXX_NS::hash_multiset< std::string > mhs_string; } namespace hash_maps{ typedef HASH_XXX_NS::hash_map< int, double > hm_i2d; typedef HASH_XXX_NS::hash_map< std::wstring, double > hm_wstr2d; } namespace hash_multimaps{ typedef HASH_XXX_NS::hash_multimap< int, double > hmm_i2d; typedef HASH_XXX_NS::hash_multimap< std::wstring const, double > hmm_wstr2d; typedef HASH_XXX_NS::hash_multimap< std::vector< int > const, hmm_wstr2d const > hmm_v_i2mm_wstr2d; } inline void f1( type< sets::s_v_int > ){ } } #endif//__remove_template_defaults_hpp__
[ "roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76" ]
[ [ [ 1, 117 ] ] ]
66596b98c4df3a2cf6ce778b06572a099ea7e5c3
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/Graphics/WS/Ordinal/AppHolder.cpp
eb6cac5c7d5b196739f0b403a9bd886d3cc664bd
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
2,326
cpp
// AppHolder.cpp // // Copyright (c) 2005 Symbian Softwares Ltd. All rights reserved. // #include "AppHolder.h" #include "Ordinal.h" #include <EikStart.h> // // EXPORTed functions // EXPORT_C CApaApplication* NewApplication() { return new CAppholderApplication; } // The below section is added to make the code compatible with v9.1 // This is because only exe files are compatible with v9.1 #if (defined __WINS__ && !defined EKA2) // E32Dll used only when WINS defined and EKA2 not defined GLDEF_C TInt E32Dll(enum TDllReason) { return KErrNone; } #else // else E32Main is used GLDEF_C TInt E32Main() { return EikStart::RunApplication(NewApplication); } #endif //////////////////////////////////////////////////////////////// // // Application class, CAppholderApplication // //////////////////////////////////////////////////////////////// TUid CAppholderApplication::AppDllUid() const { return KUidAppholder; } CApaDocument* CAppholderApplication::CreateDocumentL() { // Construct the document using its NewL() function, rather // than using new(ELeave), because it requires two-phase // construction. return new (ELeave) CAppholderDocument(*this); } //////////////////////////////////////////////////////////////// // // Document class, CAppholderDocument // //////////////////////////////////////////////////////////////// // C++ constructor CAppholderDocument::CAppholderDocument(CEikApplication& aApp) : CEikDocument(aApp) { } CEikAppUi* CAppholderDocument::CreateAppUiL() { return new (ELeave) CAppholderAppUi; } CAppholderDocument::~CAppholderDocument() { } //////////////////////////////////////////////////////////////// // // App UI class, CAppholderAppUi // //////////////////////////////////////////////////////////////// void CAppholderAppUi::ConstructL() { BaseConstructL(); iClient = CExampleWsClient::NewL(ClientRect()); } CAppholderAppUi::~CAppholderAppUi() { delete iClient; } void CAppholderAppUi::HandleCommandL(TInt aCommand) { switch (aCommand) { case EEikCmdExit: Exit(); break; } }
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 99 ] ] ]
d1de48a300c345aa462eb67862620f16fcacb242
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/validators/datatype/AbstractNumericValidator.hpp
bdc3df0e0e3e6ffdc47c681bc2ba1ee5f1aecfe4
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
5,134
hpp
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: AbstractNumericValidator.hpp,v 1.11 2004/09/08 13:56:52 peiyongz Exp $ * $Log: AbstractNumericValidator.hpp,v $ * Revision 1.11 2004/09/08 13:56:52 peiyongz * Apache License Version 2.0 * * Revision 1.10 2004/01/29 11:51:22 cargilld * Code cleanup changes to get rid of various compiler diagnostic messages. * * Revision 1.9 2003/12/23 21:50:36 peiyongz * Absorb exception thrown in getCanonicalRepresentation and return 0, * only validate when required * * Revision 1.8 2003/12/17 00:18:38 cargilld * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data. * * Revision 1.7 2003/11/28 18:53:07 peiyongz * Support for getCanonicalRepresentation * * Revision 1.6 2003/11/12 20:32:03 peiyongz * Statless Grammar: ValidationContext * * Revision 1.5 2003/10/02 19:21:06 peiyongz * Implementation of Serialization/Deserialization * * Revision 1.4 2003/05/15 18:53:26 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.3 2002/12/18 14:17:55 gareth * Fix to bug #13438. When you eant a vector that calls delete[] on its members you should use RefArrayVectorOf. * * Revision 1.2 2002/11/04 14:53:27 tng * C++ Namespace Support. * * Revision 1.1.1.1 2002/02/01 22:22:39 peiyongz * sane_include * * Revision 1.2 2001/11/22 20:23:20 peiyongz * _declspec(dllimport) and inline warning C4273 * * Revision 1.1 2001/10/01 16:13:56 peiyongz * DTV Reorganization:new classes: AbstractNumericFactValidator/ AbstractNumericValidator * */ #if !defined(ABSTRACT_NUMERIC_VALIDATOR_HPP) #define ABSTRACT_NUMERIC_VALIDATOR_HPP #include <xercesc/validators/datatype/AbstractNumericFacetValidator.hpp> #include <xercesc/util/RefVectorOf.hpp> XERCES_CPP_NAMESPACE_BEGIN class VALIDATORS_EXPORT AbstractNumericValidator : public AbstractNumericFacetValidator { public: // ----------------------------------------------------------------------- // Public ctor/dtor // ----------------------------------------------------------------------- /** @name Constructor. */ //@{ virtual ~AbstractNumericValidator(); //@} virtual void validate ( const XMLCh* const content , ValidationContext* const context = 0 , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); virtual const XMLCh* getCanonicalRepresentation ( const XMLCh* const rawData , MemoryManager* const memMgr = 0 , bool toValidate = false ) const; /*** * Support for Serialization/De-serialization ***/ DECL_XSERIALIZABLE(AbstractNumericValidator) protected: AbstractNumericValidator ( DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , const int finalSet , const ValidatorType type , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); inline void init(RefArrayVectorOf<XMLCh>* const enums , MemoryManager* const manager); // // Abstract interface // virtual void checkContent(const XMLCh* const content , ValidationContext* const context , bool asBase , MemoryManager* const manager) = 0; void boundsCheck(const XMLNumber* const , MemoryManager* const manager); private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- AbstractNumericValidator(const AbstractNumericValidator&); AbstractNumericValidator& operator=(const AbstractNumericValidator&); }; inline void AbstractNumericValidator::init(RefArrayVectorOf<XMLCh>* const enums , MemoryManager* const manager) { AbstractNumericFacetValidator::init(enums, manager); } XERCES_CPP_NAMESPACE_END #endif /** * End of file AbstractNumericValidator.hpp */
[ [ [ 1, 149 ] ] ]
bbe8a19b27b5c13d58e64788a9370138e875883d
bd205edfb0877a4177793012ac0cdbac7b88106a
/vs/SampleApp/SampleApp.cpp
31c10c8a35c65f21f688c11a7ef034fbeca018ca
[]
no_license
rburchell/skia
5916d995a88677540c774e74d88005ca22c24e6b
7530425f0ef6e39a0ee666daaff0c18029fee5dd
HEAD
2016-09-05T18:35:09.456792
2010-11-12T19:52:38
2010-11-12T23:43:37
1,045,866
1
1
null
null
null
null
UTF-8
C++
false
false
4,885
cpp
// SampleApp.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "SampleApp.h" #define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_SAMPLEAPP, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SAMPLEAPP)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // // COMMENTS: // // This function and its usage are only necessary if you want this code // to be compatible with Win32 systems prior to the 'RegisterClassEx' // function that was added to Windows 95. It is important to call this function // so that the application will get 'well formed' small icons associated // with it. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SAMPLEAPP)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_SAMPLEAPP); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } #include "SkOSWindow_Win.h" static SkOSWindow* gSkWind; // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } gSkWind = new SkOSWindow(hWnd); ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
[ "[email protected]@107f31f1-e31d-0410-a17c-a9b5b17689e2" ]
[ [ [ 1, 196 ] ] ]
80f5bba36e083eb1a7cdaa4569307c5237c9bf8b
11bae0259e13a83b274d75c7347fe1063973a4d6
/qrgui/mainwindow/errorReporter.h
cef2f342a0acd7a8d4fc238592212a03f72eb56c
[]
no_license
SashaPishnova/qreal
be02bd63738bc66d946dc4be2dc58d4dbcb38894
6577f005b5462de79828a290edd3825e9452a6b3
refs/heads/master
2020-05-20T23:51:35.476137
2011-12-22T22:09:03
2011-12-22T22:09:03
2,934,715
1
0
null
null
null
null
UTF-8
C++
false
false
1,435
h
#pragma once #include <QtCore/QString> #include <QtCore/QList> #include "mainWindow.h" #include "../../qrkernel/ids.h" #include "../../qrkernel/definitions.h" #include "error.h" #include "errorListWidget.h" #include "../toolPluginInterface/usedInterfaces/errorReporterInterface.h" namespace qReal { namespace gui { class ErrorReporter : public QObject, public ErrorReporterInterface { Q_OBJECT public: ErrorReporter(); ErrorReporter(ErrorListWidget* const errorListWidget, QDockWidget* const errorList); void addInformation(QString const &message, Id const &position = Id::rootId()); void addWarning(QString const &message, Id const &position = Id::rootId()); void addError(QString const &message, Id const &position = Id::rootId()); void addCritical(QString const &message, Id const &position = Id::rootId()); bool showErrors(ErrorListWidget* const errorListWidget, QDockWidget* const errorList) const; void clear(); void clearErrors(); public slots: void updateVisibility(bool isVisible); private: static QString severityMessage(Error const &error); void showError(Error const &error, ErrorListWidget* const errorListWidget) const; QList<Error> mErrors; ErrorListWidget* const mErrorListWidget; // Doesn't have ownership QDockWidget* const mErrorList; // Doesn't have ownership /** @brief Should error window be shown or not*/ bool mIsVisible; }; } }
[ [ [ 1, 4 ], [ 9, 9 ], [ 12, 13 ], [ 22, 22 ], [ 28, 28 ], [ 40, 40 ], [ 43, 43 ], [ 49, 49 ] ], [ [ 5, 5 ], [ 14, 15 ], [ 17, 21 ], [ 23, 27 ], [ 29, 30 ], [ 35, 35 ], [ 39, 39 ], [ 41, 42 ], [ 46, 48 ] ], [ [ 6, 8 ], [ 11, 11 ], [ 16, 16 ] ], [ [ 10, 10 ], [ 31, 34 ], [ 36, 38 ], [ 44, 45 ] ] ]
64a924dbe9c3b42139b95e3c9dc80b30fb09ee3e
969987a50394a9ebab0f8cce0ff22f6e2cfd7fb2
/devel/kanamemo/level.h
b54fa18795a0a5c227f3acb9257aa52570eb5a93
[]
no_license
jeeb/aegisub-historical
67bd9cf24e05926f1979942594e04d6b1ffce40c
b81be20fd953bd61be80bfe4c8944f1757605995
refs/heads/master
2021-05-28T03:49:26.880613
2011-09-02T00:03:40
2011-09-02T00:03:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,300
h
// Copyright (c) 2006, Rodrigo Braz Monteiro // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the Aegisub Group nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // ----------------------------------------------------------------------------- // // AEGISUB // // Website: http://aegisub.cellosoft.com // Contact: mailto:[email protected] // /////////// // Headers #include <wx/wxprec.h> ////////////// // Prototypes class GameDisplay; ///////////////////// // Game window class class LevelWindow : public wxDialog { private: GameDisplay *display; wxSlider *hiraSlider; wxSlider *kataSlider; wxCheckBox *autoLevelCheck; void OnOK(wxCommandEvent &event); void OnCancel(wxCommandEvent &event); public: LevelWindow(wxWindow *parent,GameDisplay *dsp); ~LevelWindow(); DECLARE_EVENT_TABLE(); };
[ "archmagezeratul@93549f3f-7f0a-0410-a4b3-e966c9c94f04" ]
[ [ [ 1, 65 ] ] ]
43b9498e1dde999d40c3416526d51b1b9b18609a
9426ad6e612863451ad7aac2ad8c8dd100a37a98
/Samples/smplComponent/Componet2/COM2DllApp.cpp
beb3a2a9ca19d308201394a7d29643c0863f32ac
[]
no_license
piroxiljin/ullib
61f7bd176c6088d42fd5aa38a4ba5d4825becd35
7072af667b6d91a3afd2f64310c6e1f3f6a055b1
refs/heads/master
2020-12-28T19:46:57.920199
2010-02-17T01:43:44
2010-02-17T01:43:44
57,068,293
0
0
null
2016-04-25T19:05:41
2016-04-25T19:05:41
null
WINDOWS-1251
C++
false
false
1,286
cpp
///\file ULCOMD2llApp.cpp ///\brief cpp файл класса динамической библиотеки COM-сервера(21.01.2007) #include "..\..\..\ULLib\Include\ULLib.h" #include "..\..\..\ULLib\Include\ULClassFactory.h" #include "..\\IFaces.h" #include <assert.h> #include "Component2.h" UL_DECLARE_DLLMAIN(); #ifdef _DEBUG #pragma comment(lib,"..\\..\\..\\ULLib\\Lib\\uULLibd.lib") #else #pragma comment(lib,"..\\..\\..\\ULLib\\Lib\\uULLib.lib") #endif class CCOM2DllApp: public ULApps::CULCOMDllApp { public: ///\brief Конструктор CCOM2DllApp(): ULApps::CULCOMDllApp() { }; virtual HRESULT OnRegisterServer() { return m_RegServ.RegisterServer(m_hInstance, CLSIDComponent2, _T("ULCOM2, Probe"), _T("ULCOM2.Probe"), _T("ULCOM2.Probe.1")); } virtual HRESULT OnUnregisterServer() { return m_RegServ.UnregisterServer(CLSIDComponent2, _T("ULCOM2.Probe"), _T("ULCOM2.Probe.1")); } virtual HRESULT OnGetClassObject(const CLSID& clsid, const IID& iid, void** ppvObject) { return GetClassObjectFromClassFactory<ULCOMs::CULClassFactory<CComponent2,ULCOMs::ULAgregation::CULAgregateNone<CComponent2>>> (CLSIDComponent2,clsid,iid,ppvObject); }; }; CCOM2DllApp app;
[ "UncleLab@a8b69a72-a546-0410-9fb4-5106a01aa11f" ]
[ [ [ 1, 51 ] ] ]
5415cc5280a93acbc31dcc0af9c0c2ccd6f7b549
cc5b962dfd2dc6acc0d401b1ab7b456c99c7e8c4
/Bomberman 1.0/unbreakableobject.cpp
4edea33fe3adfcdfab3409ab5c8a7fa9a06b9453
[]
no_license
andreapachas/bomberman-tsbk05
c9e47b784982185077eec2d659a217897abbacc7
8ca28cb3095428e41db12d0060fc5573b614d3de
refs/heads/master
2021-05-30T06:30:25.413561
2007-04-25T07:52:39
2007-04-25T07:52:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
199
cpp
#include "unbreakableobject.h" UnbreakableObject::UnbreakableObject(Model* model, GLfloat x, GLfloat z, GLfloat y, GLfloat rotation, GLfloat scale) : Object(model, x, z, y, rotation, scale) {}
[ "jonas.lindgren@774f44fe-ff29-0410-bf63-e573c7ae51ad" ]
[ [ [ 1, 4 ] ] ]
c10726816ad2fec6ada81ac92f83eed986cb5065
fd792229322e4042f6e88a01144665cebdb1c339
/vc/dependencies/raknet/include/RakNet/BitStream.h
b7f05c7ac7f055dcaf443ce4f8c02f89a71844d1
[]
no_license
weimingtom/mmomm
228d70d9d68834fa2470d2cd0719b9cd60f8dbcd
cab04fcad551f7f68f99fa0b6bb14cec3b962023
refs/heads/master
2021-01-10T02:14:31.896834
2010-03-15T16:15:43
2010-03-15T16:15:43
44,764,408
1
0
null
null
null
null
UTF-8
C++
false
false
71,662
h
/// \file BitStream.h /// \brief This class allows you to write and read native types as a string of bits. /// \details BitStream is used extensively throughout RakNet and is designed to be used by users as well. /// /// This file is part of RakNet Copyright 2003 Jenkins Software LLC /// /// Usage of RakNet is subject to the appropriate license agreement. /// #if defined(_MSC_VER) && _MSC_VER < 1299 // VC6 doesn't support template specialization #include "BitStream_NoTemplate.h" #else #ifndef __BITSTREAM_H #define __BITSTREAM_H #include "RakMemoryOverride.h" #include "RakNetDefines.h" #include "Export.h" #include "RakNetTypes.h" #include "RakString.h" #include "RakAssert.h" #include <math.h> #include <float.h> #ifdef _MSC_VER #pragma warning( push ) #endif /// The namespace RakNet is not consistently used. It's only purpose is to avoid compiler errors for classes whose names are very common. /// For the most part I've tried to avoid this simply by using names very likely to be unique for my classes. namespace RakNet { /// This class allows you to write and read native types as a string of bits. BitStream is used extensively throughout RakNet and is designed to be used by users as well. /// \sa BitStreamSample.txt class RAK_DLL_EXPORT BitStream { public: /// Default Constructor BitStream(); /// \brief Create the bitstream, with some number of bytes to immediately allocate. /// \details There is no benefit to calling this, unless you know exactly how many bytes you need and it is greater than BITSTREAM_STACK_ALLOCATION_SIZE. /// In that case all it does is save you one or more realloc calls. /// \param[in] initialBytesToAllocate the number of bytes to pre-allocate. BitStream( const unsigned int initialBytesToAllocate ); /// \brief Initialize the BitStream, immediately setting the data it contains to a predefined pointer. /// \details Set \a _copyData to true if you want to make an internal copy of the data you are passing. Set it to false to just save a pointer to the data. /// You shouldn't call Write functions with \a _copyData as false, as this will write to unallocated memory /// 99% of the time you will use this function to cast Packet::data to a bitstream for reading, in which case you should write something as follows: /// \code /// RakNet::BitStream bs(packet->data, packet->length, false); /// \endcode /// \param[in] _data An array of bytes. /// \param[in] lengthInBytes Size of the \a _data. /// \param[in] _copyData true or false to make a copy of \a _data or not. BitStream( unsigned char* _data, const unsigned int lengthInBytes, bool _copyData ); // Destructor ~BitStream(); /// Resets the bitstream for reuse. void Reset( void ); /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] var The value to write /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. template <class templateType> bool Serialize(bool writeToBitstream, templateType &var); /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. /// \details If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. template <class templateType> bool SerializeDelta(bool writeToBitstream, templateType &currentValue, templateType lastValue); /// \brief Bidirectional version of SerializeDelta when you don't know what the last value is, or there is no last value. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] currentValue The current value to write /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. template <class templateType> bool SerializeDelta(bool writeToBitstream, templateType &currentValue); /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] var The value to write /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. template <class templateType> bool SerializeCompressed(bool writeToBitstream, templateType &var); /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. /// \details If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. template <class templateType> bool SerializeCompressedDelta(bool writeToBitstream, templateType &currentValue, templateType lastValue); /// \brief Save as SerializeCompressedDelta(templateType &currentValue, templateType lastValue) when we have an unknown second parameter /// \return true on data read. False on insufficient data in bitstream template <class templateType> bool SerializeCompressedDelta(bool writeToBitstream, templateType &currentValue); /// \brief Bidirectional serialize/deserialize an array or casted stream or raw data. This does NOT do endian swapping. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] input a byte buffer /// \param[in] numberOfBytes the size of \a input in bytes /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool Serialize(bool writeToBitstream, char* input, const unsigned int numberOfBytes ); /// \brief Serialize a float into 2 bytes, spanning the range between \a floatMin and \a floatMax /// \param[in] f The float to write /// \param[in] floatMin Predetermined minimum value of f /// \param[in] floatMax Predetermined maximum value of f bool SerializeFloat16(bool writeToBitstream, float &f, float floatMin, float floatMax); /// \brief Bidirectional serialize/deserialize a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. /// \details Will further compress y or z axis aligned vectors. /// Accurate to 1/32767.5. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] x x /// \param[in] y y /// \param[in] z z /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. template <class templateType> // templateType for this function must be a float or double bool SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ); /// \brief Bidirectional serialize/deserialize a vector, using 10 bytes instead of 12. /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] x x /// \param[in] y y /// \param[in] z z /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. template <class templateType> // templateType for this function must be a float or double bool SerializeVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ); /// \brief Bidirectional serialize/deserialize a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] w w /// \param[in] x x /// \param[in] y y /// \param[in] z z /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. template <class templateType> // templateType for this function must be a float or double bool SerializeNormQuat(bool writeToBitstream, templateType &w, templateType &x, templateType &y, templateType &z); /// \brief Bidirectional serialize/deserialize an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each. /// \details Use 6 bytes instead of 36 /// Lossy, although the result is renormalized /// \return true on success, false on failure. template <class templateType> // templateType for this function must be a float or double bool SerializeOrthMatrix( bool writeToBitstream, templateType &m00, templateType &m01, templateType &m02, templateType &m10, templateType &m11, templateType &m12, templateType &m20, templateType &m21, templateType &m22 ); /// \brief Bidirectional serialize/deserialize numberToSerialize bits to/from the input. /// \details Right aligned data means in the case of a partial byte, the bits are aligned /// from the right (bit 0) rather than the left (as in the normal /// internal representation) You would set this to true when /// writing user data, and false when copying bitstream data, such /// as writing one bitstream to another /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data /// \param[in] input The data /// \param[in] numberOfBitsToSerialize The number of bits to write /// \param[in] rightAlignedBits if true data will be right aligned /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful. bool SerializeBits(bool writeToBitstream, unsigned char* input, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits = true ); /// \brief Write any integral type to a bitstream. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// \param[in] var The value to write template <class templateType> void Write(templateType var); /// \brief Write the dereferenced pointer to any integral type to a bitstream. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// \param[in] var The value to write template <class templateType> void WritePtr(templateType *var); /// \brief Write any integral type to a bitstream. /// \details If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <class templateType> void WriteDelta(templateType currentValue, templateType lastValue); /// \brief WriteDelta when you don't know what the last value is, or there is no last value. /// \param[in] currentValue The current value to write template <class templateType> void WriteDelta(templateType currentValue); /// \brief Write any integral type to a bitstream. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// \param[in] var The value to write template <class templateType> void WriteCompressed(templateType var); /// \brief Write any integral type to a bitstream. /// \details If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <class templateType> void WriteCompressedDelta(templateType currentValue, templateType lastValue); /// \brief Save as WriteCompressedDelta(templateType currentValue, templateType lastValue) when we have an unknown second parameter template <class templateType> void WriteCompressedDelta(templateType currentValue); /// \brief Read any integral type from a bitstream. /// \details Define __BITSTREAM_NATIVE_END if you need endian swapping. /// \param[in] var The value to read /// \return true on success, false on failure. template <class templateType> bool Read(templateType &var); /// \brief Read into a pointer to any integral type from a bitstream. /// \details Define __BITSTREAM_NATIVE_END if you need endian swapping. /// \param[in] var The value to read /// \return true on success, false on failure. template <class templateType> bool ReadPtr(templateType *var); /// \brief Read any integral type from a bitstream. /// \details If the written value differed from the value compared against in the write function, /// var will be updated. Otherwise it will retain the current value. /// ReadDelta is only valid from a previous call to WriteDelta /// \param[in] var The value to read /// \return true on success, false on failure. template <class templateType> bool ReadDelta(templateType &var); /// \brief Read any integral type from a bitstream. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// \param[in] var The value to read /// \return true on success, false on failure. template <class templateType> bool ReadCompressed(templateType &var); /// \brief Read any integral type from a bitstream. /// \details If the written value differed from the value compared against in the write function, /// var will be updated. Otherwise it will retain the current value. /// the current value will be updated. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// ReadCompressedDelta is only valid from a previous call to WriteDelta /// \param[in] var The value to read /// \return true on success, false on failure. template <class templateType> bool ReadCompressedDelta(templateType &var); /// \brief Read one bitstream to another. /// \param[in] numberOfBits bits to read /// \param bitStream the bitstream to read into from /// \return true on success, false on failure. bool Read( BitStream *bitStream, BitSize_t numberOfBits ); bool Read( BitStream *bitStream ); bool Read( BitStream &bitStream, BitSize_t numberOfBits ); bool Read( BitStream &bitStream ); /// \brief Write an array or casted stream or raw data. This does NOT do endian swapping. /// \param[in] input a byte buffer /// \param[in] numberOfBytes the size of \a input in bytes void Write( const char* input, const unsigned int numberOfBytes ); /// \brief Write one bitstream to another. /// \param[in] numberOfBits bits to write /// \param bitStream the bitstream to copy from void Write( BitStream *bitStream, BitSize_t numberOfBits ); void Write( BitStream *bitStream ); void Write( BitStream &bitStream, BitSize_t numberOfBits ); void Write( BitStream &bitStream );\ /// \brief Write a float into 2 bytes, spanning the range between \a floatMin and \a floatMax /// \param[in] f The float to write /// \param[in] floatMin Predetermined minimum value of f /// \param[in] floatMax Predetermined maximum value of f void WriteFloat16( float x, float floatMin, float floatMax ); /// \brief Write a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. /// \details Will further compress y or z axis aligned vectors. /// Accurate to 1/32767.5. /// \param[in] x x /// \param[in] y y /// \param[in] z z template <class templateType> // templateType for this function must be a float or double void WriteNormVector( templateType x, templateType y, templateType z ); /// \brief Write a vector, using 10 bytes instead of 12. /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, /// so only use if accuracy is not important. /// \param[in] x x /// \param[in] y y /// \param[in] z z template <class templateType> // templateType for this function must be a float or double void WriteVector( templateType x, templateType y, templateType z ); /// \brief Write a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy. /// \param[in] w w /// \param[in] x x /// \param[in] y y /// \param[in] z z template <class templateType> // templateType for this function must be a float or double void WriteNormQuat( templateType w, templateType x, templateType y, templateType z); /// \brief Write an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each. /// \details Use 6 bytes instead of 36 /// Lossy, although the result is renormalized template <class templateType> // templateType for this function must be a float or double void WriteOrthMatrix( templateType m00, templateType m01, templateType m02, templateType m10, templateType m11, templateType m12, templateType m20, templateType m21, templateType m22 ); /// \brief Read an array or casted stream of byte. /// \details The array is raw data. There is no automatic endian conversion with this function /// \param[in] output The result byte array. It should be larger than @em numberOfBytes. /// \param[in] numberOfBytes The number of byte to read /// \return true on success false if there is some missing bytes. bool Read( char* output, const unsigned int numberOfBytes ); /// \brief Read a float into 2 bytes, spanning the range between \a floatMin and \a floatMax /// \param[in] f The float to read /// \param[in] floatMin Predetermined minimum value of f /// \param[in] floatMax Predetermined maximum value of f bool ReadFloat16( float &f, float floatMin, float floatMax ); /// \brief Read a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes. /// \details Will further compress y or z axis aligned vectors. /// Accurate to 1/32767.5. /// \param[in] x x /// \param[in] y y /// \param[in] z z /// \return true on success, false on failure. template <class templateType> // templateType for this function must be a float or double bool ReadNormVector( templateType &x, templateType &y, templateType &z ); /// \brief Read 3 floats or doubles, using 10 bytes, where those float or doubles comprise a vector. /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, /// so only use if accuracy is not important. /// \param[in] x x /// \param[in] y y /// \param[in] z z /// \return true on success, false on failure. template <class templateType> // templateType for this function must be a float or double bool ReadVector( templateType &x, templateType &y, templateType &z ); /// \brief Read a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. /// \param[in] w w /// \param[in] x x /// \param[in] y y /// \param[in] z z /// \return true on success, false on failure. template <class templateType> // templateType for this function must be a float or double bool ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z); /// \brief Read an orthogonal matrix from a quaternion, reading 3 components of the quaternion in 2 bytes each and extrapolatig the 4th. /// \details Use 6 bytes instead of 36 /// Lossy, although the result is renormalized /// \return true on success, false on failure. template <class templateType> // templateType for this function must be a float or double bool ReadOrthMatrix( templateType &m00, templateType &m01, templateType &m02, templateType &m10, templateType &m11, templateType &m12, templateType &m20, templateType &m21, templateType &m22 ); /// \brief Sets the read pointer back to the beginning of your data. void ResetReadPointer( void ); /// \brief Sets the write pointer back to the beginning of your data. void ResetWritePointer( void ); /// \brief This is good to call when you are done with the stream to make /// sure you didn't leave any data left over void void AssertStreamEmpty( void ); /// \brief RAKNET_DEBUG_PRINTF the bits in the stream. Great for debugging. void PrintBits( char *out ) const; void PrintBits( void ) const; void PrintHex( char *out ) const; void PrintHex( void ) const; /// \brief Ignore data we don't intend to read /// \param[in] numberOfBits The number of bits to ignore void IgnoreBits( const BitSize_t numberOfBits ); /// \brief Ignore data we don't intend to read /// \param[in] numberOfBits The number of bytes to ignore void IgnoreBytes( const unsigned int numberOfBytes ); /// \brief Move the write pointer to a position on the array. /// \param[in] offset the offset from the start of the array. /// \attention /// \details Dangerous if you don't know what you are doing! /// For efficiency reasons you can only write mid-stream if your data is byte aligned. void SetWriteOffset( const BitSize_t offset ); /// \brief Returns the length in bits of the stream inline BitSize_t GetNumberOfBitsUsed( void ) const {return GetWriteOffset();} inline BitSize_t GetWriteOffset( void ) const {return numberOfBitsUsed;} /// \brief Returns the length in bytes of the stream inline BitSize_t GetNumberOfBytesUsed( void ) const {return BITS_TO_BYTES( numberOfBitsUsed );} /// \brief Returns the number of bits into the stream that we have read inline BitSize_t GetReadOffset( void ) const {return readOffset;} /// \brief Sets the read bit index void SetReadOffset( const BitSize_t newReadOffset ) {readOffset=newReadOffset;} /// \brief Returns the number of bits left in the stream that haven't been read inline BitSize_t GetNumberOfUnreadBits( void ) const {return numberOfBitsUsed - readOffset;} /// \brief Makes a copy of the internal data for you \a _data will point to /// the stream. Partial bytes are left aligned. /// \param[out] _data The allocated copy of GetData() /// \return The length in bits of the stream. BitSize_t CopyData( unsigned char** _data ) const; /// \internal /// Set the stream to some initial data. void SetData( unsigned char *input ); /// Gets the data that BitStream is writing to / reading from. /// Partial bytes are left aligned. /// \return A pointer to the internal state inline unsigned char* GetData( void ) const {return data;} /// \brief Write numberToWrite bits from the input source. /// \details Right aligned data means in the case of a partial byte, the bits are aligned /// from the right (bit 0) rather than the left (as in the normal /// internal representation) You would set this to true when /// writing user data, and false when copying bitstream data, such /// as writing one bitstream to another. /// \param[in] input The data /// \param[in] numberOfBitsToWrite The number of bits to write /// \param[in] rightAlignedBits if true data will be right aligned void WriteBits( const unsigned char* input, BitSize_t numberOfBitsToWrite, const bool rightAlignedBits = true ); /// \brief Align the bitstream to the byte boundary and then write the /// specified number of bits. /// \details This is faster than WriteBits but /// wastes the bits to do the alignment and requires you to call /// ReadAlignedBits at the corresponding read position. /// \param[in] input The data /// \param[in] numberOfBytesToWrite The size of input. void WriteAlignedBytes( const unsigned char *input, const unsigned int numberOfBytesToWrite ); // Endian swap bytes already in the bitstream void EndianSwapBytes( int byteOffset, int length ); /// \brief Aligns the bitstream, writes inputLength, and writes input. Won't write beyond maxBytesToWrite /// \param[in] input The data /// \param[in] inputLength The size of input. /// \param[in] maxBytesToWrite Max bytes to write void WriteAlignedBytesSafe( const char *input, const unsigned int inputLength, const unsigned int maxBytesToWrite ); /// \brief Read bits, starting at the next aligned bits. /// \details Note that the modulus 8 starting offset of the sequence must be the same as /// was used with WriteBits. This will be a problem with packet /// coalescence unless you byte align the coalesced packets. /// \param[in] output The byte array larger than @em numberOfBytesToRead /// \param[in] numberOfBytesToRead The number of byte to read from the internal state /// \return true if there is enough byte. bool ReadAlignedBytes( unsigned char *output, const unsigned int numberOfBytesToRead ); /// \brief Reads what was written by WriteAlignedBytesSafe. /// \param[in] input The data /// \param[in] maxBytesToRead Maximum number of bytes to read /// \return true on success, false on failure. bool ReadAlignedBytesSafe( char *input, int &inputLength, const int maxBytesToRead ); bool ReadAlignedBytesSafe( char *input, unsigned int &inputLength, const unsigned int maxBytesToRead ); /// \brief Same as ReadAlignedBytesSafe() but allocates the memory for you using new, rather than assuming it is safe to write to /// \param[in] input input will be deleted if it is not a pointer to 0 /// \return true on success, false on failure. bool ReadAlignedBytesSafeAlloc( char **input, int &inputLength, const unsigned int maxBytesToRead ); bool ReadAlignedBytesSafeAlloc( char **input, unsigned int &inputLength, const unsigned int maxBytesToRead ); /// \brief Align the next write and/or read to a byte boundary. /// \details This can be used to 'waste' bits to byte align for efficiency reasons It /// can also be used to force coalesced bitstreams to start on byte /// boundaries so so WriteAlignedBits and ReadAlignedBits both /// calculate the same offset when aligning. inline void AlignWriteToByteBoundary( void ) {numberOfBitsUsed += 8 - ( (( numberOfBitsUsed - 1 ) & 7) + 1 );} /// \brief Align the next write and/or read to a byte boundary. /// \details This can be used to 'waste' bits to byte align for efficiency reasons It /// can also be used to force coalesced bitstreams to start on byte /// boundaries so so WriteAlignedBits and ReadAlignedBits both /// calculate the same offset when aligning. inline void AlignReadToByteBoundary( void ) {readOffset += 8 - ( (( readOffset - 1 ) & 7 ) + 1 );} /// \brief Read \a numberOfBitsToRead bits to the output source. /// \details alignBitsToRight should be set to true to convert internal /// bitstream data to userdata. It should be false if you used /// WriteBits with rightAlignedBits false /// \param[in] output The resulting bits array /// \param[in] numberOfBitsToRead The number of bits to read /// \param[in] alignBitsToRight if true bits will be right aligned. /// \return true if there is enough bits to read bool ReadBits( unsigned char *output, BitSize_t numberOfBitsToRead, const bool alignBitsToRight = true ); /// \brief Write a 0 void Write0( void ); /// \brief Write a 1 void Write1( void ); /// \brief Reads 1 bit and returns true if that bit is 1 and false if it is 0. bool ReadBit( void ); /// \brief If we used the constructor version with copy data off, this /// *makes sure it is set to on and the data pointed to is copied. void AssertCopyData( void ); /// \brief Use this if you pass a pointer copy to the constructor /// *(_copyData==false) and want to overallocate to prevent /// reallocation. void SetNumberOfBitsAllocated( const BitSize_t lengthInBits ); /// \brief Reallocates (if necessary) in preparation of writing numberOfBitsToWrite void AddBitsAndReallocate( const BitSize_t numberOfBitsToWrite ); /// \internal /// \return How many bits have been allocated internally BitSize_t GetNumberOfBitsAllocated(void) const; /// \brief Read strings, non reference. bool Read(char *var); bool Read(unsigned char *var); /// Write zeros until the bitstream is filled up to \a bytes void PadWithZeroToByteLength( unsigned int bytes ); /// \internal Unrolled inner loop, for when performance is critical void WriteAlignedVar8(const char *input); /// \internal Unrolled inner loop, for when performance is critical bool ReadAlignedVar8(char *output); /// \internal Unrolled inner loop, for when performance is critical void WriteAlignedVar16(const char *input); /// \internal Unrolled inner loop, for when performance is critical bool ReadAlignedVar16(char *output); /// \internal Unrolled inner loop, for when performance is critical void WriteAlignedVar32(const char *input); /// \internal Unrolled inner loop, for when performance is critical bool ReadAlignedVar32(char *output); /// ---- Member function template specialization declarations ---- // Used for VC7 #if defined(_MSC_VER) && _MSC_VER == 1300 /// Write a bool to a bitstream. /// \param[in] var The value to write template <> void Write(bool var); /// Write a systemAddress to a bitstream /// \param[in] var The value to write template <> void Write(SystemAddress var); /// Write a uint24_t to a bitstream /// \param[in] var The value to write template <> void Write(uint24_t var); /// Write a RakNetGUID to a bitsteam /// \param[in] var The value to write template <> void Write(RakNetGuid var); /// Write an networkID to a bitstream /// \param[in] var The value to write template <> void Write(NetworkID var); /// Write a string to a bitstream /// \param[in] var The value to write template <> void Write(const char* var); template <> void Write(const unsigned char* var); template <> void Write(char* var); template <> void Write(unsigned char* var); template <> void Write(RakString var); /// \brief Write a systemAddress. /// \details If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <> void WriteDelta(SystemAddress currentValue, SystemAddress lastValue); template <> void WriteDelta(uint24_t currentValue, uint24_t lastValue); template <> void WriteDelta(RakNetGUID currentValue, RakNetGUID lastValue); /// \brief Write an networkID. /// \details If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <> void WriteDelta(NetworkID currentValue, NetworkID lastValue); /// \brief Write a bool delta. /// \details Same thing as just calling Write /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <> void WriteDelta(bool currentValue, bool lastValue); template <> void WriteCompressed(SystemAddress var); template <> void WriteCompressed(uint24_t var); template <> void WriteCompressed(RakNetGUID var); template <> void WriteCompressed(NetworkID var); template <> void WriteCompressed(bool var); /// For values between -1 and 1 template <> void WriteCompressed(float var); /// For values between -1 and 1 template <> void WriteCompressed(double var); /// Compressed string template <> void WriteCompressed(const char* var); template <> void WriteCompressed(const unsigned char* var); template <> void WriteCompressed(char* var); template <> void WriteCompressed(unsigned char* var); template <> void WriteCompressed(RakString var); /// \brief Write a bool delta. /// \details Same thing as just calling Write /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <> void WriteCompressedDelta(bool currentValue, bool lastValue); /// \brief Save as WriteCompressedDelta(bool currentValue, templateType lastValue) /// when we have an unknown second bool template <> void WriteCompressedDelta(bool currentValue); /// \brief Read a bool from a bitstream. /// \param[in] var The value to read /// \return true on success, false on failure. template <> bool Read(bool &var); /// \brief Read a systemAddress from a bitstream. /// \param[in] var The value to read /// \return true on success, false on failure. template <> bool Read(SystemAddress &var); template <> bool Read(uint24_t &var); template <> bool Read(RakNetGUID &var); /// \brief Read an NetworkID from a bitstream. /// \param[in] var The value to read /// \return true on success, false on failure. template <> bool Read(NetworkID &var); /// \brief Read a String from a bitstream. /// \param[in] var The value to read /// \return true on success, false on failure. template <> bool Read(char *&var); template <> bool Read(unsigned char *&var); template <> bool Read(RakString &var); /// \brief Read a bool from a bitstream. /// \param[in] var The value to read /// \return true on success, false on failure. template <> bool ReadDelta(bool &var); template <> bool ReadCompressed(SystemAddress &var); template <> bool ReadCompressed(uint24_t &var); template <> bool ReadCompressed(RakNetGUID &var); template <> bool ReadCompressed(NetworkID &var); template <> bool ReadCompressed(bool &var); template <> bool ReadCompressed(float &var); /// For values between -1 and 1 /// \return true on success, false on failure. template <> bool ReadCompressed(double &var); template <> bool ReadCompressed(char* &var); template <> bool ReadCompressed(unsigned char *&var); template <> bool ReadCompressed(RakString &var); /// \brief Read a bool from a bitstream. /// \param[in] var The value to read /// \return true on success, false on failure. template <> bool ReadCompressedDelta(bool &var); #endif inline static bool DoEndianSwap(void) { #ifndef __BITSTREAM_NATIVE_END return IsNetworkOrder()==false; #else return false; #endif } inline static bool IsBigEndian(void) { return IsNetworkOrder(); } inline static bool IsNetworkOrder(void) {const static bool r = IsNetworkOrderInternal(); return r;} // Not inline, won't compile on PC due to winsock include errors static bool IsNetworkOrderInternal(void); static void ReverseBytes(unsigned char *input, unsigned char *output, const unsigned int length); static void ReverseBytesInPlace(unsigned char *data,const unsigned int length); private: BitStream( const BitStream &invalid) { (void) invalid; RakAssert(0); } /// \brief Assume the input source points to a native type, compress and write it. void WriteCompressed( const unsigned char* input, const unsigned int size, const bool unsignedData ); /// \brief Assume the input source points to a compressed native type. Decompress and read it. bool ReadCompressed( unsigned char* output, const unsigned int size, const bool unsignedData ); BitSize_t numberOfBitsUsed; BitSize_t numberOfBitsAllocated; BitSize_t readOffset; unsigned char *data; /// true if the internal buffer is copy of the data passed to the constructor bool copyData; /// BitStreams that use less than BITSTREAM_STACK_ALLOCATION_SIZE use the stack, rather than the heap to store data. It switches over if BITSTREAM_STACK_ALLOCATION_SIZE is exceeded unsigned char stackData[BITSTREAM_STACK_ALLOCATION_SIZE]; }; template <class templateType> inline bool BitStream::Serialize(bool writeToBitstream, templateType &var) { if (writeToBitstream) Write(var); else return Read(var); return true; } template <class templateType> inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &currentValue, templateType lastValue) { if (writeToBitstream) WriteDelta(currentValue, lastValue); else return ReadDelta(currentValue); return true; } template <class templateType> inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &currentValue) { if (writeToBitstream) WriteDelta(currentValue); else return ReadDelta(currentValue); return true; } template <class templateType> inline bool BitStream::SerializeCompressed(bool writeToBitstream, templateType &var) { if (writeToBitstream) WriteCompressed(var); else return ReadCompressed(var); return true; } template <class templateType> inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &currentValue, templateType lastValue) { if (writeToBitstream) WriteCompressedDelta(currentValue,lastValue); else return ReadCompressedDelta(currentValue); return true; } template <class templateType> inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &currentValue) { if (writeToBitstream) WriteCompressedDelta(currentValue); else return ReadCompressedDelta(currentValue); return true; } inline bool BitStream::Serialize(bool writeToBitstream, char* input, const unsigned int numberOfBytes ) { if (writeToBitstream) Write(input, numberOfBytes); else return Read(input, numberOfBytes); return true; } template <class templateType> inline bool BitStream::SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ) { if (writeToBitstream) WriteNormVector(x,y,z); else return ReadNormVector(x,y,z); return true; } template <class templateType> inline bool BitStream::SerializeVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z ) { if (writeToBitstream) WriteVector(x,y,z); else return ReadVector(x,y,z); return true; } template <class templateType> inline bool BitStream::SerializeNormQuat(bool writeToBitstream, templateType &w, templateType &x, templateType &y, templateType &z) { if (writeToBitstream) WriteNormQuat(w,x,y,z); else return ReadNormQuat(w,x,y,z); return true; } template <class templateType> inline bool BitStream::SerializeOrthMatrix( bool writeToBitstream, templateType &m00, templateType &m01, templateType &m02, templateType &m10, templateType &m11, templateType &m12, templateType &m20, templateType &m21, templateType &m22 ) { if (writeToBitstream) WriteOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); else return ReadOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22); return true; } inline bool BitStream::SerializeBits(bool writeToBitstream, unsigned char* input, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits ) { if (writeToBitstream) WriteBits(input,numberOfBitsToSerialize,rightAlignedBits); else return ReadBits(input,numberOfBitsToSerialize,rightAlignedBits); return true; } template <class templateType> inline void BitStream::Write(templateType var) { #ifdef _MSC_VER #pragma warning(disable:4127) // conditional expression is constant #endif if (sizeof(var)==1) WriteBits( ( unsigned char* ) & var, sizeof( templateType ) * 8, true ); else { #ifndef __BITSTREAM_NATIVE_END if (DoEndianSwap()) { unsigned char output[sizeof(templateType)]; ReverseBytes((unsigned char*)&var, output, sizeof(templateType)); WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true ); } else #endif WriteBits( ( unsigned char* ) & var, sizeof(templateType) * 8, true ); } } template <class templateType> inline void BitStream::WritePtr(templateType *var) { #ifdef _MSC_VER #pragma warning(disable:4127) // conditional expression is constant #endif if (sizeof(templateType)==1) WriteBits( ( unsigned char* ) var, sizeof( templateType ) * 8, true ); else { #ifndef __BITSTREAM_NATIVE_END if (DoEndianSwap()) { unsigned char output[sizeof(templateType)]; ReverseBytes((unsigned char*) var, output, sizeof(templateType)); WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true ); } else #endif WriteBits( ( unsigned char* ) var, sizeof(templateType) * 8, true ); } } /// \brief Write a bool to a bitstream. /// \param[in] var The value to write template <> inline void BitStream::Write(bool var) { if ( var ) Write1(); else Write0(); } /// \brief Write a systemAddress to a bitstream. /// \param[in] var The value to write template <> inline void BitStream::Write(SystemAddress var) { // Hide the address so routers don't modify it var.binaryAddress=~var.binaryAddress; // Don't endian swap the address WriteBits((unsigned char*)&var.binaryAddress, sizeof(var.binaryAddress)*8, true); Write(var.port); } template <> inline void BitStream::Write(uint24_t var) { AlignWriteToByteBoundary(); AddBitsAndReallocate(3*8); if (IsBigEndian()==false) { data[( numberOfBitsUsed >> 3 ) + 0] = ((char *)&var.val)[0]; data[( numberOfBitsUsed >> 3 ) + 1] = ((char *)&var.val)[1]; data[( numberOfBitsUsed >> 3 ) + 2] = ((char *)&var.val)[2]; } else { data[( numberOfBitsUsed >> 3 ) + 0] = ((char *)&var.val)[3]; data[( numberOfBitsUsed >> 3 ) + 1] = ((char *)&var.val)[2]; data[( numberOfBitsUsed >> 3 ) + 2] = ((char *)&var.val)[1]; } numberOfBitsUsed+=3*8; } template <> inline void BitStream::Write(RakNetGUID var) { Write(var.g); } /// \brief Write an networkID to a bitstream. /// \param[in] var The value to write template <> inline void BitStream::Write(NetworkID var) { #if NETWORK_ID_SUPPORTS_PEER_TO_PEER==1 RakAssert(NetworkID::IsPeerToPeerMode()); // if (NetworkID::IsPeerToPeerMode()) // Use the function rather than directly access the member or DLL users will get an undefined external error { if (var.guid!=UNASSIGNED_RAKNET_GUID) { Write(true); Write(var.guid); } else Write(false); if (var.systemAddress!=UNASSIGNED_SYSTEM_ADDRESS) { Write(true); Write(var.systemAddress); } else Write(false); } #endif /* Write(var.guid); Write(var.systemAddress); */ Write(var.localSystemAddress); } /// \brief Write a string to a bitstream. /// \param[in] var The value to write template <> inline void BitStream::Write(RakString var) { var.Serialize(this); } template <> inline void BitStream::Write(const char * var) { RakString::Serialize(var, this); } template <> inline void BitStream::Write(const unsigned char * var) { Write((const char*)var); } template <> inline void BitStream::Write(char * var) { Write((const char*)var); } template <> inline void BitStream::Write(unsigned char * var) { Write((const char*)var); } /// \brief Write any integral type to a bitstream. /// \details If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <class templateType> inline void BitStream::WriteDelta(templateType currentValue, templateType lastValue) { if (currentValue==lastValue) { Write(false); } else { Write(true); Write(currentValue); } } /* /// \brief Write a systemAddress. /// \details If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <> inline void BitStream::WriteDelta(SystemAddress currentValue, SystemAddress lastValue) { if (currentValue==lastValue) { Write(false); } else { Write(true); Write(currentValue); } } template <> inline void BitStream::WriteDelta(RakNetGUID currentValue, RakNetGUID lastValue) { if (currentValue==lastValue) { Write(false); } else { Write(true); Write(currentValue); } } /// \brief Write a systemAddress. /// \details If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <> inline void BitStream::WriteDelta(NetworkID currentValue, NetworkID lastValue) { if (currentValue==lastValue) { Write(false); } else { Write(true); Write(currentValue); } } */ /// \brief Write a bool delta. Same thing as just calling Write /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <> inline void BitStream::WriteDelta(bool currentValue, bool lastValue) { (void) lastValue; Write(currentValue); } /// \brief WriteDelta when you don't know what the last value is, or there is no last value. /// \param[in] currentValue The current value to write template <class templateType> inline void BitStream::WriteDelta(templateType currentValue) { Write(true); Write(currentValue); } /// \brief Write any integral type to a bitstream. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// \param[in] var The value to write template <class templateType> inline void BitStream::WriteCompressed(templateType var) { #ifdef _MSC_VER #pragma warning(disable:4127) // conditional expression is constant #endif if (sizeof(var)==1) WriteCompressed( ( unsigned char* ) & var, sizeof( templateType ) * 8, true ); else { #ifndef __BITSTREAM_NATIVE_END #ifdef _MSC_VER #pragma warning(disable:4244) // '=' : conversion from 'unsigned long' to 'unsigned short', possible loss of data #endif if (DoEndianSwap()) { unsigned char output[sizeof(templateType)]; ReverseBytes((unsigned char*)&var, output, sizeof(templateType)); WriteCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true ); } else #endif WriteCompressed( ( unsigned char* ) & var, sizeof(templateType) * 8, true ); } } template <> inline void BitStream::WriteCompressed(SystemAddress var) { Write(var); } template <> inline void BitStream::WriteCompressed(RakNetGUID var) { Write(var); } template <> inline void BitStream::WriteCompressed(uint24_t var) { Write(var); } template <> inline void BitStream::WriteCompressed(NetworkID var) { Write(var); } template <> inline void BitStream::WriteCompressed(bool var) { Write(var); } /// For values between -1 and 1 template <> inline void BitStream::WriteCompressed(float var) { RakAssert(var > -1.01f && var < 1.01f); if (var < -1.0f) var=-1.0f; if (var > 1.0f) var=1.0f; Write((unsigned short)((var+1.0f)*32767.5f)); } /// For values between -1 and 1 template <> inline void BitStream::WriteCompressed(double var) { RakAssert(var > -1.01 && var < 1.01); if (var < -1.0f) var=-1.0f; if (var > 1.0f) var=1.0f; #ifdef _DEBUG RakAssert(sizeof(unsigned long)==4); #endif Write((unsigned long)((var+1.0)*2147483648.0)); } /// Compress the string template <> inline void BitStream::WriteCompressed(RakString var) { var.SerializeCompressed(this,0,false); } template <> inline void BitStream::WriteCompressed(const char * var) { RakString::SerializeCompressed(var,this,0,false); } template <> inline void BitStream::WriteCompressed(const unsigned char * var) { WriteCompressed((const char*) var); } template <> inline void BitStream::WriteCompressed(char * var) { WriteCompressed((const char*) var); } template <> inline void BitStream::WriteCompressed(unsigned char * var) { WriteCompressed((const char*) var); } /// \brief Write any integral type to a bitstream. /// \details If the current value is different from the last value /// the current value will be written. Otherwise, a single bit will be written /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <class templateType> inline void BitStream::WriteCompressedDelta(templateType currentValue, templateType lastValue) { if (currentValue==lastValue) { Write(false); } else { Write(true); WriteCompressed(currentValue); } } /// \brief Write a bool delta. Same thing as just calling Write /// \param[in] currentValue The current value to write /// \param[in] lastValue The last value to compare against template <> inline void BitStream::WriteCompressedDelta(bool currentValue, bool lastValue) { (void) lastValue; Write(currentValue); } /// \brief Save as WriteCompressedDelta(templateType currentValue, templateType lastValue) /// when we have an unknown second parameter template <class templateType> inline void BitStream::WriteCompressedDelta(templateType currentValue) { Write(true); WriteCompressed(currentValue); } /// \brief Save as WriteCompressedDelta(bool currentValue, templateType lastValue) /// when we have an unknown second bool template <> inline void BitStream::WriteCompressedDelta(bool currentValue) { Write(currentValue); } /// \brief Read any integral type from a bitstream. Define __BITSTREAM_NATIVE_END if you need endian swapping. /// \param[in] var The value to read template <class templateType> inline bool BitStream::Read(templateType &var) { #ifdef _MSC_VER #pragma warning(disable:4127) // conditional expression is constant #endif if (sizeof(var)==1) return ReadBits( ( unsigned char* ) &var, sizeof(templateType) * 8, true ); else { #ifndef __BITSTREAM_NATIVE_END #ifdef _MSC_VER #pragma warning(disable:4244) // '=' : conversion from 'unsigned long' to 'unsigned short', possible loss of data #endif if (DoEndianSwap()) { unsigned char output[sizeof(templateType)]; if (ReadBits( ( unsigned char* ) output, sizeof(templateType) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(templateType)); return true; } return false; } else #endif return ReadBits( ( unsigned char* ) & var, sizeof(templateType) * 8, true ); } } template <class templateType> inline bool BitStream::ReadPtr(templateType *var) { #ifdef _MSC_VER #pragma warning(disable:4127) // conditional expression is constant #endif if (sizeof(templateType)==1) return ReadBits( ( unsigned char* ) var, sizeof(templateType) * 8, true ); else { #ifndef __BITSTREAM_NATIVE_END #ifdef _MSC_VER #pragma warning(disable:4244) // '=' : conversion from 'unsigned long' to 'unsigned short', possible loss of data #endif if (DoEndianSwap()) { unsigned char output[sizeof(templateType)]; if (ReadBits( ( unsigned char* ) output, sizeof(templateType) * 8, true )) { ReverseBytes(output, (unsigned char*)var, sizeof(templateType)); return true; } return false; } else #endif return ReadBits( ( unsigned char* ) var, sizeof(templateType) * 8, true ); } } /// \brief Read a bool from a bitstream. /// \param[in] var The value to read template <> inline bool BitStream::Read(bool &var) { if ( readOffset + 1 > numberOfBitsUsed ) return false; if ( data[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) // Is it faster to just write it out here? var = true; else var = false; // Has to be on a different line for Mac readOffset++; return true; } /// \brief Read a systemAddress from a bitstream. /// \param[in] var The value to read template <> inline bool BitStream::Read(SystemAddress &var) { // Read(var.binaryAddress); // Don't endian swap the address ReadBits( ( unsigned char* ) & var.binaryAddress, sizeof(var.binaryAddress) * 8, true ); // Unhide the IP address, done to prevent routers from changing it var.binaryAddress=~var.binaryAddress; return Read(var.port); } template <> inline bool BitStream::Read(uint24_t &var) { AlignReadToByteBoundary(); if ( readOffset + 3*8 > numberOfBitsUsed ) return false; if (IsBigEndian()==false) { ((char *)&var.val)[0]=data[ (readOffset >> 3) + 0]; ((char *)&var.val)[1]=data[ (readOffset >> 3) + 1]; ((char *)&var.val)[2]=data[ (readOffset >> 3) + 2]; ((char *)&var.val)[3]=0; } else { ((char *)&var.val)[3]=data[ (readOffset >> 3) + 0]; ((char *)&var.val)[2]=data[ (readOffset >> 3) + 1]; ((char *)&var.val)[1]=data[ (readOffset >> 3) + 2]; ((char *)&var.val)[0]=0; } readOffset+=3*8; return true; } template <> inline bool BitStream::Read(RakNetGUID &var) { return Read(var.g); } /// \brief Read an networkID from a bitstream. /// \param[in] var The value to read template <> inline bool BitStream::Read(NetworkID &var) { #if NETWORK_ID_SUPPORTS_PEER_TO_PEER==1 RakAssert(NetworkID::IsPeerToPeerMode()); //if (NetworkID::IsPeerToPeerMode()) // Use the function rather than directly access the member or DLL users will get an undefined external error { bool hasGuid, hasSystemAddress; Read(hasGuid); if (hasGuid) Read(var.guid); else var.guid=UNASSIGNED_RAKNET_GUID; Read(hasSystemAddress); if (hasSystemAddress) Read(var.systemAddress); else var.systemAddress=UNASSIGNED_SYSTEM_ADDRESS; } #endif /* Read(var.guid); Read(var.systemAddress); */ return Read(var.localSystemAddress); } /// \brief Read an networkID from a bitstream. /// \param[in] var The value to read template <> inline bool BitStream::Read(RakString &var) { return var.Deserialize(this); } template <> inline bool BitStream::Read(char *&var) { return RakString::Deserialize(var,this); } template <> inline bool BitStream::Read(unsigned char *&var) { return RakString::Deserialize((char*) var,this); } /// \brief Read any integral type from a bitstream. /// \details If the written value differed from the value compared against in the write function, /// var will be updated. Otherwise it will retain the current value. /// ReadDelta is only valid from a previous call to WriteDelta /// \param[in] var The value to read template <class templateType> inline bool BitStream::ReadDelta(templateType &var) { bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=Read(var); return success; } /// \brief Read a bool from a bitstream. /// \param[in] var The value to read template <> inline bool BitStream::ReadDelta(bool &var) { return Read(var); } /// \brief Read any integral type from a bitstream. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// \param[in] var The value to read template <class templateType> inline bool BitStream::ReadCompressed(templateType &var) { #ifdef _MSC_VER #pragma warning(disable:4127) // conditional expression is constant #endif if (sizeof(var)==1) return ReadCompressed( ( unsigned char* ) &var, sizeof(templateType) * 8, true ); else { #ifndef __BITSTREAM_NATIVE_END if (DoEndianSwap()) { unsigned char output[sizeof(templateType)]; if (ReadCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true )) { ReverseBytes(output, (unsigned char*)&var, sizeof(templateType)); return true; } return false; } else #endif return ReadCompressed( ( unsigned char* ) & var, sizeof(templateType) * 8, true ); } } template <> inline bool BitStream::ReadCompressed(SystemAddress &var) { return Read(var); } template <> inline bool BitStream::ReadCompressed(uint24_t &var) { return Read(var); } template <> inline bool BitStream::ReadCompressed(RakNetGUID &var) { return Read(var); } template <> inline bool BitStream::ReadCompressed(NetworkID &var) { return Read(var); } template <> inline bool BitStream::ReadCompressed(bool &var) { return Read(var); } /// For values between -1 and 1 template <> inline bool BitStream::ReadCompressed(float &var) { unsigned short compressedFloat; if (Read(compressedFloat)) { var = ((float)compressedFloat / 32767.5f - 1.0f); return true; } return false; } /// For values between -1 and 1 template <> inline bool BitStream::ReadCompressed(double &var) { unsigned long compressedFloat; if (Read(compressedFloat)) { var = ((double)compressedFloat / 2147483648.0 - 1.0); return true; } return false; } /// For strings template <> inline bool BitStream::ReadCompressed(RakString &var) { return var.DeserializeCompressed(this,false); } template <> inline bool BitStream::ReadCompressed(char *&var) { return RakString::DeserializeCompressed(var,this,false); } template <> inline bool BitStream::ReadCompressed(unsigned char *&var) { return RakString::DeserializeCompressed((char*) var,this,false); } /// \brief Read any integral type from a bitstream. /// \details If the written value differed from the value compared against in the write function, /// var will be updated. Otherwise it will retain the current value. /// the current value will be updated. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1. /// For non-floating point, this is lossless, but only has benefit if you use less than half the range of the type /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte /// ReadCompressedDelta is only valid from a previous call to WriteDelta /// \param[in] var The value to read template <class templateType> inline bool BitStream::ReadCompressedDelta(templateType &var) { bool dataWritten; bool success; success=Read(dataWritten); if (dataWritten) success=ReadCompressed(var); return success; } /// \brief Read a bool from a bitstream. /// \param[in] var The value to read template <> inline bool BitStream::ReadCompressedDelta(bool &var) { return Read(var); } template <class templateType> // templateType for this function must be a float or double void BitStream::WriteNormVector( templateType x, templateType y, templateType z ) { #ifdef _DEBUG RakAssert(x <= 1.01 && y <= 1.01 && z <= 1.01 && x >= -1.01 && y >= -1.01 && z >= -1.01); #endif if (x>1.0) x=1.0; if (y>1.0) y=1.0; if (z>1.0) z=1.0; if (x<-1.0) x=-1.0; if (y<-1.0) y=-1.0; if (z<-1.0) z=-1.0; Write((bool) (x < 0.0)); if (y==0.0) Write(true); else { Write(false); WriteCompressed((float)y); //Write((unsigned short)((y+1.0f)*32767.5f)); } if (z==0.0) Write(true); else { Write(false); WriteCompressed((float)z); //Write((unsigned short)((z+1.0f)*32767.5f)); } } template <class templateType> // templateType for this function must be a float or double void BitStream::WriteVector( templateType x, templateType y, templateType z ) { templateType magnitude = sqrt(x * x + y * y + z * z); Write((float)magnitude); if (magnitude > 0.00001f) { WriteCompressed((float)(x/magnitude)); WriteCompressed((float)(y/magnitude)); WriteCompressed((float)(z/magnitude)); // Write((unsigned short)((x/magnitude+1.0f)*32767.5f)); // Write((unsigned short)((y/magnitude+1.0f)*32767.5f)); // Write((unsigned short)((z/magnitude+1.0f)*32767.5f)); } } template <class templateType> // templateType for this function must be a float or double void BitStream::WriteNormQuat( templateType w, templateType x, templateType y, templateType z) { Write((bool)(w<0.0)); Write((bool)(x<0.0)); Write((bool)(y<0.0)); Write((bool)(z<0.0)); Write((unsigned short)(fabs(x)*65535.0)); Write((unsigned short)(fabs(y)*65535.0)); Write((unsigned short)(fabs(z)*65535.0)); // Leave out w and calculate it on the target } template <class templateType> // templateType for this function must be a float or double void BitStream::WriteOrthMatrix( templateType m00, templateType m01, templateType m02, templateType m10, templateType m11, templateType m12, templateType m20, templateType m21, templateType m22 ) { double qw; double qx; double qy; double qz; // Convert matrix to quat // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ float sum; sum = 1 + m00 + m11 + m22; if (sum < 0.0f) sum=0.0f; qw = sqrt( sum ) / 2; sum = 1 + m00 - m11 - m22; if (sum < 0.0f) sum=0.0f; qx = sqrt( sum ) / 2; sum = 1 - m00 + m11 - m22; if (sum < 0.0f) sum=0.0f; qy = sqrt( sum ) / 2; sum = 1 - m00 - m11 + m22; if (sum < 0.0f) sum=0.0f; qz = sqrt( sum ) / 2; if (qw < 0.0) qw=0.0; if (qx < 0.0) qx=0.0; if (qy < 0.0) qy=0.0; if (qz < 0.0) qz=0.0; qx = _copysign( qx, m21 - m12 ); qy = _copysign( qy, m02 - m20 ); qz = _copysign( qz, m10 - m01 ); WriteNormQuat(qw,qx,qy,qz); } template <class templateType> // templateType for this function must be a float or double bool BitStream::ReadNormVector( templateType &x, templateType &y, templateType &z ) { // unsigned short sy, sz; bool yZero, zZero; bool xNeg; float cy,cz; Read(xNeg); Read(yZero); if (yZero) y=0.0; else { ReadCompressed((float)cy); y=cy; //Read(sy); //y=((float)sy / 32767.5f - 1.0f); } if (!Read(zZero)) return false; if (zZero) z=0.0; else { // if (!Read(sz)) // return false; // z=((float)sz / 32767.5f - 1.0f); if (!ReadCompressed((float)cz)) return false; z=cz; } x = (templateType) (sqrtf((templateType)1.0 - y*y - z*z)); if (xNeg) x=-x; return true; } template <class templateType> // templateType for this function must be a float or double bool BitStream::ReadVector( templateType &x, templateType &y, templateType &z ) { float magnitude; //unsigned short sx,sy,sz; if (!Read(magnitude)) return false; if (magnitude>0.00001f) { // Read(sx); // Read(sy); // if (!Read(sz)) // return false; // x=((float)sx / 32767.5f - 1.0f) * magnitude; // y=((float)sy / 32767.5f - 1.0f) * magnitude; // z=((float)sz / 32767.5f - 1.0f) * magnitude; float cx,cy,cz; ReadCompressed(cx); ReadCompressed(cy); if (!ReadCompressed(cz)) return false; x=cx; y=cy; z=cz; x*=magnitude; y*=magnitude; z*=magnitude; } else { x=0.0; y=0.0; z=0.0; } return true; } template <class templateType> // templateType for this function must be a float or double bool BitStream::ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z) { bool cwNeg, cxNeg, cyNeg, czNeg; unsigned short cx,cy,cz; Read(cwNeg); Read(cxNeg); Read(cyNeg); Read(czNeg); Read(cx); Read(cy); if (!Read(cz)) return false; // Calculate w from x,y,z x=(templateType)(cx/65535.0); y=(templateType)(cy/65535.0); z=(templateType)(cz/65535.0); if (cxNeg) x=-x; if (cyNeg) y=-y; if (czNeg) z=-z; float difference = 1.0f - x*x - y*y - z*z; if (difference < 0.0f) difference=0.0f; w = (templateType)(sqrt(difference)); if (cwNeg) w=-w; return true; } template <class templateType> // templateType for this function must be a float or double bool BitStream::ReadOrthMatrix( templateType &m00, templateType &m01, templateType &m02, templateType &m10, templateType &m11, templateType &m12, templateType &m20, templateType &m21, templateType &m22 ) { float qw,qx,qy,qz; if (!ReadNormQuat(qw,qx,qy,qz)) return false; // Quat to orthogonal rotation matrix // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/index.htm double sqw = (double)qw*(double)qw; double sqx = (double)qx*(double)qx; double sqy = (double)qy*(double)qy; double sqz = (double)qz*(double)qz; m00 = (templateType)(sqx - sqy - sqz + sqw); // since sqw + sqx + sqy + sqz =1 m11 = (templateType)(-sqx + sqy - sqz + sqw); m22 = (templateType)(-sqx - sqy + sqz + sqw); double tmp1 = (double)qx*(double)qy; double tmp2 = (double)qz*(double)qw; m10 = (templateType)(2.0 * (tmp1 + tmp2)); m01 = (templateType)(2.0 * (tmp1 - tmp2)); tmp1 = (double)qx*(double)qz; tmp2 = (double)qy*(double)qw; m20 =(templateType)(2.0 * (tmp1 - tmp2)); m02 = (templateType)(2.0 * (tmp1 + tmp2)); tmp1 = (double)qy*(double)qz; tmp2 = (double)qx*(double)qw; m21 = (templateType)(2.0 * (tmp1 + tmp2)); m12 = (templateType)(2.0 * (tmp1 - tmp2)); return true; } template <class templateType> BitStream& operator<<(BitStream& out, templateType& c) { out.Write(c); return out; } template <class templateType> BitStream& operator>>(BitStream& in, templateType& c) { bool success = in.Read(c); RakAssert(success); return in; } } #ifdef _MSC_VER #pragma warning( pop ) #endif #endif #endif // VC6
[ [ [ 1, 1967 ] ] ]
8a95d788383d64afe6f62efff84332ed1c311460
7969164c2b9f3f12f99a7df28e83551c8b6e5db8
/sorce/fish/Main.cpp
8c5faaecceb80739817912d892086b68cad4bfa5
[ "MIT" ]
permissive
montoyamoraga/shbobo
9e9ab91e0ab8b8404d63fa71b15bfb446ade11ea
48246bbc29f2aa5b55644241b369d74e37e9f916
refs/heads/main
2023-07-04T19:02:16.494183
2008-08-14T01:42:07
2008-08-14T01:42:07
326,004,619
1
1
MIT
2021-04-11T23:47:58
2021-01-01T15:27:42
C
UTF-8
C++
false
false
1,769
cpp
#include <stdio.h> #include <string.h> //#include <ctype.h> #include "Chub.h" #include "_chubbing.c" #include "../JuceLibraryCode/JuceHeader.h" using namespace juce; #include "Chubbalyzer.h" #include "Chubagwonzer.h" BorderSize<int> bsi; BorderSize<int> gsi; #include "Garcon.h" Garcon * mastro; #include "Atom.h" #include "Recipe.h" #include "Grub.h" #include "Ecole.h" GoneFishing * gf; #include "Actions.h" #include "Zelda.h" #include "Julia.h" //#include "Chain.h" //ChainWin * cw; #include "_constructing.c" #include "_acting.c" #include "_editing.c" #include "_cursing.c" #include "_mousing.c" #include "_painting.c" #include "_parzing.c" #include "_printing.c" #include "_resizing.c" #include "_changing.c" #include "_commanding.c" //#include "_chubbing.c" #include "_fishing.c" #include "_filing.c" class ShboboFish : public JUCEApplication { public: ShboboFish(){} ~ShboboFish(){} void initialise (const String& commandLine) { //Julia::juliaz = Array <Julia* >(); bsi = BorderSize<int>(0,8,0,8); gsi = BorderSize<int>(0,4,0,4); mastro = new Garcon(); gf = new GoneFishing(); //cw = new ChainWin(); LookAndFeel::setDefaultLookAndFeel(mastro); Bloque::pathify(); new Julia(); new TooltipWindow(); //MenuBarModel::setMacMainMenu ( mastro); //mastro->chooseFileToOpen(); } void shutdown() { //jj = 0; //tt = 0; } const String getApplicationName() { return "Fish"; } const String getApplicationVersion() { return ProjectInfo::versionString; } bool moreThanOneInstanceAllowed() { return false; } void anotherInstanceStarted (const String& commandLine) { new Julia(); } private: }; START_JUCE_APPLICATION (ShboboFish)
[ [ [ 1, 8 ], [ 10, 87 ] ], [ [ 9, 9 ] ] ]
462ac03832eae39ca4983eeb0a55d0d8d1cd1f58
78d2527df34c524b0742f7e2a9686ea98c5a1bc8
/src/input/wav.cpp
c781d1dd507ce699d112e4229b9ae98b2771cdca
[]
no_license
BackupTheBerlios/flamenco
0a5f51c10f9bd089c59b16af070d68e567b72d6b
7352e727d3bb8b45f5ce8e512874280cecd1f8f1
refs/heads/master
2021-01-19T21:28:12.881078
2008-12-29T15:46:46
2008-12-29T15:46:46
39,894,137
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
4,278
cpp
/* libflamenco - lightweight and efficient software sound mixing library. (c) Trickster Games, 2008. Licensed under GPL license. Реализация источника звука из wav-файла. */ #include <flamenco/flamenco.h> #pragma warning(disable:4201) // Отключение предупреждения о nameless struct. #include <mmsystem.h> using namespace flamenco; // Конструктор. wav_decoder::wav_decoder( std::auto_ptr<source> source ) : mSource(source), mDataOffset(0), mSampleRate(0), mSampleCount(0), mChannelCount(0), mChannelBuffer(NULL) { assert(mSource.get()); // Проверяем заголовок RIFF. const u32 RIFF = 'FFIR', WAVE = 'EVAW'; u32 chunkId; mSource->read(&chunkId, sizeof(u32), 1); if (chunkId != RIFF) throw std::runtime_error("File is not a valid RIFF container."); mSource->seek(4, SEEK_CUR); mSource->read(&chunkId, sizeof(u32), 1); if (chunkId != WAVE) throw std::runtime_error("File is not a valid WAVE container."); // Читаем настройки. const u32 FMT = ' tmf'; mSource->read(&chunkId, sizeof(u32), 1); if (chunkId != FMT) throw std::runtime_error("Missing 'fmt ' section after RIFF header."); u32 chunkSize; mSource->read(&chunkSize, sizeof(u32), 1); WAVEFORMATEX format; mSource->read(&format, sizeof(WAVEFORMATEX), 1); // Проверяем правильность формата. if (format.wFormatTag != WAVE_FORMAT_PCM) throw std::runtime_error("Compressed wave files are not supported."); if (format.wBitsPerSample != 16) throw std::runtime_error("Unsupported sample format (expected 16 bits)."); mSampleRate = format.nSamplesPerSec; mChannelCount = format.nChannels; assert(0 != mChannelCount); if (mChannelCount > 2) throw std::runtime_error("Expected mono or stereo stream."); // Создаем буфер для преобразования семплов. mChannelBuffer.reset(new s16[CHANNEL_BUFFER_SIZE_IN_SAMPLES * mChannelCount]); // Перематываем на начало следующего чанка и ищем секцию 'data'. const u32 DATA = 'atad'; mSource->seek(chunkSize - sizeof(WAVEFORMATEX), SEEK_CUR); for (;;) { if (mSource->read(&chunkId, sizeof(u32), 1) != 1) throw std::runtime_error("EOF while looking for 'data' section."); mSource->read(&chunkSize, sizeof(u32), 1); if (chunkId == DATA) break; mSource->seek(chunkSize, SEEK_CUR); } // Секция найдена, в chunkSize ее размер. mSampleCount = chunkSize / (sizeof(s16) * mChannelCount); mDataOffset = mSource->tell(); } // Копирует в левый и правый каналы count декодированных семплов. u32 wav_decoder::unpack( f32 * left, f32 * right, u32 count ) { // Количество семплов, которые можно считать. const u32 PORTION_SIZE = sizeof(s16) * mChannelCount, READ_COUNT = std::min(count, mSampleCount - (mSource->tell() - mDataOffset) / PORTION_SIZE); u32 samplesRead = mSource->read(mChannelBuffer.get(), PORTION_SIZE, READ_COUNT); assert(samplesRead == READ_COUNT); // Моно. if (mChannelCount == 1) { for (u32 i = 0; i < CHANNEL_BUFFER_SIZE_IN_SAMPLES; ++i) *left++ = *right++ = static_cast<f32>(mChannelBuffer[i]) / (1 << 15); } else // Стерео. { for (u32 i = 0; i < CHANNEL_BUFFER_SIZE_IN_SAMPLES; ++i) { *left++ = static_cast<f32>(mChannelBuffer[(i << 1)]) / (1 << 15); *right++ = static_cast<f32>(mChannelBuffer[(i << 1) + 1]) / (1 << 15); } } return READ_COUNT; } // Установка курсора начала декодирования на заданный семпл. void wav_decoder::seek( u32 sample ) { assert(sample < mSampleCount); mSource->seek(mDataOffset + sample * mChannelCount * sizeof(s16), SEEK_SET); }
[ "devnull@localhost", "eJ@GAME", "[email protected]" ]
[ [ [ 1, 6 ], [ 8, 9 ], [ 13, 58 ], [ 60, 64 ], [ 66, 66 ], [ 68, 71 ], [ 74, 75 ], [ 77, 84 ], [ 86, 87 ], [ 89, 89 ], [ 91, 91 ], [ 93, 94 ], [ 97, 97 ], [ 100, 101 ], [ 103, 104 ] ], [ [ 7, 7 ], [ 11, 12 ], [ 72, 73 ], [ 98, 99 ], [ 102, 102 ], [ 105, 105 ] ], [ [ 10, 10 ], [ 59, 59 ], [ 65, 65 ], [ 67, 67 ], [ 76, 76 ], [ 85, 85 ], [ 88, 88 ], [ 90, 90 ], [ 92, 92 ], [ 95, 96 ] ] ]
0158846f63ae4763234ff6a8132d7596c5624ad1
e84247553b17a94179af5db1b6d83e745a5aa11e
/lab source code/20085528谢行sy0303.cpp
f8a2dcd94aea94122c624de0b630f0b3551d1acc
[]
no_license
xhbang/Solution-to-C-Class
3eb055d4ff0d8eaeec7749ac9686420076f95818
6c6b6110fa6dffa97997c6d705dcde2ff8e2ca7b
refs/heads/master
2020-05-18T17:02:17.974295
2011-12-03T03:22:18
2011-12-03T03:22:18
2,903,122
0
0
null
null
null
null
MacCentralEurope
C++
false
false
372
cpp
#include <stdio.h> #include <limits.h> void main() { int a, b, c, people=12; printf("hello,please enter the num a, b, c:"); scanf("%d,%d,%d,&a,&b,&c"); while(people<INT_MAX && people%5!=a || people%8!=b || people!= c) people++; if(people<INT_MAX£©{ printf("oh,yeah,this is what u want:"); printf("%d",people); } else printf("no solution!") }
[ [ [ 1, 16 ] ] ]
c573d5fa4523dee470e86ea1399cf79e443b27ef
2345acdc4a1a96c23ff7579fbe3e8771fe03f665
/Excellent_Adventure_Master/EffectManager.h
e1650c2c126fcee9cd10a7989f90c4f2c0df0846
[]
no_license
Bionic-Badger/Excellent-Adventure
7310e62fbc9f754ada2a39d9e9df61905ade2fe8
8d053ab603ca013bdf3b883528e8611574ed9618
refs/heads/master
2021-01-16T20:41:05.608323
2010-08-24T07:45:02
2010-08-24T07:45:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,319
h
#ifndef _EFFECT_MANAGER_H #define _EFFECT_MANAGER_H #include "Globals.h" #include "Spectrum.h" #include "PowerManagement.h" #include "Canvas.h" #define EM_MODE_IDLE 0x00 #define EM_MODE_RING 0x01 // 16 + submodes #define EM_MODE_CALL 0x10 #define EM_MODE_CALLENDED 0x11 // Overtime: when someone has been on the line too long #define EM_MODE_CALL_OVERTIME 0x12 #define EM_MODE_CALLENDED_FADE_END 0x13 #define EM_MODE_CALLENDED_REBOOTED 0x14 // 64 + submodes #define EM_MODE_DISABLE 0x40 #define EM_MODE_DISABLE_FADE_END 0x41 #define EM_MODE_DISABLE_STANDBY 0x42 #define EFFECTMODE_INTRO 0 #define EFFECTMODE_LOOP 1 #define EFFECTMODE_OUTRO 2 #define EM_CALL_DURATION_FRAMES ((1000 / EFFECT_POLL_DELAY_MS) * MAX_CALL_DURATION_SEC) // Idle -> Ring -> // The effect manager (EM) controls the effect scheduling for each booth. It // is driven by a timer interrupt service routine (ISR), and switches between // various effects based on different conditions. class EffectManager; struct Effect { int (*func) ( Canvas *, EffectManager *, char ); int duration; }; class EffectManager { Effect * m_effectsIdle; Effect * m_effectsRing; Effect * m_effectsCall; Effect * m_effectsOver; bool m_rebooting; bool m_rebootingPowerUp; char m_sizeIdle; char m_currentIdle; char m_sizeRing; char m_currentRing; char m_sizeCall; char m_currentCall; char m_sizeOver; char m_currentOver; int m_laserCallCount; // m_disablePanels tells the system to disable the panels. // m_panelsDisabled is the status bool m_disablePanels; bool m_panelsDisabled; bool m_laserOn; char m_mode; char m_modePrevious; unsigned long m_pollDelay; unsigned long m_duration; unsigned long m_pollLaser; Canvas m_canvas; Spectrum m_spectrum; PowerManagement * m_pm; void InitPanels(); void InitSpectrum(); void InitPins(); public: EffectManager ( PowerManagement * pm ); ~EffectManager(); void Destroy(); // An effect is a static function that is called for each frame of the // animation. The "type" of an effect is its void InitHardware(); void AddEffectsArrays ( Effect * effectsIdle, char sizeIdle, Effect * effectsRing, char sizeRing, Effect * effectsCall, char sizeCall, Effect * effectsOver, char sizeOver ); void SetMode ( char mode ); unsigned short GetRandomNumber(); void InstallAnimator(); unsigned short * GetSpectrum(); // These two are power management calls, not to be used for rebooting // panels. void EnableEffects(); void DisableEffects(); bool EffectsDisabled(); void RebootPanels(); bool RebootComplete(); // Note that this will be called during a ring, and will be auto-cut off // at the beginning of the next frame. void LaserOn(); void LaserOff(); void PollLaser ( unsigned long time ); void Poll ( unsigned long time, bool offHook ); }; //extern void ISRGlobal(); #endif
[ "[email protected]", "chris@[email protected]", "chris@.(none)" ]
[ [ [ 1, 2 ], [ 6, 7 ], [ 22, 22 ], [ 26, 26 ], [ 30, 31 ], [ 33, 35 ], [ 38, 39 ], [ 47, 51 ], [ 88, 88 ], [ 93, 96 ], [ 98, 98 ], [ 100, 100 ], [ 117, 117 ], [ 120, 120 ], [ 147, 152 ] ], [ [ 3, 5 ], [ 8, 21 ], [ 27, 28 ], [ 36, 37 ], [ 40, 46 ], [ 54, 87 ], [ 91, 91 ], [ 99, 99 ], [ 103, 110 ], [ 115, 115 ], [ 118, 119 ], [ 121, 145 ] ], [ [ 23, 25 ], [ 29, 29 ], [ 32, 32 ], [ 52, 53 ], [ 89, 90 ], [ 92, 92 ], [ 97, 97 ], [ 101, 102 ], [ 111, 114 ], [ 116, 116 ], [ 146, 146 ] ] ]
06d2323eb2d4ece6549a62a3db1164f728a4d27e
ad8046a7c792e31fab898fa13a7693ff34ef2b83
/eFilm/CustomeMessageExample/AUTOCLIENT/DlgProxy.cpp
8d37ffe0003717818ae25efed43e162a1bc69790
[]
no_license
alibinjamil/datamedris
df5f205775e78b76f15155c27e316f81beba1660
3f4711ef3c43e21870261bfbcab7fbafd369e114
refs/heads/master
2016-08-12T06:06:00.915112
2010-12-22T08:47:14
2010-12-22T08:47:14
44,970,197
0
0
null
null
null
null
UTF-8
C++
false
false
3,174
cpp
// DlgProxy.cpp : implementation file // #include "stdafx.h" #include "eFilmAutoClient.h" #include "DlgProxy.h" #include "eFilmAutoClientDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CEFilmAutoClientDlgAutoProxy IMPLEMENT_DYNCREATE(CEFilmAutoClientDlgAutoProxy, CCmdTarget) CEFilmAutoClientDlgAutoProxy::CEFilmAutoClientDlgAutoProxy() { EnableAutomation(); // To keep the application running as long as an automation // object is active, the constructor calls AfxOleLockApp. AfxOleLockApp(); // Get access to the dialog through the application's // main window pointer. Set the proxy's internal pointer // to point to the dialog, and set the dialog's back pointer to // this proxy. ASSERT (AfxGetApp()->m_pMainWnd != NULL); ASSERT_VALID (AfxGetApp()->m_pMainWnd); ASSERT_KINDOF(CEFilmAutoClientDlg, AfxGetApp()->m_pMainWnd); m_pDialog = (CEFilmAutoClientDlg*) AfxGetApp()->m_pMainWnd; m_pDialog->m_pAutoProxy = this; } CEFilmAutoClientDlgAutoProxy::~CEFilmAutoClientDlgAutoProxy() { // To terminate the application when all objects created with // with automation, the destructor calls AfxOleUnlockApp. // Among other things, this will destroy the main dialog if (m_pDialog != NULL) m_pDialog->m_pAutoProxy = NULL; AfxOleUnlockApp(); } void CEFilmAutoClientDlgAutoProxy::OnFinalRelease() { // When the last reference for an automation object is released // OnFinalRelease is called. The base class will automatically // deletes the object. Add additional cleanup required for your // object before calling the base class. CCmdTarget::OnFinalRelease(); } BEGIN_MESSAGE_MAP(CEFilmAutoClientDlgAutoProxy, CCmdTarget) //{{AFX_MSG_MAP(CEFilmAutoClientDlgAutoProxy) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() BEGIN_DISPATCH_MAP(CEFilmAutoClientDlgAutoProxy, CCmdTarget) //{{AFX_DISPATCH_MAP(CEFilmAutoClientDlgAutoProxy) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_DISPATCH_MAP END_DISPATCH_MAP() // Note: we add support for IID_IEFilmAutoClient to support typesafe binding // from VBA. This IID must match the GUID that is attached to the // dispinterface in the .ODL file. // {B9C9813B-B211-43F3-92C9-3575CCA9FBF3} static const IID IID_IEFilmAutoClient = { 0xb9c9813b, 0xb211, 0x43f3, { 0x92, 0xc9, 0x35, 0x75, 0xcc, 0xa9, 0xfb, 0xf3 } }; BEGIN_INTERFACE_MAP(CEFilmAutoClientDlgAutoProxy, CCmdTarget) INTERFACE_PART(CEFilmAutoClientDlgAutoProxy, IID_IEFilmAutoClient, Dispatch) END_INTERFACE_MAP() // The IMPLEMENT_OLECREATE2 macro is defined in StdAfx.h of this project // {17AE9AFA-1C3B-4714-8189-E62124E04A25} IMPLEMENT_OLECREATE2(CEFilmAutoClientDlgAutoProxy, "EFilmAutoClient.Application", 0x17ae9afa, 0x1c3b, 0x4714, 0x81, 0x89, 0xe6, 0x21, 0x24, 0xe0, 0x4a, 0x25) ///////////////////////////////////////////////////////////////////////////// // CEFilmAutoClientDlgAutoProxy message handlers
[ [ [ 1, 88 ] ] ]
7e21c4d760b9a46c287da54818f57854cca46a10
de98f880e307627d5ce93dcad1397bd4813751dd
/Sls/StringUtil.h
1616923edd42acc0d6da7fb68b2c5a5e16bdf0a0
[]
no_license
weimingtom/sls
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
refs/heads/master
2021-01-10T22:20:55.638757
2011-03-19T06:23:49
2011-03-19T06:23:49
44,464,621
2
0
null
null
null
null
UTF-8
C++
false
false
305
h
#ifndef STRINGUTIL_H #define STRINGUTIL_H class CStringUtil { public: static BOOL MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize); static BOOL MByteToWCharExt(LPCSTR lpcszStr, LPWSTR &lpwszStr); static BOOL WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize); }; #endif
[ [ [ 1, 11 ] ] ]
e98b1b321b791446ef810982ce93340feececf9f
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/idmimetypes.hpp
78925f0c855796aedc8f374db5545e8beb592e7d
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
2,121
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'IdMIMETypes.pas' rev: 6.00 #ifndef IdMIMETypesHPP #define IdMIMETypesHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Idmimetypes { //-- type declarations ------------------------------------------------------- typedef AnsiString IdMIMETypes__1[7]; //-- var, const, procedure --------------------------------------------------- static const char MIMESplit = '\x2f'; #define MIMEXVal "x-" #define MIMETypeApplication "application/" #define MIMETypeAudio "audio/" #define MIMETypeImage "image/" #define MIMETypeMessage "message/" #define MIMETypeMultipart "multipart/" #define MIMETypeText "text/" #define MIMETypeVideo "video/" static const Shortint MaxMIMEType = 0x6; #define MIMESubOctetStream "octet-stream" #define MIMESubMacBinHex40 "mac-binhex40" static const Shortint MaxMIMESubTypes = 0x1; #define MIMEEncBase64 "base64" #define MIMEEncUUEncode "x-uu" #define MIMEEncXXEncode "x-xx" static const Shortint MaxMIMEBinToASCIIType = 0x2; #define MIMEEncRSAMD2 "x-rsa-md2" #define MIMEEncRSAMD4 "x-rsa-md4" #define MIMEEncRSAMD5 "x-rsa-md5" #define MIMEEncNISTSHA "x-nist-sha" static const Shortint MaxMIMEMessageDigestType = 0x3; #define MIMEEncRLECompress "x-rle-compress" static const Shortint MaxMIMECompressType = 0x0; static const Shortint MaxMIMEEncType = 0x7; #define MIMEFullApplicationOctetStream "application/octet-stream" extern PACKAGE AnsiString MIMEMediaType[7]; extern PACKAGE bool __fastcall ReturnMIMEType(AnsiString &MediaType, AnsiString &EncType); } /* namespace Idmimetypes */ using namespace Idmimetypes; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // IdMIMETypes
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 60 ] ] ]
4030a7c8bd0a8046d58f6661768faf4f70efa07e
723202e673511cf9f243177d964dfeba51cb06a3
/09/oot/epa_labs/l2/src/other/CDiamond.cpp
1dd27905b7c21ca5bcfc627cd7a30f210ffe3b09
[]
no_license
aeremenok/a-team-777
c2ffe04b408a266f62c523fb8d68c87689f2a2e9
0945efbe00c3695c9cc3dbcdb9177ff6f1e9f50b
refs/heads/master
2020-12-24T16:50:12.178873
2009-06-16T14:55:41
2009-06-16T14:55:41
32,388,114
0
0
null
null
null
null
UTF-8
C++
false
false
3,884
cpp
#include "stdafx.h" #include "afxwin.h" #include "..\stdafx.h" #include "iostream.h" #include "math.h" #include "..\OurConstants.h" #include "..\Elements.h" #include "CDiamond.h" int CDiamond::KOLdiamond = 0; //getters const double CDiamond::getL()const { return this->l; }; const double CDiamond::getU()const { return this->u; }; //setters void CDiamond::setL(int newL){ this->l = newL; }; void CDiamond::setU(double newU){ this->u = newU; }; //pure virtual function double CDiamond::S()const{ return this->l * this->l * sin(this->u); }; double CDiamond::P()const{ return 4 * this->l; }; CDiamond::CDiamond(CPoint p1, CPoint p2, COLORREF aColor) : CShape( p1, p2, aColor), IDdiamond(KOLdiamond) { KOLdiamond++; t1 = p1; t2 = p2; int l1 = abs(abs(this->m_EnclosingRect.TopLeft().x) - abs(this->m_EnclosingRect.BottomRight().x)); int l2 = abs(abs(this->m_EnclosingRect.TopLeft().y) - abs(this->m_EnclosingRect.BottomRight().y)); m_EnclosingRect = new CRect(p1.x, p1.y, p1.x + l1, p1.y - l2); double h = abs(abs(m_EnclosingRect.TopLeft().y) - abs(m_EnclosingRect.BottomRight().y )); double l = abs(abs(m_EnclosingRect.TopLeft().x) - abs(m_EnclosingRect.BottomRight().x )); double a = sqrt(h*h+l*l); if(l==0 || a==0){ t3 = CPoint(m_EnclosingRect.TopLeft()); t4 = CPoint(m_EnclosingRect.BottomRight()); m_EnclosingRect.NormalizeRect(); return; } if(h > l){ t2 = CPoint(m_EnclosingRect.BottomRight().x, m_EnclosingRect.TopLeft().y-l); t3 = CPoint(m_EnclosingRect.BottomRight().x, m_EnclosingRect.TopLeft().y); t4 = CPoint(m_EnclosingRect.TopLeft().x, m_EnclosingRect.TopLeft().y-l); m_EnclosingRect.NormalizeRect(); return; } double u = acos(l/a) ; double n = a / (2 * (l / a)); t3 = CPoint(m_EnclosingRect.TopLeft().x+n,m_EnclosingRect.TopLeft().y); t4 = CPoint(m_EnclosingRect.BottomRight().x-n,m_EnclosingRect.BottomRight().y); t2 = CPoint(m_EnclosingRect.BottomRight().x,m_EnclosingRect.BottomRight().y); m_EnclosingRect.NormalizeRect(); } void CDiamond::Move(CSize& aSize) { m_EnclosingRect += aSize; // Move the rectangle t1 += aSize; t2 += aSize; t3 += aSize; t4 += aSize; } CDiamond::~CDiamond() { } // Draw a CDiamond object void CDiamond::Draw(CDC* pDC, CElement* pElement, int l) { // Create a pen for this object and // initialize it to the object color and line width of 1 pixel CPen aPen; COLORREF aColor = m_Color; // Initialize with element color if(this == pElement || l==1) // This element selected? aColor = SELECT_COLOR; // Set highlight color if(!aPen.CreatePen(PS_SOLID, m_Pen, aColor)) { // Pen creation failed. Abort the program. AfxMessageBox("Pen creation failed drawing a line", MB_OK); AfxAbort(); } CPen* pOldPen = pDC->SelectObject(&aPen); // Select the pen // Now draw the line pDC->SetTextColor(RGB(255, 255, 0)); pDC->SetTextAlign(TA_BOTTOM | TA_NOUPDATECP); CString text = ""; text += convertIntToChar(this->IDdiamond) ; text +="("; text += convertIntToChar(this->getID()) ; text +=")"; pDC->TextOut(this->m_EnclosingRect.TopLeft().x, this->m_EnclosingRect.BottomRight().y , text); //pDC->Rectangle(m_EnclosingRect); pDC->MoveTo(t1); pDC->LineTo(t3); pDC->LineTo(t2); pDC->LineTo(t4); pDC->LineTo(t1); pDC->SelectObject(pOldPen); // Restore the old pen } void CDiamond::Serialize(CArchive& ar) { CShape::Serialize(ar); if (ar.IsStoring()) { ar <<l<<t1.x<<t1.y<<t2.x<<t2.y<<t3.x<<t3.y<<t4.x<<t4.y; } else { ar >>l>>t1.x>>t1.y>>t2.x>>t2.y>>t3.x>>t3.y>>t4.x>>t4.y; } };
[ "emmanpavel@9273621a-9230-0410-b1c6-9ffd80c20a0c" ]
[ [ [ 1, 158 ] ] ]
64bdbfe2aa13edd0ef35737a24b4606b96953a1c
faacd0003e0c749daea18398b064e16363ea8340
/lyxlib/scrollbar.h
8f3c891b9e4974030a750031f090a40dffc0171e
[]
no_license
yjfcool/lyxcar
355f7a4df7e4f19fea733d2cd4fee968ffdf65af
750be6c984de694d7c60b5a515c4eb02c3e8c723
refs/heads/master
2016-09-10T10:18:56.638922
2009-09-29T06:03:19
2009-09-29T06:03:19
42,575,701
0
0
null
null
null
null
UTF-8
C++
false
false
2,752
h
/* * Copyright (C) 2008 Pavlov Denis * * Comments unavailable. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or any later version. * */ #ifndef __SCROLLBAR_H__ #define __SCROLLBAR_H__ #include <QWidget> #include <QPixmap> #include "skinner.h" #include "buttons.h" class ALyxScrollBar : public QWidget { Q_OBJECT public: ALyxScrollBar(QWidget *parent = 0, ASkinner *s = 0); ~ALyxScrollBar(); void setSingleStep(int step) { m_singleStep = step; calculateSliderButton(); repaint(); } int singleStep() { return m_singleStep; } void setPosition(int position) { m_position = position; repaint(); } int position() { return m_position; } void setMaximumPosition(int position) { m_maximumPosition = position; if(m_position > m_maximumPosition) { m_position = m_maximumPosition; } calculateSliderButton(); repaint(); } int maximumPosition() { return m_maximumPosition; } void setMinimumPosition(int position) { m_minimumPosition = position; if(m_position < m_minimumPosition) { m_position = m_minimumPosition; } calculateSliderButton(); repaint(); } int minimumPosition() { return m_minimumPosition; } private: ASkinner *m_skinner; QPixmap backbtn_up; QPixmap backbtn_down; QPixmap forwardbtn_up; QPixmap forwardbtn_down; QPixmap slider_up; QPixmap slider_down; QPixmap bar_begin; QPixmap bar_end; QPixmap bar_fill; int m_position; int m_maximumPosition; int m_minimumPosition; int m_sliderOffset; // Current slider position in pixels int m_sliderStep; // Slider one step (when pressing forward or backward button) in items int m_sliderPage; // Slider page step (when pressing on a slider bar above or below the slider) in items int m_singleStep; // Button press causes scroll to <step> position steps int tmp_sliderMin; int tmp_sliderLength; float tmp_sliderStep; bool tmp_sliderPressed; QPoint tmp_sliderPressPos; int tmp_sliderInitialPos; QTimer *scrollRepeatTimer; int scrollRepeatDirection; // Calculate temporary values for slider button positioning. void calculateSliderButton(); private slots: void scrollRepeat(); signals: // Position it was changed to and number of steps to reach this position. void changed(int position, int steps); protected: void resizeEvent(QResizeEvent *e); void paintEvent(QPaintEvent *e); void mousePressEvent(QMouseEvent *e); void mouseReleaseEvent(QMouseEvent *e); void mouseMoveEvent(QMouseEvent *e); }; #endif
[ "futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9" ]
[ [ [ 1, 97 ] ] ]
58c2693d63ceab0e94841a67d18d7b28a6745357
8bbbcc2bd210d5608613c5c591a4c0025ac1f06b
/nes/mapper/010.cpp
c91fac012984b6406c47268cc0e79f21b308d185
[]
no_license
PSP-Archive/NesterJ-takka
140786083b1676aaf91d608882e5f3aaa4d2c53d
41c90388a777c63c731beb185e924820ffd05f93
refs/heads/master
2023-04-16T11:36:56.127438
2008-12-07T01:39:17
2008-12-07T01:39:17
357,617,280
1
0
null
null
null
null
UTF-8
C++
false
false
3,215
cpp
///////////////////////////////////////////////////////////////////// // Mapper 10 void NES_mapper10_Init() { g_NESmapper.Reset = NES_mapper10_Reset; g_NESmapper.MemoryWrite = NES_mapper10_MemoryWrite; g_NESmapper.PPU_Latch_FDFE = NES_mapper10_PPU_Latch_FDFE; } void NES_mapper10_Reset() { int i; // set CPU bank pointers g_NESmapper.set_CPU_banks4(0,1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1); for(i = 0; i < sizeof(g_NESmapper.Mapper10.regs)/sizeof(g_NESmapper.Mapper10.regs[0]); i++) g_NESmapper.Mapper10.regs[i] = 0; g_NESmapper.Mapper10.regs[2] = 4; g_NESmapper.Mapper10.latch_0000 = 0xFE; g_NESmapper.Mapper10.latch_1000 = 0xFE; NES_mapper10_set_VROM_0000(); NES_mapper10_set_VROM_1000(); } void NES_mapper10_PPU_Latch_FDFE(uint32 addr) { if(addr & 0x1000) { g_NESmapper.Mapper10.latch_1000 = (addr & 0x0FF0) >> 4; NES_mapper10_set_VROM_1000(); } else { g_NESmapper.Mapper10.latch_0000 = (addr & 0x0FF0) >> 4; NES_mapper10_set_VROM_0000(); } } void NES_mapper10_set_VROM_0000() { int bank_num = (g_NESmapper.Mapper10.latch_0000 == 0xFD) ? g_NESmapper.Mapper10.regs[1] : g_NESmapper.Mapper10.regs[2]; bank_num <<= 2; g_NESmapper.set_PPU_bank0(bank_num+0); g_NESmapper.set_PPU_bank1(bank_num+1); g_NESmapper.set_PPU_bank2(bank_num+2); g_NESmapper.set_PPU_bank3(bank_num+3); } void NES_mapper10_set_VROM_1000() { int bank_num = (g_NESmapper.Mapper10.latch_1000 == 0xFD) ? g_NESmapper.Mapper10.regs[3] : g_NESmapper.Mapper10.regs[4]; bank_num <<= 2; g_NESmapper.set_PPU_bank4(bank_num+0); g_NESmapper.set_PPU_bank5(bank_num+1); g_NESmapper.set_PPU_bank6(bank_num+2); g_NESmapper.set_PPU_bank7(bank_num+3); } void NES_mapper10_MemoryWrite(uint32 addr, uint8 data) { switch(addr & 0xF000) { case 0xA000: { uint8 bank_num; g_NESmapper.Mapper10.regs[0] = data; // 16K ROM bank at $8000 bank_num = g_NESmapper.Mapper10.regs[0]; g_NESmapper.set_CPU_bank4(bank_num*2); g_NESmapper.set_CPU_bank5(bank_num*2+1); } break; case 0xB000: { // B000-BFFF: select 4k VROM for (0000) $FD latch g_NESmapper.Mapper10.regs[1] = data; NES_mapper10_set_VROM_0000(); } break; case 0xC000: { // C000-CFFF: select 4k VROM for (0000) $FE latch g_NESmapper.Mapper10.regs[2] = data; NES_mapper10_set_VROM_0000(); } break; case 0xD000: { // D000-DFFF: select 4k VROM for (1000) $FD latch g_NESmapper.Mapper10.regs[3] = data; NES_mapper10_set_VROM_1000(); } break; case 0xE000: { // E000-EFFF: select 4k VROM for (1000) $FE latch g_NESmapper.Mapper10.regs[4] = data; NES_mapper10_set_VROM_1000(); } break; case 0xF000: { g_NESmapper.Mapper10.regs[5] = data; if(g_NESmapper.Mapper10.regs[5] & 0x01) { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ); } else { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT); } } break; } } void NES_mapper10_SNSS_fixup() { NES_mapper10_set_VROM_0000(); NES_mapper10_set_VROM_1000(); } /////////////////////////////////////////////////////////////////////
[ "takka@e750ed6d-7236-0410-a570-cc313d6b6496" ]
[ [ [ 1, 139 ] ] ]
3d447e1950cd5857981db6533dfbbc3325988fad
05f4bd87bd001ab38701ff8a71d91b198ef1cb72
/TPTaller/TP3/src/DecLongPad.cpp
b1fda521018816cfa741f17f220553d47e0ff69d
[]
no_license
oscarcp777/tpfontela
ef6828a57a0bc52dd7313cde8e55c3fd9ff78a12
2489442b81dab052cf87b6dedd33cbb51c2a0a04
refs/heads/master
2016-09-01T18:40:21.893393
2011-12-03T04:26:33
2011-12-03T04:26:33
35,110,434
0
0
null
null
null
null
UTF-8
C++
false
false
1,303
cpp
// DecLongPad.cpp: implementation of the DecLongPad class. // ////////////////////////////////////////////////////////////////////// #include "DecLongPad.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// #include "Escenario.h" #include "Define.h" DecLongPad::DecLongPad() { } int DecLongPad::aplicar(){ Escenario* escenario = Escenario::obtenerInstancia(); Pad*pad=NULL; int decUnTercioDeAltura=0; std::string padUltimaColision = escenario->getTejo()->obtenerUltimaColisionPad(); if(padUltimaColision.compare(PAD_CLIENTE1)==0) pad = escenario->getPadCliente1(); else if(padUltimaColision.compare(PAD_CLIENTE2)==0) pad = escenario->getPadCliente2(); if(pad==NULL) //si ya se aplico, no se puede volver a aplicar el bonus return -2; int decMax = pad->getAlturaDefault()/3; decUnTercioDeAltura= pad->getAltura() - pad->getAlturaDefault()/3; if(decUnTercioDeAltura < decMax) return -1; pad->setModificar(true); pad->setAltura(decUnTercioDeAltura); return 0; } DecLongPad::~DecLongPad() { if(DEBUG_DESTRUCTOR==1) std::cout<<" entro al destructor de DecLongPad"<<endl; }
[ "rdubini@a1477896-89e5-11dd-84d8-5ff37064ad4b" ]
[ [ [ 1, 49 ] ] ]
6673433b906654423cf2404f3277c9de36144f74
740ed7e8d98fc0af56ee8e0832e3bd28f08cf362
/src/game/megaman_demo/states/MegamanStandingRightShoot.cpp
afcfd3682c2669193dedf2dc1659749b4b661e09
[]
no_license
fgervais/armconsoledemogame
420c53f926728b30fe1723733de2f32961a6a6d9
9158c0e684db16c4327b51aec45d1e4eed96b2d4
refs/heads/master
2021-01-10T11:27:43.912609
2010-07-29T18:53:06
2010-07-29T18:53:06
44,270,121
0
0
null
null
null
null
UTF-8
C++
false
false
4,375
cpp
/* * MegamanRunningRightShot.cpp * * Created on: 2010-05-29 * Author: Basse * Modified: Brass */ #include "MegamanStandingRightShoot.h" #include "MegamanRunningRightShot.h" #include "MegamanRunningRight.h" #include "MegamanJumpingRight.h" #include "MegamanRunningLeft.h" #include "MegamanStandingRight.h" #include "Bitmap.h" #include "Megaman.h" #include "Buster.h" #include "ShotgunPellet.h" #include "shotgunShotRight.h" #include "BusterShotRight.h" #include "ThrowingAxe.h" #include "ThrowingAxeShotRight.h" #include "Physics.h" #include "Environment.h" #include <iostream> using namespace std; MegamanState* MegamanStandingRightShoot::instance = 0; MegamanStandingRightShoot::MegamanStandingRightShoot(uint32_t animationWidth, uint32_t animationHeight, Bitmap** animationanimationFrames, uint32_t numberOfFrame, Bitmap** animationMasks) : MegamanState(animationWidth, animationHeight, animationanimationFrames, numberOfFrame, animationMasks) { } MegamanStandingRightShoot::~MegamanStandingRightShoot() { } MegamanState* MegamanStandingRightShoot::getInstance() { if(instance == 0) { Bitmap** animationFrames = new Bitmap*[2]; animationFrames[0] = new Bitmap("src/display/state/MegamanShootRight/0.bmp"); animationFrames[1] = new Bitmap("src/display/state/MegamanShootRight/1.bmp"); Bitmap** animationMasks = new Bitmap*[2]; animationMasks[0] = new Bitmap("src/display/state/MegamanShootRight/mask0.bmp"); animationMasks[1] = new Bitmap("src/display/state/MegamanShootRight/mask1.bmp"); instance = new MegamanStandingRightShoot(35, 35, animationFrames, 2, animationMasks); } //instance->reset(); return instance; } /* BASE CLASS FUNCTION OVERRIDE */ void MegamanStandingRightShoot::jump(Megaman* sprite) { sprite->setVelocityY(-sprite->getCurrentJumpPower()); sprite->setState(MegamanJumpingRight::getInstance()); } void MegamanStandingRightShoot::shot(Megaman* sprite) { sprite->setState(MegamanStandingRightShoot::getInstance()); } void MegamanStandingRightShoot::runRight(Megaman* sprite) { sprite->setState(MegamanRunningRight::getInstance()); } void MegamanStandingRightShoot::stopShooting(Megaman* sprite){ //sprite->setState(MegamanStandingRight::getInstance()); } void MegamanStandingRightShoot::runLeft(Megaman* sprite) { sprite->setState(MegamanRunningLeft::getInstance()); } void MegamanStandingRightShoot::initialize(Megaman* sprite) { uint32_t currentWeapon = sprite->getCurrentWeapon(); //Create a new buster, gives him his spawning position and add it to the parent sprite switch(currentWeapon) { case 1 : { ThrowingAxe* buster = new ThrowingAxe(ThrowingAxeShotRight::getInstance(), sprite->getEnvironment(), sprite->getPositionX(), sprite->getPositionY()); buster->enableCollisionCheck(); sprite->addChild(buster); sprite->incCurrentBusterNum(); break; } case 0 : { Buster* buster = new Buster(BusterShotRight::getInstance(), sprite->getEnvironment(), sprite->getPositionX()+sprite->getWidth()/2, sprite->getPositionY()); buster->enableCollisionCheck(); sprite->addChild(buster); sprite->incCurrentBusterNum(); break; } case 2 : { for(uint32_t i=0; i<sprite->getPelletNum(); i++){ ShotgunPellet* buster = new ShotgunPellet(ShotgunShotRight::getInstance(), sprite->getEnvironment(), sprite->getPositionX(), sprite->getPositionY(), sprite->getCount(), (i+1)*1234); buster->enableCollisionCheck(); sprite->addChild(buster); sprite->incCurrentBusterNum(); } } } cout << "Buster created" << endl; } void MegamanStandingRightShoot::update(Megaman* sprite) { // Update current frame if(sprite->getCurrentFrame() < (numberOfFrame-1)) { sprite->incCurrentFrame(); } else { // The first frame is displayed only once when we transition from // a standing position sprite->setCurrentFrame(1); } // If we loose contact with the ground, then we are falling // In our case, falling and jumping is handled by the same state if(!sprite->isOnGround()) { sprite->setState(MegamanJumpingRight::getInstance()); } //Linger Effect if(sprite->getCounter(this) >= 5) { sprite->setState(MegamanStandingRight::getInstance()); } else { sprite->incCounter(this); } }
[ [ [ 1, 145 ] ] ]
43fcc75af52ed666557ce894daaa49d4f4a8de6e
4d1a438ee0c80053e33431d10683ce4872118957
/dumbhippo/branches/linux-client-1-1-32-bugfix/client/common/hippoipc/hippo-serialized-listener.cpp
f3a7abe0f4cf8b2251b202c1fe0d0a979354271a
[]
no_license
nihed/magnetism
7a5223e7dd0ae172937358c1b72df7e9ec5f28b8
c64dfb9b221862e81c9e77bb055f65dcee422027
refs/heads/master
2016-09-05T20:01:07.262277
2009-04-29T06:48:39
2009-04-29T06:48:39
39,454,577
1
0
null
null
null
null
UTF-8
C++
false
false
5,784
cpp
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */ #include "hippo-serialized-listener.h" #include <string> class HippoSerializedListenerArgs { public: virtual ~HippoSerializedListenerArgs() {}; virtual void invoke(HippoIpcListener *listener) = 0; }; class HippoSerializedListenerOnConnect : public HippoSerializedListenerArgs { public: void invoke(HippoIpcListener *listener); }; void HippoSerializedListenerOnConnect::invoke(HippoIpcListener *listener) { listener->onConnect(); } class HippoSerializedListenerOnDisconnect : public HippoSerializedListenerArgs { public: HippoSerializedListenerOnDisconnect() { } void invoke(HippoIpcListener *listener); }; void HippoSerializedListenerOnDisconnect::invoke(HippoIpcListener *listener) { listener->onDisconnect(); } class HippoSerializedListenerOnUserJoin : public HippoSerializedListenerArgs { public: HippoSerializedListenerOnUserJoin(HippoEndpointId endpoint, const char *chatId, const char *userId, bool participant) { endpoint_ = endpoint; chatId_ = chatId; userId_ = userId; participant_ = participant; } void invoke(HippoIpcListener *listener); private: HippoEndpointId endpoint_; std::string chatId_; std::string userId_; bool participant_; }; void HippoSerializedListenerOnUserJoin::invoke(HippoIpcListener *listener) { listener->onUserJoin(endpoint_, chatId_.c_str(), userId_.c_str(), participant_); } class HippoSerializedListenerOnUserLeave : public HippoSerializedListenerArgs { public: HippoSerializedListenerOnUserLeave(HippoEndpointId endpoint, const char *chatId, const char *userId) { endpoint_ = endpoint; chatId_ = chatId; userId_ = userId; } void invoke(HippoIpcListener *listener); private: HippoEndpointId endpoint_; std::string chatId_; std::string userId_; }; void HippoSerializedListenerOnUserLeave::invoke(HippoIpcListener *listener) { listener->onUserLeave(endpoint_, chatId_.c_str(), userId_.c_str()); } class HippoSerializedListenerOnMessage : public HippoSerializedListenerArgs { public: HippoSerializedListenerOnMessage(HippoEndpointId endpoint, const char *chatId, const char *userId, const char *message, int sentiment, double timestamp, long serial) { endpoint_ = endpoint; chatId_ = chatId; userId_ = userId; message_ = message; sentiment_ = sentiment; timestamp_ = timestamp; serial_ = serial; } void invoke(HippoIpcListener *listener); private: HippoEndpointId endpoint_; std::string chatId_; std::string userId_; std::string message_; int sentiment_; double timestamp_; long serial_; }; void HippoSerializedListenerOnMessage::invoke(HippoIpcListener *listener) { listener->onMessage(endpoint_, chatId_.c_str(), userId_.c_str(), message_.c_str(), sentiment_, timestamp_, serial_); } class HippoSerializedListenerUserInfo : public HippoSerializedListenerArgs { public: HippoSerializedListenerUserInfo(HippoEndpointId endpoint, const char *userId, const char *name, const char *smallPhotoUrl, const char *currentSong, const char *currentArtist, bool musicPlaying) { endpoint_ = endpoint; userId_ = userId; name_ = name; smallPhotoUrl_ = smallPhotoUrl; currentSong_ = currentSong; currentArtist_ = currentArtist; musicPlaying_ = musicPlaying; } void invoke(HippoIpcListener *listener); private: HippoEndpointId endpoint_; std::string userId_; std::string name_; std::string smallPhotoUrl_; std::string currentSong_; std::string currentArtist_; bool musicPlaying_; }; void HippoSerializedListenerUserInfo::invoke(HippoIpcListener *listener) { listener->userInfo(endpoint_, userId_.c_str(), name_.c_str(), smallPhotoUrl_.c_str(), currentSong_.c_str(), currentArtist_.c_str(), musicPlaying_); } HippoSerializedListener::HippoSerializedListener() { args_ = 0; } HippoSerializedListener::~HippoSerializedListener() { clear(); } void HippoSerializedListener::invoke(HippoIpcListener *listener) { if (args_) args_->invoke(listener); } void HippoSerializedListener::onConnect() { clear(); args_ = new HippoSerializedListenerOnConnect(); } void HippoSerializedListener::onDisconnect() { clear(); args_ = new HippoSerializedListenerOnDisconnect(); } void HippoSerializedListener::onUserJoin(HippoEndpointId endpoint, const char *chatId, const char *userId, bool participant) { clear(); args_ = new HippoSerializedListenerOnUserJoin(endpoint, chatId, userId, participant); } void HippoSerializedListener::onUserLeave(HippoEndpointId endpoint, const char *chatId, const char *userId) { clear(); args_ = new HippoSerializedListenerOnUserLeave(endpoint, chatId, userId); } void HippoSerializedListener::onMessage(HippoEndpointId endpoint, const char *chatId, const char *userId, const char *message, int sentiment, double timestamp, long serial) { clear(); args_ = new HippoSerializedListenerOnMessage(endpoint, chatId, userId, message, sentiment, timestamp, serial); } void HippoSerializedListener::userInfo(HippoEndpointId endpoint, const char *userId, const char *name, const char *smallPhotoUrl, const char *currentSong, const char *currentArtist, bool musicPlaying) { clear(); args_ = new HippoSerializedListenerUserInfo(endpoint, userId, name, smallPhotoUrl, currentSong, currentArtist, musicPlaying); } void HippoSerializedListener::clear() { if (args_) { delete args_; args_ = 0; } }
[ "otaylor@69951b7c-304f-11de-8daa-cfecb5f7ff5b" ]
[ [ [ 1, 219 ] ] ]
c4afd37be07a2fb3d7203e9bc70ef910ad710c2e
10c14a95421b63a71c7c99adf73e305608c391bf
/gui/core/qlist.h
e29609a27e1df6018410f0d750fe5e7310fc3885
[]
no_license
eaglezzb/wtlcontrols
73fccea541c6ef1f6db5600f5f7349f5c5236daa
61b7fce28df1efe4a1d90c0678ec863b1fd7c81c
refs/heads/master
2021-01-22T13:47:19.456110
2009-05-19T10:58:42
2009-05-19T10:58:42
33,811,815
0
0
null
null
null
null
UTF-8
C++
false
false
24,595
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QLIST_H #define QLIST_H // #include <QtCore/qiterator.h> // #include <QtCore/qatomic.h> // #include <QtCore/qalgorithms.h> #include "core/qiterator.h" #include "core/qatomic.h" #include "core/qalgorithms.h" #ifndef QT_NO_STL #include <iterator> #include <list> #endif #include <new> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) template <typename T> class QVector; template <typename T> class QSet; struct Q_GUI_EXPORT QListData { struct Data { QBasicAtomicInt ref; int alloc, begin, end; uint sharable : 1; void *array[1]; }; enum { DataHeaderSize = sizeof(Data) - sizeof(void *) }; Data *detach(); // remove in 5.0 Data *detach2(); void realloc(int alloc); static Data shared_null; Data *d; void **erase(void **xi); void **append(); void **append(const QListData &l); void **prepend(); void **insert(int i); void remove(int i); void remove(int i, int n); void move(int from, int to); inline int size() const { return d->end - d->begin; } inline bool isEmpty() const { return d->end == d->begin; } inline void **at(int i) const { return d->array + d->begin + i; } inline void **begin() const { return d->array + d->begin; } inline void **end() const { return d->array + d->end; } }; template <typename T> class QList { struct Node { void *v; #if defined(Q_CC_BOR) Q_INLINE_TEMPLATE T &t(); #else Q_INLINE_TEMPLATE T &t() { return *reinterpret_cast<T*>(QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic ? v : this); } #endif }; union { QListData p; QListData::Data *d; }; public: inline QList() : d(&QListData::shared_null) { d->ref.ref(); } inline QList(const QList<T> &l) : d(l.d) { d->ref.ref(); if (!d->sharable) detach_helper(); } ~QList(); QList<T> &operator=(const QList<T> &l); bool operator==(const QList<T> &l) const; inline bool operator!=(const QList<T> &l) const { return !(*this == l); } inline int size() const { return p.size(); } inline void detach() { if (d->ref != 1) detach_helper(); } inline bool isDetached() const { return d->ref == 1; } inline void setSharable(bool sharable) { if (!sharable) detach(); d->sharable = sharable; } inline bool isEmpty() const { return p.isEmpty(); } void clear(); const T &at(int i) const; const T &operator[](int i) const; T &operator[](int i); void append(const T &t); void append(const QList<T> &t); void prepend(const T &t); void insert(int i, const T &t); void replace(int i, const T &t); void removeAt(int i); int removeAll(const T &t); bool removeOne(const T &t); T takeAt(int i); T takeFirst(); T takeLast(); void move(int from, int to); void swap(int i, int j); int indexOf(const T &t, int from = 0) const; int lastIndexOf(const T &t, int from = -1) const; QBool contains(const T &t) const; int count(const T &t) const; class const_iterator; class iterator { public: Node *i; typedef std::random_access_iterator_tag iterator_category; typedef ptrdiff_t difference_type; typedef T value_type; typedef T *pointer; typedef T &reference; inline iterator() : i(0) {} inline iterator(Node *n) : i(n) {} inline iterator(const iterator &o): i(o.i){} inline T &operator*() const { return i->t(); } inline T *operator->() const { return &i->t(); } inline T &operator[](int j) const { return i[j].t(); } inline bool operator==(const iterator &o) const { return i == o.i; } inline bool operator!=(const iterator &o) const { return i != o.i; } inline bool operator<(const iterator& other) const { return i < other.i; } inline bool operator<=(const iterator& other) const { return i <= other.i; } inline bool operator>(const iterator& other) const { return i > other.i; } inline bool operator>=(const iterator& other) const { return i >= other.i; } #ifndef QT_STRICT_ITERATORS inline bool operator==(const const_iterator &o) const { return i == o.i; } inline bool operator!=(const const_iterator &o) const { return i != o.i; } inline bool operator<(const const_iterator& other) const { return i < other.i; } inline bool operator<=(const const_iterator& other) const { return i <= other.i; } inline bool operator>(const const_iterator& other) const { return i > other.i; } inline bool operator>=(const const_iterator& other) const { return i >= other.i; } #endif inline iterator &operator++() { ++i; return *this; } inline iterator operator++(int) { Node *n = i; ++i; return n; } inline iterator &operator--() { i--; return *this; } inline iterator operator--(int) { Node *n = i; i--; return n; } inline iterator &operator+=(int j) { i+=j; return *this; } inline iterator &operator-=(int j) { i-=j; return *this; } inline iterator operator+(int j) const { return iterator(i+j); } inline iterator operator-(int j) const { return iterator(i-j); } inline int operator-(iterator j) const { return i - j.i; } }; friend class iterator; class const_iterator { public: Node *i; typedef std::random_access_iterator_tag iterator_category; typedef ptrdiff_t difference_type; typedef T value_type; typedef const T *pointer; typedef const T &reference; inline const_iterator() : i(0) {} inline const_iterator(Node *n) : i(n) {} inline const_iterator(const const_iterator &o): i(o.i) {} #ifdef QT_STRICT_ITERATORS inline explicit const_iterator(const iterator &o): i(o.i) {} #else inline const_iterator(const iterator &o): i(o.i) {} #endif inline const T &operator*() const { return i->t(); } inline const T *operator->() const { return &i->t(); } inline const T &operator[](int j) const { return i[j].t(); } inline bool operator==(const const_iterator &o) const { return i == o.i; } inline bool operator!=(const const_iterator &o) const { return i != o.i; } inline bool operator<(const const_iterator& other) const { return i < other.i; } inline bool operator<=(const const_iterator& other) const { return i <= other.i; } inline bool operator>(const const_iterator& other) const { return i > other.i; } inline bool operator>=(const const_iterator& other) const { return i >= other.i; } inline const_iterator &operator++() { ++i; return *this; } inline const_iterator operator++(int) { Node *n = i; ++i; return n; } inline const_iterator &operator--() { i--; return *this; } inline const_iterator operator--(int) { Node *n = i; i--; return n; } inline const_iterator &operator+=(int j) { i+=j; return *this; } inline const_iterator &operator-=(int j) { i-=j; return *this; } inline const_iterator operator+(int j) const { return const_iterator(i+j); } inline const_iterator operator-(int j) const { return const_iterator(i-j); } inline int operator-(const_iterator j) const { return i - j.i; } }; friend class const_iterator; // stl style inline iterator begin() { detach(); return reinterpret_cast<Node *>(p.begin()); } inline const_iterator begin() const { return reinterpret_cast<Node *>(p.begin()); } inline const_iterator constBegin() const { return reinterpret_cast<Node *>(p.begin()); } inline iterator end() { detach(); return reinterpret_cast<Node *>(p.end()); } inline const_iterator end() const { return reinterpret_cast<Node *>(p.end()); } inline const_iterator constEnd() const { return reinterpret_cast<Node *>(p.end()); } iterator insert(iterator before, const T &t); iterator erase(iterator pos); iterator erase(iterator first, iterator last); // more Qt typedef iterator Iterator; typedef const_iterator ConstIterator; inline int count() const { return p.size(); } inline int length() const { return p.size(); } // Same as count() inline T& first() { Q_ASSERT(!isEmpty()); return *begin(); } inline const T& first() const { Q_ASSERT(!isEmpty()); return *begin(); } T& last() { Q_ASSERT(!isEmpty()); return *(--end()); } const T& last() const { Q_ASSERT(!isEmpty()); return *(--end()); } inline void removeFirst() { Q_ASSERT(!isEmpty()); erase(begin()); } inline void removeLast() { Q_ASSERT(!isEmpty()); erase(--end()); } inline bool startsWith(const T &t) const { return !isEmpty() && first() == t; } inline bool endsWith(const T &t) const { return !isEmpty() && last() == t; } QList<T> mid(int pos, int length = -1) const; T value(int i) const; T value(int i, const T &defaultValue) const; // stl compatibility inline void push_back(const T &t) { append(t); } inline void push_front(const T &t) { prepend(t); } inline T& front() { return first(); } inline const T& front() const { return first(); } inline T& back() { return last(); } inline const T& back() const { return last(); } inline void pop_front() { removeFirst(); } inline void pop_back() { removeLast(); } inline bool empty() const { return isEmpty(); } typedef int size_type; typedef T value_type; typedef value_type *pointer; typedef const value_type *const_pointer; typedef value_type &reference; typedef const value_type &const_reference; typedef ptrdiff_t difference_type; #ifdef QT3_SUPPORT inline QT3_SUPPORT iterator remove(iterator pos) { return erase(pos); } inline QT3_SUPPORT int remove(const T &t) { return removeAll(t); } inline QT3_SUPPORT int findIndex(const T& t) const { return indexOf(t); } inline QT3_SUPPORT iterator find(const T& t) { int i = indexOf(t); return (i == -1 ? end() : (begin()+i)); } inline QT3_SUPPORT const_iterator find (const T& t) const { int i = indexOf(t); return (i == -1 ? end() : (begin()+i)); } inline QT3_SUPPORT iterator find(iterator from, const T& t) { int i = indexOf(t, from - begin()); return i == -1 ? end() : begin()+i; } inline QT3_SUPPORT const_iterator find(const_iterator from, const T& t) const { int i = indexOf(t, from - begin()); return i == -1 ? end() : begin()+i; } #endif // comfort QList<T> &operator+=(const QList<T> &l); inline QList<T> operator+(const QList<T> &l) const { QList n = *this; n += l; return n; } inline QList<T> &operator+=(const T &t) { append(t); return *this; } inline QList<T> &operator<< (const T &t) { append(t); return *this; } inline QList<T> &operator<<(const QList<T> &l) { *this += l; return *this; } QVector<T> toVector() const; QSet<T> toSet() const; static QList<T> fromVector(const QVector<T> &vector); static QList<T> fromSet(const QSet<T> &set); #ifndef QT_NO_STL static inline QList<T> fromStdList(const std::list<T> &list) { QList<T> tmp; qCopy(list.begin(), list.end(), std::back_inserter(tmp)); return tmp; } inline std::list<T> toStdList() const { std::list<T> tmp; qCopy(constBegin(), constEnd(), std::back_inserter(tmp)); return tmp; } #endif private: void detach_helper(); void free(QListData::Data *d); void node_construct(Node *n, const T &t); void node_destruct(Node *n); void node_copy(Node *from, Node *to, Node *src); void node_destruct(Node *from, Node *to); }; #if defined(Q_CC_BOR) template <typename T> Q_INLINE_TEMPLATE T &QList<T>::Node::t() { return QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic ? *(T*)v:*(T*)this; } #endif template <typename T> Q_INLINE_TEMPLATE void QList<T>::node_construct(Node *n, const T &t) { if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) n->v = new T(t); else if (QTypeInfo<T>::isComplex) new (n) T(t); else *reinterpret_cast<T*>(n) = t; } template <typename T> Q_INLINE_TEMPLATE void QList<T>::node_destruct(Node *n) { if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) delete reinterpret_cast<T*>(n->v); else if (QTypeInfo<T>::isComplex) reinterpret_cast<T*>(n)->~T(); } template <typename T> Q_INLINE_TEMPLATE void QList<T>::node_copy(Node *from, Node *to, Node *src) { if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) while(from != to) (from++)->v = new T(*reinterpret_cast<T*>((src++)->v)); else if (QTypeInfo<T>::isComplex) while(from != to) new (from++) T(*reinterpret_cast<T*>(src++)); } template <typename T> Q_INLINE_TEMPLATE void QList<T>::node_destruct(Node *from, Node *to) { if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) while(from != to) --to, delete reinterpret_cast<T*>(to->v); else if (QTypeInfo<T>::isComplex) while (from != to) --to, reinterpret_cast<T*>(to)->~T(); } template <typename T> Q_INLINE_TEMPLATE QList<T> &QList<T>::operator=(const QList<T> &l) { if (d != l.d) { l.d->ref.ref(); if (!d->ref.deref()) free(d); d = l.d; if (!d->sharable) detach_helper(); } return *this; } template <typename T> inline typename QList<T>::iterator QList<T>::insert(iterator before, const T &t) { Node *n = reinterpret_cast<Node *>(p.insert(before.i-reinterpret_cast<Node *>(p.begin()))); node_construct(n,t); return n; } template <typename T> inline typename QList<T>::iterator QList<T>::erase(iterator it) { node_destruct(it.i); return reinterpret_cast<Node *>(p.erase(reinterpret_cast<void**>(it.i))); } template <typename T> inline const T &QList<T>::at(int i) const { Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::at", "index out of range"); return reinterpret_cast<Node *>(p.at(i))->t(); } template <typename T> inline const T &QList<T>::operator[](int i) const { Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::operator[]", "index out of range"); return reinterpret_cast<Node *>(p.at(i))->t(); } template <typename T> inline T &QList<T>::operator[](int i) { Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::operator[]", "index out of range"); detach(); return reinterpret_cast<Node *>(p.at(i))->t(); } template <typename T> inline void QList<T>::removeAt(int i) { if(i >= 0 && i < p.size()) { detach(); node_destruct(reinterpret_cast<Node *>(p.at(i))); p.remove(i); } } template <typename T> inline T QList<T>::takeAt(int i) { Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::take", "index out of range"); detach(); Node *n = reinterpret_cast<Node *>(p.at(i)); T t = n->t(); node_destruct(n); p.remove(i); return t; } template <typename T> inline T QList<T>::takeFirst() { T t = first(); removeFirst(); return t; } template <typename T> inline T QList<T>::takeLast() { T t = last(); removeLast(); return t; } template <typename T> Q_OUTOFLINE_TEMPLATE void QList<T>::append(const T &t) { detach(); if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) { node_construct(reinterpret_cast<Node *>(p.append()), t); } else { const T cpy(t); node_construct(reinterpret_cast<Node *>(p.append()), cpy); } } template <typename T> inline void QList<T>::prepend(const T &t) { detach(); if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) { node_construct(reinterpret_cast<Node *>(p.prepend()), t); } else { const T cpy(t); node_construct(reinterpret_cast<Node *>(p.prepend()), cpy); } } template <typename T> inline void QList<T>::insert(int i, const T &t) { detach(); if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) { node_construct(reinterpret_cast<Node *>(p.insert(i)), t); } else { const T cpy(t); node_construct(reinterpret_cast<Node *>(p.insert(i)), cpy); } } template <typename T> inline void QList<T>::replace(int i, const T &t) { Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::replace", "index out of range"); detach(); if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) { reinterpret_cast<Node *>(p.at(i))->t() = t; } else { const T cpy(t); reinterpret_cast<Node *>(p.at(i))->t() = cpy; } } template <typename T> inline void QList<T>::swap(int i, int j) { Q_ASSERT_X(i >= 0 && i < p.size() && j >= 0 && j < p.size(), "QList<T>::swap", "index out of range"); detach(); void *t = d->array[d->begin + i]; d->array[d->begin + i] = d->array[d->begin + j]; d->array[d->begin + j] = t; } template <typename T> inline void QList<T>::move(int from, int to) { Q_ASSERT_X(from >= 0 && from < p.size() && to >= 0 && to < p.size(), "QList<T>::move", "index out of range"); detach(); p.move(from, to); } template<typename T> Q_OUTOFLINE_TEMPLATE QList<T> QList<T>::mid(int pos, int alength) const { if (alength < 0) alength = size() - pos; if (pos == 0 && alength == size()) return *this; QList<T> cpy; if (pos + alength > size()) alength = size() - pos; for (int i = pos; i < pos + alength; ++i) cpy += at(i); return cpy; } template<typename T> Q_OUTOFLINE_TEMPLATE T QList<T>::value(int i) const { if (i < 0 || i >= p.size()) { return T(); } return reinterpret_cast<Node *>(p.at(i))->t(); } template<typename T> Q_OUTOFLINE_TEMPLATE T QList<T>::value(int i, const T& defaultValue) const { return ((i < 0 || i >= p.size()) ? defaultValue : reinterpret_cast<Node *>(p.at(i))->t()); } template <typename T> Q_OUTOFLINE_TEMPLATE void QList<T>::detach_helper() { Node *n = reinterpret_cast<Node *>(p.begin()); QListData::Data *x = p.detach2(); node_copy(reinterpret_cast<Node *>(p.begin()), reinterpret_cast<Node *>(p.end()), n); if (!x->ref.deref()) free(x); } template <typename T> Q_OUTOFLINE_TEMPLATE QList<T>::~QList() { if (d && !d->ref.deref()) free(d); } template <typename T> Q_OUTOFLINE_TEMPLATE bool QList<T>::operator==(const QList<T> &l) const { if (p.size() != l.p.size()) return false; if (d == l.d) return true; Node *i = reinterpret_cast<Node *>(p.end()); Node *b = reinterpret_cast<Node *>(p.begin()); Node *li = reinterpret_cast<Node *>(l.p.end()); while (i != b) { --i; --li; if (!(i->t() == li->t())) return false; } return true; } // ### Qt 5: rename freeData() to avoid confusion with std::free() template <typename T> Q_OUTOFLINE_TEMPLATE void QList<T>::free(QListData::Data *data) { node_destruct(reinterpret_cast<Node *>(data->array + data->begin), reinterpret_cast<Node *>(data->array + data->end)); if (data->ref == 0) qFree(data); } template <typename T> Q_OUTOFLINE_TEMPLATE void QList<T>::clear() { *this = QList<T>(); } template <typename T> Q_OUTOFLINE_TEMPLATE int QList<T>::removeAll(const T &_t) { detach(); const T t = _t; int removedCount=0, i=0; Node *n; while (i < p.size()) if ((n = reinterpret_cast<Node *>(p.at(i)))->t() == t) { node_destruct(n); p.remove(i); ++removedCount; } else { ++i; } return removedCount; } template <typename T> Q_OUTOFLINE_TEMPLATE bool QList<T>::removeOne(const T &_t) { detach(); int index = indexOf(_t); if (index != -1) { removeAt(index); return true; } return false; } template <typename T> Q_OUTOFLINE_TEMPLATE typename QList<T>::iterator QList<T>::erase(typename QList<T>::iterator afirst, typename QList<T>::iterator alast) { for (Node *n = afirst.i; n < alast.i; ++n) node_destruct(n); int idx = afirst - begin(); p.remove(idx, alast - afirst); return begin() + idx; } template <typename T> Q_OUTOFLINE_TEMPLATE QList<T> &QList<T>::operator+=(const QList<T> &l) { detach(); Node *n = reinterpret_cast<Node *>(p.append(l.p)); node_copy(n, reinterpret_cast<Node *>(p.end()), reinterpret_cast<Node *>(l.p.begin())); return *this; } template <typename T> inline void QList<T>::append(const QList<T> &t) { *this += t; } template <typename T> Q_OUTOFLINE_TEMPLATE int QList<T>::indexOf(const T &t, int from) const { if (from < 0) from = qMax(from + p.size(), 0); if (from < p.size()) { Node *n = reinterpret_cast<Node *>(p.at(from -1)); Node *e = reinterpret_cast<Node *>(p.end()); while (++n != e) if (n->t() == t) return n - reinterpret_cast<Node *>(p.begin()); } return -1; } template <typename T> Q_OUTOFLINE_TEMPLATE int QList<T>::lastIndexOf(const T &t, int from) const { if (from < 0) from += p.size(); else if (from >= p.size()) from = p.size()-1; if (from >= 0) { Node *b = reinterpret_cast<Node *>(p.begin()); Node *n = reinterpret_cast<Node *>(p.at(from + 1)); while (n-- != b) { if (n->t() == t) return n - b; } } return -1; } template <typename T> Q_OUTOFLINE_TEMPLATE QBool QList<T>::contains(const T &t) const { Node *b = reinterpret_cast<Node *>(p.begin()); Node *i = reinterpret_cast<Node *>(p.end()); while (i-- != b) if (i->t() == t) return QBool(true); return QBool(false); } template <typename T> Q_OUTOFLINE_TEMPLATE int QList<T>::count(const T &t) const { int c = 0; Node *b = reinterpret_cast<Node *>(p.begin()); Node *i = reinterpret_cast<Node *>(p.end()); while (i-- != b) if (i->t() == t) ++c; return c; } Q_DECLARE_SEQUENTIAL_ITERATOR(List) Q_DECLARE_MUTABLE_SEQUENTIAL_ITERATOR(List) QT_END_NAMESPACE QT_END_HEADER #endif // QLIST_H
[ "zhangyinquan@0feb242a-2539-11de-a0d7-251e5865a1c7" ]
[ [ [ 1, 694 ] ] ]
58b5e41ce795b4de274720d094fc924f34187978
5504cdea188dd5ceec6ab38863ef4b4f72c70b21
/pcsxrr/Win32/ConfigurePlugins.cpp
f186384172400df930ea4a9136c3193eab67e348
[]
no_license
mauzus/pcsxrr
959051bed227f96045a9bba8971ba5dffc24ad33
1b4c66d6a2938da55761280617d288f3c65870d7
refs/heads/master
2021-03-12T20:00:56.954014
2011-03-21T01:16:35
2011-03-21T01:16:35
32,238,897
1
0
null
null
null
null
UTF-8
C++
false
false
20,526
cpp
/* Pcsx - Pc Psx Emulator * Copyright (C) 1999-2003 Pcsx Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <windows.h> #include <windowsx.h> #include <stdio.h> #include "PsxCommon.h" #include "plugin.h" #include "resource.h" #include "Win32.h" #include "maphkeys.h" int tempDest; //this is for the compiler to not throw in a million of warnings //adelikat: Changed from storing into the registry to saving into a config file void SaveConfig() { char Str_Tmp[1024]; char Conf_File[1024] = ".\\pcsx.ini"; //TODO: make a global for other files WritePrivateProfileString("Plugins", "Bios", Config.Bios, Conf_File); WritePrivateProfileString("Plugins", "GPU", Config.Gpu , Conf_File); WritePrivateProfileString("Plugins", "SPU", Config.Spu , Conf_File); WritePrivateProfileString("Plugins", "CDR", Config.Cdr , Conf_File); WritePrivateProfileString("Plugins", "Pad1", Config.Pad1 , Conf_File); WritePrivateProfileString("Plugins", "Pad2", Config.Pad2 , Conf_File); WritePrivateProfileString("Plugins", "MCD1", Config.Mcd1 , Conf_File); WritePrivateProfileString("Plugins", "MCD2", Config.Mcd2 , Conf_File); //WritePrivateProfileString("Plugins", "Net", Config.Net , Conf_File); //adelikat: Netplay was disabled so let's not save it wsprintf(Str_Tmp, "%d", Config.Xa); WritePrivateProfileString("Plugins", "Xa", Str_Tmp, Conf_File); wsprintf(Str_Tmp, "%d", Config.Sio); WritePrivateProfileString("Plugins", "Sio", Str_Tmp, Conf_File); wsprintf(Str_Tmp, "%d", Config.Mdec); WritePrivateProfileString("Plugins", "Mdec", Str_Tmp, Conf_File); wsprintf(Str_Tmp, "%d", Config.PsxAuto); WritePrivateProfileString("Plugins", "PsxAuto", Str_Tmp, Conf_File); wsprintf(Str_Tmp, "%d", Config.PsxType); WritePrivateProfileString("Plugins", "PsxType", Str_Tmp, Conf_File); wsprintf(Str_Tmp, "%d", Config.QKeys); WritePrivateProfileString("Plugins", "QKeys", Str_Tmp, Conf_File); wsprintf(Str_Tmp, "%d", Config.Cdda); WritePrivateProfileString("Plugins", "Cdda", Str_Tmp, Conf_File); wsprintf(Str_Tmp, "%d", Config.Cpu); WritePrivateProfileString("Plugins", "CPU", Str_Tmp, Conf_File); wsprintf(Str_Tmp, "%d", Config.PauseAfterPlayback); WritePrivateProfileString("Plugins", "PauseAfterPlayback", Str_Tmp, Conf_File); wsprintf(Str_Tmp, "%d", Config.PsxOut); WritePrivateProfileString("Plugins", "PsxOut", Str_Tmp, Conf_File); wsprintf(Str_Tmp, "%d", Config.RCntFix); WritePrivateProfileString("Plugins", "RCntFix", Str_Tmp, Conf_File); wsprintf(Str_Tmp, "%d", Config.VSyncWA); WritePrivateProfileString("Plugins", "VSyncWA", Str_Tmp, Conf_File); for (int i = 0; i <= EMUCMDMAX; i++) { wsprintf(Str_Tmp, "%d", EmuCommandTable[i].key); WritePrivateProfileString("Hotkeys", EmuCommandTable[i].name, Str_Tmp, Conf_File); } for (int i = 0; i <= EMUCMDMAX; i++) { wsprintf(Str_Tmp, "%d", EmuCommandTable[i].keymod); WritePrivateProfileString("HotkeysKeyMods", EmuCommandTable[i].name, Str_Tmp, Conf_File); } } int LoadConfig() { char Conf_File[1024] = ".\\pcsx.ini"; //TODO: make a global for other files GetPrivateProfileString("Plugins", "Bios", "scph1001.bin", &Config.Bios[0], 256, Conf_File); GetPrivateProfileString("Plugins", "GPU", "gpuTASsoft.dll", &Config.Gpu[0], 256, Conf_File); GetPrivateProfileString("Plugins", "SPU", "", &Config.Spu[0], 256, Conf_File); GetPrivateProfileString("Plugins", "CDR", "cdrTASiso.dll", &Config.Cdr[0], 256, Conf_File); GetPrivateProfileString("Plugins", "Pad1", "padSeguDPP.dll", &Config.Pad1[0], 256, Conf_File); GetPrivateProfileString("Plugins", "Pad2", "padSeguDPP.dll", &Config.Pad2[0], 256, Conf_File); GetPrivateProfileString("Plugins", "MCD1", "", &Config.Mcd1[0], 256, Conf_File); GetPrivateProfileString("Plugins", "MCD2", "", &Config.Mcd2[0], 256, Conf_File); //GetPrivateProfileString("Plugins", "Net", "Disabled", &Config.Net[0], 256, Conf_File); //adelikat: Netplay was disabled so let's not load it Config.Xa = GetPrivateProfileInt("Plugins", "Xa", 0, Conf_File); Config.Mdec = GetPrivateProfileInt("Plugins", "Mdec", 0, Conf_File); Config.PsxAuto = GetPrivateProfileInt("Plugins", "PsxAuto", 0, Conf_File); Config.PsxType = GetPrivateProfileInt("Plugins", "PsxType", 0, Conf_File); Config.QKeys = GetPrivateProfileInt("Plugins", "QKeys", 0, Conf_File); Config.Cdda = GetPrivateProfileInt("Plugins", "Cdda", 0, Conf_File); Config.Cpu = GetPrivateProfileInt("Plugins", "CPU", 0, Conf_File); Config.PauseAfterPlayback = GetPrivateProfileInt("Plugins", "PauseAfterPlayback", 0, Conf_File); Config.PsxOut = GetPrivateProfileInt("Plugins", "PsxOut", 0, Conf_File); Config.RCntFix = GetPrivateProfileInt("Plugins", "RCntFix", 0, Conf_File); Config.VSyncWA = GetPrivateProfileInt("Plugins", "VSyncWA", 0, Conf_File); int temp; for (int i = 0; i <= EMUCMDMAX-1; i++) { temp = GetPrivateProfileInt("Hotkeys", EmuCommandTable[i].name, 65535, Conf_File); if (temp != 65535) EmuCommandTable[i].key = temp; } for (int i = 0; i <= EMUCMDMAX-1; i++) { temp = GetPrivateProfileInt("HotkeysKeyMods", EmuCommandTable[i].name, 65535, Conf_File); if (temp != 65535) EmuCommandTable[i].keymod = temp; } return 0; } ///////////////////////////////////////////////////////// #define ComboAddPlugin(hw, str) { \ lp = (char *)malloc(strlen(FindData.cFileName)+8); \ sprintf(lp, "%s", FindData.cFileName); \ i = ComboBox_AddString(hw, tmpStr); \ tempDest = ComboBox_SetItemData(hw, i, lp); \ if (_stricmp(str, lp)==0) \ tempDest = ComboBox_SetCurSel(hw, i); \ } BOOL OnConfigurePluginsDialog(HWND hW) { WIN32_FIND_DATA FindData; HANDLE Find; HANDLE Lib; PSEgetLibType PSE_GetLibType; PSEgetLibName PSE_GetLibName; PSEgetLibVersion PSE_GetLibVersion; HWND hWC_GPU=GetDlgItem(hW,IDC_LISTGPU); HWND hWC_SPU=GetDlgItem(hW,IDC_LISTSPU); HWND hWC_CDR=GetDlgItem(hW,IDC_LISTCDR); HWND hWC_PAD1=GetDlgItem(hW,IDC_LISTPAD1); HWND hWC_PAD2=GetDlgItem(hW,IDC_LISTPAD2); HWND hWC_BIOS=GetDlgItem(hW,IDC_LISTBIOS); char tmpStr[256]; char *lp; int i; strcpy(tmpStr, Config.PluginsDir); strcat(tmpStr, "*.dll"); Find = FindFirstFile(tmpStr, &FindData); do { if (Find==INVALID_HANDLE_VALUE) break; sprintf(tmpStr,"%s%s", Config.PluginsDir, FindData.cFileName); Lib = LoadLibrary(tmpStr); if (Lib!=NULL) { PSE_GetLibType = (PSEgetLibType) GetProcAddress((HMODULE)Lib,"PSEgetLibType"); PSE_GetLibName = (PSEgetLibName) GetProcAddress((HMODULE)Lib,"PSEgetLibName"); PSE_GetLibVersion = (PSEgetLibVersion) GetProcAddress((HMODULE)Lib,"PSEgetLibVersion"); if (PSE_GetLibType != NULL && PSE_GetLibName != NULL && PSE_GetLibVersion != NULL) { unsigned long version = PSE_GetLibVersion(); long type; sprintf(tmpStr, "%s %d.%d", PSE_GetLibName(), (int)(version>>8)&0xff, (int)version&0xff); type = PSE_GetLibType(); if (type & PSE_LT_CDR) { ComboAddPlugin(hWC_CDR, Config.Cdr); } if (type & PSE_LT_SPU) { ComboAddPlugin(hWC_SPU, Config.Spu); } if (type & PSE_LT_GPU) { ComboAddPlugin(hWC_GPU, Config.Gpu); } if (type & PSE_LT_PAD) { PADquery query; query = (PADquery)GetProcAddress((HMODULE)Lib, "PADquery"); if (query != NULL) { if (query() & 0x1) ComboAddPlugin(hWC_PAD1, Config.Pad1); if (query() & 0x2) ComboAddPlugin(hWC_PAD2, Config.Pad2); } else { // just a guess ComboAddPlugin(hWC_PAD1, Config.Pad1); } } } } } while (FindNextFile(Find,&FindData)); if (Find!=INVALID_HANDLE_VALUE) FindClose(Find); // BIOS lp=(char *)malloc(strlen("HLE") + 1); sprintf(lp, "HLE"); i=ComboBox_AddString(hWC_BIOS, "Internal HLE Bios"); tempDest = ComboBox_SetItemData(hWC_BIOS, i, lp); if (_stricmp(Config.Bios, lp)==0) tempDest = ComboBox_SetCurSel(hWC_BIOS, i); strcpy(tmpStr, Config.BiosDir); strcat(tmpStr, "*"); Find=FindFirstFile(tmpStr, &FindData); do { if (Find==INVALID_HANDLE_VALUE) break; if (!strcmp(FindData.cFileName, ".")) continue; if (!strcmp(FindData.cFileName, "..")) continue; if (FindData.nFileSizeLow != 1024 * 512) continue; lp = (char *)malloc(strlen(FindData.cFileName)+8); sprintf(lp, "%s", (char *)FindData.cFileName); i = ComboBox_AddString(hWC_BIOS, FindData.cFileName); tempDest = ComboBox_SetItemData(hWC_BIOS, i, lp); if (_stricmp(Config.Bios, FindData.cFileName)==0) tempDest = ComboBox_SetCurSel(hWC_BIOS, i); } while (FindNextFile(Find,&FindData)); if (Find!=INVALID_HANDLE_VALUE) FindClose(Find); if (ComboBox_GetCurSel(hWC_CDR ) == -1) tempDest = ComboBox_SetCurSel(hWC_CDR, 0); if (ComboBox_GetCurSel(hWC_GPU ) == -1) tempDest = ComboBox_SetCurSel(hWC_GPU, 0); if (ComboBox_GetCurSel(hWC_SPU ) == -1) tempDest = ComboBox_SetCurSel(hWC_SPU, 0); if (ComboBox_GetCurSel(hWC_PAD1) == -1) tempDest = ComboBox_SetCurSel(hWC_PAD1, 0); if (ComboBox_GetCurSel(hWC_PAD2) == -1) tempDest = ComboBox_SetCurSel(hWC_PAD2, 0); if (ComboBox_GetCurSel(hWC_BIOS) == -1) tempDest = ComboBox_SetCurSel(hWC_BIOS, 0); return TRUE; } #define CleanCombo(item) \ hWC = GetDlgItem(hW, item); \ iCnt = ComboBox_GetCount(hWC); \ for (i=0; i<iCnt; i++) { \ lp = (char *)ComboBox_GetItemData(hWC, i); \ if (lp) free(lp); \ } \ tempDest = ComboBox_ResetContent(hWC); void CleanUpCombos(HWND hW) { int i,iCnt;HWND hWC;char * lp; CleanCombo(IDC_LISTGPU); CleanCombo(IDC_LISTSPU); CleanCombo(IDC_LISTCDR); CleanCombo(IDC_LISTPAD1); CleanCombo(IDC_LISTPAD2); CleanCombo(IDC_LISTBIOS); } void OnCancel(HWND hW) { CleanUpCombos(hW); EndDialog(hW,FALSE); } char *GetSelDLL(HWND hW,int id) { HWND hWC = GetDlgItem(hW,id); int iSel; iSel = ComboBox_GetCurSel(hWC); if (iSel<0) return NULL; return (char *)ComboBox_GetItemData(hWC, iSel); } void OnOK(HWND hW) { char * gpuDLL=GetSelDLL(hW,IDC_LISTGPU); char * pad1DLL=GetSelDLL(hW,IDC_LISTPAD1); char * pad2DLL=GetSelDLL(hW,IDC_LISTPAD2); char * biosFILE=GetSelDLL(hW,IDC_LISTBIOS); if ((gpuDLL==NULL) ||(pad1DLL==NULL) || (pad2DLL==NULL) ||(biosFILE==NULL)) { MessageBox(hW,"Configuration not OK!","Error",MB_OK|MB_ICONERROR); return; } strcpy(Config.Bios, biosFILE); strcpy(Config.Gpu, gpuDLL); strcpy(Config.Pad1, pad1DLL); strcpy(Config.Pad2, pad2DLL); SaveConfig(); CleanUpCombos(hW); if (!ConfPlug) { NeedReset = 1; ReleasePlugins(); LoadPlugins(); } EndDialog(hW,TRUE); } #define ConfPlugin(src, confs, name) \ void *drv; \ src conf; \ char * pDLL = GetSelDLL(hW, confs); \ char file[256]; \ if(pDLL==NULL) return; \ strcpy(file, Config.PluginsDir); \ strcat(file, pDLL); \ drv = SysLoadLibrary(file); \ if (drv == NULL) return; \ conf = (src) SysLoadSym(drv, name); \ if (SysLibError() == NULL) conf(); \ SysCloseLibrary(drv); void ConfigureGPU(HWND hW) { ConfPlugin(GPUconfigure, IDC_LISTGPU, "GPUconfigure"); } void ConfigureSPU(HWND hW) { //ConfPlugin(SPUconfigure, IDC_LISTSPU, "SPUconfigure"); SPUconfigure(); } void ConfigureCDR(HWND hW) { //ConfPlugin(CDRconfigure, IDC_LISTCDR, "CDRconfigure"); CDRconfigure(); } void ConfigureNET(HWND hW) { ConfPlugin(NETconfigure, IDC_LISTNET, "NETconfigure"); } void ConfigurePAD1(HWND hW) { ConfPlugin(PADconfigure, IDC_LISTPAD1, "PADconfigure"); } void ConfigurePAD2(HWND hW) { ConfPlugin(PADconfigure, IDC_LISTPAD2, "PADconfigure"); } void AboutGPU(HWND hW) { ConfPlugin(GPUabout, IDC_LISTGPU, "GPUabout"); } //void AboutSPU(HWND hW) { // ConfPlugin(SPUabout, IDC_LISTSPU, "SPUabout"); //} //void AboutCDR(HWND hW) { // ConfPlugin(CDRabout, IDC_LISTCDR, "CDRabout"); //} void AboutNET(HWND hW) { ConfPlugin(NETabout, IDC_LISTNET, "NETabout"); } void AboutPAD1(HWND hW) { ConfPlugin(PADabout, IDC_LISTPAD1, "PADabout"); } void AboutPAD2(HWND hW) { ConfPlugin(PADabout, IDC_LISTPAD2, "PADabout"); } #define TestPlugin(src, confs, name) \ void *drv; \ src conf; \ int ret = 0; \ char * pDLL = GetSelDLL(hW, confs); \ char file[256]; \ if (pDLL== NULL) return; \ strcpy(file, Config.PluginsDir); \ strcat(file, pDLL); \ drv = SysLoadLibrary(file); \ if (drv == NULL) return; \ conf = (src) SysLoadSym(drv, name); \ if (SysLibError() == NULL) { \ ret = conf(); \ if (ret == 0) \ SysMessage(_("This plugin reports that should work correctly")); \ else SysMessage(_("This plugin reports that should not work correctly")); \ } \ SysCloseLibrary(drv); void TestGPU(HWND hW) { TestPlugin(GPUtest, IDC_LISTGPU, "GPUtest"); } //void TestSPU(HWND hW) { // TestPlugin(SPUtest, IDC_LISTSPU, "SPUtest"); //} //void TestCDR(HWND hW) { // TestPlugin(CDRtest, IDC_LISTCDR, "CDRtest"); //} void TestNET(HWND hW) { TestPlugin(NETtest, IDC_LISTNET, "NETtest"); } void TestPAD1(HWND hW) { TestPlugin(PADtest, IDC_LISTPAD1, "PADtest"); } void TestPAD2(HWND hW) { TestPlugin(PADtest, IDC_LISTPAD2, "PADtest"); } #include <shlobj.h> int SelectPath(HWND hW, char *Title, char *Path) { LPITEMIDLIST pidl; BROWSEINFO bi; char Buffer[256]; bi.hwndOwner = hW; bi.pidlRoot = NULL; bi.pszDisplayName = Buffer; bi.lpszTitle = Title; bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS; bi.lpfn = NULL; bi.lParam = 0; if ((pidl = SHBrowseForFolder(&bi)) != NULL) { if (SHGetPathFromIDList(pidl, Path)) { int len = strlen(Path); if (Path[len - 1] != '\\') { strcat(Path,"\\"); } return 0; } } return -1; } BOOL CALLBACK ConfigurePluginsDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_INITDIALOG: SetWindowText(hW, _("Configuration")); Button_SetText(GetDlgItem(hW, IDOK), _("OK")); Button_SetText(GetDlgItem(hW, IDCANCEL), _("Cancel")); Static_SetText(GetDlgItem(hW, IDC_GRAPHICS), _("Graphics")); Static_SetText(GetDlgItem(hW, IDC_FIRSTCONTROLLER), _("First Controller")); Static_SetText(GetDlgItem(hW, IDC_SECONDCONTROLLER), _("Second Controller")); Static_SetText(GetDlgItem(hW, IDC_SOUND), _("Sound")); Static_SetText(GetDlgItem(hW, IDC_CDROM), _("CD-ROM")); Static_SetText(GetDlgItem(hW, IDC_BIOS), _("Bios")); Button_SetText(GetDlgItem(hW, IDC_CONFIGGPU), _("Configure...")); Button_SetText(GetDlgItem(hW, IDC_TESTGPU), _("Test...")); Button_SetText(GetDlgItem(hW, IDC_ABOUTGPU), _("About...")); Button_SetText(GetDlgItem(hW, IDC_CONFIGSPU), _("Configure...")); Button_SetText(GetDlgItem(hW, IDC_TESTSPU), _("Test...")); Button_SetText(GetDlgItem(hW, IDC_ABOUTSPU), _("About...")); Button_SetText(GetDlgItem(hW, IDC_CONFIGCDR), _("Configure...")); Button_SetText(GetDlgItem(hW, IDC_TESTCDR), _("Test...")); Button_SetText(GetDlgItem(hW, IDC_ABOUTCDR), _("About...")); Button_SetText(GetDlgItem(hW, IDC_CONFIGPAD1), _("Configure...")); Button_SetText(GetDlgItem(hW, IDC_TESTPAD1), _("Test...")); Button_SetText(GetDlgItem(hW, IDC_ABOUTPAD1), _("About...")); Button_SetText(GetDlgItem(hW, IDC_CONFIGPAD2), _("Configure...")); Button_SetText(GetDlgItem(hW, IDC_TESTPAD2), _("Test...")); Button_SetText(GetDlgItem(hW, IDC_ABOUTPAD2), _("About...")); return OnConfigurePluginsDialog(hW); case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_CONFIGGPU: ConfigureGPU(hW); return TRUE; case IDC_CONFIGSPU: ConfigureSPU(hW); return TRUE; case IDC_CONFIGCDR: ConfigureCDR(hW); return TRUE; case IDC_CONFIGPAD1: ConfigurePAD1(hW); return TRUE; case IDC_CONFIGPAD2: ConfigurePAD2(hW); return TRUE; case IDC_TESTGPU: TestGPU(hW); return TRUE; //case IDC_TESTSPU: TestSPU(hW); return TRUE; //case IDC_TESTCDR: TestCDR(hW); return TRUE; case IDC_TESTPAD1: TestPAD1(hW); return TRUE; case IDC_TESTPAD2: TestPAD2(hW); return TRUE; case IDC_ABOUTGPU: AboutGPU(hW); return TRUE; //case IDC_ABOUTSPU: AboutSPU(hW); return TRUE; //case IDC_ABOUTCDR: AboutCDR(hW); return TRUE; case IDC_ABOUTPAD1: AboutPAD1(hW); return TRUE; case IDC_ABOUTPAD2: AboutPAD2(hW); return TRUE; case IDCANCEL: OnCancel(hW); if (CancelQuit) { SysClose(); exit(1); } return TRUE; case IDOK: OnOK(hW); return TRUE; } } return FALSE; } void ConfigurePlugins(HWND hWnd) { DialogBox(gApp.hInstance, MAKEINTRESOURCE(IDD_CONFIG), hWnd, (DLGPROC)ConfigurePluginsDlgProc); } // NetPlay Config Dialog BOOL OnConfigureNetPlayDialog(HWND hW) { WIN32_FIND_DATA FindData; HANDLE Find; HANDLE Lib; PSEgetLibType PSE_GetLibType; PSEgetLibName PSE_GetLibName; PSEgetLibVersion PSE_GetLibVersion; HWND hWC_NET=GetDlgItem(hW,IDC_LISTNET); char tmpStr[256]; char *lp; int i; strcpy(tmpStr, Config.PluginsDir); strcat(tmpStr, "*.dll"); Find = FindFirstFile(tmpStr, &FindData); lp = (char *)malloc(strlen("Disabled")+8); sprintf(lp, "Disabled"); i = ComboBox_AddString(hWC_NET, "Disabled"); tempDest = ComboBox_SetItemData(hWC_NET, i, lp); tempDest = ComboBox_SetCurSel(hWC_NET, 0); do { if (Find==INVALID_HANDLE_VALUE) break; sprintf(tmpStr,"%s%s", Config.PluginsDir, FindData.cFileName); Lib = LoadLibrary(tmpStr); if (Lib!=NULL) { PSE_GetLibType = (PSEgetLibType) GetProcAddress((HMODULE)Lib,"PSEgetLibType"); PSE_GetLibName = (PSEgetLibName) GetProcAddress((HMODULE)Lib,"PSEgetLibName"); PSE_GetLibVersion = (PSEgetLibVersion) GetProcAddress((HMODULE)Lib,"PSEgetLibVersion"); if (PSE_GetLibType != NULL && PSE_GetLibName != NULL && PSE_GetLibVersion != NULL) { unsigned long version = PSE_GetLibVersion(); long type; sprintf(tmpStr, "%s %d.%d", PSE_GetLibName(), (int)(version>>8)&0xff, (int)version&0xff); type = PSE_GetLibType(); if (type & PSE_LT_NET && ((version >> 16) == 2)) { ComboAddPlugin(hWC_NET, Config.Net); } } } } while (FindNextFile(Find,&FindData)); if (Find!=INVALID_HANDLE_VALUE) FindClose(Find); return TRUE; } BOOL CALLBACK ConfigureNetPlayDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam) { int i,iCnt;HWND hWC;char * lp; switch(uMsg) { case WM_INITDIALOG: SetWindowText(hW, _("NetPlay Configuration")); Button_SetText(GetDlgItem(hW, IDOK), _("OK")); Button_SetText(GetDlgItem(hW, IDCANCEL), _("Cancel")); Static_SetText(GetDlgItem(hW, IDC_NETPLAY), _("NetPlay")); Button_SetText(GetDlgItem(hW, IDC_CONFIGNET), _("Configure...")); Button_SetText(GetDlgItem(hW, IDC_TESTNET), _("Test...")); Button_SetText(GetDlgItem(hW, IDC_ABOUTNET), _("About...")); Static_SetText(GetDlgItem(hW, IDC_NETPLAYNOTE), _("Note: The NetPlay Plugin Directory should be the same as the other Plugins.")); OnConfigureNetPlayDialog(hW); return TRUE; case WM_COMMAND: { switch (LOWORD(wParam)) { case IDC_CONFIGNET: ConfigureNET(hW); return TRUE; case IDC_TESTNET: TestNET(hW); return TRUE; case IDC_ABOUTNET: AboutNET(hW); return TRUE; case IDCANCEL: CleanCombo(IDC_LISTNET); EndDialog(hW,FALSE); return TRUE; case IDOK: strcpy(Config.Net, GetSelDLL(hW, IDC_LISTNET)); SaveConfig(); CleanUpCombos(hW); NeedReset = 1; ReleasePlugins(); LoadPlugins(); CleanCombo(IDC_LISTNET); EndDialog(hW,TRUE); return TRUE; } } } return FALSE; }
[ "mauzus@b38eb22e-9255-0410-b643-f940c3bf2d76", "andres.delikat@b38eb22e-9255-0410-b643-f940c3bf2d76", "[email protected]@b38eb22e-9255-0410-b643-f940c3bf2d76", "mgambrell@b38eb22e-9255-0410-b643-f940c3bf2d76" ]
[ [ [ 1, 29 ], [ 74, 75 ], [ 80, 82 ], [ 114, 115 ], [ 122, 123 ], [ 125, 290 ], [ 292, 333 ], [ 336, 338 ], [ 341, 359 ], [ 363, 363 ], [ 367, 404 ], [ 408, 408 ], [ 412, 484 ], [ 488, 491 ], [ 494, 497 ], [ 500, 627 ] ], [ [ 30, 73 ], [ 76, 79 ], [ 83, 90 ], [ 92, 113 ], [ 116, 121 ], [ 124, 124 ] ], [ [ 91, 91 ] ], [ [ 291, 291 ], [ 334, 335 ], [ 339, 340 ], [ 360, 362 ], [ 364, 366 ], [ 405, 407 ], [ 409, 411 ], [ 485, 487 ], [ 492, 493 ], [ 498, 499 ] ] ]
0dfa3794038bb0d07ed8aec33d7635427b4225a9
3c0d7fc6c0187a8a0eae01b15a77e8e302e524e8
/server/src/sprite/player.cpp
de771c192774ad35f569ed18eb5ad0e1444bf097
[ "Artistic-2.0" ]
permissive
klusark/mdpr
0342bea08e9585a46d8d1c5ada29a662875d9d6f
da2b2287e4ed7eab302255221381a9bcbc5e5dcd
refs/heads/master
2021-01-01T15:30:10.633491
2009-08-23T05:14:36
2009-08-23T05:14:36
32,649,940
0
0
null
null
null
null
UTF-8
C++
false
false
4,016
cpp
#include "player.hpp" #include "genericSprite.hpp" #include "network/packets.hpp" #include "powerup/puck.hpp" #include "helpers.hpp" #include "animation.hpp" Player::Player(const std::string &name) : GenericSprite(name, "player"), rolling(false), crouching(false), running(false), idle(false), jumpingUp(false), velocity(0) { spriteType = playerType; keyMap[keyLeft] = false; keyMap[keyRight] = false; keyMap[keyDown] = false; keyMap[keyUp] = false; keyMap[keyAction] = false; keyMapTwo[keyLeft] = false; keyMapTwo[keyRight] = false; keyMapTwo[keyDown] = false; keyMapTwo[keyUp] = false; keyMapTwo[keyAction]= false; changeAnimation("idle"); setYAccel(50.0f); hasPowerUp = true; currentPowerup = Poco::SharedPtr<genericPowerUp>(new Puck(this)); } Player::~Player() { } void Player::update() { if (keyLock){ wasKeyLocked = true; keyMap[keyLeft] = false; keyMap[keyRight] = false; keyMap[keyDown] = false; keyMap[keyUp] = false; keyMap[keyAction] = false; } if (!keyLock && wasKeyLocked){ keyMap[keyLeft] = keyMapTwo[keyLeft]; keyMap[keyRight] = keyMapTwo[keyRight]; keyMap[keyDown] = keyMapTwo[keyDown]; keyMap[keyUp] = keyMapTwo[keyUp]; keyMap[keyAction] = keyMapTwo[keyAction]; } if (currentState == aliveState){ if ((keyMap[keyAction] == true) && hasPowerUp && (keyMap[keyLeft] + keyMap[keyRight] == 0)){ currentPowerup->onActionKey(); } running = false; if (onGround){ if (!rolling){ velocity = (float)(-1 * keyMap[keyLeft] + keyMap[keyRight]) * runSpeed; } if (jumpingUp){ jumpingUp = false; } if (crouching){ velocity = 0; } if (velocity != 0){ if (keyMap[keyDown]){ rolling = true; }else if (rolling){ }else{ running = true; } if (velocity < 0){ flipped = true; }else{ flipped = false; } }else if (!rolling){ if (keyMap[keyDown]){ crouching = true; }else if (crouching){ currentAnimation->resume(); //crouchingDown = true; //crouching = false; }else if (keyMap[keyUp]){ jumpingUp = true; setYVelocity(-50.0f); } } if ((running + rolling + crouching + jumpingUp) > 1){ throw 0; } if ((running + rolling + crouching + jumpingUp) == 0){ idle = true; }else{ idle = false; } if (running && currentAnimation->name != "run"){ changeAnimation("run"); }else if (rolling && currentAnimation->name != "roll"){ changeAnimation("roll"); }else if(crouching && currentAnimation->name != "crouch"){ changeAnimation("crouch"); }else if(jumpingUp && currentAnimation->name != "jumpUp"){ changeAnimation("jumpUp"); }else if (idle && currentAnimation->name != "idle"){ changeAnimation("idle"); } setXVelocity(velocity); } } GenericSprite::update(); } void Player::crouchingFinish() { currentAnimation->reset(); crouching = false; } void Player::rollingFinish() { crouching = true; rolling = false; currentAnimation->reset(); changeAnimation("crouch"); currentAnimation->reset(); currentAnimation->currentFrame = 1; currentAnimation->playBackward = true; currentAnimation->pause(); } void Player::onAnimationFinish() { if (rolling == true){ rollingFinish(); } if (crouching == true && !keyMap[keyDown]){ crouchingFinish(); } } void Player::death(unsigned short cause) { GenericSprite::death(cause); /*if (cause == stringToCRC("gun")){ currentState = dyingState; changeAnimation("dieGun"); currentAnimation->onFinish.connect(boost::bind(&genericSprite::death, this, cause)); animationLock = true; keyLock = true; setXVelocity(0); }*/ } GenericSprite::collidesWithContainer Player::getCollidesWith() { GenericSprite::collidesWithContainer colidesWith; colidesWith.insert(stringToCRC("test")); return colidesWith; }
[ "joelteichroeb@localhost" ]
[ [ [ 1, 179 ] ] ]
8199cb198fd2493253f82c30d27ad53181eb3e4b
81215fde203e75b157f2a3e3507d99897c6d2020
/src/colinegraphicsitem.cpp
066c130eca64116d899ff160aabafe7e62750625
[]
no_license
fuyasing/RankView
fb8e039843088a54da2ad10979726234ea467712
b4d99cdfa03699ec41f8581db9262a367306b5a4
refs/heads/master
2020-05-17T10:58:47.709718
2011-06-25T14:05:05
2011-06-25T14:05:05
1,738,411
0
1
null
2012-08-04T14:49:30
2011-05-12T13:31:00
C++
UTF-8
C++
false
false
1,872
cpp
#include "colinegraphicsitem.h" #include "conodegraphicsitem.h" #include <QPainter> #include <QPen> CoLineGraphicsItem::CoLineGraphicsItem(CoNodeGraphicsItem *sourceNode, CoNodeGraphicsItem *destNode) { this->setAcceptedMouseButtons(0); this->setAcceptHoverEvents(0); m_source = sourceNode; m_dest = destNode; m_sourcePoint = m_source->pos(); m_destPoint = m_dest->pos(); m_source->addLine(this); m_dest->addLine(this); } CoNodeGraphicsItem* CoLineGraphicsItem::sourceNode() const { return m_source; } CoNodeGraphicsItem* CoLineGraphicsItem::destNode() const { return m_dest; } QRectF CoLineGraphicsItem::boundingRect() const { if(!m_source || !m_dest) return QRectF(); return QRectF(m_sourcePoint,QSizeF(abs(m_source->x()-m_dest->x()),abs(m_source->y()-m_dest->y()))); } void CoLineGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { if(!m_source || !m_dest) return; QLineF line(m_sourcePoint.x()+m_source->boundingRect().width()/2,m_sourcePoint.y()+m_source->boundingRect().height()/2,m_destPoint.x()+m_dest->boundingRect().width()/2, m_destPoint.y()+m_dest->boundingRect().height()/2); // QLineF line(m_sourcePoint,m_destPoint); if (qFuzzyCompare(line.length(), qreal(0.))) return; painter->setPen(QPen(Qt::black,1,Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); painter->drawLine(line); painter->save(); painter->scale(scaleFactor, scaleFactor); painter->restore(); } /*void CoLineGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { QGraphicsItem::hoverEnterEvent(event); //update(); } void CoLineGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { QGraphicsItem::hoverLeaveEvent(event); //update(); }*/
[ [ [ 1, 62 ] ] ]
a3f33e4edec37709a1ec55519159c84cc074cba8
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/contrib/nluaserver/src/lua/ldump.cc
2b858bf27fe29853c0747217037b8581824aeef1
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
3,494
cc
/* ** $Id: ldump.cc 567 2004-03-26 00:39:30Z enlight $ ** save bytecodes ** See Copyright Notice in lua.h */ #include <stddef.h> #define ldump_c #include "lua/lua.h" #include "lua/lobject.h" #include "lua/lopcodes.h" #include "lua/lstate.h" #include "lua/lundump.h" #define DumpVector(b,n,size,D) DumpBlock(b,(n)*(size),D) #define DumpLiteral(s,D) DumpBlock("" s,(sizeof(s))-1,D) typedef struct { lua_State* L; lua_Chunkwriter write; void* data; } DumpState; static void DumpBlock(const void* b, size_t size, DumpState* D) { lua_unlock(D->L); (*D->write)(D->L,b,size,D->data); lua_lock(D->L); } static void DumpByte(int y, DumpState* D) { char x=(char)y; DumpBlock(&x,sizeof(x),D); } static void DumpInt(int x, DumpState* D) { DumpBlock(&x,sizeof(x),D); } static void DumpSize(size_t x, DumpState* D) { DumpBlock(&x,sizeof(x),D); } static void DumpNumber(lua_Number x, DumpState* D) { DumpBlock(&x,sizeof(x),D); } static void DumpString(TString* s, DumpState* D) { if (s==NULL || getstr(s)==NULL) DumpSize(0,D); else { size_t size=s->tsv.len+1; /* include trailing '\0' */ DumpSize(size,D); DumpBlock(getstr(s),size,D); } } static void DumpCode(const Proto* f, DumpState* D) { DumpInt(f->sizecode,D); DumpVector(f->code,f->sizecode,sizeof(*f->code),D); } static void DumpLocals(const Proto* f, DumpState* D) { int i,n=f->sizelocvars; DumpInt(n,D); for (i=0; i<n; i++) { DumpString(f->locvars[i].varname,D); DumpInt(f->locvars[i].startpc,D); DumpInt(f->locvars[i].endpc,D); } } static void DumpLines(const Proto* f, DumpState* D) { DumpInt(f->sizelineinfo,D); DumpVector(f->lineinfo,f->sizelineinfo,sizeof(*f->lineinfo),D); } static void DumpUpvalues(const Proto* f, DumpState* D) { int i,n=f->sizeupvalues; DumpInt(n,D); for (i=0; i<n; i++) DumpString(f->upvalues[i],D); } static void DumpFunction(const Proto* f, const TString* p, DumpState* D); static void DumpConstants(const Proto* f, DumpState* D) { int i,n; DumpInt(n=f->sizek,D); for (i=0; i<n; i++) { const TObject* o=&f->k[i]; DumpByte(ttype(o),D); switch (ttype(o)) { case LUA_TNUMBER: DumpNumber(nvalue(o),D); break; case LUA_TSTRING: DumpString(tsvalue(o),D); break; case LUA_TNIL: break; default: lua_assert(0); /* cannot happen */ break; } } DumpInt(n=f->sizep,D); for (i=0; i<n; i++) DumpFunction(f->p[i],f->source,D); } static void DumpFunction(const Proto* f, const TString* p, DumpState* D) { DumpString((f->source==p) ? NULL : f->source,D); DumpInt(f->lineDefined,D); DumpByte(f->nups,D); DumpByte(f->numparams,D); DumpByte(f->is_vararg,D); DumpByte(f->maxstacksize,D); DumpLines(f,D); DumpLocals(f,D); DumpUpvalues(f,D); DumpConstants(f,D); DumpCode(f,D); } static void DumpHeader(DumpState* D) { DumpLiteral(LUA_SIGNATURE,D); DumpByte(VERSION,D); DumpByte(luaU_endianness(),D); DumpByte(sizeof(int),D); DumpByte(sizeof(size_t),D); DumpByte(sizeof(Instruction),D); DumpByte(SIZE_OP,D); DumpByte(SIZE_A,D); DumpByte(SIZE_B,D); DumpByte(SIZE_C,D); DumpByte(sizeof(lua_Number),D); DumpNumber(TEST_NUMBER,D); } /* ** dump function as precompiled chunk */ void luaU_dump (lua_State* L, const Proto* Main, lua_Chunkwriter w, void* data) { DumpState D; D.L=L; D.write=w; D.data=data; DumpHeader(&D); DumpFunction(Main,NULL,&D); }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 170 ] ] ]
ea43073356a25bc16dcf329f12dd4aa2e13b4815
8b3186e126ac2d19675dc19dd473785de97068d2
/bmt_prod/core/camera.cpp
ddcdb4bc6f58a77c9bcbbe11530c3ec533ada390
[]
no_license
leavittx/revenge
e1fd7d6cd1f4a1fb1f7a98de5d16817a0c93da47
3389148f82e6434f0619df47c076c60c8647ed86
refs/heads/master
2021-01-01T17:28:26.539974
2011-08-25T20:25:14
2011-08-25T20:25:14
618,159
2
0
null
null
null
null
UTF-8
C++
false
false
1,946
cpp
#include "camera.h" Camera::Camera() { m_type = NONE; m_startTime = 0; m_endTime = 0; m_positionSpline = 0; m_targetSpline = 0; } Camera::~Camera() { if (m_positionSpline) { delete m_positionSpline; m_positionSpline = 0; } if (m_targetSpline) { delete m_targetSpline; m_targetSpline = 0; } } void Camera::initLinear(Vector3 startPosition, Vector3 endPosition, Vector3 startTarget, Vector3 endTarget, Vector3 startUp, Vector3 endUp, int startTime, int endTime) { m_type = LINEAR; m_startPosition = startPosition; m_endPosition = endPosition; m_startTarget = startTarget; m_endTarget = endTarget; m_startUp = startUp; m_endUp = endUp; m_startTime = startTime; m_endTime = endTime; } void Camera::initCatmullRom(CatmullRomCurve &positionSpline, CatmullRomCurve &targetSpline, int startTime, int endTime) { m_type = CATMULL_ROM; m_positionSpline = positionSpline.clone(); m_targetSpline = targetSpline.clone(); m_startTime = startTime; m_endTime = endTime; } void Camera::use() { const int time = g_system.getTime(); float t = Math::calcPosInt(time, m_startTime, m_endTime); use(t); } void Camera::use(float t) { Vector3 position; Vector3 target; Vector3 upwards; switch(m_type) { case NONE: g_debug << "Trying to use an uninitialized camera!" << endl; break; case LINEAR: { position = m_startPosition + (m_endPosition - m_startPosition) * t; target = m_startTarget + (m_endTarget - m_startTarget) * t; upwards = m_startUp + (m_endUp - m_startUp) * t; } break; case CATMULL_ROM: { position = m_positionSpline->getValue(t); target = m_targetSpline->getValue(t); upwards = Vector3(0, 1, 0); } break; }; glLoadIdentity(); gluLookAt(position.x, position.y, position.z, target.x, target.y, target.z, upwards.x, upwards.y, upwards.z); }
[ [ [ 1, 95 ] ] ]
90afd81a38c7ac98e0e9eca333b2b0eccde3bdf5
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/tokenizer/simple_example_3.cpp
013f2443194a1d8cc603d9e5fd86c20eb8ca36d9
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
WINDOWS-1252
C++
false
false
708
cpp
// © Copyright John R. Bandela 2001. // 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/tokenizer for documenation // simple_example_3.cpp #include<iostream> #include<boost/tokenizer.hpp> #include<string> int main(){ using namespace std; using namespace boost; string s = "12252001"; int offsets[] = {2,2,4}; offset_separator f(offsets, offsets+3); tokenizer<offset_separator> tok(s,f); for(tokenizer<offset_separator>::iterator beg=tok.begin(); beg!=tok.end();++beg){ cout << *beg << "\n"; } return 0; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 25 ] ] ]
f8f3301c4115797d8193b90bef9aa6595080eef5
3187b0dd0d7a7b83b33c62357efa0092b3943110
/src/dlib/map/map_kernel_abstract.h
4a05b2586d45e3112504e8806980d10bd615a087
[ "BSL-1.0" ]
permissive
exi/gravisim
8a4dad954f68960d42f1d7da14ff1ca7a20e92f2
361e70e40f58c9f5e2c2f574c9e7446751629807
refs/heads/master
2021-01-19T17:45:04.106839
2010-10-22T09:11:24
2010-10-22T09:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,816
h
// Copyright (C) 2003 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_MAP_KERNEl_ABSTRACT_ #ifdef DLIB_MAP_KERNEl_ABSTRACT_ #include "../interfaces/map_pair.h" #include "../interfaces/enumerable.h" #include "../interfaces/remover.h" #include "../serialize.h" #include "../memory_manager/memory_manager_kernel_abstract.h" #include <functional> namespace dlib { template < typename domain, typename range, typename mem_manager = memory_manager<char>::kernel_1a, typename compare = std::less<domain> > class map : public enumerable<map_pair<domain,range> >, public asc_pair_remover<domain,range,compare> { /*! REQUIREMENTS ON domain domain must be comparable by compare where compare is a functor compatible with std::less and domain is swappable by a global swap() and domain must have a default constructor REQUIREMENTS ON range range is swappable by a global swap() and range must have a default constructor REQUIREMENTS ON mem_manager must be an implementation of memory_manager/memory_manager_kernel_abstract.h or must be an implementation of memory_manager_global/memory_manager_global_kernel_abstract.h or must be an implementation of memory_manager_stateless/memory_manager_stateless_kernel_abstract.h mem_manager::type can be set to anything. POINTERS AND REFERENCES TO INTERNAL DATA swap(), is_in_domain(), and operator[] functions do not invalidate pointers or references to internal data. All other functions have no such guarantee. INITIAL VALUE size() == 0 ENUMERATION ORDER The enumerator will iterate over the domain (and each associated range element) elements in ascending order according to the compare functor. (i.e. the elements are enumerated in sorted order) WHAT THIS OBJECT REPRESENTS map contains items of type domain and range This object is similar an array. It maps items of type domain on to items of type range. definition of equivalent: a is equivalent to b if a < b == false and b < a == false !*/ public: typedef domain domain_type; typedef range range_type; typedef compare compare_type; typedef mem_manager mem_manager_type; map( ); /*! ensures - #*this is properly initialized throws - std::bad_alloc or any exception thrown by domain's or range's constructor. !*/ virtual ~map( ); /*! ensures - all memory associated with *this has been released !*/ void clear( ); /*! ensures - #*this has its initial value throws - std::bad_alloc or any exception thrown by domain's or range's constructor. if this exception is thrown then *this is unusable until clear() is called and succeeds !*/ void add ( domain& d, range& r ); /*! requires - &d != &r (i.e. d and r cannot be the same variable) - is_in_domain(d) == false ensures - #is_in_domain(d) == true - #operator[](d) == r - #d and #r have initial values for their types - #size() == size() + 1 - #at_start() == true throws - std::bad_alloc or any exception thrown by domain's or range's constructor. if add() throws then it has no effect !*/ bool is_in_domain ( const domain& d ) const; /*! ensures - returns whether or not an element equivalent to d is in the domain of *this !*/ void remove ( const domain& d, domain& d_copy, range& r ); /*! requires - &d != &r (i.e. d and r cannot be the same variable) - &d != &d_copy (i.e. d and d_copy cannot be the same variable) - &r != &d_copy (i.e. r and d_copy cannot be the same variable) - is_in_domain(d) == true ensures - #is_in_domain(d) == false - #d_copy is equivalent to d - the element in the range of *this associated with #d_copy has been swapped into #r - #size() == size() - 1 - #at_start() == true !*/ void destroy ( const domain& d ); /*! requires - is_in_domain(d) == true ensures - #is_in_domain(d) == false - #size() == size() - 1 - #at_start() == true !*/ range& operator[] ( const domain& d ); /*! requires - is_in_domain(d) == true ensures - returns a non-const reference to the element in the range of *this associated with the element equivalent to d !*/ const range& operator[] ( const domain& d ) const; /*! requires - is_in_domain(d) == true ensures - returns a const reference to the element in the range of *this associated with the element equivalent to d !*/ void swap ( map& item ); /*! ensures - swaps *this and item !*/ private: // restricted functions map(map&); // copy constructor map& operator=(map&); // assignment operator }; template < typename domain, typename range, typename mem_manager, typename compare > inline void swap ( map<domain,range,mem_manager,compare>& a, map<domain,range,mem_manager,compare>& b ) { a.swap(b); } /*! provides a global swap function !*/ template < typename domain, typename range, typename mem_manager, typename compare > void deserialize ( map<domain,range,mem_manager,compare>& item, std::istream& in ); /*! provides deserialization support !*/ } #endif // DLIB_MAP_KERNEl_ABSTRACT_
[ [ [ 1, 232 ] ] ]
c722767a9ddec6b045285778139b4d660c8f110e
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/library_include_forward.hpp
08165f774118ac9b1e25093254e9949d03ec89a7
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
14,602
hpp
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // #ifndef AOSLCPP_AOSL__LIBRARY_INCLUDE_FORWARD_HPP #define AOSLCPP_AOSL__LIBRARY_INCLUDE_FORWARD_HPP // Begin prologue. // // // End prologue. #include <xsd/cxx/version.hxx> #if (XSD_INT_VERSION != 3030000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> #include <xsd/cxx/xml/dom/serialization-header.hxx> #include <xsd/cxx/tree/serialization.hxx> #include <xsd/cxx/tree/serialization/byte.hxx> #include <xsd/cxx/tree/serialization/unsigned-byte.hxx> #include <xsd/cxx/tree/serialization/short.hxx> #include <xsd/cxx/tree/serialization/unsigned-short.hxx> #include <xsd/cxx/tree/serialization/int.hxx> #include <xsd/cxx/tree/serialization/unsigned-int.hxx> #include <xsd/cxx/tree/serialization/long.hxx> #include <xsd/cxx/tree/serialization/unsigned-long.hxx> #include <xsd/cxx/tree/serialization/boolean.hxx> #include <xsd/cxx/tree/serialization/float.hxx> #include <xsd/cxx/tree/serialization/double.hxx> #include <xsd/cxx/tree/serialization/decimal.hxx> #include <xsd/cxx/tree/std-ostream-operators.hxx> /** * @brief C++ namespace for the %http://www.w3.org/2001/XMLSchema * schema namespace. */ namespace xml_schema { // anyType and anySimpleType. // /** * @brief C++ type corresponding to the anyType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::type Type; /** * @brief C++ type corresponding to the anySimpleType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::simple_type< Type > SimpleType; /** * @brief Alias for the anyType type. */ typedef ::xsd::cxx::tree::type Container; // 8-bit // /** * @brief C++ type corresponding to the byte XML Schema * built-in type. */ typedef signed char Byte; /** * @brief C++ type corresponding to the unsignedByte XML Schema * built-in type. */ typedef unsigned char UnsignedByte; // 16-bit // /** * @brief C++ type corresponding to the short XML Schema * built-in type. */ typedef short Short; /** * @brief C++ type corresponding to the unsignedShort XML Schema * built-in type. */ typedef unsigned short UnsignedShort; // 32-bit // /** * @brief C++ type corresponding to the int XML Schema * built-in type. */ typedef int Int; /** * @brief C++ type corresponding to the unsignedInt XML Schema * built-in type. */ typedef unsigned int UnsignedInt; // 64-bit // /** * @brief C++ type corresponding to the long XML Schema * built-in type. */ typedef long long Long; /** * @brief C++ type corresponding to the unsignedLong XML Schema * built-in type. */ typedef unsigned long long UnsignedLong; // Supposed to be arbitrary-length integral types. // /** * @brief C++ type corresponding to the integer XML Schema * built-in type. */ typedef long long Integer; /** * @brief C++ type corresponding to the nonPositiveInteger XML Schema * built-in type. */ typedef long long NonPositiveInteger; /** * @brief C++ type corresponding to the nonNegativeInteger XML Schema * built-in type. */ typedef unsigned long long NonNegativeInteger; /** * @brief C++ type corresponding to the positiveInteger XML Schema * built-in type. */ typedef unsigned long long PositiveInteger; /** * @brief C++ type corresponding to the negativeInteger XML Schema * built-in type. */ typedef long long NegativeInteger; // Boolean. // /** * @brief C++ type corresponding to the boolean XML Schema * built-in type. */ typedef bool Boolean; // Floating-point types. // /** * @brief C++ type corresponding to the float XML Schema * built-in type. */ typedef float Float; /** * @brief C++ type corresponding to the double XML Schema * built-in type. */ typedef double Double; /** * @brief C++ type corresponding to the decimal XML Schema * built-in type. */ typedef double Decimal; // String types. // /** * @brief C++ type corresponding to the string XML Schema * built-in type. */ typedef ::xsd::cxx::tree::string< char, SimpleType > String; /** * @brief C++ type corresponding to the normalizedString XML Schema * built-in type. */ typedef ::xsd::cxx::tree::normalized_string< char, String > NormalizedString; /** * @brief C++ type corresponding to the token XML Schema * built-in type. */ typedef ::xsd::cxx::tree::token< char, NormalizedString > Token; /** * @brief C++ type corresponding to the Name XML Schema * built-in type. */ typedef ::xsd::cxx::tree::name< char, Token > Name; /** * @brief C++ type corresponding to the NMTOKEN XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtoken< char, Token > Nmtoken; /** * @brief C++ type corresponding to the NMTOKENS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtokens< char, SimpleType, Nmtoken > Nmtokens; /** * @brief C++ type corresponding to the NCName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::ncname< char, Name > Ncname; /** * @brief C++ type corresponding to the language XML Schema * built-in type. */ typedef ::xsd::cxx::tree::language< char, Token > Language; // ID/IDREF. // /** * @brief C++ type corresponding to the ID XML Schema * built-in type. */ typedef ::xsd::cxx::tree::id< char, Ncname > Id; /** * @brief C++ type corresponding to the IDREF XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idref< char, Ncname, Type > Idref; /** * @brief C++ type corresponding to the IDREFS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idrefs< char, SimpleType, Idref > Idrefs; // URI. // /** * @brief C++ type corresponding to the anyURI XML Schema * built-in type. */ typedef ::xsd::cxx::tree::uri< char, SimpleType > Uri; // Qualified name. // /** * @brief C++ type corresponding to the QName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::qname< char, SimpleType, Uri, Ncname > Qname; // Binary. // /** * @brief Binary buffer type. */ typedef ::xsd::cxx::tree::buffer< char > Buffer; /** * @brief C++ type corresponding to the base64Binary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::base64_binary< char, SimpleType > Base64Binary; /** * @brief C++ type corresponding to the hexBinary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::hex_binary< char, SimpleType > HexBinary; // Date/time. // /** * @brief Time zone type. */ typedef ::xsd::cxx::tree::time_zone TimeZone; /** * @brief C++ type corresponding to the date XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date< char, SimpleType > Date; /** * @brief C++ type corresponding to the dateTime XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date_time< char, SimpleType > DateTime; /** * @brief C++ type corresponding to the duration XML Schema * built-in type. */ typedef ::xsd::cxx::tree::duration< char, SimpleType > Duration; /** * @brief C++ type corresponding to the gDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gday< char, SimpleType > Gday; /** * @brief C++ type corresponding to the gMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth< char, SimpleType > Gmonth; /** * @brief C++ type corresponding to the gMonthDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth_day< char, SimpleType > GmonthDay; /** * @brief C++ type corresponding to the gYear XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear< char, SimpleType > Gyear; /** * @brief C++ type corresponding to the gYearMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear_month< char, SimpleType > GyearMonth; /** * @brief C++ type corresponding to the time XML Schema * built-in type. */ typedef ::xsd::cxx::tree::time< char, SimpleType > Time; // Entity. // /** * @brief C++ type corresponding to the ENTITY XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entity< char, Ncname > Entity; /** * @brief C++ type corresponding to the ENTITIES XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entities< char, SimpleType, Entity > Entities; // Namespace information and list stream. Used in // serialization functions. // /** * @brief Namespace serialization information. */ typedef ::xsd::cxx::xml::dom::namespace_info< char > NamespaceInfo; /** * @brief Namespace serialization information map. */ typedef ::xsd::cxx::xml::dom::namespace_infomap< char > NamespaceInfomap; /** * @brief List serialization stream. */ typedef ::xsd::cxx::tree::list_stream< char > ListStream; /** * @brief Serialization wrapper for the %double type. */ typedef ::xsd::cxx::tree::as_double< Double > AsDouble; /** * @brief Serialization wrapper for the %decimal type. */ typedef ::xsd::cxx::tree::as_decimal< Decimal > AsDecimal; /** * @brief Simple type facet. */ typedef ::xsd::cxx::tree::facet Facet; // Flags and properties. // /** * @brief Parsing and serialization flags. */ typedef ::xsd::cxx::tree::flags Flags; /** * @brief Parsing properties. */ typedef ::xsd::cxx::tree::properties< char > Properties; // Parsing/serialization diagnostics. // /** * @brief Error severity. */ typedef ::xsd::cxx::tree::severity Severity; /** * @brief Error condition. */ typedef ::xsd::cxx::tree::error< char > Error; /** * @brief List of %error conditions. */ typedef ::xsd::cxx::tree::diagnostics< char > Diagnostics; // Exceptions. // /** * @brief Root of the C++/Tree %exception hierarchy. */ typedef ::xsd::cxx::tree::exception< char > Exception; /** * @brief Exception indicating that the size argument exceeds * the capacity argument. */ typedef ::xsd::cxx::tree::bounds< char > Bounds; /** * @brief Exception indicating that a duplicate ID value * was encountered in the object model. */ typedef ::xsd::cxx::tree::duplicate_id< char > DuplicateId; /** * @brief Exception indicating a parsing failure. */ typedef ::xsd::cxx::tree::parsing< char > Parsing; /** * @brief Exception indicating that an expected element * was not encountered. */ typedef ::xsd::cxx::tree::expected_element< char > ExpectedElement; /** * @brief Exception indicating that an unexpected element * was encountered. */ typedef ::xsd::cxx::tree::unexpected_element< char > UnexpectedElement; /** * @brief Exception indicating that an expected attribute * was not encountered. */ typedef ::xsd::cxx::tree::expected_attribute< char > ExpectedAttribute; /** * @brief Exception indicating that an unexpected enumerator * was encountered. */ typedef ::xsd::cxx::tree::unexpected_enumerator< char > UnexpectedEnumerator; /** * @brief Exception indicating that the text content was * expected for an element. */ typedef ::xsd::cxx::tree::expected_text_content< char > ExpectedTextContent; /** * @brief Exception indicating that a prefix-namespace * mapping was not provided. */ typedef ::xsd::cxx::tree::no_prefix_mapping< char > NoPrefixMapping; /** * @brief Exception indicating that the type information * is not available for a type. */ typedef ::xsd::cxx::tree::no_type_info< char > NoTypeInfo; /** * @brief Exception indicating that the types are not * related by inheritance. */ typedef ::xsd::cxx::tree::not_derived< char > NotDerived; /** * @brief Exception indicating a serialization failure. */ typedef ::xsd::cxx::tree::serialization< char > Serialization; /** * @brief Error handler callback interface. */ typedef ::xsd::cxx::xml::error_handler< char > ErrorHandler; /** * @brief DOM interaction. */ namespace dom { /** * @brief Automatic pointer for DOMDocument. */ using ::xsd::cxx::xml::dom::auto_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA /** * @brief DOM user data key for back pointers to tree nodes. */ const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } #include "aosl/source_uri_forward.hpp" // Forward declarations. // namespace aosl { class Library_include; } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__LIBRARY_INCLUDE_FORWARD_HPP
[ "klaim@localhost" ]
[ [ [ 1, 610 ] ] ]
2afb28416f78c72c7cbfd2777257e11fbdb59f09
a0de58fc332fb03adc139946006d9e4f472870eb
/raytracer/src/sphere.cpp
0d397dc0be37c446eca091786eb197214c17603e
[]
no_license
BackupTheBerlios/flashphoto-svn
7679f76e378a5d35353f606d218e38fd62243ee6
8feffa2b721489b6fa83fbd08f44e1c751b37837
refs/heads/master
2020-06-04T01:58:28.579762
2006-10-30T23:12:06
2006-10-30T23:12:06
40,673,101
0
0
null
null
null
null
UTF-8
C++
false
false
1,095
cpp
#include "sphere.h" #include <cmath> /*-<==>----------------------------------------------------------------- / Constructor /----------------------------------------------------------------------*/ CSphere::CSphere(SCALAR aradius) { radius = aradius; } /*-<==>----------------------------------------------------------------- / /----------------------------------------------------------------------*/ bool CSphere::hits (const CLine &line, SCALAR &t_hit) { VECTOR lloc=line.loc-loc; SCALAR a=line.dir.dot(lloc); SCALAR bp=(lloc.dot(line.dir)*lloc.dot(line.dir))- ((lloc.dot(lloc))-(radius*radius)); // Si la raiz no tiene solucion, no hay interseccion if((bp)<0.0f) return false; SCALAR b=std::sqrt(bp); SCALAR t2=std::abs(a)+b; SCALAR t1=std::abs(a)-b; //if((t1>=SMALL_AMOUNT)&&((t1<t2)||(t2<SMALL_AMOUNT))) if(t1>=SMALL_AMOUNT) t_hit=t1; else t_hit=t2; return (t_hit>1e-3); } VECTOR CSphere::getNormal(const VECTOR &hit_loc) { VECTOR T; T=hit_loc-loc; T.normalize(); return T; }
[ "gmiranda@697c275a-9409-0410-946e-c1ffe88a986e" ]
[ [ [ 1, 51 ] ] ]
4769cbd7feb950cb496a745fa59749061d3dbd03
d37a1d5e50105d82427e8bf3642ba6f3e56e06b8
/DVR/HHVClientDemo/HHVClientDemo/HWndManager.h
7278d34a2bb5cae09a78693a3007d270afa3e362
[]
no_license
080278/dvrmd-filter
176f4406dbb437fb5e67159b6cdce8c0f48fe0ca
b9461f3bf4a07b4c16e337e9c1d5683193498227
refs/heads/master
2016-09-10T21:14:44.669128
2011-10-17T09:18:09
2011-10-17T09:18:09
32,274,136
0
0
null
null
null
null
GB18030
C++
false
false
3,505
h
//--------------------------------------------------------------------------- #ifndef CMonitorAreaManagerH #define CMonitorAreaManagerH #include<map> using namespace std; //画面分割模式 #define SPLIT_1 0 #define SPLIT_4 1 #define SPLIT_6 2 #define SPLIT_9 3 #define SPLIT_16 4 #define SPLIT_25 5 #define SPLIT_36 6 #define SPLIT_3 7 #define SPLIT_6_2 8 #define SPLIT_49 9 #define SPLIT_64 10 #define MAX_CLIENT_WINDOW 128 #define HWNDISNULL -100 struct S_HWND_INDEX { S_HWND_INDEX(){ memset(this, 0x00, sizeof(S_HWND_INDEX) ); bFree = true; } int index; HWND hWnd; bool bFree; //窗口是否空闲 true表示空闲, false表示占用 }; //--------------------------------------------------------------------------- class CHWndManager { private: HWND m_hParentWnd; int m_SpliteHandle;//分割handle,由分割库InitSplit返回 S_HWND_INDEX m_mWndFree[MAX_CLIENT_WINDOW]; public: CHWndManager(); ~CHWndManager(); int InitSplit(HWND hParentWnd); HWND GetHWnd( int channel ); HWND GetFocusHWnd( ); void SelectChannel(POINT pt); void SetSplitMode ( int currIndex,int num, int clickNum = 0 ); int GetFocus(); void SetFocus( int index ); void SetFocus( HWND hWnd ); //debug end int m_videoWindowNum; //当前画面分割数 void SetOsdTextEx(int index, int line, char* text, COLORREF osdcolor); private: BOOL CheckHwndFree_NoMutex(HWND hWnd, int& index);//检查一个窗口是否空闲. 空闲则返回为true; 占用则返回false 2008-07-11 ma }; typedef int (__stdcall *fHWnd_Init)(HWND hParentWnd); typedef void (__stdcall *fHWnd_Clear)(int spliteHandle); typedef HWND (__stdcall *fHWnd_GetHWnd)(int spliteHandle, int index ); typedef int (__stdcall *fHWnd_GetFocus)(int spliteHandle); typedef void (__stdcall *fHWnd_SetFocus)(int spliteHandle, int index); typedef bool (__stdcall *fHWnd_SetSplitMode)(int spliteHandle, int nPlayer, int num); typedef void (__stdcall *fHWnd_OnUpdateFocus)(int spliteHandle, POINT pt) ; typedef void (__stdcall *fHWnd_SetPaintBG)(int spliteHandle, int index, BOOL bPaitBG); typedef int (__stdcall *fHWnd_GetIndex)(int spliteHandle, HWND hWnd); typedef bool (__stdcall *fHWnd_SetSplitMode_WithOrder)(int spliteHandle, int nPlayer, int num, int order); typedef bool (__stdcall *fHWnd_GetVisible)(int spliteHandle, int index); typedef void (__stdcall *fHWnd_SetOsdTextEx)(int spliteHandle, int index, int line, char* text, COLORREF crColor); extern fHWnd_Init HWnd_Init ; extern fHWnd_Clear HWnd_Clear ; extern fHWnd_GetHWnd HWnd_GetHWnd ; extern fHWnd_GetFocus HWnd_GetFocus ; extern fHWnd_SetFocus HWnd_SetFocus ; extern fHWnd_SetSplitMode HWnd_SetSplitMode ; extern fHWnd_OnUpdateFocus HWnd_OnUpdateFocus ; extern fHWnd_SetPaintBG HWnd_SetPaintBG ; extern fHWnd_GetIndex HWnd_GetIndex ; extern fHWnd_SetSplitMode_WithOrder HWnd_SetSplitMode_WithOrder; extern fHWnd_SetOsdTextEx HWnd_SetOsdTextEx; extern fHWnd_GetVisible HWnd_GetVisible; //2008-08-25 extern HMODULE ghWndDLL ; int LoadHWndDll(); int FreeHWndDll(); #endif
[ "[email protected]@27769579-7047-b306-4d6f-d36f87483bb3" ]
[ [ [ 1, 95 ] ] ]
0e28d0d25c8aad07c3c6060978c3d51461814f66
9399383d7e227c4812e19f08a2d2c20cf66a0031
/AboutDlg.h
d5b4723e990f3198032cdd4f712e3e8746991a44
[]
no_license
mattttttttsu/Edit-Engine-Test
bf5bf22c2b1a8937bc4ed062616d422153b7cb65
e3f74ba821a7ddb2f235c0cc519f899cc0b045ae
refs/heads/master
2021-01-10T19:11:27.119238
2011-11-29T18:52:40
2011-11-29T18:52:40
2,877,257
0
0
null
null
null
null
UTF-8
C++
false
false
1,123
h
// aboutdlg.h : interface of the CAboutDlg class // ///////////////////////////////////////////////////////////////////////////// #ifndef _ABOUTDLG_H_ #define _ABOUTDLG_H_ namespace EditTest { class CAboutDlg : public CDialogImpl<CAboutDlg> { public: enum { IDD = IDD_ABOUTBOX }; BEGIN_MSG_MAP(CAboutDlg); MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog); COMMAND_ID_HANDLER(IDOK, OnCloseCmd); COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd); END_MSG_MAP(); // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { CenterWindow(GetParent()); return TRUE; } LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { EndDialog(wID); return 0; } }; }; #endif
[ [ [ 1, 41 ] ] ]
c37214697e18a091800805650f031419fa8fc212
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/src/OpenSteerUT/AbstractVehicleUtilities.h
fcad479fc0dacc837f5b9153e359d3b4a89b8467
[]
no_license
janfietz/edunetgames
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
04d787b0afca7c99b0f4c0692002b4abb8eea410
refs/heads/master
2016-09-10T19:24:04.051842
2011-04-17T11:00:09
2011-04-17T11:00:09
33,568,741
0
0
null
null
null
null
UTF-8
C++
false
false
4,822
h
#ifndef __ABSTRACTVEHICLEUTILITIES_H__ #define __ABSTRACTVEHICLEUTILITIES_H__ //----------------------------------------------------------------------------- // Copyright (c) 2009, Jan Fietz, Cyrus Preuss // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of EduNetGames nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- //#include "EduNetCommon/EduNetCommon.h" #include "OpenSteer/AbstractVehicle.h" #include "OpenSteer/Color.h" #include "OpenSteer/Camera.h" #include "OpenSteer/SimpleVehicle.h" #include "OpenSteer/Plugin.h" //----------------------------------------------------------------------------- namespace OpenSteer { using namespace OpenSteer; class VehicleUtilities { public: // draws a gray disk on the XZ plane under a given vehicle static void highlightVehicleUtility ( AbstractRenderer* pRenderer, const AbstractVehicle& vehicle); // draws a gray circle on the XZ plane under a given vehicle static void circleHighlightVehicleUtility ( AbstractRenderer* pRenderer, const AbstractVehicle& vehicle); // draw a box around a vehicle aligned with its local space // xxx not used as of 11-20-02 static void drawBoxHighlightOnVehicle (AbstractRenderer* pRenderer, const AbstractVehicle& v, const Color& color); // draws a colored circle (perpendicular to view axis) around the center // of a given vehicle. The circle's radius is the vehicle's radius times // radiusMultiplier. static void drawCircleHighlightOnVehicle (AbstractRenderer* pRenderer, const AbstractVehicle& v, const float radiusMultiplier, const Color& color); // select the "next" vehicle: cycle through the registry static void selectNextVehicle (void); // select vehicle nearest the given screen position (e.g.: of the mouse) static void selectVehicleNearestScreenPosition (OpenSteer::AbstractRenderer* pRenderer, int x, int y); // ---------------------------------------------------------- mouse support // Find the AbstractVehicle whose screen position is nearest the // given window coordinates, typically the mouse position. Note // this will return NULL if there are no AbstractVehicles. static AbstractVehicle* findVehicleNearestScreenPosition (OpenSteer::AbstractRenderer* pRenderer, int x, int y); }; //------------------------------------------------------------------------- template <class Super, EntityClassId classId = 0> class VehicleClassIdMixin : public Super { public: VehicleClassIdMixin() { } VehicleClassIdMixin( OpenSteer::ProximityDatabase* pd ):Super( pd ) { } virtual ~VehicleClassIdMixin() { } // AbstractEntity interface virtual AbstractEntity* cloneEntity( void ) const { return new VehicleClassIdMixin(); } // important implement new clone functionality //------------------------------------------------------------------------- virtual OpenSteer::AbstractVehicle* cloneVehicle( void ) const { OpenSteer::AbstractVehicle* pkVehicle = new VehicleClassIdMixin(); return pkVehicle; } virtual EntityClassId getClassId( void ) const { static EntityClassId sClassId = classId; return sClassId; } private: }; } #endif // __ABSTRACTVEHICLEUTILITIES_H__
[ "janfietz@localhost" ]
[ [ [ 1, 131 ] ] ]
4c5b7a713218e93ebfa165197a5480cb9f3b18f3
6a925ad6f969afc636a340b1820feb8983fc049b
/librtsp/librtsp/src/RTSPPacketBuilder.cpp
ed68473698ffb22a22fb23ea198bc1514930e235
[]
no_license
dulton/librtsp
c1ac298daecd8f8008f7ab1c2ffa915bdbb710ad
8ab300dc678dc05085f6926f016b32746c28aec3
refs/heads/master
2021-05-29T14:59:37.037583
2010-05-30T04:07:28
2010-05-30T04:07:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
304
cpp
/*!@file RTSPPacketBuilder.cpp @brief Copyright (c) 2009 HUST ITEC VoIP Lab. All rights reserved. @author Wentao Tang @date 2009.3.21 @version 1.0 */ #include "RTSPPacketBuilder.h" RTSPPacketBuilder::RTSPPacketBuilder(void) { } RTSPPacketBuilder::~RTSPPacketBuilder(void) { }
[ "TangWentaoHust@95ff1050-1aa1-11de-b6aa-3535bc3264a2" ]
[ [ [ 1, 19 ] ] ]
2318cfb90710fdc94b163b1570282df2838f94c0
38d9a3374e52b67ca01ed8bbf11cd0b878cce2a5
/branches/tbeta/CCV-fid/addons/ofxFFMV/src/ofxffmv.h
f56443258d8eeec9983a60ea000aa7a92b67a895
[]
no_license
hugodu/ccv-tbeta
8869736cbdf29685a62d046f4820e7a26dcd05a7
246c84989eea0b5c759944466db7c591beb3c2e4
refs/heads/master
2021-04-01T10:39:18.368714
2011-03-09T23:05:24
2011-03-09T23:05:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,003
h
#ifndef OFXFFMV_H_INCLUDED #define OFXFFMV_H_INCLUDED #include "pgrflycapture.h" #include "stdio.h" #include <iostream> // // The maximum number of cameras on the bus. // #define _MAX_CAMS 10 class ofxffmv { public: ofxffmv(); ~ofxffmv(); void initFFMV(int wid,int hei,int rate,int startX=0,int startY=0); void setDeviceID(int id); int getDeviceID(); void grabFrame(); int getCamWidth(); int getCamHeight(); void listDevices(); static int getDeviceCount(); FlyCaptureImage fcImage[_MAX_CAMS]; void setMemoryChannel(int nr); private: // This acts as a handle to the camera. FlyCaptureContext context[_MAX_CAMS]; int fcCameraID; int fcMemoryChannel; int camWidth; int camHeight; // Enumerate the cameras on the bus. FlyCaptureInfoEx arInfo[ _MAX_CAMS ]; unsigned int camNum ; }; #endif // OFXFFMV_H_INCLUDED
[ "schlupek@463ed9da-a5aa-4e33-a7e2-2d3b412cff85" ]
[ [ [ 1, 39 ] ] ]
519c1dea50498016f05387776b7f4ac27b1fbb2b
0d0772b87c1870a071d363e7ff00d895a1966647
/salomon/tools/WinSalomon/trunk/WinSalomon/StringHelper.h
654167a4de070ea9e26c07c2dc2626cc53501616
[]
no_license
BackupTheBerlios/salomon-svn
89b51a6e6fc4dbd873d62f3f642aa5fe2482ce89
5cec21e148039ca4fd7585f21a72e650d7d4a030
refs/heads/master
2021-01-13T01:49:11.013026
2008-01-10T16:49:55
2008-01-10T16:49:55
40,799,700
0
0
null
null
null
null
UTF-8
C++
false
false
1,053
h
#pragma once /* * Copyright (C) 2005 Salomon Team * * This file is part of Salomon. * * Salomon is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Salomon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Salomon; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <jni.h> #include <string> class StringHelper { public: static jobjectArray getStringArray(JNIEnv *env, char **strv, int strc); static jstring getString(JNIEnv *env, const char *s); };
[ "nico@365c1dc3-c9e6-0310-9dba-f6f9a6fbeba6" ]
[ [ [ 1, 35 ] ] ]
625ce708439421211df4b65dcd9a40d2ce735cb9
fdfaf8e8449c5e80d93999ea665db48feaecccbe
/trunk/cg ex2/BVHWriter.cpp
f1d5ceece01b5858c9a1e4aef3fa3c8d813e30bb
[]
no_license
BackupTheBerlios/glhuji2005-svn
879e60533f820d1bdcfa436fd27894774c27a0b7
3afe113b265704e385c94fabaf99a7d1ad1fdb02
refs/heads/master
2016-09-01T17:25:30.876585
2006-09-03T18:04:19
2006-09-03T18:04:19
40,673,356
0
0
null
null
null
null
UTF-8
C++
false
false
5,495
cpp
#include "StdAfx.h" #include "BVHWriter.h" using namespace std; //Make the code a little more readable typedef ArticulatedFigure::Node Node; typedef ArticulatedFigure::ParamMappingArr ParamMappingArr; BVHWriter::BVHWriter(void) { } BVHWriter::~BVHWriter(void) { } void BVHWriter::write( ArticulatedFigure &inFigure, string &inOutputFilename ) { mOutputStream.open( inOutputFilename.c_str(), ios_base::out ); //----------------- Write Out Start Tag ---------------- mOutputStream << "HIERARCHY" << endl << endl; //-------------- Write Out Nodes ------------- ArticulatedFigure::NodePtrListIt it = inFigure.mRootNodes.begin(); for( ; it != inFigure.mRootNodes.end(); it++ ) { Node *n = *it; mLinearNodeList.push_back(n); mOutputStream << "ROOT " << n->pNodeName.c_str() << endl; writeNode(*n, 0); } //-------------- Write Out Movements ------------- mOutputStream << "MOTION" << endl; mOutputStream << "Frames: " << inFigure.getNumOfFrames() << endl; mOutputStream << "Frame Time: " << inFigure.getFrameTime() << endl; mOutputStream << endl << endl; //-------------- Write Out Actual Motion Vectors! ------------- for( int i = 0; i < inFigure.getNumOfFrames(); i++ ) { ArticulatedFigure::NodePtrListIt it = mLinearNodeList.begin(); for( ; it != mLinearNodeList.end(); it++ ) { if( it != mLinearNodeList.begin() ) mOutputStream << " "; Node *n = *it; ParamMappingArr &mapArr = n->pChannelMapping; int numChannels = n->pNumChannels; Vector3d &pos = n->pOffsets[i]; Vector3d &rot = n->pRotations[i]; if( !n->pFilteredOffsets.empty() ) pos = n->pFilteredOffsets[i]; if( !n->pFilteredRotations.empty() ) rot = n->pFilteredRotations[i]; for( int j = 0; j < numChannels; j++ ) { switch( mapArr.pArr[j] ) { case XROT: mOutputStream << rot[0]; break; case YROT: mOutputStream << rot[1]; break; case ZROT: mOutputStream << rot[2]; break; case XPOS: mOutputStream << pos[0]; break; case YPOS: mOutputStream << pos[1]; break; case ZPOS: mOutputStream << pos[2]; break; } if( j != (numChannels-1)) mOutputStream << " "; } } mOutputStream << endl; } mOutputStream.close(); } void BVHWriter::writeNode( ArticulatedFigure::Node &inNode, int inLevel ) { string indent = ""; for( int i = 0; i < inLevel; i++ ) indent += "\t"; //----------- Opening "{" ---------------- mOutputStream << indent.c_str() << "{" << endl; //----------- OFFSET ---------------- mOutputStream << indent.c_str() << "\t" << "OFFSET "; mOutputStream << inNode.pPosition[0] << " " << inNode.pPosition[1] << " " << inNode.pPosition[2] << endl; if( inNode.pChildren.size() > 0 ) //not an end node { //-------------------------- Channels ------------------------------- int numChannels = inNode.pNumChannels; mOutputStream << indent.c_str() << "\t" << "CHANNELS " << numChannels << " "; ParamMappingArr &mapArr = inNode.pChannelMapping; for( int i = 0; i < numChannels; i++ ) { switch( mapArr.pArr[i] ) { case XROT: mOutputStream << "Xrotation"; break; case YROT: mOutputStream << "Yrotation"; break; case ZROT: mOutputStream << "Zrotation"; break; case XPOS: mOutputStream << "Xposition"; break; case YPOS: mOutputStream << "Yposition"; break; case ZPOS: mOutputStream << "Zposition"; break; default: case INVALID_PLCMNT: cout << "ERROR: invalid channel mapping in node " << inNode.pNodeName.c_str() << endl; exit(0); break; } if( i != (numChannels-1) ) mOutputStream << " "; } mOutputStream << endl; //-------------------------- Print Children ------------------------------- for( ArticulatedFigure::NodePtrListIt it = inNode.pChildren.begin(); it != inNode.pChildren.end(); it++ ) { Node *n = *it; mLinearNodeList.push_back(n); mOutputStream << indent.c_str() << "\t" ; if( n->pChildren.size() == 0 ) mOutputStream << "End Site" << endl; else mOutputStream << "JOINT " << n->pNodeName.c_str() << endl; writeNode( *n, inLevel+1 ); } } //----------- Closing "}" ---------------- mOutputStream << indent.c_str() << "}" << endl; }
[ "playmobil@c8a6d0be-e207-0410-856a-d97b7f264bab", "itai@c8a6d0be-e207-0410-856a-d97b7f264bab" ]
[ [ [ 1, 39 ], [ 41, 44 ], [ 46, 59 ], [ 66, 181 ] ], [ [ 40, 40 ], [ 45, 45 ], [ 60, 65 ] ] ]
293d2a7da61a4c35f9d30589c21a76cafa138fd9
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Src/Lokapala/Operator/UserAdminDlg.cpp
3f93f9ee7415051dba32bfe98d0b6d0e01bf9ea2
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UTF-8
C++
false
false
4,920
cpp
// UserAdmin.cpp : implementation file // #include "stdafx.h" #include "Operator.h" #include "UserAdminDlg.h" #include "UsersDataDTO.h" // CUserAdminDlg dialog IMPLEMENT_DYNAMIC(CUserAdminDlg, CDialog) CUserAdminDlg::CUserAdminDlg(CWnd* pParent /*=NULL*/) : CDialog(CUserAdminDlg::IDD, pParent) { } CUserAdminDlg::~CUserAdminDlg() { } void CUserAdminDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_NAME, m_name); DDX_Control(pDX, IDC_LOWPASS, m_lowPassword); DDX_Control(pDX, IDC_HIGHPASS, m_highPassword); DDX_Control(pDX, IDC_LEVEL, m_level); DDX_Control(pDX, IDC_USERLIST, m_userList); } BEGIN_MESSAGE_MAP(CUserAdminDlg, CDialog) ON_BN_CLICKED(IDC_USER_ADD, &CUserAdminDlg::OnBnClickedUserAdd) ON_BN_CLICKED(IDC_USER_DELETE, &CUserAdminDlg::OnBnClickedUserDelete) ON_LBN_SELCHANGE(IDC_USERLIST, &CUserAdminDlg::OnLbnSelchangeUserlist) ON_WM_CTLCOLOR() END_MESSAGE_MAP() // CUserAdminDlg message handlers /**@brief 다이얼로그로부터 입력값을 읽어들인다. */ void CUserAdminDlg::GetInputVariables(CString *a_name, CString *a_lowPassword, CString *a_highPassword, int *a_level) { m_name.GetWindowTextW(*a_name); m_lowPassword.GetWindowTextW(*a_lowPassword); m_highPassword.GetWindowTextW(*a_highPassword); CString value; m_level.GetWindowTextW(value); *a_level = _ttoi(value); } /**@brief 특정 유저의 정보를 입력창에 띄운다. */ void CUserAdminDlg::SetInputVariables(void *a_user) { CUserDataDTO *user = (CUserDataDTO *)a_user; m_name.SetWindowTextW(user->m_name); m_lowPassword.SetWindowTextW(user->m_lowLevelPassword); CString value; value.Format(_T("%d"), user->m_level); m_level.SetWindowTextW(value); } /**@brief 유저 추가 버튼 클릭 */ void CUserAdminDlg::OnBnClickedUserAdd() { // TODO: Add your control notification handler code here CString name, lowPassword, highPassword; int level; GetInputVariables(&name, &lowPassword, &highPassword, &level); CUserDataDTO user(_T(""), name, lowPassword, highPassword, level); CCBFMediator::Instance()->AddUser( (void *)&user); ShowUsers(); } /**@brief 유저 삭제 버튼 클릭 */ void CUserAdminDlg::OnBnClickedUserDelete() { // TODO: Add your control notification handler code here int selectedCount = m_userList.GetSelCount(); CString id; CArray<int,int> selectedIndex; selectedIndex.SetSize(selectedCount); m_userList.GetSelItems(selectedCount, selectedIndex.GetData()); for(int i=0; i<selectedCount; i++) { m_userList.GetText(selectedIndex[i], id); int tokenIndex = 0; id = id.Tokenize(_T("/"),tokenIndex); CCBFMediator::Instance()->DeleteUser(&id); } ShowUsers(); } /**@brief 현재 유저 목록을 표시 */ void CUserAdminDlg::ShowUsers() { m_userList.ResetContent(); CUsersDataDTO *pUsersData = (CUsersDataDTO *)CCBFMediator::Instance()->GetUsers(); POSITION pos = pUsersData->m_users.GetStartPosition(); CString key; CUserDataDTO value; while(pos != NULL) { pUsersData->m_users.GetNextAssoc(pos, key, value); CString userDisplay; userDisplay = value.m_lowLevelPassword + _T("/") + value.m_name; m_userList.AddString(userDisplay); } } BOOL CUserAdminDlg::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here ShowUsers(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } /**@brief 리스트박스에서 유저를 선택했을 때. */ void CUserAdminDlg::OnLbnSelchangeUserlist() { // TODO: Add your control notification handler code here int selectedCount = m_userList.GetSelCount(); if(selectedCount == 0) { return; } CArray<int,int> selectedIndex; selectedIndex.SetSize(selectedCount); m_userList.GetSelItems(selectedCount, selectedIndex.GetData()); int selected = selectedIndex[0]; CString userId; m_userList.GetText(selected, userId); selected = 0; userId = userId.Tokenize(_T("/"), selected); CUsersDataDTO *usersData = (CUsersDataDTO *)CCBFMediator::Instance()->GetUsers(); CUserDataDTO *user = usersData->GetUserById(userId); SetInputVariables((void *)user); } /**@brief 다이얼로그 배경색, 스태틱 컨트롤 배경색 조정 */ HBRUSH CUserAdminDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); // TODO: Change any attributes of the DC here switch( nCtlColor ) { case CTLCOLOR_DLG : return (HBRUSH)CreateSolidBrush( RGB(244,243,238) ); // 원하는 색상코드를 입력한다. break; case CTLCOLOR_STATIC : pDC->SetTextColor(RGB(0,0,0)); pDC->SetBkColor(RGB(244,243,238)); break; } // TODO: Return a different brush if the default is not desired return hbr; }
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
[ [ [ 1, 182 ] ] ]
d65bdb667f17e057d0f1e0130894b2e749735bd9
080d0991b0b9246584851c8378acbd5111c9220e
/10019 - Funny encryption method/10019.cpp
aefa68c43d26c2351fc21c4fdf0941e5add6494a
[]
no_license
jlstr/acm
93c9bc3192dbfbeb5e39c18193144503452dac2a
cd3f99e66ac5eb9e16a5dccaf563ca489e08abc3
refs/heads/master
2021-01-16T19:33:50.867234
2011-09-29T19:56:16
2011-09-29T19:56:16
8,509,059
1
0
null
null
null
null
UTF-8
C++
false
false
1,866
cpp
#include <stdio.h> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int casos; scanf("%d", &casos); while (casos--){ int x1, x2, temp, temp2; scanf("%x",&x2); //<---- read number in hexdecimal system(i.e. 265) //en x2 queda en hexadecimal, ahora convertirlo a decimal. temp2 = x1 = 0; temp = x2; while (temp > 0){ //Convierto a decimal pero con la cifra menos significativa a la izquierda temp2 = temp2 * 10 + temp % 16; temp /= 16; } while (temp2 > 0){ //Invierto para que quede con cifra menos significativa a la derecha x1 = x1 * 10 + temp2 % 10; temp2 /= 10; } //Aqui en x1 y en x2 esta procesado correctamente el num en decimal. int b = 0; temp2 = 0; temp = x1; while (temp > 0){ temp2 = temp2 * 10 + temp % 2; temp /= 2; } while (temp2 > 0){ //Invierto para que quede con cifra menos significativa a la derecha b = b * 10 + temp2 % 10; temp2 /= 10; } int b1 = 0; while (b){ if (b % 10 == 1) b1++; b /= 10; } printf("%d ", b1); b = 0; temp2 = 0; temp = x2; while (temp > 0){ temp2 = temp2 * 10 + temp % 2; temp /= 2; } while (temp2 > 0){ //Invierto para que quede con cifra menos significativa a la derecha b = b * 10 + temp2 % 10; temp2 /= 10; } b1 = 0; while (b){ if (b % 10 == 1) b1++; b /= 10; } printf("%d\n", b1); } return 0; }
[ [ [ 1, 63 ] ] ]
7057dcdfc7e1f8c59a5ed8972416f58330f1c405
028e528de8082baa7b0d8a43a46004beb776a41b
/Engine5/cameraclass.h
71a70a143c014504796ddeed25b374a24259be3c
[]
no_license
Headcool/Test
5825ee92104e1b364081d4daecc7b825f3557cde
107ccae5eb346ede3f5315c5d84303e3dda97663
refs/heads/master
2020-03-25T04:22:23.164254
2011-01-24T22:57:14
2011-01-24T22:57:14
1,289,186
0
0
null
null
null
null
UTF-8
C++
false
false
901
h
//////////////////////////////////////////////////////////////////////////////// // Filename: cameraclass.h //////////////////////////////////////////////////////////////////////////////// #ifndef _CAMERACLASS_H_ #define _CAMERACLASS_H_ ////////////// // INCLUDES // ////////////// #include <d3dx10math.h> //////////////////////////////////////////////////////////////////////////////// // Class name: CameraClass //////////////////////////////////////////////////////////////////////////////// class CameraClass { public: CameraClass(); CameraClass(const CameraClass&); ~CameraClass(); void SetPosition(float, float, float); void SetRotation(float, float, float); void Render(); void GetViewMatrix(D3DXMATRIX&); private: D3DXMATRIX m_viewMatrix; float m_positionX, m_positionY, m_positionZ; float m_rotationX, m_rotationY, m_rotationZ; }; #endif
[ [ [ 1, 37 ] ] ]
3c57ad9a778e30c4a509363452fd529dd1db6c67
b82e8474685b37b51f3e1ca3f513e01320298c3c
/src/sudokucasewidget.h
03a88791173dcddac53246de23ffb509a50c7849
[]
no_license
mariogeiger/Sudoku-Resolver-Multicore
4cc1054bda38508f1125063a8df253bcc82cd382
16a424ea7eb3e4eb123e5f7a80f31121229e98f2
refs/heads/master
2021-05-27T20:28:40.247966
2011-12-14T17:04:00
2011-12-14T17:04:00
778,389
0
1
null
null
null
null
UTF-8
C++
false
false
1,093
h
#ifndef SUDOKUCASEWIDGET_H #define SUDOKUCASEWIDGET_H #include <QLCDNumber> #include <QWheelEvent> #include <QMouseEvent> #include <QFocusEvent> #include <QKeyEvent> class SudokuWidget; class SudokuCaseWidget : public QLCDNumber { Q_OBJECT public: Q_ENUMS(DisplayMode) enum DisplayMode { Edit, Normal, Error, NoError }; SudokuCaseWidget(SudokuWidget* parent); void setRange(int min, int max) {_min = min; _max = max;} void setNullValue(int nul) { _nul = nul; } public slots: void display(int num, DisplayMode mode = Normal); void setDisplayMode(DisplayMode mode); signals: void valueChanged(int value); void valueEdited(int value); protected: virtual void wheelEvent(QWheelEvent* event); virtual void mouseDoubleClickEvent(QMouseEvent* /*event*/); virtual void focusInEvent(QFocusEvent* /*event*/); virtual void focusOutEvent(QFocusEvent* /*event*/); virtual void keyPressEvent(QKeyEvent* event); private: int _min, _max; int _nul; DisplayMode displayMode; bool errorMode; }; #endif // SUDOKUCASEWIDGET_H
[ [ [ 1, 41 ] ] ]
333306ce0e1c051c9df8120afce02196f8110d87
00fdb9c8335382401ee0a8c06ad6ebdcaa136b40
/ARM9/source/glib/glglobal.cpp
fd1c019c583af4d581e66e6adc99f6b45b71112a
[]
no_license
Mbmax/ismart-kernel
d82633ba0864f9f697c3faa4ebc093a51b8463b2
f80d8d7156897d019eb4e16ef9cec8a431d15ed3
refs/heads/master
2016-09-06T13:28:25.260481
2011-03-29T10:31:04
2011-03-29T10:31:04
35,029,299
1
2
null
null
null
null
GB18030
C++
false
false
1,889
cpp
#include <stdlib.h> #include <string.h> #include <stdarg.h> #include <NDS.h> #include "glib.h" #include "glmemtool.h" #include "glglobal.h" CglScreenMain *pScreenMain; CglScreenMainOverlay *pScreenMainOverlay; CglScreenSub *pScreenSub; void glDefaultMemorySetting(void) { videoSetMode(MODE_5_2D | DISPLAY_BG2_ACTIVE | DISPLAY_BG3_ACTIVE | DISPLAY_SPR_ACTIVE | DISPLAY_SPR_2D | DISPLAY_SPR_2D_BMP_256); videoSetModeSub(MODE_2_2D | DISPLAY_BG2_ACTIVE | DISPLAY_SPR_ACTIVE | DISPLAY_SPR_2D | DISPLAY_SPR_2D_BMP_256); // videoSetModeSub(MODE_2_2D | DISPLAY_BG2_ACTIVE | DISPLAY_SPR_2D | DISPLAY_SPR_2D_BMP_256); vramSetMainBanks(VRAM_A_MAIN_BG_0x06000000, VRAM_B_MAIN_SPRITE_0x06400000, VRAM_C_MAIN_BG_0x06020000,VRAM_D_SUB_SPRITE); vramSetBankE(VRAM_E_LCD); vramSetBankF(VRAM_F_LCD); vramSetBankG(VRAM_G_LCD); vramSetBankH(VRAM_H_SUB_BG); vramSetBankI(VRAM_I_LCD); } void glDefaultClassCreate(void) { //创建主屏的显示模式,双显示模式,BG3 ,BG2 , 缓冲模式可以进行切换显示 pScreenMain=new CglScreenMain(); //创建主屏的OVERLay ,sprite 的设置和显示,一共12个sprite pScreenMainOverlay=new CglScreenMainOverlay(); //创建子屏的显示,同OVERLAY一样也是Sprite pScreenSub=new CglScreenSub(); } void glDefaultClassFree(void) { delete pScreenMain; pScreenMain=NULL; delete pScreenMainOverlay; pScreenMainOverlay=NULL; delete pScreenSub; pScreenSub=NULL; } //static void (*glDebugPrint)(const char* s)=NULL; void glSetFuncDebugPrint(void (*_DebugPrint)(const char* s)) { // glDebugPrint=_DebugPrint; } /* void glDebugPrintf(const char* format, ...) { if(glDebugPrint==NULL) return; char strbuf[256]; va_list args; va_start( args, format ); vsprintf( strbuf, format, args ); glDebugPrint(strbuf); } */
[ "feng.flash@4bd7f34a-4c62-84e7-1fb2-5fbc975ebfb2" ]
[ [ [ 1, 67 ] ] ]
92b6ec1c76e34412f523237aef3c80cdb07ca697
48d325e5c8648382c8f790a5e8762b36ffd7c45a
/qtshoot/taskenemybullet.h
ecfdad5512bea26f9b0faf17959f6099d2d7d2de
[]
no_license
tomozh/qtshoot
46184f4bf7ad9e36f4a358b862ec17e415a0ece0
332aaedc89c398cc9f79c908c77bd2dd6978ec44
refs/heads/master
2020-07-07T10:59:31.554012
2011-12-09T18:04:09
2011-12-09T18:04:09
2,948,875
0
0
null
null
null
null
UTF-8
C++
false
false
478
h
#ifndef TASKENEMYBULLET_H #define TASKENEMYBULLET_H #include "taskchara.h" class taskEnemyBullet : public TaskChara { public: taskEnemyBullet(const QPointF& pt, int zorder, const QPointF& spd, const QPointF& acc); virtual void oneFrame(); virtual void render(QPainter* painter); virtual void addDamage(int power); protected: QPointF m_spd; QPointF m_acc; int m_anm; int m_frameCount; }; #endif // TASKENEMYBULLET_H
[ "tomo@aspire.(none)" ]
[ [ [ 1, 22 ] ] ]
9cbf7208867037655b10947b241d65f5677576d1
822ab63b75d4d4e2925f97b9360a1b718b5321bc
/TDIH_new/GraphicsMenubar.cpp
f56c29aa674248d38b4c90740be7dff24e9a3625
[]
no_license
sriks/decii
71e4becff5c30e77da8f87a56383e02d48b78b28
02c58fbaea69c2448249710d13f2e774762da2c3
refs/heads/master
2020-05-17T23:03:27.822905
2011-12-16T07:29:38
2011-12-16T07:29:38
32,251,281
0
0
null
null
null
null
UTF-8
C++
false
false
3,641
cpp
#include <QPen> #include <QDebug> #include <QAction> #include <QTextDocument> #include <QTextOption> #include <QAbstractScrollArea> #include <QScrollBar> #include <QGraphicsPathItem> #include <QGraphicsBlurEffect> #include <QGraphicsLinearLayout> #include <QGraphicsView> #include "GraphicsMenubar.h" struct GraphicsMenubarPrivate { QGraphicsView* view; // non owning }; GraphicsMenubar::GraphicsMenubar(Qt::Orientation orientation,QGraphicsItem* parent) :KSegmentWidget(orientation,parent) { d = new GraphicsMenubarPrivate; this->setClickable(false); // Preparing default skin. QGraphicsPathItem* bkg = new QGraphicsPathItem(this); bkg->setOpacity(0.7); QColor bkgColor("#AAAAAA"); bkg->setBrush(QBrush(bkgColor)); bkg->setPen(QPen(Qt::NoPen)); QGraphicsBlurEffect* blur = new QGraphicsBlurEffect(this); blur->setBlurRadius(20); bkg->setGraphicsEffect(blur); this->setNormalBackground(bkg); } GraphicsMenubar::~GraphicsMenubar() { qDebug()<<__PRETTY_FUNCTION__; delete d; for(int i=0;i<actions().count();++i) { this->removeAction(actions().at(i)); } qDebug()<<__PRETTY_FUNCTION__<<" end"; } void GraphicsMenubar::setAlignment(QAbstractScrollArea* parentScrollArea,Qt::Alignment alignment) { qDebug()<<__PRETTY_FUNCTION__; Q_UNUSED(alignment); connect(parentScrollArea->verticalScrollBar(),SIGNAL(valueChanged(int)), this,SLOT(updatePosition())); connect(parentScrollArea->horizontalScrollBar(),SIGNAL(valueChanged(int)), this,SLOT(updatePosition())); d->view = scene()->views().at(0); updatePosition(); qDebug()<<__PRETTY_FUNCTION__<<" end"; } void GraphicsMenubar::updatePosition() { qDebug()<<__PRETTY_FUNCTION__; QPointF scrollBarScenePos = d->view->mapToScene(0,d->view->verticalScrollBar()->value()); int yPos = scrollBarScenePos.y() + (d->view->viewport()->height() - d->view->verticalScrollBar()->value()); yPos -= this->size().height(); // adjust so that menubar is visible. this->setPos(0,yPos); qDebug()<<__PRETTY_FUNCTION__<<" end"; } void GraphicsMenubar::addAction(QAction* action) { qDebug()<<__PRETTY_FUNCTION__; QGraphicsWidget::addAction(action); KSegmentWidget* menuItem = new KSegmentWidget(Qt::Vertical); menuItem->setObjectName(action->text()); int preferredWidth = 70; menuItem->setPreferredWidth(preferredWidth); menuItem->setSelectable(false); // if(!action->icon().isNull()) { // menuItem->addItem(new QGraphicsPixmapItem(action->icon().pixmap())); // menuItem->setPreferredWidth(action->icon().pixmap().width()); // preferredWidth = action->icon().pixmap().width(); // } if(!action->text().isEmpty()) { QGraphicsTextItem* menuItemText = new QGraphicsTextItem(action->text()); QTextDocument* doc = menuItemText->document(); doc->setTextWidth(preferredWidth-20); QFont f = doc->defaultFont(); f.setPixelSize(10); doc->setDefaultFont(f); // QTextOption textOpt = doc->defaultTextOption(); // textOpt.setAlignment(Qt::AlignCenter); // doc->setDefaultTextOption(textOpt); menuItemText->setDocument(doc); QGraphicsWidget* item = menuItem->addItem(menuItemText); menuItem->layout()->setAlignment(item,Qt::AlignRight); } connect(menuItem,SIGNAL(clicked(int,QPointF)),action,SIGNAL(triggered())); addItem(menuItem); layout()->setAlignment(menuItem,Qt::AlignCenter); } // eof
[ "srikanthsombhatla@016151e7-202e-141d-2e90-f2560e693586" ]
[ [ [ 1, 99 ] ] ]
777bdeba4d19463057980a517b8fb643cf2928cd
9f364d3df1bb587de60fc1184bcc5a0965271ee6
/shirt/src/Main.cpp
e9b22537deb0ac9ab4d78ccafb3b823d52e2433d
[]
no_license
kelvin-sudani/ros
6e9cda4c652ad15f18e03d5287be2c82bea68ca1
a5dd723ae5c7b7fc3a20ca3f84ed78c6c7a36bd5
refs/heads/master
2021-01-15T19:59:29.624196
2011-12-09T12:55:35
2011-12-09T12:55:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,417
cpp
// ShirtDetection v1.2: Find the approximate color type of a person's tshirt. by Shervin Emami ([email protected]), 30th Aug 2010. // If trying to debug the color detector code, enable SHOW_DEBUG_IMAGE: //#define SHOW_DEBUG_IMAGE #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers //#include <stdio.h> //#include <tchar.h> #include <cstdio> // Used for "printf" #include <string> // Used for C++ strings #include <iostream> // Used for C++ cout print statements //#include <cmath> // Used to calculate square-root for statistics // Include OpenCV libraries #include <cv.h> #include <cvaux.h> #include <cxcore.h> #include <highgui.h> #include "ImageUtils.h" // Used for easy image cropping, resizing, rotating, etc. #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <cv_bridge/CvBridge.h> #include "sensor_msgs/Image.h" #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> using namespace std; // Various color types for detected shirt colors. enum {cBLACK=0,cWHITE, cGREY, cRED, cORANGE, cYELLOW, cGREEN, cAQUA, cBLUE, cPURPLE, cPINK, NUM_COLOR_TYPES}; char* sCTypes[NUM_COLOR_TYPES] = {"Black", "White","Grey","Red","Orange","Yellow","Green","Aqua","Blue","Purple","Pink"}; uchar cCTHue[NUM_COLOR_TYPES] = {0, 0, 0, 0, 20, 30, 55, 85, 115, 138, 161}; uchar cCTSat[NUM_COLOR_TYPES] = {0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255}; uchar cCTVal[NUM_COLOR_TYPES] = {0, 255, 120, 255, 255, 255, 255, 255, 255, 255, 255}; // Face Detection HaarCascade Classifier file for OpenCV (downloadable from "http://alereimondo.no-ip.org/OpenCV/34"). const char* cascadeFileFace = "haarcascades/haarcascade_frontalface_alt.xml"; // Path to the Face Detection HaarCascade XML file // Perform face or nose or mouth feature detection on the input image, using the given Haar cascade classifier. // You can specify min detectable feature size, in case you are looking for small features like eyes. // Returns a list of rectangles for detected regions. // Remember to call "cvReleaseHaarClassifierCascade( &cascade );" later. vector<CvRect> findObjectsInImage(IplImage *origImg, CvHaarClassifierCascade* cascade, CvSize minFeatureSize = cvSize(20, 20)) { CvMemStorage* storage; vector<CvRect> detRects;// = new vector<CvRect>; storage = cvCreateMemStorage(0); cvClearMemStorage( storage ); // If the image is color, use a greyscale copy of the image. IplImage *detectImg = origImg; // Assume the input image is to be used. IplImage *greyImg = 0; if (origImg->nChannels > 1) { greyImg = cvCreateImage(cvSize(origImg->width, origImg->height), 8, 1 ); std::cout << "[Converting detectImg " << greyImg->width << "x" << greyImg->height << "]" << std::endl; printImageInfo(greyImg); cvCvtColor( origImg, greyImg, CV_BGR2GRAY ); std::cout << "Got greyscale img." << std::endl; detectImg = greyImg; // Use the greyscale version as the input. } // Enhance / Normalise the image contrast (optional) //cvEqualizeHist(detectImg, detectImg); double t = (double)cvGetTickCount(); CvSeq* rects = cvHaarDetectObjects( detectImg, cascade, storage, 1.1, 2, CV_HAAR_DO_CANNY_PRUNING, minFeatureSize ); // Minimum face size changed from "cvSize(30, 30)" t = (double)cvGetTickCount() - t; std::cout << "detection time = " << t/((double)cvGetTickFrequency()*1000.) << "ms\n"; // Get all the detected regions for(int i = 0; i < (rects ? rects->total : 0); i++ ) { CvRect *r = (CvRect*)cvGetSeqElem( rects, i ); detRects.push_back(*r); std::cout << "Found object at (" << r->x << ", " << r->y << ") of size (" << r->width << "x" << r->height << ").\n"; } std::cout << "Found " << detRects.size() << " objects." << std::endl; //cvReleaseHaarClassifierCascade( &cascade ); if (greyImg) cvReleaseImage( &greyImg ); cvReleaseMemStorage( &storage ); return detRects; } // Determine what type of color the HSV pixel is. Returns the colorType between 0 and NUM_COLOR_TYPES. int getPixelColorType(int H, int S, int V) { int color; if (V < 75) color = cBLACK; else if (V > 190 && S < 27) color = cWHITE; else if (S < 53 && V < 185) color = cGREY; else { // Is a color if (H < 14) color = cRED; else if (H < 25) color = cORANGE; else if (H < 34) color = cYELLOW; else if (H < 73) color = cGREEN; else if (H < 102) color = cAQUA; else if (H < 127) color = cBLUE; else if (H < 149) color = cPURPLE; else if (H < 175) color = cPINK; else // full circle color = cRED; // back to Red } return color; } namespace enc = sensor_msgs::image_encodings; class ImageEdge { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; public: ImageEdge() : it_(nh_) { image_pub_ = it_.advertise("image_edge", 1); image_sub_ = it_.subscribe("gscam/image_raw", 1, &ImageEdge::imageCb, this); cv::namedWindow("Image"); } ~ImageEdge() { cv::destroyWindow("Image"); } void imageCb(const sensor_msgs::ImageConstPtr& msg) { cv_bridge::CvImagePtr cv_ptr; sensor_msgs::CvBridge bridge; IplImage* imageIn; try { imageIn = bridge.imgMsgToCv(msg, enc::BGR8); } catch (sensor_msgs::CvBridgeException& e) { ROS_ERROR("CvBridge exception: %s", e.what()); return; } // Load the HaarCascade classifier for face detection. Added by Shervin on 22/9/09 cout << "Loading Face HaarCascade in '" << cascadeFileFace << "'" << endl; CvHaarClassifierCascade* cascadeFace = (CvHaarClassifierCascade*)cvLoad(cascadeFileFace, 0, 0, 0 ); if( !cascadeFace ) { cerr << "ERROR: Couldn't load face detector classifier in '" << cascadeFileFace << "'\n"; exit(1); } IplImage* imageDisplay = cvCloneImage(imageIn); // If trying to debug the color detector code, enable this: #ifdef SHOW_DEBUG_IMAGE // Create a HSV image showing the color types of the whole image, for debugging. IplImage *imageInHSV = cvCreateImage(cvGetSize(imageIn), 8, 3); cvCvtColor(imageIn, imageInHSV, CV_BGR2HSV); // (note that OpenCV stores RGB images in B,G,R order. IplImage* imageDisplayHSV = cvCreateImage(cvGetSize(imageIn), 8, 3); // Create an empty HSV image //cvSet(imageDisplayHSV, cvScalar(0,0,0, 0)); // Clear HSV image to blue. int hIn = imageDisplayHSV->height; int wIn = imageDisplayHSV->width; int rowSizeIn = imageDisplayHSV->widthStep; // Size of row in bytes, including extra padding char *imOfsDisp = imageDisplayHSV->imageData; // Pointer to the start of the image HSV pixels. char *imOfsIn = imageInHSV->imageData; // Pointer to the start of the input image HSV pixels. for (int y=0; y<hIn; y++) { for (int x=0; x<wIn; x++) { // Get the HSV pixel components uchar H = *(uchar*)(imOfsIn + y*rowSizeIn + x*3 + 0); // Hue uchar S = *(uchar*)(imOfsIn + y*rowSizeIn + x*3 + 1); // Saturation uchar V = *(uchar*)(imOfsIn + y*rowSizeIn + x*3 + 2); // Value (Brightness) // Determine what type of color the HSV pixel is. int ctype = getPixelColorType(H, S, V); //ctype = x / 60; // Show the color type on the displayed image, for debugging. *(uchar*)(imOfsDisp + (y)*rowSizeIn + (x)*3 + 0) = cCTHue[ctype]; // Hue *(uchar*)(imOfsDisp + (y)*rowSizeIn + (x)*3 + 1) = cCTSat[ctype]; // Full Saturation (except for black & white) *(uchar*)(imOfsDisp + (y)*rowSizeIn + (x)*3 + 2) = cCTVal[ctype]; // Full Brightness } } // Display the HSV debugging image IplImage *imageDisplayHSV_RGB = cvCreateImage(cvGetSize(imageDisplayHSV), 8, 3); cvCvtColor(imageDisplayHSV, imageDisplayHSV_RGB, CV_HSV2BGR); // (note that OpenCV stores RGB images in B,G,R order. cvNamedWindow("Colors", 1); cvShowImage("Colors", imageDisplayHSV_RGB); #endif // SHOW_DEBUG_IMAGE // First, search for all the frontal faces in the image CvRect foundFace = cvRect(0, 0, 0, 0); // Set init values if nothing was detected. vector<CvRect> rectFaces; double timeFaceDetectStart = (double)cvGetTickCount(); // Record the timing. rectFaces = findObjectsInImage(imageIn, cascadeFace); double tallyFaceDetectTime = (double)cvGetTickCount() - timeFaceDetectStart; cout << "Found " << rectFaces.size() << " faces in " << tallyFaceDetectTime/((double)cvGetTickFrequency()*1000.) << "ms\n"; // Process each detected face cout << "Detecting shirt colors below the faces." << endl; for (int r=0; r<rectFaces.size(); r++) { float initialConfidence = 1.0f; int bottom; CvRect rectFace = rectFaces[r]; drawRectangle(imageDisplay, rectFace, CV_RGB(255,0,0)); // Create the shirt region, to be below the detected face and of similar size. float SHIRT_DY = 1.4f; // Distance from top of face to top of shirt region, based on detected face height. float SHIRT_SCALE_X = 0.6f; // Width of shirt region compared to the detected face float SHIRT_SCALE_Y = 0.6f; // Height of shirt region compared to the detected face CvRect rectShirt; rectShirt.x = rectFace.x + (int)(0.5f * (1.0f-SHIRT_SCALE_X) * (float)rectFace.width); rectShirt.y = rectFace.y + (int)(SHIRT_DY * (float)rectFace.height) + (int)(0.5f * (1.0f-SHIRT_SCALE_Y) * (float)rectFace.height); rectShirt.width = (int)(SHIRT_SCALE_X * rectFace.width); rectShirt.height = (int)(SHIRT_SCALE_Y * rectFace.height); cout << "Shirt region is from " << rectShirt.x << ", " << rectShirt.y << " to " << rectShirt.x + rectShirt.width - 1 << ", " << rectShirt.y + rectShirt.height - 1 << endl; // If the shirt region goes partly below the image, try just a little below the face bottom = rectShirt.y+rectShirt.height-1; if (bottom > imageIn->height-1) { SHIRT_DY = 0.95f; // Distance from top of face to top of shirt region, based on detected face height. SHIRT_SCALE_Y = 0.3f; // Height of shirt region compared to the detected face // Use a higher shirt region rectShirt.y = rectFace.y + (int)(SHIRT_DY * (float)rectFace.height) + (int)(0.5f * (1.0f-SHIRT_SCALE_Y) * (float)rectFace.height); rectShirt.height = (int)(SHIRT_SCALE_Y * rectFace.height); initialConfidence = initialConfidence * 0.5f; // Since we are using a smaller region, we are less confident about the results now. cout << "Warning: Shirt region goes past the end of the image. Trying to reduce the shirt region position to " << rectShirt.y << " with a height of " << rectShirt.height << endl; } // Try once again if it is partly below the image. bottom = rectShirt.y+rectShirt.height-1; if (bottom > imageIn->height-1) { bottom = imageIn->height-1; // Limit the bottom rectShirt.height = bottom - (rectShirt.y-1); // Adjust the height to use the new bottom initialConfidence = initialConfidence * 0.7f; // Since we are using a smaller region, we are less confident about the results now. cout << "Warning: Shirt region still goes past the end of the image. Trying to reduce the shirt region height to " << rectShirt.height << endl; } // Make sure the shirt region is in the image if (rectShirt.height <= 1) { cout << "Warning: Shirt region is not in the image at all, so skipping this face." << endl; } else { // Show the shirt region drawRectangle(imageDisplay, rectShirt, CV_RGB(255,255,255)); // Convert the shirt region from RGB colors to HSV colors //cout << "Converting shirt region to HSV" << endl; IplImage *imageShirt = cropRectangle(imageIn, rectShirt); IplImage *imageShirtHSV = cvCreateImage(cvGetSize(imageShirt), 8, 3); cvCvtColor(imageShirt, imageShirtHSV, CV_BGR2HSV); // (note that OpenCV stores RGB images in B,G,R order. if( !imageShirtHSV ) { cerr << "ERROR: Couldn't convert Shirt image from BGR2HSV." << endl; exit(1); } //cout << "Determining color type of the shirt" << endl; int h = imageShirtHSV->height; // Pixel height int w = imageShirtHSV->width; // Pixel width int rowSize = imageShirtHSV->widthStep; // Size of row in bytes, including extra padding char *imOfs = imageShirtHSV->imageData; // Pointer to the start of the image HSV pixels. // Create an empty tally of pixel counts for each color type int tallyColors[NUM_COLOR_TYPES]; for (int i=0; i<NUM_COLOR_TYPES; i++) tallyColors[i] = 0; // Scan the shirt image to find the tally of pixel colors for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { // Get the HSV pixel components uchar H = *(uchar*)(imOfs + y*rowSize + x*3 + 0); // Hue uchar S = *(uchar*)(imOfs + y*rowSize + x*3 + 1); // Saturation uchar V = *(uchar*)(imOfs + y*rowSize + x*3 + 2); // Value (Brightness) // Determine what type of color the HSV pixel is. int ctype = getPixelColorType(H, S, V); // Keep count of these colors. tallyColors[ctype]++; } } // Print a report about color types, and find the max tally //cout << "Number of pixels found using each color type (out of " << (w*h) << ":\n"; int tallyMaxIndex = 0; int tallyMaxCount = -1; int pixels = w * h; for (int i=0; i<NUM_COLOR_TYPES; i++) { int v = tallyColors[i]; cout << sCTypes[i] << " " << (v*100/pixels) << "%, "; if (v > tallyMaxCount) { tallyMaxCount = tallyColors[i]; tallyMaxIndex = i; } } cout << endl; int percentage = initialConfidence * (tallyMaxCount * 100 / pixels); cout << "Color of shirt: " << sCTypes[tallyMaxIndex] << " (" << percentage << "% confidence)." << endl << endl; // Display the color type over the shirt in the image. CvFont font; //cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.55,0.7, 0,1,CV_AA); // For OpenCV 1.1 cvInitFont(&font,CV_FONT_HERSHEY_PLAIN,0.8,1.0, 0,1, CV_AA); // For OpenCV 2.0 char text[256]; sprintf(text, "%d%%", percentage); cvPutText(imageDisplay, sCTypes[tallyMaxIndex], cvPoint(rectShirt.x, rectShirt.y + rectShirt.height + 12), &font, CV_RGB(255,0,0)); cvPutText(imageDisplay, text, cvPoint(rectShirt.x, rectShirt.y + rectShirt.height + 24), &font, CV_RGB(255,0,0)); // Free resources. cvReleaseImage( &imageShirtHSV ); cvReleaseImage( &imageShirt ); }//end if valid height }//end for loop // Display the RGB debugging image cvNamedWindow("Shirt", 1); cvShowImage("Shirt", imageDisplay); // Pause cvWaitKey(3); // Close everything //cvDestroyWindow("Shirt"); // Free resources. cvReleaseHaarClassifierCascade( &cascadeFace ); cvReleaseImage(&imageDisplay); //cvReleaseImage(&imageIn); } }; // C/C++ entry point int main(int argc, char **argv) { cout << "Shirt Color Detection, by Shervin Emami, 7th Nov 2009." << endl; cout << "usage: ShirtDetection [image_file]" << endl; ros::init(argc, argv, "image_edge"); ImageEdge ic; ros::spin(); return 0; }
[ "[email protected]", "aghos7@straylight.(none)" ]
[ [ [ 1, 345 ], [ 347, 347 ], [ 349, 368 ] ], [ [ 346, 346 ], [ 348, 348 ] ] ]
16545f1d7df947a981dc1d5269e269c3a28e8329
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
/GameServer/MapGroupKernel/EventPack.h
a9f1b3c72b2008ced4d14b252e0231f9438b1609
[]
no_license
cronoszeu/revresyksgpr
78fa60d375718ef789042c452cca1c77c8fa098e
5a8f637e78f7d9e3e52acdd7abee63404de27e78
refs/heads/master
2020-04-16T17:33:10.793895
2010-06-16T12:52:45
2010-06-16T12:52:45
35,539,807
0
2
null
null
null
null
UTF-8
C++
false
false
1,145
h
#pragma once #include "SharedBaseFunc.h" const int EVENTPACK_SIZE = 1024 + 2*sizeof(USHORT) + sizeof(ULONG); class CEventPack { public: CEventPack(DWORD idEvent, ULONG idKey, DWORD idAction=0); CEventPack(const char* pPackBuf, int nPackSize); virtual ~CEventPack(); public: // appilcation CEventPack& operator <<(const int nData); CEventPack& operator <<(const String& str); CEventPack& operator >>(int& nData); CEventPack& operator >>(String& str); public: // const int GetEventType() const { return m_idEventType; } ULONG GetObjID() const { return m_idKey; } int GetAction() const { return m_idAction; } const char* GetBuf() const { return m_buf; } int GetSize() const { return m_ptr - m_buf; } protected: union{ char m_buf[EVENTPACK_SIZE]; struct{ USHORT m_idEventType; USHORT m_idAction; ULONG m_idKey; char m_setParam[1]; }; }; protected: // ctrl bool IsUnite() { return !m_bSplit; } bool IsSplit() { return m_bSplit; } bool CheckLen(int nSize) { return m_ptr+nSize <= m_setParam; } protected: bool m_bSplit; char* m_ptr; };
[ "rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1" ]
[ [ [ 1, 49 ] ] ]
c80d5a94eb4f25a2c939570a7a546ba4a9ec6be7
3ec3b97044e4e6a87125470cfa7eef535f26e376
/entheh-elemental_sun/main.cpp
57b18248becb89dfa26965c14bea4a33bedefc3d
[]
no_license
strategist922/TINS-Is-not-speedhack-2010
6d7a43ebb9ab3b24208b3a22cbcbb7452dae48af
718b9d037606f0dbd9eb6c0b0e021eeb38c011f9
refs/heads/master
2021-01-18T14:14:38.724957
2010-10-17T14:04:40
2010-10-17T14:04:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,923
cpp
#include "elemsun.h" #include "datafile.h" #include <aldumb.h> #include <jpgalleg.h> static int white; static int black; static int darkGrey; static int darkGreen; static int lightGreen; static int green; static int buttonFillColour; static int buttonFillHighlight; static int darkRed; static int lightRed; static int red; static int darkYellow; static void setColours() { white=makecol(255,255,255); black=makecol(0,0,0); darkGrey=makecol(85,85,85); darkGreen=makecol(60,160,100); lightGreen=makecol(96,255,160); green=makecol(85,255,85); buttonFillColour=makecol(60,90,140); buttonFillHighlight=makecol(140,170,220); darkRed=makecol(160,90,70); lightRed=makecol(255,144,112); red=makecol(192,0,0); darkYellow=makecol(128,128,0); } #define MOUSE_REPEAT_INITIAL 30 #define MOUSE_REPEAT_SUBSEQUENT 4 #define MAP_DRAW_XBASE 80 #define MAP_DRAW_YBASE 80 #define MAP_DRAW_XSTEP 32 #define MAP_DRAW_YSTEP 32 #define LEVEL_LEFT 480 #define LEVEL_RIGHT 624 #define LEVEL_TOP 16 #define LEVEL_BOTTOM 40 #define LEVEL_BUTTON_W 24 #define COLOUR_DRAW_X 480 #define COLOUR_DRAW_YBASE (48-COLOUR_DRAW_YSTEP) #define COLOUR_DRAW_YSTEP 32 #define BEHAVIOUR_DRAW_LEFT 480 #define BEHAVIOUR_DRAW_RIGHT 624 #define BEHAVIOUR_DRAW_TOP (COLOUR_DRAW_YBASE+COLOUR_DRAW_YSTEP*MAX_COLOURS+4) #define BEHAVIOUR_DRAW_BOTTOM (BEHAVIOUR_DRAW_TOP+4+MAX_BEHAVIOURS*BEHAVIOUR_DRAW_YSTEP+4) #define BEHAVIOUR_DRAW_X 484 #define BEHAVIOUR_DRAW_YBASE (BEHAVIOUR_DRAW_TOP+4) #define BEHAVIOUR_DRAW_YSTEP 15 #define STATS_DRAW_LEFT 480 #define STATS_DRAW_RIGHT 624 #define STATS_DRAW_Y (BEHAVIOUR_DRAW_BOTTOM+4) #define GO_DRAW_LEFT 480 #define GO_DRAW_LEFTRIGHT 548 #define GO_DRAW_RIGHTLEFT 556 #define GO_DRAW_RIGHT 624 #define GO_DRAW_TOP (STATS_DRAW_Y+LINE_SPACING*2+4) #define GO_DRAW_BOTTOM 464 #define OPTIONS_BUTTON_LEFT 400 #define OPTIONS_BUTTON_RIGHT 464 #define OPTIONS_BUTTON_TOP 440 #define OPTIONS_BUTTON_BOTTOM 464 #define OPTIONS_MENU_LEFT 336 #define OPTIONS_MENU_RIGHT 464 #define OPTIONS_SLIDER_LEFT 394 #define OPTIONS_SLIDER_W 46 #define OPTION_H 24 #define OPTION_INSTRUCTIONS 0 #define OPTION_SOUND 1 #define OPTION_MUSIC 2 #define OPTION_SWITCH_MODE 3 #define OPTION_ABOUT 4 #define OPTION_EXIT 5 #define NUM_OPTIONS 6 char optionText[NUM_OPTIONS][64]={ "Instructions", "Sound -----|", "Music -----|", "Switch mode", "About", "Exit", }; #define LINE_SPACING 15 #define CYCLE_TIME 30 #define SMOKE_FRAME_TIME 4 #define SMOKE_NUM_FRAMES 4 struct DraggableBehaviour { Behaviour *behaviour; int colour; int currentX,currentY; int destX,destY; int codeW,codeH; bool lastHover; }; static int logicTime=0; static volatile int trueTime=0; static int lastPingTime=-1; static volatile bool wantQuit=false; static DATAFILE *dat; static BITMAP *scrbuf; static AL_DUH_PLAYER *adp; #if MAX_COLOURS!=8 #error Oops! #endif static const int numSides[MAX_COLOURS]={0,1,2,3,4,5,8,12}; static int level; static int levelReached=0; unsigned char oldMap[MAP_H][MAP_W]; unsigned char newMap[MAP_H][MAP_W]; unsigned char smokeMap[MAP_H][MAP_W]; static DraggableBehaviour allBehaviours[MAX_BEHAVIOURS]; static DraggableBehaviour *assignedBehaviours[MAX_COLOURS]; static DraggableBehaviour *currentDrag; static int currentDragOption; static int mx,my; static int currentDragX,currentDragY; static int lastMb; static int mouseRepeatCounter; static int levelTime; static int heat; static int cycles; static bool success; static bool showOptions; static int numOptionsShown; static bool showInstructions; static bool showAbout; static int soundVolume=5,musicVolume=5; static bool windowed=true; static void timerProc() { trueTime++; } END_OF_STATIC_FUNCTION(timerProc); static void closeProc() { wantQuit=true; } static void calculateBehaviourPositions() { //Put the assigned ones first, next to their colours for (int i=1; i<MAX_COLOURS; i++) { if (assignedBehaviours[i]!=NULL) { assignedBehaviours[i]->destX=COLOUR_DRAW_X+40; assignedBehaviours[i]->destY=COLOUR_DRAW_YBASE+i*COLOUR_DRAW_YSTEP+COLOUR_DRAW_YSTEP/2-text_height(font)/2; } } //Put the remaining ones in a section below int y=BEHAVIOUR_DRAW_YBASE; for (int i=0; i<MAX_BEHAVIOURS; i++) { if (allBehaviours[i].behaviour==NULL) break; if (allBehaviours[i].colour==-1) { allBehaviours[i].destX=BEHAVIOUR_DRAW_X; allBehaviours[i].destY=y; y+=BEHAVIOUR_DRAW_YSTEP; } } } static void resetLevel() { memcpy(oldMap,levels[level].map,sizeof(oldMap)); memcpy(newMap,levels[level].map,sizeof(newMap)); heat=0; cycles=0; levelTime=-1; success=false; } static void setColour(DraggableBehaviour *b, int c) { //Unassign this behaviour its old colour if (b->colour>=0) assignedBehaviours[b->colour]=NULL; //If any behaviour already has the new colour, give it our old colour if (c>=0 && assignedBehaviours[c]!=NULL) setColour(assignedBehaviours[c],b->colour); //Assign this behaviour the new colour b->colour=c; if (b->colour>=0) assignedBehaviours[b->colour]=b; } static void startLevel(int _level) { level=_level; resetLevel(); for (int i=0; i<MAX_BEHAVIOURS; i++) { allBehaviours[i].behaviour=levels[level].behaviours[i]; allBehaviours[i].colour=-1; } for (int i=1; i<MAX_COLOURS; i++) assignedBehaviours[i]=NULL; //Memory! for (int i=0; i<MAX_BEHAVIOURS; i++) { int c=levels[level].behaviourColours[i]; if (c>0 && c<MAX_COLOURS) setColour(&allBehaviours[i],c); } calculateBehaviourPositions(); for (int i=0; i<MAX_BEHAVIOURS; i++) { if (allBehaviours[i].behaviour==NULL) break; allBehaviours[i].currentX=allBehaviours[i].destX; allBehaviours[i].currentY=allBehaviours[i].destY; allBehaviours[i].codeW=0; allBehaviours[i].codeH=0; allBehaviours[i].lastHover=false; } currentDrag=NULL; currentDragOption=-1; } static void init() { scrbuf=create_bitmap(640,480); font=(FONT *)dat[THE_FONT].dat; startLevel(0); int pos=mouse_pos; mx=pos>>16; my=pos&65535; lastMb=-1; mouseRepeatCounter=-1; showOptions=false; showInstructions=true; showAbout=false; numOptionsShown=0; } static void shutDown() { destroy_bitmap(scrbuf); } static int getDropTarget(int mx, int my) { if (mx>=COLOUR_DRAW_X && my>=COLOUR_DRAW_YBASE) { int c=(my-COLOUR_DRAW_YBASE)/COLOUR_DRAW_YSTEP; if (c>=1 && c<MAX_COLOURS) return c; } if (mx>=BEHAVIOUR_DRAW_LEFT && mx<BEHAVIOUR_DRAW_RIGHT && my>=BEHAVIOUR_DRAW_TOP && my<BEHAVIOUR_DRAW_BOTTOM) { return -1; } if (mx>=MAP_DRAW_XBASE && my>=MAP_DRAW_YBASE) { int x=(mx-MAP_DRAW_XBASE)/MAP_DRAW_XSTEP; int y=(my-MAP_DRAW_YBASE)/MAP_DRAW_YSTEP; if (x<MAP_W && y<MAP_H && newMap[y][x]!=0) return newMap[y][x]; } return -2; } static void rect2(BITMAP *bmp, int x1, int y1, int x2, int y2, int c) { hline(bmp,x1-2,y1,x2+3,c); hline(bmp,x1-2,y2,x2+1,c); vline(bmp,x1,y1-2,y2+1,c); vline(bmp,x2,y1-3,y2+2,c); } static void rectfill2(BITMAP *bmp, int x1, int y1, int x2, int y2, int c) { drawing_mode(DRAW_MODE_TRANS,NULL,0,0); set_trans_blender(0,0,0,216); rectfill(bmp,x1,y1,x2,y2,c); solid_mode(); } static void drawButton(int left, int right, int top, int bottom, const char *text, int customFillHighlight, int lightColour, bool enabled, int optionNumber=-2) { int fillColour,textColour; if (!enabled) { fillColour=buttonFillColour; textColour=buttonFillHighlight; } else if (currentDragOption==optionNumber || (currentDrag==NULL && currentDragOption==-1 && mx>=left && mx<right && my>=top && my<bottom)) { fillColour=customFillHighlight; textColour=white; } else { fillColour=buttonFillColour; textColour=lightColour; } rect2(scrbuf,left,top,right-1,bottom-1,black); rectfill2(scrbuf,left+1,top+1,right-2,bottom-2,fillColour); textout_centre_ex(scrbuf,font,text,(left+right)/2,(top+bottom)/2-text_height(font)/2,textColour,-1); } static void drawInstructions() { rect2(scrbuf,32,16,447,431,black); rectfill2(scrbuf,33,17,446,430,white); int x=240,y=22; textout_centre_ex(scrbuf,font,"Elemental Sun",x,y,darkYellow,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"Welcome to Your eternal life as a Sun God.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"The Sun contains various chemical elements.",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"Your job is to define the properties of each element.",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"Do this by dragging the available functions on to them.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"If You are successful, the sun will generate heat",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"and provide life for everyone on Earth.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"The sun operates in cycles. During each cycle,",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"all the functions are run on all the elements.",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"Then each element emits heat, and the heat is",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"collected and added to Your total.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"An element's value in heat is equal to",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"the number of sides its drawing has.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"If two functions write to the same square,",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"the square will be occupied by the less valuable element.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"All elements are unstable until You decree otherwise.",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"If an element is not refreshed, it decays to nothing.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"Best of luck with this valuable work.",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"We are certain trillions of life-forms are in good hands.",x,y,black,-1); y+=LINE_SPACING; } static void drawAbout() { rect2(scrbuf,32,16,447,431,black); rectfill2(scrbuf,33,17,446,430,white); int x=240,y=22; textout_centre_ex(scrbuf,font,"Elemental Sun",x,y,darkYellow,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"Copyright (C) 2010 Ben 'ent-\"Bruce `Wants a cool name",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"like Chris Barry or Steve Terry` Perry\"-heh*' Davis",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"*The 'th' is hardly pronounced anyway.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"Written in 59 hours for TINS 2010.",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"~~ tins.amarillion.org/2010 ~~",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"It's a 72-hour game programming competition.",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"I spent the other 14 hours sleeping.",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"That's not much sleep. I hope I didn't make an mistakes.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"Please feel free to distribute unmodified",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"copies of this game free of charge.",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"Make sure you include the source code.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"Developed using Allegro 4.4.0.1,",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"JPGAlleg 2.6 and DUMB v0.9.3.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"If you look closely, this game features many sheep.",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"They can most clearly be seen in the final line",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"of the instructions.",x,y,black,-1); y+=LINE_SPACING; y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"Special thanks to Amarillion for organising",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"the competition, and for allowing me to compete",x,y,black,-1); y+=LINE_SPACING; textout_centre_ex(scrbuf,font,"even after my entry 'Aliens on Fire' last time.",x,y,black,-1); y+=LINE_SPACING; } static void drawStatusMessage(const char *message) { rect2(scrbuf,160,MAP_DRAW_YBASE+MAP_H*MAP_DRAW_YSTEP+4,319,MAP_DRAW_YBASE+MAP_H*MAP_DRAW_YSTEP+27,black); rectfill2(scrbuf,161,MAP_DRAW_YBASE+MAP_H*MAP_DRAW_YSTEP+5,318,MAP_DRAW_YBASE+MAP_H*MAP_DRAW_YSTEP+26,white); textout_centre_ex(scrbuf,font,message,240,MAP_DRAW_YBASE+MAP_H*MAP_DRAW_YSTEP+16-text_height(font)/2,red,-1); } static void draw() { blit((BITMAP *)dat[BACKGROUND].dat,scrbuf,0,0,0,0,640,480); int dropTarget=-2; if (currentDrag!=NULL && currentDragOption==-1) dropTarget=getDropTarget(mx,my); //Draw the map for (int y=0; y<MAP_H; y++) { for (int x=0; x<MAP_W; x++) { int xs=MAP_DRAW_XBASE+x*MAP_DRAW_XSTEP; int ys=MAP_DRAW_YBASE+y*MAP_DRAW_YSTEP; int c=newMap[y][x]; if (c>=1) { BITMAP *sprite=(BITMAP *)dat[SPRITES_000-1+c].dat; if (c==dropTarget) { set_trans_blender(0,0,0,0); draw_lit_sprite(scrbuf,sprite,xs,ys,48); } else draw_sprite(scrbuf,sprite,xs,ys); } if (levelTime>=1 && smokeMap[y][x]!=0) { int frame=((levelTime-1)%CYCLE_TIME)/SMOKE_FRAME_TIME; if (frame<SMOKE_NUM_FRAMES) { BITMAP *smoke=(BITMAP *)dat[SMOKE_000+frame].dat; draw_sprite(scrbuf,smoke,xs,ys); } } } } //Draw the colours down the side, for behaviours to be assigned to for (int c=1; c<MAX_COLOURS; c++) { int xs=COLOUR_DRAW_X; int ys=COLOUR_DRAW_YBASE+c*COLOUR_DRAW_YSTEP; BITMAP *sprite=(BITMAP *)dat[SPRITES_000-1+c].dat; if (c==dropTarget) { set_trans_blender(0,0,0,0); draw_lit_sprite(scrbuf,sprite,xs,ys,48); } else draw_sprite(scrbuf,sprite,xs,ys); } //Draw the box for unassigned behaviours rect2(scrbuf,BEHAVIOUR_DRAW_LEFT,BEHAVIOUR_DRAW_TOP,BEHAVIOUR_DRAW_RIGHT-1,BEHAVIOUR_DRAW_BOTTOM-1,black); //Draw the stats if (levelTime<0) { textprintf_centre_ex(scrbuf,font,(STATS_DRAW_LEFT+STATS_DRAW_RIGHT)/2,STATS_DRAW_Y,black,-1,"Get %d heat",levels[level].targetHeat); textprintf_centre_ex(scrbuf,font,(STATS_DRAW_LEFT+STATS_DRAW_RIGHT)/2,STATS_DRAW_Y+LINE_SPACING,black,-1,"in %d %s!",levels[level].targetCycles,levels[level].targetCycles==1?"cycle":"cycles"); } else { textout_ex(scrbuf,font,"Heat:",STATS_DRAW_LEFT,STATS_DRAW_Y,black,-1); textprintf_right_ex(scrbuf,font,STATS_DRAW_RIGHT,STATS_DRAW_Y,black,-1,"%d/%d",heat,levels[level].targetHeat); textout_ex(scrbuf,font,"Cycle:",STATS_DRAW_LEFT,STATS_DRAW_Y+LINE_SPACING,black,-1); textprintf_right_ex(scrbuf,font,STATS_DRAW_RIGHT,STATS_DRAW_Y+LINE_SPACING,black,-1,"%d/%d",cycles,levels[level].targetCycles); } //Draw the level indicator and buttons drawButton(LEVEL_LEFT,LEVEL_LEFT+LEVEL_BUTTON_W,LEVEL_TOP,LEVEL_BOTTOM,"<",buttonFillHighlight,white,level>0); drawButton(LEVEL_RIGHT-LEVEL_BUTTON_W,LEVEL_RIGHT,LEVEL_TOP,LEVEL_BOTTOM,">",buttonFillHighlight,white,level<levelReached); textprintf_centre_ex(scrbuf,font,(LEVEL_LEFT+LEVEL_RIGHT)/2,(LEVEL_TOP+LEVEL_BOTTOM)/2-text_height(font)/2,black,-1,"Level %d/%d",level+1,numLevels); //Draw the 'go' or 'stop' button if (showInstructions || showAbout) drawButton(GO_DRAW_LEFT,GO_DRAW_RIGHT,GO_DRAW_TOP,GO_DRAW_BOTTOM,"OK",buttonFillHighlight,white,true); else if (levelTime<0) drawButton(GO_DRAW_LEFT,GO_DRAW_RIGHT,GO_DRAW_TOP,GO_DRAW_BOTTOM,"GO!",darkGreen,lightGreen,true); else if (success) { if (level<levelReached) { drawButton(GO_DRAW_LEFT,GO_DRAW_LEFTRIGHT,GO_DRAW_TOP,GO_DRAW_BOTTOM,"Redo",darkRed,lightRed,true); drawButton(GO_DRAW_RIGHTLEFT,GO_DRAW_RIGHT,GO_DRAW_TOP,GO_DRAW_BOTTOM,"Next",darkGreen,lightGreen,true); } else drawButton(GO_DRAW_LEFT,GO_DRAW_RIGHT,GO_DRAW_TOP,GO_DRAW_BOTTOM,"Redo",darkRed,lightRed,true); } else if (cycles>=levels[level].targetCycles) { drawButton(GO_DRAW_LEFT,GO_DRAW_RIGHT,GO_DRAW_TOP,GO_DRAW_BOTTOM,"Retry",darkRed,lightRed,true); } else drawButton(GO_DRAW_LEFT,GO_DRAW_RIGHT,GO_DRAW_TOP,GO_DRAW_BOTTOM,"Stop",darkRed,lightRed,true); //Draw the options button drawButton(OPTIONS_BUTTON_LEFT,OPTIONS_BUTTON_RIGHT,OPTIONS_BUTTON_TOP,OPTIONS_BUTTON_BOTTOM,"Options",buttonFillHighlight,white,true); //Draw the status message if (success) { if (level<levelReached) drawStatusMessage("TARGET ACHIEVED"); else drawStatusMessage("GAME COMPLETE"); } else if (cycles>=levels[level].targetCycles) drawStatusMessage("TARGET MISSED"); //Draw the available behaviours for (int i=0; i<MAX_BEHAVIOURS; i++) { Behaviour *b=allBehaviours[i].behaviour; if (b!=NULL) { int x=allBehaviours[i].currentX, y=allBehaviours[i].currentY; textout_ex(scrbuf,font,b->name,x,y,black,-1); } } //If options are enabled, draw them for (int i=0; i<=5; i++) optionText[OPTION_SOUND][6+i]=(soundVolume==i?'|':'-'); for (int i=0; i<=5; i++) optionText[OPTION_MUSIC][6+i]=(musicVolume==i?'|':'-'); strcpy(optionText[OPTION_SWITCH_MODE],windowed?"Go full screen":"Go windowed"); int y=OPTIONS_BUTTON_TOP-OPTION_H*numOptionsShown; for (int i=NUM_OPTIONS-numOptionsShown; i<NUM_OPTIONS; i++) { drawButton(OPTIONS_MENU_LEFT,OPTIONS_MENU_RIGHT,y,y+OPTION_H,optionText[i],buttonFillHighlight,white,true,i); y+=OPTION_H; } //If other screens are enabled, draw them if (showInstructions) drawInstructions(); if (showAbout) drawAbout(); //Draw the code popups for (int i=0; i<MAX_BEHAVIOURS; i++) { Behaviour *b=allBehaviours[i].behaviour; if (b!=NULL) { int codeW=allBehaviours[i].codeW, codeH=allBehaviours[i].codeH; if (codeW>0 && codeH>0) { //Calculate where to draw the code int xcode=allBehaviours[i].currentX-8-codeW, ycode=allBehaviours[i].currentY; if (ycode+codeH>476) ycode=476-codeH; rect2(scrbuf,xcode,ycode,xcode+codeW-1,ycode+codeH-1,black); if (codeW>2 && codeH>2) { rectfill2(scrbuf,xcode+1,ycode+1,xcode+codeW-2,ycode+codeH-2,darkGrey); set_clip_rect(scrbuf,xcode+4,ycode+4,xcode+codeW-5,ycode+codeH-5); for (int l=0; l<b->numSourceLines; l++) { textout_ex(scrbuf,font,b->sourceLines[l],xcode+4,ycode+4+l*LINE_SPACING,green,-1); } set_clip_rect(scrbuf,0,0,scrbuf->w-1,scrbuf->h-1); } } } } //Draw the mouse pointer draw_sprite(scrbuf,(BITMAP *)dat[POINTER].dat,mx,my); acquire_screen(); blit(scrbuf,screen,0,0,0,0,640,480); release_screen(); } static void updateLevelMemory() { //Memory! for (int i=0; i<MAX_BEHAVIOURS; i++) { levels[level].behaviourColours[i]=allBehaviours[i].colour; } } static void playPing() { if (logicTime>lastPingTime) { play_sample((SAMPLE *)dat[SFX_PING].dat,64*soundVolume/5,128,1000,false); lastPingTime=logicTime; } } static void switchMode(bool alreadyReverting) { al_pause_duh(adp); windowed=!windowed; int gfxMode=(windowed?GFX_AUTODETECT_WINDOWED:GFX_AUTODETECT_FULLSCREEN); if (set_gfx_mode(gfxMode,640,480,0,0)!=0) { if (alreadyReverting) { set_gfx_mode(GFX_TEXT,0,0,0,0); allegro_message("Unable to revert to previous mode (windowed/full screen)"); exit(EXIT_FAILURE); } else switchMode(true); } //Try both modes. Hopefully bloody Windows will succeed for at least one of them! set_display_switch_mode(SWITCH_BACKGROUND); set_display_switch_mode(SWITCH_BACKAMNESIA); logicTime=trueTime; al_resume_duh(adp); } static void update() { int mb=mouse_b; int pos=mouse_pos; mx=pos>>16; my=pos&65535; bool showOkButton=(showInstructions || showAbout); if (showOkButton && mb!=0 && lastMb==0) {playPing(); showInstructions=showAbout=false;} calculateBehaviourPositions(); for (int i=0; i<MAX_BEHAVIOURS; i++) { DraggableBehaviour *b=&allBehaviours[i]; if (b->behaviour==NULL) break; if (mb!=0 && currentDrag==NULL && currentDragOption==-1 && levelTime<0) { if (mx>=b->currentX && mx<b->currentX+text_length(font,b->behaviour->name) && my>=b->currentY && my<b->currentY+text_height(font)) { playPing(); currentDrag=b; currentDragX=mx-b->currentX; currentDragY=my-b->currentY; } } if (currentDrag==b) { if (mb!=0) { b->currentX=mx-currentDragX; b->currentY=my-currentDragY; } else { //Work out where it has been dropped, and set or clear its colour accordingly int c=getDropTarget(mx,my); if (c!=-2) {playPing(); setColour(b,c); updateLevelMemory();} currentDrag=NULL; calculateBehaviourPositions(); } } if (currentDrag!=b) { b->currentX=b->destX+(b->currentX-b->destX)*3/4; b->currentY=b->destY+(b->currentY-b->destY)*3/4; } //Is the mouse over this behaviour? int x=b->currentX, y=b->currentY; int destW=0,destH=0; bool hover=false; if ((currentDrag==NULL && currentDragOption==-1) || currentDrag==b) { if (mx>=x && mx<x+text_length(font,b->behaviour->name) && my>=y && my<y+text_height(font)) { //Get the longest line length in the code int maxLen=0; for (int l=0; l<b->behaviour->numSourceLines; l++) { int len=text_length(font,b->behaviour->sourceLines[l]); if (len>maxLen) maxLen=len; } //Calculate the destination code view size destW=maxLen+8; destH=b->behaviour->numSourceLines*LINE_SPACING+8; hover=true; } } if (hover && !b->lastHover) { int pan=32+(b->currentX-8-destW/2)*192/640; if (pan<0) pan=0; play_sample((SAMPLE *)dat[SFX_WSHH].dat,32*soundVolume/5,pan,1000,false); } if (!hover && b->lastHover) { int pan=32+(b->currentX-8-b->codeW/2)*192/640; if (pan<0) pan=0; play_sample((SAMPLE *)dat[SFX_SHHW].dat,32*soundVolume/5,pan,1000,false); } b->lastHover=hover; //Scale the code window b->codeW=destW+(b->codeW-destW)*3/4; b->codeH=destH+(b->codeH-destH)*3/4; } if (!showOkButton && mb!=0 && lastMb==0 && mx>=GO_DRAW_LEFT && mx<GO_DRAW_RIGHT && my>=GO_DRAW_TOP && my<GO_DRAW_BOTTOM) { if (levelTime<0) { //GO! playPing(); levelTime=0; } else if (success && level<levelReached) { //Redo if (mx<GO_DRAW_LEFTRIGHT) {playPing(); resetLevel();} //Next if (mx>=GO_DRAW_RIGHTLEFT) {playPing(); startLevel(level+1);} } else { //Stop/Retry playPing(); resetLevel(); } } if (mb!=0 && lastMb==0 && mx>=OPTIONS_BUTTON_LEFT && mx<OPTIONS_BUTTON_RIGHT && my>=OPTIONS_BUTTON_TOP && my<OPTIONS_BUTTON_BOTTOM) { playPing(); showOptions=!showOptions; lastMb=mb; } if (showOptions && numOptionsShown<NUM_OPTIONS) numOptionsShown++; if (!showOptions && numOptionsShown>0) numOptionsShown--; if (showOptions) { bool justClicked=false; if (mx>=OPTIONS_MENU_LEFT && mx<OPTIONS_MENU_RIGHT && my>=OPTIONS_BUTTON_TOP-OPTION_H*NUM_OPTIONS && my<OPTIONS_BUTTON_TOP) { int option=(my-(OPTIONS_BUTTON_TOP-OPTION_H*NUM_OPTIONS))/OPTION_H; if (option==OPTION_INSTRUCTIONS && mb!=0 && lastMb==0) {playPing(); showOptions=false; showInstructions=true;} if ((option==OPTION_SOUND || option==OPTION_MUSIC) && mb!=0 && currentDragOption==-1) {currentDragOption=option; justClicked=true;} if (option==OPTION_SWITCH_MODE && mb!=0 && lastMb==0) {playPing(); switchMode(false);} if (option==OPTION_ABOUT && mb!=0 && lastMb==0) {playPing(); showOptions=false; showAbout=true;} if (option==OPTION_EXIT && mb!=0 && lastMb==0) {playPing(); showOptions=false; wantQuit=true;} } else if (mb!=0 && lastMb==0) {playPing(); showOptions=false;} int sliderPos=(mx-OPTIONS_SLIDER_LEFT)*5/OPTIONS_SLIDER_W; if (sliderPos<0) sliderPos=0; if (sliderPos>5) sliderPos=5; if (currentDragOption==OPTION_SOUND && sliderPos!=soundVolume) {soundVolume=sliderPos; playPing();} if (currentDragOption==OPTION_MUSIC) musicVolume=sliderPos; if (justClicked) playPing(); } if (mb==0) currentDragOption=-1; if (mb!=0 && (lastMb==0 || mouseRepeatCounter==0)) { if (mx>=LEVEL_LEFT && mx<LEVEL_LEFT+LEVEL_BUTTON_W && my>=LEVEL_TOP && my<LEVEL_BOTTOM) { if (level>0) {playPing(); startLevel(level-1);} if (mouseRepeatCounter<0) mouseRepeatCounter=MOUSE_REPEAT_INITIAL; else mouseRepeatCounter=MOUSE_REPEAT_SUBSEQUENT; } else if (mx>=LEVEL_RIGHT-LEVEL_BUTTON_W && mx<LEVEL_RIGHT && my>=LEVEL_TOP && my<LEVEL_BOTTOM) { if (level<levelReached) {playPing(); startLevel(level+1);} if (mouseRepeatCounter<0) mouseRepeatCounter=MOUSE_REPEAT_INITIAL; else mouseRepeatCounter=MOUSE_REPEAT_SUBSEQUENT; } } if (mouseRepeatCounter>0) mouseRepeatCounter--; if (mb==0 || currentDrag!=NULL || currentDragOption!=-1) mouseRepeatCounter=-1; lastMb=mb; if (levelTime>=0) { if (levelTime%CYCLE_TIME==0) { memcpy(oldMap,newMap,sizeof(newMap)); memset(newMap,255,sizeof(newMap)); memset(smokeMap,0,sizeof(smokeMap)); for (int y=0; y<MAP_H; y++) { for (int x=0; x<MAP_W; x++) { DraggableBehaviour *b=assignedBehaviours[oldMap[y][x]]; if (b!=NULL) b->behaviour->animate(x,y); } } int smokeCount=0, smokePan=0; for (int y=0; y<MAP_H; y++) { for (int x=0; x<MAP_W; x++) { if (newMap[y][x]==255) { newMap[y][x]=0; if (oldMap[y][x]!=0) smokeMap[y][x]=1; } if (cycles<levels[level].targetCycles) heat+=numSides[newMap[y][x]]; smokeCount+=smokeMap[y][x]; smokePan+=smokeMap[y][x]*x; } } if (smokeCount>0) { smokePan=32+smokePan*192/((MAP_W-1)*smokeCount); int smokeVol=(int)(sqrt(smokeCount)*16); if (smokeVol>64) smokeVol=64; play_sample((SAMPLE *)dat[SFX_POW].dat,smokeVol*soundVolume/5,smokePan,1000,false); } if (cycles<levels[level].targetCycles) { if (smokeCount==0) playPing(); cycles++; } if (!success && cycles<=levels[level].targetCycles && heat>=levels[level].targetHeat) { playPing(); success=true; if (levelReached==level && levelReached<numLevels-1) levelReached++; } } levelTime++; } } static void handleKey(int k) { if (k>>8==KEY_ESC) { //'Esc' closes the currently open popup if any, or else stops the level if (showInstructions) {playPing(); showInstructions=false;} else if (showAbout) {playPing(); showAbout=false;} else if (showOptions) {playPing(); showOptions=false;} else if (levelTime>=0) {playPing(); resetLevel();} //When in full screen, 'Esc' is also an emergency 'go windowed' key else if (!windowed) switchMode(false); } } int main() { LOCK_VARIABLE(trueTime); LOCK_FUNCTION(timerProc); set_config_file("elemsun.ini"); allegro_init(); set_window_title("Elemental Sun"); set_close_button_callback(closeProc); windowed=get_config_int("elemsun","windowed",windowed); soundVolume=get_config_int("elemsun","sound",soundVolume); musicVolume=get_config_int("elemsun","music",musicVolume); levelReached=get_config_int("elemsun","level",levelReached); soundVolume=MID(0,soundVolume,5); musicVolume=MID(0,musicVolume,5); levelReached=MID(0,levelReached,numLevels-1); jpgalleg_init(); atexit(&dumb_exit); install_timer(); install_keyboard(); install_mouse(); reserve_voices(64,-1); set_volume_per_voice(0); install_sound(DIGI_AUTODETECT,MIDI_NONE,NULL); dumb_register_dat_it_quick(DUMB_DAT_IT); readSource(); int gfxMode=(windowed?GFX_AUTODETECT_WINDOWED:GFX_AUTODETECT_FULLSCREEN); int desktopDepth=desktop_color_depth(); if (desktopDepth>8) set_color_depth(desktopDepth); if (desktopDepth<=8 || set_gfx_mode(gfxMode,640,480,0,0)!=0) { set_color_depth(32); if (set_gfx_mode(gfxMode,640,480,0,0)!=0) { set_color_depth(24); if (set_gfx_mode(gfxMode,640,480,0,0)!=0) { set_color_depth(16); if (set_gfx_mode(gfxMode,640,480,0,0)!=0) { set_color_depth(15); if (set_gfx_mode(gfxMode,640,480,0,0)!=0) { allegro_message("Unable to set graphics mode: %s",allegro_error); return EXIT_FAILURE; } } } } } //Try both modes. Hopefully bloody Windows will succeed for at least one of them! set_display_switch_mode(SWITCH_BACKGROUND); set_display_switch_mode(SWITCH_BACKAMNESIA); //I wanted to load the datafile first and then use fixup_datafile(), //but alas, it doesn't work on JPEGs! dat=load_datafile("elemsun.dat"); if (dat==NULL) { set_gfx_mode(GFX_TEXT,0,0,0,0); allegro_message("Unable to load elemsun.dat"); return EXIT_FAILURE; } setColours(); adp=al_start_duh((DUH *)dat[THE_MUSIC].dat,2,0,musicVolume/5.0,4096,44100); init(); install_int_ex(timerProc,BPS_TO_TIMER(50)); while (!wantQuit) { al_duh_set_volume(adp,musicVolume/5.0); al_poll_duh(adp); draw(); while (!wantQuit && logicTime>=trueTime) rest(1); while (!wantQuit && keypressed()) handleKey(readkey()); int numUpdates=0; while (!wantQuit && logicTime<trueTime) { update(); logicTime++; numUpdates++; if (numUpdates==10) {logicTime=trueTime; break;} } } al_stop_duh(adp); shutDown(); set_gfx_mode(GFX_TEXT,0,0,0,0); set_config_int("elemsun","windowed",windowed); set_config_int("elemsun","sound",soundVolume); set_config_int("elemsun","music",musicVolume); set_config_int("elemsun","level",levelReached); return EXIT_SUCCESS; } END_OF_MAIN();
[ [ [ 1, 786 ] ] ]
8cc1d8f829e8732211375d4f5c721ceae5b6d839
8a2e417c772eba9cf4653d0c688dd3ac96590964
/prop-src/keywords.h
ca733e7bb8faddf6b8650ad6ff868251284d26bc
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
romix/prop-cc
1a190ba6ed8922428352826de38efb736e464f50
3f7f2e4a4d0b717f4e4f3dbd4c7f9d1f35572f8f
refs/heads/master
2023-08-30T12:55:00.192286
2011-07-19T20:56:39
2011-07-19T20:56:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,817
h
/////////////////////////////////////////////////////////////////////////////// // This file is generated automatically using Prop (version 2.4.0), // last updated on Jul 1, 2011. // The original source file is "..\..\prop-src\keywords.ph". /////////////////////////////////////////////////////////////////////////////// #define PROP_PRINTER_USED #define PROP_REGEXP_MATCHING_USED #include <propdefs.h> #line 1 "../../prop-src/keywords.ph" /////////////////////////////////////////////////////////////////////////////// // // This file defines the lexical structure of the Prop language. // /////////////////////////////////////////////////////////////////////////////// #ifndef prop_lexemes_h #define prop_lexemes_h /////////////////////////////////////////////////////////////////////////////// // // Here are some regular expression abbreviations. // /////////////////////////////////////////////////////////////////////////////// #line 16 "../../prop-src/keywords.ph" #line 16 "../../prop-src/keywords.ph" /////////////////////////////////////////////////////////////////////////////// // // Main keywords are keywords that can start Prop constructs. // /////////////////////////////////////////////////////////////////////////////// #line 37 "../../prop-src/keywords.ph" #line 109 "../../prop-src/keywords.ph" /////////////////////////////////////////////////////////////////////////////// // // PropToken is the class of all terminals in Prop. // /////////////////////////////////////////////////////////////////////////////// #line 118 "../../prop-src/keywords.ph" #line 130 "../../prop-src/keywords.ph" enum PropToken { XX_r_e_w_r_i_t_eXX = 256, XX_i_n_f_e_r_e_n_c_eXX = 257, XX_m_a_t_c_hXX = 258, XX_m_a_t_c_h_a_l_lXX = 259, XX_m_a_t_c_h_s_c_a_nXX = 260, XX_r_e_f_i_n_eXX = 261, XX_c_l_a_s_s_o_fXX = 262, XX_t_y_p_eXX = 263, XX_d_a_t_a_t_y_p_eXX = 264, XX_i_n_s_t_a_n_t_i_a_t_eXX = 265, XX_l_e_x_e_m_eXX = 266, XX_b_i_t_f_i_e_l_dXX = 267, XX_b_e_g_i_nXX = 268, XX_s_y_n_t_a_xXX = 269, XX_d_a_t_a_f_l_o_wXX = 270, XX_m_o_d_u_l_eXX = 271, XX_s_i_g_n_a_t_u_r_eXX = 272, XX_c_o_n_s_t_r_a_i_n_tXX = 273, XX_d_e_c_l_a_r_eXX = 274, XX_p_r_o_c_e_d_u_r_eXX = 275, XX_f_u_nXX = 276, XX_f_u_n_c_t_i_o_nXX = 277, XX_g_r_a_p_h_t_y_p_eXX = 278, XX_g_r_a_p_h_r_e_w_r_i_t_eXX = 279, XX_c_u_t_r_e_w_r_i_t_eXX = 280, XX_f_a_i_l_r_e_w_r_i_t_eXX = 281, XX_a_t_t_r_i_b_u_t_e_g_r_a_m_m_a_rXX = 282, XX_i_fXX = 283, XX_t_h_e_nXX = 284, XX_e_l_s_eXX = 285, XX_e_l_s_i_fXX = 286, XX_w_h_i_l_eXX = 287, XX_l_o_o_pXX = 288, XX_i_sXX = 289, XX_c_l_a_s_sXX = 290, XX_u_n_i_f_i_a_b_l_eXX = 291, XX_o_fXX = 292, XX_d_oXX = 293, XX_b_r_e_a_kXX = 294, XX_c_o_n_t_i_n_u_eXX = 295, XX_g_o_t_oXX = 296, XX_w_h_e_r_eXX = 297, XX_a_sXX = 298, XX_p_u_b_l_i_cXX = 299, XX_p_r_o_t_e_c_t_e_dXX = 300, XX_p_r_i_v_a_t_eXX = 301, XX_c_o_n_s_tXX = 302, XX_e_x_t_e_r_nXX = 303, XX_m_u_t_a_b_l_eXX = 304, XX_a_p_p_l_i_c_a_t_i_v_eXX = 305, XX_v_i_r_t_u_a_lXX = 306, XX_t_r_u_eXX = 307, XX_f_a_l_s_eXX = 308, XX_c_o_l_l_e_c_t_a_b_l_eXX = 309, XX_f_i_n_a_l_i_z_a_b_l_eXX = 310, XX_p_r_i_n_t_a_b_l_eXX = 311, XX_t_r_a_c_e_dXX = 312, XX_p_e_r_s_i_s_t_e_n_tXX = 313, XX_t_r_e_e_p_a_r_s_e_rXX = 314, XX_i_n_l_i_n_eXX = 315, XX_w_i_t_hXX = 316, XX_s_w_i_t_c_hXX = 317, XX_u_n_s_i_g_n_e_dXX = 318, XX_s_i_g_n_e_dXX = 319, XX_f_o_rXX = 320, XX_c_a_t_e_g_o_r_yXX = 321, XX_f_u_n_c_t_o_rXX = 322, XX_f_e_a_t_u_r_eXX = 323, XX_s_h_a_r_i_n_gXX = 324, XX_r_e_l_a_t_i_o_nXX = 325, XX_v_i_e_wXX = 326, XX_i_n_h_e_r_i_t_e_dXX = 327, XX_r_e_t_u_r_nXX = 328, XX_s_y_n_t_h_e_s_i_z_e_dXX = 329, XX_l_a_wXX = 330, XX_l_e_f_tdkXX = 331, XX_r_i_g_h_tdkXX = 332, XX_e_x_p_e_c_tdkXX = 333, XX_p_r_e_cdkXX = 334, XX_m_a_p_o_fXX = 335, XX_s_e_t_o_fXX = 336, XX_b_a_g_o_fXX = 337, XX_m_u_l_t_i_m_a_p_o_fXX = 338, XX_l_i_s_t_o_fXX = 339, XX_p_r_i_q_u_e_u_e_o_fXX = 340, XX_q_u_e_u_e_o_fXX = 341, XX_d_e_q_u_e_o_fXX = 342, XX_t_u_p_l_e_o_fXX = 343, XX_f_o_r_a_l_lXX = 344, XX_e_x_i_s_t_sXX = 345, XX_d_o_mXX = 346, XX_r_a_nXX = 347, XX_a_r_bXX = 348, XX_l_e_s_sXX = 349, XX_i_n_c_l_u_d_eXX = 350, XX_l_f_pXX = 351, XX_g_f_pXX = 352, XX_h_o_mXX = 353, XX_i_m_p_l_i_e_sdkXX = 354, XX_x_o_rdkXX = 355, XX_e_q_u_i_vdkXX = 356, XX_t_i_m_edkXX = 357, XX_s_p_a_c_edkXX = 358, XX_n_o_d_e_sdkXX = 359, XX_e_d_g_e_sdkXX = 360, XX_i_n_d_e_xdkXX = 361, XX_h_a_s_hdkXX = 362, XX_e_q_u_a_l_i_t_ydkXX = 363, XX_p_r_e_o_r_d_e_rdkXX = 364, XX_p_o_s_t_o_r_d_e_rdkXX = 365, XX_b_e_f_o_r_edkXX = 366, XX_t_o_p_d_o_w_ndkXX = 367, XX_b_o_t_t_o_m_u_pdkXX = 368, XX_s_t_r_a_t_e_g_ydkXX = 369, XX_o_r_d_e_rdkXX = 370, XX_p_r_a_g_m_adkXX = 371, XX_c_a_s_eXX = 372, XX_a_n_dXX = 373, XX_e_n_dXX = 374, XXcocoXX = 375, XXcococoXX = 376, XXdmcndoXX = 377, XXdkdkXX = 378, XXcgcgXX = 379, XXhmhmXX = 380, XXclclXX = 381, XXcncnXX = 382, XXcndoXX = 383, XXdmdmXX = 384, XXdodoXX = 385, XXdodnXX = 386, XXdmdnXX = 387, XXcldnXX = 388, XXcndnXX = 389, XXckdnXX = 390, XXcpdnXX = 391, XXcfdnXX = 392, XXdndnXX = 393, XXcbdnXX = 394, XXdmdmdnXX = 395, XXdododnXX = 396, XXcgdnXX = 397, XXhmdnXX = 398, XXfodnXX = 399, XXdndoXX = 400, XXdmcnXX = 401, XXdmdndoXX = 402, XXdkdnXX = 403, XXdkcnXX = 404, LONG_BAR = 405, CONS_TOK = 406, DOMAIN_TOK = 407, CONS_EXP = 408, META_QUOTE = 409, POLY_DATATYPE = 410, ATTRIB_ID = 411, XXcihmXX = 412, XXhmcjXX = 413, XXflhmXX = 414, XXhmfnXX = 415, XXhlhmXX = 416, XXhmhnXX = 417, XXcociXX = 418, XXcoflXX = 419, XXgagaXX = 420, XXchchXX = 421, INT_TOK = 422, REAL_TOK = 423, CHAR_TOK = 424, STRING_TOK = 425, ID_TOK = 426, REGEXP_TOK = 427, QUARK_TOK = 428, BIGINT_TOK = 429, PUNCTUATIONS = 430 }; /////////////////////////////////////////////////////////////////////////////// // // Pretty printing methods for PropToken // /////////////////////////////////////////////////////////////////////////////// class PrettyOStream; extern std::ostream& operator<<(std::ostream&, PropToken); extern PrettyOStream& operator<<(PrettyOStream&, PropToken); #line 130 "../../prop-src/keywords.ph" #line 130 "../../prop-src/keywords.ph" #endif #line 133 "../../prop-src/keywords.ph" /* ------------------------------- Statistics ------------------------------- Merge matching rules = yes Number of DFA nodes merged = 0 Number of ifs generated = 0 Number of switches generated = 0 Number of labels = 0 Number of gotos = 0 Adaptive matching = disabled Fast string matching = disabled Inline downcasts = disabled -------------------------------------------------------------------------- */
[ [ [ 1, 139 ] ] ]
ccf22b690b7cd0dadde28477805910eef2c48e31
df238aa31eb8c74e2c208188109813272472beec
/BCGInclude/BCGPIntelliSenseLB.h
74ec963794694dd263f48f1a29ea56cdce7172de
[]
no_license
myme5261314/plugin-system
d3166f36972c73f74768faae00ac9b6e0d58d862
be490acba46c7f0d561adc373acd840201c0570c
refs/heads/master
2020-03-29T20:00:01.155206
2011-06-27T15:23:30
2011-06-27T15:23:30
39,724,191
0
0
null
null
null
null
UTF-8
C++
false
false
4,949
h
#if !defined(AFX_BCGPINTELLISENSELB_H__46A739E6_3403_4577_9EBE_E2E59A7D1A1C__INCLUDED_) #define AFX_BCGPINTELLISENSELB_H__46A739E6_3403_4577_9EBE_E2E59A7D1A1C__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of BCGControlBar Library Professional Edition // Copyright (C) 1998-2008 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // // BCGPIntelliSenseLB.h : header file // #include "BCGCBPro.h" #ifndef BCGP_EXCLUDE_EDIT_CTRL class CBCGPEditCtrl; class BCGCBPRODLLEXPORT CBCGPBaseIntelliSenseLB : public CListBox { DECLARE_DYNCREATE (CBCGPBaseIntelliSenseLB) // Construction public: CBCGPBaseIntelliSenseLB(); // Attributes public: virtual CSize GetMaxItemSize () const {return m_sizeMaxItem;} CFont* m_pFont; static int m_nNumVisibleItems; CSize m_sizeMaxItem; int m_nLBHeight; static int m_nImageToFocusRectSpacing; static int m_nFocusRectToTextSpacing; static int m_nRightSpacing; static COLORREF m_clrSelectedItemBkColor; static COLORREF m_clrSelectedItemTextColor; static COLORREF m_clrWindow; static COLORREF m_clrWindowText; // Operations public: void SetImageList (CImageList* pImageList) {m_pImageList = pImageList;} virtual CSize GetImageSize (int iIdx); virtual CSize GetTextSize (CString& str); virtual void SelectCurrentWord () {} // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBCGPBaseIntelliSenseLB) public: virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); virtual void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct); virtual int CompareItem(LPCOMPAREITEMSTRUCT /*lpCompareItemStruct*/) {return -1;} virtual BOOL PreTranslateMessage(MSG* pMsg); virtual void DeleteItem(LPDELETEITEMSTRUCT lpDeleteItemStruct); //}}AFX_VIRTUAL // Implementation public: virtual ~CBCGPBaseIntelliSenseLB(); // Generated message map functions protected: //{{AFX_MSG(CBCGPBaseIntelliSenseLB) afx_msg void OnDblclk(); afx_msg void OnDestroy(); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnKillfocus(); afx_msg void OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnNcDestroy(); afx_msg void OnSysColorChange(); //}}AFX_MSG DECLARE_MESSAGE_MAP() CImageList* m_pImageList; protected: CBCGPEditCtrl* GetParentEditCtrl (); virtual void InsertDataToEditCtrl () {} void UpdateColors (); }; ///////////////////////////////////////////////////////////////////////////// // CBCGPIntelliSenseLB window class BCGCBPRODLLEXPORT CBCGPIntelliSenseLB : public CBCGPBaseIntelliSenseLB { DECLARE_DYNCREATE (CBCGPIntelliSenseLB) // Construction public: CBCGPIntelliSenseLB(); // Attributes public: static BOOL m_bComparenoCase; // Operations public: virtual void SelectCurrentWord (); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBCGPIntelliSenseLB) public: virtual int CompareItem(LPCOMPAREITEMSTRUCT lpCompareItemStruct); //}}AFX_VIRTUAL // Implementation public: virtual ~CBCGPIntelliSenseLB(); // Generated message map functions protected: //{{AFX_MSG(CBCGPIntelliSenseLB) afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); //}}AFX_MSG DECLARE_MESSAGE_MAP() int m_nInitOffset; int m_nInitRow; protected: virtual void InsertDataToEditCtrl (); }; class BCGCBPRODLLEXPORT CBCGPSymImagesLB : public CBCGPBaseIntelliSenseLB { DECLARE_DYNCREATE (CBCGPSymImagesLB) // Construction public: CBCGPSymImagesLB() { } // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBCGPIntelliSenseLB) //}}AFX_VIRTUAL // Implementation public: virtual ~CBCGPSymImagesLB() { } // Generated message map functions protected: //{{AFX_MSG(CBCGPSymImagesLB) afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); //}}AFX_MSG DECLARE_MESSAGE_MAP() protected: virtual void InsertDataToEditCtrl (); }; #endif // BCGP_EXCLUDE_EDIT_CTRL ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BCGPINTELLISENSELB_H__46A739E6_3403_4577_9EBE_E2E59A7D1A1C__INCLUDED_)
[ "myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5" ]
[ [ [ 1, 194 ] ] ]
add6a17b5e354ec83b057c29ad70e22bd86db279
cfdcbf4dcfe7fe617bf48506a76a7728bcd83a3c
/source/Scene.cpp
3768ce572dbd2286c8a2d1e85fe63e2f1ef470d3
[]
no_license
jonny64/glslscene
f927eafb0c0ae7699f7789484260ac520225c3de
189045b273bfad23aabd22551a8a6b7164b8b94e
refs/heads/master
2021-01-19T08:10:23.343158
2009-03-19T17:29:28
2009-03-19T17:29:28
33,747,143
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
21,055
cpp
#include "Scene.h" const int MAX_NAME_LENGTH = 50; using namespace scene; // this stuff cannot should be done only after // opengl context is initialized void Scene::Init() { // load scene LoadFromFile(SCENE_FILE_NAME.c_str()); m_light = light; InitShaders(); } void Scene::DrawObjectGeometry(int objID) { meshes[objID].RenderGeometry(); } void Scene::DrawObject(int objID) { material[meshes[objID].MaterialId].Bind(); meshes[objID].Render(); } void Scene::DrawBumpmappedObject(int objID) { material[meshes[objID].MaterialId].Bind(); meshes[objID].Render(); return; glBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, m_indexVBOs[objID] ); // transfer normals glEnableClientState(GL_NORMAL_ARRAY); glBindBufferARB( GL_ARRAY_BUFFER_ARB, m_normVBOs[objID] ); glNormalPointer(GL_FLOAT,0,(GLvoid*)0); // transfer texture coordinates glClientActiveTextureARB(GL_TEXTURE0_ARB); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glBindBufferARB( GL_ARRAY_BUFFER_ARB, m_texVBOs[objID] ); glTexCoordPointer(3,GL_FLOAT,0,(GLvoid*)0); // transfer vertices glEnableClientState(GL_VERTEX_ARRAY); glBindBufferARB( GL_ARRAY_BUFFER_ARB, m_vertexVBOs[objID] ); glVertexPointer(3, GL_FLOAT, 0, (GLvoid*)0); // transfer additional attributes #ifdef TANGENT glEnableVertexAttribArrayARB( TANGENT_GENERIC_ATTRIBUTE_INDEX ); //void glVertexAttribPointer(GLuint index, //GLint size, //GLenum type, //GLboolean normalized, //GLsizei stride, //const GLvoid *pointer) glVertexAttribPointerARB( TANGENT_GENERIC_ATTRIBUTE_INDEX, 3, GL_FLOAT, GL_FALSE, 0, 0 ); #endif glDrawArrays( GL_TRIANGLES, 0, meshes[objID].IndexCount * 3 ); // clean up #ifdef TANGENT glDisableVertexAttribArrayARB( TANGENT_GENERIC_ATTRIBUTE_INDEX ); #endif glDisableClientState( GL_VERTEX_ARRAY ); glDisableClientState( GL_NORMAL_ARRAY ); glDisableClientState( GL_TEXTURE_COORD_ARRAY ); } void Scene::BuildMaterials() { glActiveTextureARB(GL_TEXTURE0_ARB); glEnable(GL_TEXTURE_2D); for (int i = 0; i < MaterialCount; i++) { material[i].Build(); } } void Scene::Render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.2f); // start using shader. OpenGL calls go through vertex // and then fragment program associated to the shader if (defaultShader) defaultShader->begin(); OutMirrorAndReflection(); //OutScene(); m_shadowMap.StoreLightMatrices(m_light.Position); m_shadowMap.FlushShadowMap(&Scene::OutSceneGeometry, this); m_shadowMap.ApplyShadowMap(&Scene::OutScene, this); // stop using shader. OpenGL calls will go through regular pipeline if (defaultShader) defaultShader->end(); m_camera.Update(); m_camera.Look(); glutSwapBuffers(); } void Scene::SetCommonShaderUniforms(cwc::glShader* shader) { shader->setUniform1i("tex", 0); shader->setUniform3f("vecLight", m_light.Position.x, m_light.Position.y, m_light.Position.z); shader->setUniform3f("lightColor", m_light.Color.x, m_light.Color.y, m_light.Color.z); // this TU holds shadow map shader->setUniform1i("shadowMap", SHADOW_MAP_TEXTURE_INDEX); shader->setUniform1i("shadowMapTexture", SHADOW_MAP_TEXTURE_INDEX); } void Scene::InitShaders() { cwc::glInfo oGLInfo; oGLInfo.Init(); bool bOk = cwc::HasGLSLSupport(); // if we have shader support if (bOk) { defaultShader = shader_manager.loadfromFile( "shaders/default.vert", "shaders/default.frag" ); #ifdef OLD_CUP_SHADER cupShader = shader_manager.loadfromFile( "shaders/cupOld.vert", "shaders/cupOld.frag" ); #else cupShader = shader_manager.loadfromFile( "shaders/cupBump.vert", "shaders/cupBump.frag" ); #endif mirrorShader = shader_manager.loadfromFile( "shaders/mirror.vert", "shaders/mirror.frag" ); wireGauzeShader = shader_manager.loadfromFile( "shaders/wireGauze.vert", "shaders/wireGauze.frag" ); ceramicShader = shader_manager.loadfromFile( "shaders/ceramic.vert", "shaders/ceramic.frag" ); } // setup uniform variables cupShader->begin(); cupShader->setUniform3f("LightPos", m_light.Position.x, m_light.Position.y, m_light.Position.z); cupShader->setUniform1i("DecalTex", 0 ); cupShader->setUniform1i("BumpTex", BUMP_TEXTURE_INDEX); #ifdef TANGENT cupShader->BindAttribLocation( TANGENT_GENERIC_ATTRIBUTE_INDEX, "Tangent" ); #endif mirrorShader->begin(); mirrorShader->setUniform1i("tex", 0); mirrorShader->setUniform1i("shadowMap", SHADOW_MAP_TEXTURE_INDEX ); mirrorShader->setUniform1i("shadowMapTexture", SHADOW_MAP_TEXTURE_INDEX); wireGauzeShader->begin(); wireGauzeShader->setUniform1i("tex", 0); wireGauzeShader->setUniform1i("opacityTex", OPACITY_TEXTURE_INDEX); wireGauzeShader->setUniform3f("vecLight", m_light.Position.x, m_light.Position.y, m_light.Position.z); defaultShader->begin(); defaultShader->setUniform1i("tex", 0); defaultShader->setUniform3f("vecLight", m_light.Position.x, m_light.Position.y, m_light.Position.z); defaultShader->setUniform3f("lightColor", m_light.Color.x, m_light.Color.y, m_light.Color.z); // this TU holds shadow map defaultShader->setUniform1i("shadowMap", SHADOW_MAP_TEXTURE_INDEX); defaultShader->setUniform1i("shadowMapTexture", SHADOW_MAP_TEXTURE_INDEX); ceramicShader->begin(); ceramicShader->setUniform1i("tex1", 0); ceramicShader->setUniform1i("tex2", 1); ceramicShader->setUniform3f("vecLight", m_light.Position.x, m_light.Position.y, m_light.Position.z); ceramicShader->setUniform3f("lightColor", m_light.Color.x, m_light.Color.y, m_light.Color.z); ceramicShader->setUniform1i("shadowMap", SHADOW_MAP_TEXTURE_INDEX ); ceramicShader->setUniform1i("shadowMapTexture", SHADOW_MAP_TEXTURE_INDEX); glUseProgram(0); } void Scene::OutMirrorGeometry() { // search for and out mirror for (int objIndex = 0; objIndex < MeshCount; objIndex++) { bool currObjIsMirror = ( meshes[objIndex].Name == MIRROR_OBJ_NAME); if (currObjIsMirror) { defaultShader->end(); // no texturing glClientActiveTextureARB(GL_TEXTURE0_ARB); glDisable(GL_TEXTURE_2D); glDisableClientState(GL_TEXTURE_COORD_ARRAY); DrawObjectGeometry(objIndex); defaultShader->begin(); return; } }; } void Scene::OutMirrorTextured() { // search for and out mirror for (int objIndex = 0; objIndex < MeshCount; objIndex++) { bool currObjIsMirror = ( meshes[objIndex].Name == MIRROR_OBJ_NAME); if (currObjIsMirror) { DrawObject(objIndex); return; } }; } void Scene::OutMirrorAndReflection() { // enable writing to all buffers glDepthMask(TRUE); glDepthFunc(GL_LESS); glStencilMask( (GLuint)~0 ); glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE); m_camera.SetupMirroredModelview(); // mark mirror area glEnable(GL_STENCIL_TEST); glStencilFunc(GL_ALWAYS, 0x80, 0x80); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); glDepthMask(GL_FALSE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDisable(GL_LIGHTING); glColor4f(0,0,0,1); OutMirrorGeometry(); glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); glColor4f(1.0,1.0,1.0,1.0); glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); // out scene in mirror area(marked with seven bit in stencil) glEnable(GL_STENCIL_TEST); glDepthMask(GL_TRUE); glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE); glStencilFunc(GL_EQUAL, 0x80, 0x80); glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); OutScene(); glDisable(GL_CULL_FACE); glDisable(GL_STENCIL_TEST); glStencilMask((GLuint)~0); glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // return to staright camera glMatrixMode(GL_MODELVIEW); glLoadIdentity(); m_camera.Update(); m_camera.Look(); // draw mirror glDisable(GL_STENCIL_TEST); glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE); glEnable(GL_BLEND); // ... resColor = straightPixelColor * srcRGBfactor + mirroredPixelColor * dstRGBfactor // ... glBlendFuncSeparate( srcRGBfactor, dstRGBfactor, sAlpha, dAlpha ) glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE); glBlendEquation(GL_FUNC_ADD); glColor4fv(MIRROR_COLOR); glDisable(GL_LIGHTING); mirrorShader->begin(); OutMirrorTextured(); defaultShader->begin(); glDisable(GL_BLEND); } void Scene::OutObject(int objIndex, bool geometryOnly) { if (meshes[objIndex].Name == MIRROR_OBJ_NAME) return; // setup necessary textures if (!geometryOnly) { defaultShader->begin(); DrawObject(objIndex); } else { DrawObjectGeometry(objIndex); } } void Scene::OutCup( int objIndex ) { assert(cupShader != NULL); cupShader->begin(); cupShader->setUniform3f("LightPos", m_light.Position.x, m_light.Position.y, m_light.Position.z ); DrawBumpmappedObject(objIndex); cupShader->end(); defaultShader->begin(); } void Scene::OutWireGauze( int objIndex ) { assert(wireGauzeShader!=NULL); wireGauzeShader->begin(); DrawObject(objIndex); defaultShader->begin(); } void Scene::OutBread( int objIndex ) { assert(ceramicShader!=NULL); ceramicShader->begin(); DrawObject(objIndex); defaultShader->begin(); } void Scene::OutSceneGeometry() { // for each scene object for (int objIndex = 0; objIndex < MeshCount; objIndex++) { OutObject(objIndex, true); // not only geometry: texturing is ON }; } void Scene::OutScene() { for (int objIndex = 0; objIndex < MeshCount; objIndex++) { if (meshes[objIndex].Name == CUP_OBJ_NAME) OutCup(objIndex); else if (meshes[objIndex].Name == WIRE_OBJ_NAME) OutWireGauze(objIndex); else if (meshes[objIndex].Name == CERAMIC_OBJ_NAME) OutBread(objIndex); else OutObject(objIndex, false); // not only geometry: texturing is ON }; // finally, mark light source position with cube m_light.Render(); } int Scene::LoadMaterial (FILE *f) { // èùåì ïåðâóþ îòêðûâàþùóþ ñêîáêó fscanf(f,"%s",str); while (strcmp(str,"{")!=0) { fscanf(f,"%s",str); }; // êîëè÷åñòâî îòêðûâàþùèõ ñêîáîê int LevelCount = 1; // ïîêà íå âñòðåòèëè òàêîãî æå êîëè÷åñòâà çàêðûâàþùèõ ñêîáîê while (LevelCount > 0) { fscanf(f,"%s",str); if (strcmp(str,"{")==0) LevelCount++; if (strcmp(str,"}")==0) LevelCount--; // çàãðóçèòü äèôóçíóþ êàðòó if (strcmp(str,"*MAP_DIFFUSE")==0) { fscanf(f,"%s",str); while (strcmp(str,"*MAP_CLASS")!=0) { fscanf(f,"%s",str); }; fscanf(f,"%s",str); // îáû÷íàÿ äèôóçíàÿ êàðòà if (strcmp(str,"\"Bitmap\"")==0) { fscanf(f,"%s",str); while (strcmp(str,"*BITMAP")!=0) { fscanf(f,"%s",str); }; // èìÿ òåêñòóðû fscanf(f,"%s",str); str[strlen(str)-1]=0; material[MaterialCount].DiffuseMap.CountMap=1; strcpy(material[MaterialCount].DiffuseMap.Tex1,str+1); } // ìèêñîâàííûé ìàòåðèàë if (strcmp(str,"\"Mix\"")==0) { material[MaterialCount].DiffuseMap.CountMap=3; fscanf(f,"%s",str); while (strcmp(str,"*BITMAP")!=0) { fscanf(f,"%s",str); }; // èìÿ òåêñòóðû fscanf(f,"%s",str); str[strlen(str)-1]=0; strcpy(material[MaterialCount].DiffuseMap.Tex1,str+1); fscanf(f,"%s",str); while (strcmp(str,"*BITMAP")!=0) { fscanf(f,"%s",str); }; // èìÿ òåêñòóðû fscanf(f,"%s",str); str[strlen(str)-1]=0; strcpy(material[MaterialCount].DiffuseMap.Tex2,str+1); fscanf(f,"%s",str); while (strcmp(str,"*BITMAP")!=0) { fscanf(f,"%s",str); }; // èìÿ òåêñòóðû fscanf(f,"%s",str); str[strlen(str)-1]=0; strcpy(material[MaterialCount].DiffuseMap.Tex3,str+1); }//if (strcmp(str,"\"Mix\"")==0) // ìèêñîâàííûé ìàòåðèàë if (strcmp(str,"\"Composite\"")==0) { material[MaterialCount].DiffuseMap.CountMap=2; fscanf(f,"%s",str); while (strcmp(str,"*BITMAP")!=0) { fscanf(f,"%s",str); }; // èìÿ òåêñòóðû fscanf(f,"%s",str); str[strlen(str)-1]=0; strcpy(material[MaterialCount].DiffuseMap.Tex1,str+1); fscanf(f,"%s",str); while (strcmp(str,"*BITMAP")!=0) { fscanf(f,"%s",str); }; // èìÿ òåêñòóðû fscanf(f,"%s",str); str[strlen(str)-1]=0; strcpy(material[MaterialCount].DiffuseMap.Tex2,str+1); }//if (strcmp(str,"\"Composite\"")==0) }//if (strcmp(str,"*MAP_DIFFUSE")==0) };//while fscanf(f,"%s",str); if (strcmp(str,"*MAP_BUMP")==0) { fscanf(f,"%s",str); while (strcmp(str,"*MAP_CLASS")!=0) { fscanf(f,"%s",str); }; fscanf(f,"%s",str); // áàìï êàðòà if (strcmp(str,"\"Bitmap\"")==0) { fscanf(f,"%s",str); while (strcmp(str,"*BITMAP")!=0) { fscanf(f,"%s",str); }; // èìÿ òåêñòóðû fscanf(f,"%s",str); str[strlen(str)-1]=0; material[MaterialCount].BumpMap.CountMap=1; strcpy(material[MaterialCount].BumpMap.Tex1,str+1); } } // çàãðóçèòü êàðòó ïðîçðà÷íîñòè else if (strcmp(str,"*MAP_OPACITY")==0) { fscanf(f,"%s",str); while (strcmp(str,"*MAP_CLASS")!=0) { fscanf(f,"%s",str); }; fscanf(f,"%s",str); // îáû÷íàÿ êàðòà ïðîçðà÷íîñòè if (strcmp(str,"\"Bitmap\"")==0) { fscanf(f,"%s",str); while (strcmp(str,"*BITMAP")!=0) { fscanf(f,"%s",str); }; // èìÿ òåêñòóðû fscanf(f,"%s",str); str[strlen(str)-1]=0; material[MaterialCount].OpacityMap.CountMap=1; strcpy(material[MaterialCount].OpacityMap.Tex1,str+1); } } MaterialCount++; return SUCCESS; } int Scene::LoadObject(FILE *f) { // Ñ×ÈÒÛÂÀÍÈÅ ÈÌÅÍÈ ÎÁÚÅÊÒÀ fscanf(f,"%s",str); while (strcmp(str,"*NODE_NAME")!=0) { fscanf(f,"%s",str); }; //meshes[MeshCount].Name=new char name[MAX_NAME_LENGTH]; fscanf(f,"%s",&name); meshes[MeshCount].Name = dequote(string(name)); // Ñ×ÈÒÛÂÀÍÈÅ ÏÅÐÂÎÉ ÑÒÐÎÊÈ ÌÀÒÐÈÖÛ fscanf(f,"%s",str); while (strcmp(str,"*TM_ROW0")!=0) { fscanf(f,"%s",str); }; fscanf(f,"%f %f %f",&meshes[MeshCount].Matrix[0],&meshes[MeshCount].Matrix[1],&meshes[MeshCount].Matrix[2]); // Ñ×ÈÒÛÂÀÍÈÅ ÂÒÎÐÎÉ ÑÒÐÎÊÈ ÌÀÒÐÈÖÛ fscanf(f,"%s",str); while (strcmp(str,"*TM_ROW1")!=0) { fscanf(f,"%s",str); }; fscanf(f,"%f %f %f",&meshes[MeshCount].Matrix[4],&meshes[MeshCount].Matrix[5],&meshes[MeshCount].Matrix[6]); // Ñ×ÈÒÛÂÀÍÈÅ ÒÐÅÒÜÅÉ ÑÒÐÎÊÈ ÌÀÒÐÈÖÛ fscanf(f,"%s",str); while (strcmp(str,"*TM_ROW2")!=0) { fscanf(f,"%s",str); }; fscanf(f,"%f %f %f",&meshes[MeshCount].Matrix[8],&meshes[MeshCount].Matrix[9],&meshes[MeshCount].Matrix[10]); // Ñ×ÈÒÛÂÀÍÈÅ ×ÅÒÂÅÐÒÎÉ ÑÒÐÎÊÈ ÌÀÒÐÈÖÛ fscanf(f,"%s",str); while (strcmp(str,"*TM_ROW3")!=0) { fscanf(f,"%s",str); }; fscanf(f,"%f %f %f",&meshes[MeshCount].Matrix[12],&meshes[MeshCount].Matrix[13],&meshes[MeshCount].Matrix[14]); // Ñ×ÈÒÛÂÀÍÈß ÊÎËÈ×ÅÑÒÂÎ ÂÅÐÒÅÊÑΠfscanf(f,"%s",str); while (strcmp(str,"*MESH_NUMVERTEX")!=0) { fscanf(f,"%s",str); }; fscanf(f,"%i",&meshes[MeshCount].VertexCount); meshes[MeshCount].Vertex=new float[3*meshes[MeshCount].VertexCount]; // C×ÈÒÛÂÀÍÈÅ ÊÎËÈ×ÅÑÒÂÀ ÈÍÄÅÊÑΠfscanf(f,"%s",str); while (strcmp(str,"*MESH_NUMFACES")!=0) { fscanf(f,"%s",str); }; fscanf(f,"%i",&meshes[MeshCount].IndexCount); meshes[MeshCount].Index=new unsigned int[3*meshes[MeshCount].IndexCount]; meshes[MeshCount].Normals=new float [9*meshes[MeshCount].IndexCount]; // Ñ×ÈÒÛÂÀÍÈÅ ÂÅÐØÈÍ for (int i=0;i<meshes[MeshCount].VertexCount;i++) { fscanf(f,"%s",str); while (strcmp(str,"*MESH_VERTEX")!=0) { fscanf(f,"%s",str); }; int k; fscanf(f,"%i%f%f%f",&k,&meshes[MeshCount].Vertex[i*3+0],&meshes[MeshCount].Vertex[i*3+1],&meshes[MeshCount].Vertex[i*3+2]); } // Ñ×ÈÒÛÂÀÍÈÅ ÈÍÄÅÊÑΠfor (int i=0;i<meshes[MeshCount].IndexCount;i++) { fscanf(f,"%s",str); while (strcmp(str,"*MESH_FACE")!=0) { fscanf(f,"%s",str); }; int k; fscanf(f," %i: A: %i B: %i C: %i",&k,&meshes[MeshCount].Index[i*3+0],&meshes[MeshCount].Index[i*3+1],&meshes[MeshCount].Index[i*3+2]); }; // Ñ×ÈÒÛÂÀÍÈÅ ÊÎËÈ×ÅÑÒÂÀ ÒÅÊÑÒÓÐÍÛÕ ÊÎÎÐÄÈÍÀÒ fscanf(f,"%s",str); while (strcmp(str,"*MESH_NUMTVERTEX")!=0) { fscanf(f,"%s",str); }; fscanf(f,"%i",&meshes[MeshCount].TexCount); meshes[MeshCount].TexCord=new float[3*meshes[MeshCount].TexCount]; // Ñ×ÈÒÛÂÀÍÈÅ ÒÅÊÑÒÓÐÍÛÕ ÊÎÎÐÄÈÍÀÒ for (int i=0;i<meshes[MeshCount].TexCount;i++) { fscanf(f,"%s",str); while (strcmp(str,"*MESH_TVERT")!=0) { fscanf(f,"%s",str); }; int k; fscanf(f,"%i%f%f%f",&k,&meshes[MeshCount].TexCord[i*3+0],&meshes[MeshCount].TexCord[i*3+1],&meshes[MeshCount].TexCord[i*3+2]); } // Ñ×ÈÒÛÂÀÍÈÅ ÈÍÄÅÊÑΠÒÅÊÑÒÓÐÍÛÕ ÊÎÎÐÄÈÍÀÒ meshes[MeshCount].IndexTexCoord=new unsigned int[3*meshes[MeshCount].IndexCount]; for (int i=0;i<meshes[MeshCount].IndexCount;i++) { fscanf(f,"%s",str); while (strcmp(str,"*MESH_TFACE")!=0) { fscanf(f,"%s",str); }; int k; fscanf(f,"%i%i%i%i",&k,&meshes[MeshCount].IndexTexCoord[i*3+0],&meshes[MeshCount].IndexTexCoord[i*3+1],&meshes[MeshCount].IndexTexCoord[i*3+2]); }; // ÇÀÃÐÓÇÊÀ ÍÎÐÌÀËÅÉ for (int i=0;i<meshes[MeshCount].IndexCount*3;i++) { fscanf(f,"%s",str); while (strcmp(str,"*MESH_VERTEXNORMAL")!=0) { fscanf(f,"%s",str); }; int k; fscanf(f,"%i%f%f%f",&k,&meshes[MeshCount].Normals[i*3+0],&meshes[MeshCount].Normals[i*3+1],&meshes[MeshCount].Normals[i*3+2]); meshes[MeshCount].CalcNormal(meshes[MeshCount].Normals[i*3+0],meshes[MeshCount].Normals[i*3+1],meshes[MeshCount].Normals[i*3+2]); }; // ÇÀÃÐÓÇÊÀ ÈÍÄÅÊÑÀ ÌÀÒÅÐÈÀËÀ fscanf(f,"%s",str); while (strcmp(str,"*MATERIAL_REF")!=0) { fscanf(f,"%s",str); }; fscanf(f,"%i",&meshes[MeshCount].MaterialId); // ÏÅÐÅÑÒÐÎÅÍÈÅ ÌÎÄÅËÈ meshes[MeshCount].Build(); MeshCount++; return SUCCESS; } int Scene::LoadLightObject (FILE *f) { // Ñ×ÈÒÛÂÀÍÈÅ ×ÅÒÂÅÐÒÎÉ ÑÒÐÎÊÈ ÑÒÐÎÊÈ ÌÀÒÐÈÖÛ - ÏÎÇÈÖÈß ÈÑÒÎ×ÍÈÊÀ ÑÂÅÒÀ fscanf(f,"%s",str); while (strcmp(str,"*TM_ROW3")!=0) { fscanf(f,"%s",str); }; //fscanf(f,"%f %f %f",&light.position[0],&light.position[1],&light.position[2]); fscanf(f,"%f %f %f", &light.Position[0],&light.Position[1],&light.Position[2]); // äèôóçíûé è çåðêàëüíûé öâåò èñòî÷íèêà ñâåòà fscanf(f,"%s",str); while (strcmp(str,"*LIGHT_COLOR")!=0) { fscanf(f,"%s",str); }; //fscanf(f,"%f %f %f", &light.color[0], &light.color[1], &light.color[2]); fscanf(f,"%f %f %f", &light.Color[0], &light.Color[1], &light.Color[2]); return SUCCESS; }; int Scene::LoadFromFile(const char *name) { FILE *sceneFile = fopen(name, "rt"); assert(sceneFile != NULL); if (sceneFile == NULL) return FAILURE; while (fscanf(sceneFile,"%s",str)!=EOF) { if (strcmp(str,"*GEOMOBJECT")==0) { LoadObject(sceneFile); } if (strcmp(str,"*LIGHTOBJECT")==0) { LoadLightObject(sceneFile); } if (strcmp(str,"*MATERIAL")==0) { LoadMaterial(sceneFile); } } BuildMaterials(); return SUCCESS; }
[ "astro64m@bf710128-d37f-11dd-87b6-9d1a99559f42" ]
[ [ [ 1, 727 ] ] ]
66217c670006bac038882972173a538409690d9e
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleFilesys/TFileSys.cpp
91e998c985017e8fffd5488b36d7a32a923ffe99
[]
no_license
SoylentGraham/Tootle
4ae4e8352f3e778e3743e9167e9b59664d83b9cb
17002da0936a7af1f9b8d1699d6f3e41bab05137
refs/heads/master
2021-01-24T22:44:04.484538
2010-11-03T22:53:17
2010-11-03T22:53:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,997
cpp
#include <TootleCore/TLMaths.h> // gr: I don't know why but this needs to be included before "TFileFreetype.h" or "rand" isn't found #include <TootleCore/TEventChannel.h> #include "TFileSys.h" #include "TLFileSys.h" namespace TLFileSys { extern TPtr<TLFileSys::TFileFactory> g_pFileFactory; } //---------------------------------------------------------- // constructor //---------------------------------------------------------- TLFileSys::TFileSys::TFileSys(TRefRef FileSysRef,TRefRef FileSysTypeRef) : m_FileSysRef ( FileSysRef ), m_FileSysTypeRef ( FileSysTypeRef ), m_UpdatingFileList ( false ) { } //---------------------------------------------------------- // check this file belongs to this file system, if not break //---------------------------------------------------------- Bool TLFileSys::TFileSys::CheckIsFileFromThisFileSys(TPtr<TFile>& pFile) { if ( !pFile ) { TLDebug_Break("File expected"); return FALSE; } // check matching file sys if ( pFile->GetFileSysRef() != GetFileSysRef() ) { TLDebug_Break("Expected file to be in this file sys"); return FALSE; } return TRUE; } //---------------------------------------------------------- // create new file into the file list - returns existing file if it already exists in our file sys //---------------------------------------------------------- TPtr<TLFileSys::TFile> TLFileSys::TFileSys::CreateFileInstance(const TString& Filename) { // see if this file already exists // gr: note: NOT a reference! don't want to overwrite the NULL TPtr TPtr<TFile> pFile = GetFile( Filename ); // already created/exists just return current one if ( pFile ) { return pFile; } // create new file object pFile = TLFileSys::g_pFileFactory->CreateFileInstance( Filename, GetFileSysRef() ); // failed to create/init if ( !pFile ) return pFile; // add to our list if ( m_Files.Exists( pFile ) ) { TLDebug_Break("Shouldn't find this new file in our list"); } else { m_Files.Add( pFile ); } return pFile; } //---------------------------------------------------------- // remove file - NULL's ptr too //---------------------------------------------------------- Bool TLFileSys::TFileSys::RemoveFileInstance(TPtr<TFile> pFile) { if ( !pFile ) { TLDebug_Break("File expected"); return FALSE; } // do removal from factory if ( TLFileSys::g_pFileFactory ) { TLFileSys::g_pFileFactory->RemoveFileInstance( pFile ); } // remove from OUR list if ( !m_Files.Remove( pFile ) ) { TLDebug_Break("Should have removed instance... suggests file is NOT stored in this file sys..."); return FALSE; } return TRUE; } //---------------------------------------------------------- // update file list if it's out of date. // returns FALSE if no changes, WAIT if possible changes, // TRUE if there were any changes //---------------------------------------------------------- SyncBool TLFileSys::TFileSys::UpdateFileList() { // gr: just to stop recursing -although we're not getting stuck in a loop- // we're doing excessive work. // routine updateFileList, a file changes, triggers a reload of the asset // which triggers another UpdateFileList but the timestamp is out of date // (over 10 seconds, so this probably only goes wrong when debugging...) // and causes duplicated work. // when we become threaded, in theory the file system[s] will be locked from message // handling until it's all done anyway so we won't have this trouble... if ( m_UpdatingFileList ) { // no changes return SyncWait; } Bool ReloadFilelist = FALSE; // if timestamp is valid compare with current time if ( m_LastFileListUpdate.IsValid() ) { TLTime::TTimestamp TimeNow = TLTime::GetTimeNow(); if ( m_LastFileListUpdate.GetSecondsDiff( TimeNow ) > (s32)GetFilelistTimeoutSecs() ) { ReloadFilelist = TRUE; } } else { // timestamp is invalid, get filelist ReloadFilelist = TRUE; } // file list doesnt need reloading, return no changes if ( !ReloadFilelist ) return SyncFalse; // mark as updating file list m_UpdatingFileList = true; // reload file list, if failed return no change SyncBool LoadResult = LoadFileList(); // update timestamp m_LastFileListUpdate.SetTimestampNow(); if ( LoadResult == SyncTrue ) { #ifdef _DEBUG TTempString Debug_String("New file list for file sys: "); this->GetFileSysRef().GetString( Debug_String ); Debug_String.Appendf(". %d files: \n", GetFileList().GetSize() ); for ( u32 f=0; f<GetFileList().GetSize(); f++ ) { TLFileSys::TFile& File = *(GetFileList().ElementAt(f)); File.Debug_GetString( Debug_String ); TLDebug_Print( Debug_String ); Debug_String.Empty(); } #endif } // no longer updating m_UpdatingFileList = false; return LoadResult; } //---------------------------------------------------------- // update timestamp and flush missing files. returns true if any files were removed or changed //---------------------------------------------------------- Bool TLFileSys::TFileSys::FinaliseFileList() { Bool Changed = false; // update time stamp of file list m_LastFileListUpdate.SetTimestampNow(); // flush missing/null files for ( s32 f=GetFileList().GetSize()-1; f>=0; f-- ) { TPtr<TFile>& pFile = GetFileList().ElementAt(f); // if flagged missing then remove instance (we still flag it in case soemthing has a TPtr to it still) if ( pFile->GetFlags()( TFile::Lost ) ) { RemoveFileInstance( pFile ); Changed = true; continue; } // for any files that have changed, send out notification if ( pFile->IsOutOfDate() ) { // get manager to notify that file has changed TLFileSys::g_pFactory->OnFileChanged( pFile->GetFileAndTypeRef(), this->GetFileSysRef() ); Changed = true; } } return Changed; }
[ [ [ 1, 59 ], [ 61, 61 ], [ 63, 223 ] ], [ [ 60, 60 ], [ 62, 62 ] ] ]
1a55583690acec8210e568a83557121fd2e34365
e5ded38277ec6db30ef7721a9f6f5757924e130e
/Cpp/SoSe10/Blatt05.Aufgabe02/stdafx.cpp
3de00d94576b5927f0189da32fabe4f9b994c835
[]
no_license
TetsuoCologne/sose10
67986c8a014c4bdef19dc52e0e71e91602600aa0
67505537b0eec497d474bd2d28621e36e8858307
refs/heads/master
2020-05-27T04:36:02.620546
2010-06-22T20:47:08
2010-06-22T20:47:08
32,480,813
0
0
null
null
null
null
UTF-8
C++
false
false
304
cpp
// stdafx.cpp : source file that includes just the standard includes // Blatt05.Aufgabe02.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "[email protected]@f2f8bf26-27bb-74d3-be08-1e18597623ec" ]
[ [ [ 1, 8 ] ] ]
c56c98ac5d2a55419d69edfc0a9a1a6317825f29
216ae2fd7cba505c3690eaae33f62882102bd14a
/utils/nxogre/include/NxOgreBox.h
dbd1801bda0b34cdfe1420d90dc25b53e1e98237
[]
no_license
TimelineX/balyoz
c154d4de9129a8a366c1b8257169472dc02c5b19
5a0f2ee7402a827bbca210d7c7212a2eb698c109
refs/heads/master
2021-01-01T05:07:59.597755
2010-04-20T19:53:52
2010-04-20T19:53:52
56,454,260
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,282
h
/** File: NxOgreBox.h Created on: 15-Mar-09 Author: Robin Southern "betajaen" SVN: $Id$ © Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org This file is part of NxOgre. NxOgre is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NxOgre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with NxOgre. If not, see <http://www.gnu.org/licenses/>. */ #ifndef NXOGRE_BOX_H #define NXOGRE_BOX_H #include "NxOgreStable.h" #include "NxOgreCommon.h" #include "NxOgrePointerClass.h" #include "NxOgreShape.h" #include "NxOgreShapeBlueprint.h" namespace NxOgre_Namespace { /** \brief */ class NxOgrePublicClass Box : public PointerClass<Classes::_Box>, public Shape { friend class RigidBodyPrototype; public: // Functions using ::NxOgre::PointerClass<Classes::_Box>::operator new; using ::NxOgre::PointerClass<Classes::_Box>::operator delete; using ::NxOgre::PointerClass<Classes::_Box>::getClassType; /** \brief Box constructor with width, height, depth size argument as a Vec3. \note The Box class's dimensions are full diameter of the box, and not the radius as it is in PhysX. */ Box(const Vec3& dimensions, ShapeBlueprint* box_blueprint = new ShapeBlueprint()); /** \brief Box constructor with width, height, depth size argument as seperate float components.. \note The Box class's dimensions are full diameter of the box, and not the radius as it is in PhysX. */ Box(Real w, Real h, Real d, ShapeBlueprint* blueprint = new ShapeBlueprint()); /** \brief Box constructor with width, height, depth size argument as a single float component. \note The Box class's dimensions are full diameter of the box, and not the radius as it is in PhysX. */ Box(Real whd_dimensions, ShapeBlueprint* box_blueprint = new ShapeBlueprint()); /** \brief Box destructor. \warning Deleting the Box whilst it is attached to a shape will probably cause a nasty crash. */ ~Box(void); /** \brief Get the shape type based upon the Classes::xxxx enum. */ Enums::ShapeFunctionType getShapeFunctionType() const; /** \brief Get the size of the shape */ Vec3 getSize() const; /** \brief Set the size of the shape */ void setSize(const Vec3&); /** \brief Set the size of the shape */ void setSize(float w, float h, float d); /** \brief Get the box represented as world space OBB. \note This function only works when the box is attached. */ SimpleBox getWorldOBB(void); protected: /** \internal DO NOT USE. */ NxShapeDesc* create(); /** \internal DO NOT USE. */ void assign(NxShape*); protected: NxBoxShape* mBoxShape; }; // class Box } // namespace NxOgre_Namespace #endif
[ "umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b" ]
[ [ [ 1, 125 ] ] ]
6474653a6e49843eedfd2a167b89e1eb5e223b69
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
/Projects/elastix/elastix_sources_v4/src/Core/Kernel/elxTransformixMain.h
f604556ecc776bc994ebc4c5fdaf4a279f4413ce
[]
no_license
mijc/Diploma
95fa1b04801ba9afb6493b24b53383d0fbd00b33
bae131ed74f1b344b219c0ffe0fffcd90306aeb8
refs/heads/master
2021-01-18T13:57:42.223466
2011-02-15T14:19:49
2011-02-15T14:19:49
1,369,569
0
0
null
null
null
null
UTF-8
C++
false
false
4,271
h
/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __elxTransformixMain_H_ #define __elxTransformixMain_H_ #include "elxElastixMain.h" namespace elastix { using namespace itk; /** * \class TransformixMain * \brief A class with all functionality to configure transformix. * * The TransformixMain class inherits from ElastixMain. We overwrite the Run() * -function. In the new Run() the Run()-function from the * ElastixTemplate-class is not called (as in elxElastixMain.cxx), * because this time we don't want to start a registration, but * just apply a transformation to an input image. * * \ingroup Kernel */ class TransformixMain : public ElastixMain { public: /** Standard itk. */ typedef TransformixMain Self; typedef ElastixMain Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro( Self ); /** Run-time type information (and related methods). */ itkTypeMacro( TransformixMain, ElastixMain ); /** Typedef's from Superclass. */ /** typedef's from itk base Object. */ typedef Superclass::ObjectType ObjectType; typedef Superclass::ObjectPointer ObjectPointer; typedef Superclass::DataObjectType DataObjectType; typedef Superclass::DataObjectPointer DataObjectPointer; /** Elastix components. */ typedef Superclass::ElastixBaseType ElastixBaseType; typedef Superclass::ConfigurationType ConfigurationType; typedef Superclass::ArgumentMapType ArgumentMapType; typedef Superclass::ConfigurationPointer ConfigurationPointer; typedef Superclass::ObjectContainerType ObjectContainerType; typedef Superclass::DataObjectContainerType DataObjectContainerType; typedef Superclass::ObjectContainerPointer ObjectContainerPointer; typedef Superclass::DataObjectContainerPointer DataObjectContainerPointer; /** Typedefs for the database that holds pointers to New() functions. * Those functions are used to instantiate components, such as the metric etc. */ typedef Superclass::ComponentDatabaseType ComponentDatabaseType; typedef Superclass::ComponentDatabasePointer ComponentDatabasePointer; typedef Superclass::PtrToCreator PtrToCreator; typedef Superclass::ComponentDescriptionType ComponentDescriptionType; typedef Superclass::PixelTypeDescriptionType PixelTypeDescriptionType; typedef Superclass::ImageDimensionType ImageDimensionType; typedef Superclass::DBIndexType DBIndexType; /** Typedef for class that populates a ComponentDatabase. */ typedef Superclass::ComponentLoaderType ComponentLoaderType; typedef Superclass::ComponentLoaderPointer ComponentLoaderPointer; /** Overwrite Run() from base-class. */ virtual int Run( void ); /** Overwrite Run( argmap ) from superclass. Simply calls the superclass. */ virtual int Run( ArgumentMapType & argmap ); /** Get and Set input- and outputImage. */ virtual void SetInputImageContainer( DataObjectContainerType * inputImageContainer ); protected: TransformixMain(){}; virtual ~TransformixMain(){}; /** InitDBIndex sets m_DBIndex to the value obtained * from the ComponentDatabase. */ virtual int InitDBIndex( void ); private: TransformixMain( const Self& ); // purposely not implemented void operator=( const Self& ); // purposely not implemented }; // end class TransformixMain } // end namespace elastix #endif // end #ifndef __elxTransformixMain_h
[ [ [ 1, 118 ] ] ]
182058fde3bc9953f2d7c180c8d9f6e17f51645d
8133a41b9ab1b8d34140a417fda6598d9b756b0b
/3rdparty/glm/gtx/quaternion.inl
a65b2c072f338beb3702b08d1daccc67091e71f4
[ "MIT", "Apache-2.0" ]
permissive
senseproject/SensEngine
96146ffab61ac357b694c9d26938ee75d33f3bdd
00a49c6004a104de165be1b4c1f17b5c05fe0577
refs/heads/master
2016-09-06T17:26:25.044944
2011-08-17T03:58:28
2011-08-17T03:58:28
1,863,979
11
2
null
null
null
null
UTF-8
C++
false
false
7,680
inl
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2005-12-21 // Updated : 2008-11-27 // Licence : This source is under MIT License // File : glm/gtx/quaternion.inl /////////////////////////////////////////////////////////////////////////////////////////////////// #include <limits> namespace glm{ namespace gtx{ namespace quaternion { template <typename valType> GLM_FUNC_QUALIFIER detail::tvec3<valType> cross ( detail::tvec3<valType> const & v, detail::tquat<valType> const & q ) { return gtc::quaternion::inverse(q) * v; } template <typename valType> GLM_FUNC_QUALIFIER detail::tvec3<valType> cross ( detail::tquat<valType> const & q, detail::tvec3<valType> const & v ) { return q * v; } template <typename T> GLM_FUNC_QUALIFIER detail::tquat<T> squad ( detail::tquat<T> const & q1, detail::tquat<T> const & q2, detail::tquat<T> const & s1, detail::tquat<T> const & s2, T const & h) { return mix(mix(q1, q2, h), mix(s1, s2, h), T(2) * h (T(1) - h)); } template <typename T> GLM_FUNC_QUALIFIER detail::tquat<T> intermediate ( detail::tquat<T> const & prev, detail::tquat<T> const & curr, detail::tquat<T> const & next ) { detail::tquat<T> invQuat = gtc::quaternion::inverse(curr); return ext((log(next + invQuat) + log(prev + invQuat)) / T(-4)) * curr; } template <typename T> GLM_FUNC_QUALIFIER detail::tquat<T> exp ( detail::tquat<T> const & q, T const & exponent ) { detail::tvec3<T> u(q.x, q.y, q.z); float a = glm::length(u); detail::tvec3<T> v(u / a); return detail::tquat<T>(cos(a), sin(a) * v); } template <typename T> GLM_FUNC_QUALIFIER detail::tquat<T> log ( detail::tquat<T> const & q ) { if((q.x == T(0)) && (q.y == T(0)) && (q.z == T(0))) { if(q.w > T(0)) return detail::tquat<T>(log(q.w), T(0), T(0), T(0)); else if(q.w < T(0)) return detail::tquat<T>(log(-q.w), T(3.1415926535897932384626433832795), T(0),T(0)); else return detail::tquat<T>(std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity()); } else { T Vec3Len = sqrt(q.x * q.x + q.y * q.y + q.z * q.z); T QuatLen = sqrt(Vec3Len * Vec3Len + q.w * q.w); T t = atan(Vec3Len, T(q.w)) / Vec3Len; return detail::tquat<T>(t * q.x, t * q.y, t * q.z, log(QuatLen)); } } template <typename T> GLM_FUNC_QUALIFIER detail::tquat<T> pow ( detail::tquat<T> const & x, T const & y ) { if(abs(x.w) > T(0.9999)) return x; float Angle = acos(y); float NewAngle = Angle * y; float Div = sin(NewAngle) / sin(Angle); return detail::tquat<T>( cos(NewAngle), x.x * Div, x.y * Div, x.z * Div); } //template <typename T> //GLM_FUNC_QUALIFIER detail::tquat<T> sqrt //( // detail::tquat<T> const & q //) //{ // T q0 = T(1) - dot(q, q); // return T(2) * (T(1) + q0) * q; //} template <typename T> GLM_FUNC_QUALIFIER detail::tvec3<T> rotate ( detail::tquat<T> const & q, detail::tvec3<T> const & v ) { return q * v; } template <typename T> GLM_FUNC_QUALIFIER detail::tvec4<T> rotate ( detail::tquat<T> const & q, detail::tvec4<T> const & v ) { return q * v; } template <typename T> GLM_FUNC_QUALIFIER T angle ( detail::tquat<T> const & x ) { return glm::degrees(acos(x.w) * T(2)); } template <typename T> GLM_FUNC_QUALIFIER detail::tvec3<T> axis ( detail::tquat<T> const & x ) { T tmp1 = T(1) - x.w * x.w; if(tmp1 <= T(0)) return detail::tvec3<T>(0, 0, 1); T tmp2 = T(1) / sqrt(tmp1); return detail::tvec3<T>(x.x * tmp2, x.y * tmp2, x.z * tmp2); } template <typename valType> GLM_FUNC_QUALIFIER detail::tquat<valType> angleAxis ( valType const & angle, valType const & x, valType const & y, valType const & z ) { return angleAxis(angle, detail::tvec3<valType>(x, y, z)); } template <typename valType> GLM_FUNC_QUALIFIER detail::tquat<valType> angleAxis ( valType const & angle, detail::tvec3<valType> const & v ) { detail::tquat<valType> result; valType a = glm::radians(angle); valType s = glm::sin(a * valType(0.5)); result.w = glm::cos(a * valType(0.5)); result.x = v.x * s; result.y = v.y * s; result.z = v.z * s; return result; } template <typename T> GLM_FUNC_QUALIFIER T extractRealComponent ( detail::tquat<T> const & q ) { T w = T(1.0) - q.x * q.x - q.y * q.y - q.z * q.z; if(w < T(0)) return T(0); else return -sqrt(w); } template <typename valType> GLM_FUNC_QUALIFIER valType roll ( detail::tquat<valType> const & q ) { return atan2(valType(2) * (q.x * q.y + q.w * q.z), q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z); } template <typename valType> GLM_FUNC_QUALIFIER valType pitch ( detail::tquat<valType> const & q ) { return atan2(valType(2) * (q.y * q.z + q.w * q.x), q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z); } template <typename valType> GLM_FUNC_QUALIFIER valType yaw ( detail::tquat<valType> const & q ) { return asin(valType(-2) * (q.x * q.z - q.w * q.y)); } template <typename valType> GLM_FUNC_QUALIFIER detail::tvec3<valType> eularAngles ( detail::tquat<valType> const & x ) { return detail::tvec3<valType>(pitch(x), yaw(x), roll(x)); } template <typename T> GLM_FUNC_QUALIFIER detail::tquat<T> shortMix ( detail::tquat<T> const & x, detail::tquat<T> const & y, T const & a ) { if(a <= typename detail::tquat<T>::value_type(0)) return x; if(a >= typename detail::tquat<T>::value_type(1)) return y; T fCos = dot(x, y); detail::tquat<T> y2(y); //BUG!!! tquat<T> y2; if(fCos < T(0)) { y2 = -y; fCos = -fCos; } //if(fCos > 1.0f) // problem T k0, k1; if(fCos > T(0.9999)) { k0 = T(1) - a; k1 = T(0) + a; //BUG!!! 1.0f + a; } else { T fSin = sqrt(T(1) - fCos * fCos); T fAngle = atan(fSin, fCos); T fOneOverSin = T(1) / fSin; k0 = sin((T(1) - a) * fAngle) * fOneOverSin; k1 = sin((T(0) + a) * fAngle) * fOneOverSin; } return detail::tquat<T>( k0 * x.w + k1 * y2.w, k0 * x.x + k1 * y2.x, k0 * x.y + k1 * y2.y, k0 * x.z + k1 * y2.z); } template <typename T> GLM_FUNC_QUALIFIER detail::tquat<T> fastMix ( detail::tquat<T> const & x, detail::tquat<T> const & y, T const & a ) { return glm::normalize(x * (T(1) - a) + (y * a)); } }//namespace quaternion }//namespace gtx }//namespace glm
[ [ [ 1, 303 ] ] ]
448d96775ac413c11457485a84ebedc8660675e5
49db059c239549a8691fda362adf0654c5749fb1
/2010/prjibelski/task2/TimerDialog.h
150dee703e67e30ca5a30342093266a79a8b72e0
[]
no_license
bondarevts/amse-qt
1a063f27c45a80897bb4751ae5c10f5d9d80de1b
2b9b76c7a5576bc1079fc037adcf039fed4dc848
refs/heads/master
2020-05-07T21:19:48.773724
2010-12-07T07:53:51
2010-12-07T07:53:51
35,804,478
0
0
null
null
null
null
UTF-8
C++
false
false
943
h
#ifndef _TIMER_DIALOG_H_ #define _TIMER_DIALOG_H_ #include <QDialog> #include <QPushButton> #include <QLineEdit> #include <QLCDNumber> #include <QComboBox> #include <QTimer> #include <QEvent> #include <QLabel> class TimerDialog: public QDialog { Q_OBJECT; public: TimerDialog(); /* Timer data */ unsigned short currentTimer; unsigned int currentTime1; unsigned int currentTime2; unsigned int timer1Period; unsigned int timer2Period; int timer1Id; int timer2Id; /* GUI elemets for displaying time */ QLabel * timer1Label; QLabel * timer2Label; QLCDNumber * currentTime1Number; QLCDNumber * currentTime2Number; /* GUI */ QComboBox * timerComboBox; QPushButton * setPeriodButton; QPushButton * stopTimerButton; QLineEdit * periodLineEdit; void timerEvent( QTimerEvent *e ); public slots: void setPeriod(); void stopTimer(); void changeCurrentTimer(); }; #endif /* _TIMER_DIALOG_H_ */
[ "andrewprzh@1a14799f-55e9-4979-7f51-533a2053511e" ]
[ [ [ 1, 50 ] ] ]
4e76a460fd2fd3b66e0a415fc6f141cc36133aab
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/wave/cpplexer/validate_universal_char.hpp
1fedadff0603be2f463f4cc86b91b73b162e02e4
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
13,546
hpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library Grammar for universal character validation (see C++ standard: Annex E) http://www.boost.org/ Copyright (c) 2001-2007 Hartmut Kaiser. 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) =============================================================================*/ #if !defined(VALIDATE_UNIVERSAL_CHAR_HPP_55F1B811_CD76_4C72_8344_CBC69CF3B339_INCLUDED) #define VALIDATE_UNIVERSAL_CHAR_HPP_55F1B811_CD76_4C72_8344_CBC69CF3B339_INCLUDED #include <boost/assert.hpp> #include <boost/wave/wave_config.hpp> #include <boost/wave/util/file_position.hpp> #include <boost/wave/cpplexer/cpplexer_exceptions.hpp> // this must occur after all of the includes and before any code appears #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_PREFIX #endif /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace wave { namespace cpplexer { namespace impl { enum universal_char_type { universal_char_type_valid = 0, universal_char_type_invalid = 1, universal_char_type_base_charset = 2, universal_char_type_not_allowed_for_identifiers = 3 }; /////////////////////////////////////////////////////////////////////////// // // is_range is a helper function for the classification by brute force // below // /////////////////////////////////////////////////////////////////////////// inline bool in_range(unsigned long ch, unsigned long l, unsigned long u) { return (l <= ch && ch <= u); } /////////////////////////////////////////////////////////////////////////////// // // classify_universal_char // // This function classifies an universal character value into 4 subranges: // universal_char_type_valid // the universal character value is valid for identifiers // universal_char_type_invalid // the universal character value is not valid for its usage inside // identifiers (see C++ Standard: 2.2.2 [lex.charset]) // universal_char_type_base_charset // the universal character value designates a character from the base // character set // universal_char_type_not_allowed_for_identifiers // the universal character value is not allowed in an identifier // // Implementation note: // This classification isn't implemented very effectively here. This // function should be rewritten with some range run matching algorithm. // /////////////////////////////////////////////////////////////////////////////// inline universal_char_type classify_universal_char (unsigned long ch) { // test for invalid characters if (ch <= 0x0020 || in_range(ch, 0x007f, 0x009f)) return universal_char_type_invalid; // test for characters in the range of the base character set if (in_range(ch, 0x0021, 0x005f) || in_range(ch, 0x0061, 0x007e)) return universal_char_type_base_charset; // test for additional valid character values (see C++ Standard: Annex E) if (in_range(ch, 0x00c0, 0x00d6) || in_range(ch, 0x00d8, 0x00f6) || in_range(ch, 0x00f8, 0x01f5) || in_range(ch, 0x01fa, 0x0217) || in_range(ch, 0x0250, 0x02a8) || in_range(ch, 0x1e00, 0x1e9a) || in_range(ch, 0x1ea0, 0x1ef9)) { return universal_char_type_valid; // Latin } if (0x0384 == ch || in_range(ch, 0x0388, 0x038a) || 0x038c == ch || in_range(ch, 0x038e, 0x03a1) || in_range(ch, 0x03a3, 0x03ce) || in_range(ch, 0x03d0, 0x03d6) || 0x03da == ch || 0x03dc == ch || 0x03de == ch || 0x03e0 == ch || in_range(ch, 0x03e2, 0x03f3) || in_range(ch, 0x1f00, 0x1f15) || in_range(ch, 0x1f18, 0x1f1d) || in_range(ch, 0x1f20, 0x1f45) || in_range(ch, 0x1f48, 0x1f4d) || in_range(ch, 0x1f50, 0x1f57) || 0x1f59 == ch || 0x1f5b == ch || 0x1f5d == ch || in_range(ch, 0x1f5f, 0x1f7d) || in_range(ch, 0x1f80, 0x1fb4) || in_range(ch, 0x1fb6, 0x1fbc) || in_range(ch, 0x1fc2, 0x1fc4) || in_range(ch, 0x1fc6, 0x1fcc) || in_range(ch, 0x1fd0, 0x1fd3) || in_range(ch, 0x1fd6, 0x1fdb) || in_range(ch, 0x1fe0, 0x1fec) || in_range(ch, 0x1ff2, 0x1ff4) || in_range(ch, 0x1ff6, 0x1ffc)) { return universal_char_type_valid; // Greek } if (in_range(ch, 0x0401, 0x040d) || in_range(ch, 0x040f, 0x044f) || in_range(ch, 0x0451, 0x045c) || in_range(ch, 0x045e, 0x0481) || in_range(ch, 0x0490, 0x04c4) || in_range(ch, 0x04c7, 0x04c8) || in_range(ch, 0x04cb, 0x04cc) || in_range(ch, 0x04d0, 0x04eb) || in_range(ch, 0x04ee, 0x04f5) || in_range(ch, 0x04f8, 0x04f9)) { return universal_char_type_valid; // Cyrillic } if (in_range(ch, 0x0531, 0x0556) || in_range(ch, 0x0561, 0x0587)) return universal_char_type_valid; // Armenian if (in_range(ch, 0x05d0, 0x05ea) || in_range(ch, 0x05f0, 0x05f4)) return universal_char_type_valid; // Hebrew if (in_range(ch, 0x0621, 0x063a) || in_range(ch, 0x0640, 0x0652) || in_range(ch, 0x0670, 0x06b7) || in_range(ch, 0x06ba, 0x06be) || in_range(ch, 0x06c0, 0x06ce) || in_range(ch, 0x06e5, 0x06e7)) { return universal_char_type_valid; // Arabic } if (in_range(ch, 0x0905, 0x0939) || in_range(ch, 0x0958, 0x0962)) return universal_char_type_valid; // Devanagari if (in_range(ch, 0x0985, 0x098c) || in_range(ch, 0x098f, 0x0990) || in_range(ch, 0x0993, 0x09a8) || in_range(ch, 0x09aa, 0x09b0) || 0x09b2 == ch || in_range(ch, 0x09b6, 0x09b9) || in_range(ch, 0x09dc, 0x09dd) || in_range(ch, 0x09df, 0x09e1) || in_range(ch, 0x09f0, 0x09f1)) { return universal_char_type_valid; // Bengali } if (in_range(ch, 0x0a05, 0x0a0a) || in_range(ch, 0x0a0f, 0x0a10) || in_range(ch, 0x0a13, 0x0a28) || in_range(ch, 0x0a2a, 0x0a30) || in_range(ch, 0x0a32, 0x0a33) || in_range(ch, 0x0a35, 0x0a36) || in_range(ch, 0x0a38, 0x0a39) || in_range(ch, 0x0a59, 0x0a5c) || 0x0a5e == ch) { return universal_char_type_valid; // Gurmukhi } if (in_range(ch, 0x0a85, 0x0a8b) || 0x0a8d == ch || in_range(ch, 0x0a8f, 0x0a91) || in_range(ch, 0x0a93, 0x0aa8) || in_range(ch, 0x0aaa, 0x0ab0) || in_range(ch, 0x0ab2, 0x0ab3) || in_range(ch, 0x0ab5, 0x0ab9) || 0x0ae0 == ch) { return universal_char_type_valid; // Gujarati } if (in_range(ch, 0x0b05, 0x0b0c) || in_range(ch, 0x0b0f, 0x0b10) || in_range(ch, 0x0b13, 0x0b28) || in_range(ch, 0x0b2a, 0x0b30) || in_range(ch, 0x0b32, 0x0b33) || in_range(ch, 0x0b36, 0x0b39) || in_range(ch, 0x0b5c, 0x0b5d) || in_range(ch, 0x0b5f, 0x0b61)) { return universal_char_type_valid; // Oriya } if (in_range(ch, 0x0b85, 0x0b8a) || in_range(ch, 0x0b8e, 0x0b90) || in_range(ch, 0x0b92, 0x0b95) || in_range(ch, 0x0b99, 0x0b9a) || 0x0b9c == ch || in_range(ch, 0x0b9e, 0x0b9f) || in_range(ch, 0x0ba3, 0x0ba4) || in_range(ch, 0x0ba8, 0x0baa) || in_range(ch, 0x0bae, 0x0bb5) || in_range(ch, 0x0bb7, 0x0bb9)) { return universal_char_type_valid; // Tamil } if (in_range(ch, 0x0c05, 0x0c0c) || in_range(ch, 0x0c0e, 0x0c10) || in_range(ch, 0x0c12, 0x0c28) || in_range(ch, 0x0c2a, 0x0c33) || in_range(ch, 0x0c35, 0x0c39) || in_range(ch, 0x0c60, 0x0c61)) { return universal_char_type_valid; // Telugu } if (in_range(ch, 0x0c85, 0x0c8c) || in_range(ch, 0x0c8e, 0x0c90) || in_range(ch, 0x0c92, 0x0ca8) || in_range(ch, 0x0caa, 0x0cb3) || in_range(ch, 0x0cb5, 0x0cb9) || in_range(ch, 0x0ce0, 0x0ce1)) { return universal_char_type_valid; // Kannada } if (in_range(ch, 0x0d05, 0x0d0c) || in_range(ch, 0x0d0e, 0x0d10) || in_range(ch, 0x0d12, 0x0d28) || in_range(ch, 0x0d2a, 0x0d39) || in_range(ch, 0x0d60, 0x0d61)) { return universal_char_type_valid; // Malayalam } if (in_range(ch, 0x0e01, 0x0e30) || in_range(ch, 0x0e32, 0x0e33) || in_range(ch, 0x0e40, 0x0e46) || in_range(ch, 0x0e4f, 0x0e5b)) { return universal_char_type_valid; // Thai } return universal_char_type_not_allowed_for_identifiers; } /////////////////////////////////////////////////////////////////////////////// // // validate_identifier_name // // The validate_identifier_name function tests a given identifier name for // its validity with regard to eventually contained universal characters. // These should be in valid ranges (see the function // classify_universal_char above). // // If the identifier name contains invalid or not allowed universal // characters a corresponding lexing_exception is thrown. // /////////////////////////////////////////////////////////////////////////////// template <typename StringT> inline void validate_identifier_name (StringT const &name, int line, int column, StringT const &file_name) { using namespace std; // some systems have strtoul in namespace std:: typename StringT::size_type pos = name.find_first_of('\\'); while (StringT::npos != pos) { // the identifier name contains a backslash (must be universal char) BOOST_ASSERT('u' == name[pos+1] || 'U' == name[pos+1]); StringT uchar_val(name.substr(pos+2, ('u' == name[pos+1]) ? 4 : 8)); universal_char_type type = classify_universal_char(strtoul(uchar_val.c_str(), 0, 16)); if (universal_char_type_valid != type) { // an invalid char was found, so throw an exception StringT error_uchar(name.substr(pos, ('u' == name[pos+1]) ? 6 : 10)); if (universal_char_type_invalid == type) { BOOST_WAVE_LEXER_THROW(lexing_exception, universal_char_invalid, error_uchar, line, column, file_name.c_str()); } else if (universal_char_type_base_charset == type) { BOOST_WAVE_LEXER_THROW(lexing_exception, universal_char_base_charset, error_uchar, line, column, file_name.c_str()); } else { BOOST_WAVE_LEXER_THROW(lexing_exception, universal_char_not_allowed, error_uchar, line, column, file_name.c_str()); } } // find next universal char (if appropriate) pos = name.find_first_of('\\', pos+2); } } /////////////////////////////////////////////////////////////////////////////// // // validate_literal // // The validate_literal function tests a given string or character literal // for its validity with regard to eventually contained universal // characters. These should be in valid ranges (see the function // classify_universal_char above). // // If the string or character literal contains invalid or not allowed // universal characters a corresponding lexing_exception is thrown. // /////////////////////////////////////////////////////////////////////////////// template <typename StringT> inline void validate_literal (StringT const &name, int line, int column, StringT const &file_name) { using namespace std; // some systems have strtoul in namespace std:: typename StringT::size_type pos = name.find_first_of('\\'); while (StringT::npos != pos) { // the literal contains a backslash (may be universal char) if ('u' == name[pos+1] || 'U' == name[pos+1]) { StringT uchar_val(name.substr(pos+2, ('u' == name[pos+1]) ? 4 : 8)); universal_char_type type = classify_universal_char(strtoul(uchar_val.c_str(), 0, 16)); if (universal_char_type_valid != type && universal_char_type_not_allowed_for_identifiers != type) { // an invalid char was found, so throw an exception StringT error_uchar(name.substr(pos, ('u' == name[pos+1]) ? 6 : 10)); if (universal_char_type_invalid == type) { BOOST_WAVE_LEXER_THROW(lexing_exception, universal_char_invalid, error_uchar, line, column, file_name.c_str()); } else { BOOST_WAVE_LEXER_THROW(lexing_exception, universal_char_base_charset, error_uchar, line, column, file_name.c_str()); } } } // find next universal char (if appropriate) pos = name.find_first_of('\\', pos+2); } } /////////////////////////////////////////////////////////////////////////////// } // namespace impl } // namespace cpplexer } // namespace wave } // namespace boost // the suffix header occurs after all of the code #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_SUFFIX #endif #endif // !defined(VALIDATE_UNIVERSAL_CHAR_HPP_55F1B811_CD76_4C72_8344_CBC69CF3B339_INCLUDED)
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 322 ] ] ]
ba251d2693a0dcbaeeeffd3139a849074c8b359a
48d325e5c8648382c8f790a5e8762b36ffd7c45a
/qtshoot/taskenemy1.h
4a2dc6f179faa2ded65df057cf674a392dfa8e04
[]
no_license
tomozh/qtshoot
46184f4bf7ad9e36f4a358b862ec17e415a0ece0
332aaedc89c398cc9f79c908c77bd2dd6978ec44
refs/heads/master
2020-07-07T10:59:31.554012
2011-12-09T18:04:09
2011-12-09T18:04:09
2,948,875
0
0
null
null
null
null
UTF-8
C++
false
false
432
h
#ifndef TASKENEMY1_H #define TASKENEMY1_H #include <QPointF> #include <QPainter> #include "taskchara.h" class taskEnemy1 : public TaskChara { public: taskEnemy1(const QPointF& pt, int zorder, const QPointF& vec); virtual void oneFrame(); virtual void render(QPainter* painter); virtual void addDamage(int power); private: int m_frameCount; QPointF m_vec; }; #endif // TASKENEMY1_H
[ "tomo@aspire.(none)" ]
[ [ [ 1, 22 ] ] ]
6fb2e5186470391ef7495896087ce7b193105750
105cc69f4207a288be06fd7af7633787c3f3efb5
/HovercraftUniverse/HovercraftUniverse/VisualEventParser.cpp
1a87603cc1fe50e8e6f49b95a5306edf8891d5de
[]
no_license
allenjacksonmaxplayio/uhasseltaacgua
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
ad54e9aa3ad841b8fc30682bd281c790a997478d
refs/heads/master
2020-12-24T21:21:28.075897
2010-06-09T18:05:23
2010-06-09T18:05:23
56,725,792
0
0
null
null
null
null
UTF-8
C++
false
false
452
cpp
#include "VisualEventParser.h" #include "CollisionEvent.h" namespace HovUni { VisualEventParser::~VisualEventParser(void) { } VisualEvent* VisualEventParser::parse(ZCom_BitStream* stream){ if ( !VisualEvent::checkEventClass(stream) ){ return 0; } VisualEventType type = VisualEvent::readType(stream); switch (type) { case onCollision: return CollisionEvent::parse(stream); default: return 0; break; } } }
[ "pintens.pieterjan@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c" ]
[ [ [ 1, 26 ] ] ]
cf4f87bea1eb07dd16daccc63125bbd456becaab
fb4cf44e2c146b26ddde6350180cc420611fe17a
/SDK/BetterBTSAI.cpp
560be5b2ea403304d19575b94629d7cd7b3fd224
[]
no_license
dharkness/civ4bullai
93e0685ef53e404ac4ffa5c1aecf4edaf61acd61
e56c8a4f1172e2d2b15eb87eaa78adb9d357fae6
refs/heads/master
2022-09-15T23:31:55.030351
2010-11-13T07:23:13
2010-11-13T07:23:13
267,723,017
0
0
null
null
null
null
UTF-8
C++
false
false
267
cpp
#include "CvGameCoreDLL.h" #include "BetterBTSAI.h" // AI decision making logging void logBBAI(char* format, ... ) { #ifdef LOG_AI static char buf[2048]; _vsnprintf( buf, 2048-4, format, (char*)(&format+1) ); gDLL->logMsg("BBAI.log", buf); #endif }
[ "fim-fuyu@31ee56aa-37e8-4f44-8bdf-1f84a3affbab" ]
[ [ [ 1, 14 ] ] ]
2e2387a83d8b8cabb88f827baeb4310a4865c36a
9566086d262936000a914c5dc31cb4e8aa8c461c
/EnigmaClient-Console/Application.hpp
3a522c7406c6a9302ee0aab15d916d9016e3bbd5
[]
no_license
pazuzu156/Enigma
9a0aaf0cd426607bb981eb46f5baa7f05b66c21f
b8a4dfbd0df206e48072259dbbfcc85845caad76
refs/heads/master
2020-06-06T07:33:46.385396
2011-12-19T03:14:15
2011-12-19T03:14:15
3,023,618
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,000
hpp
#ifndef APPLICATION_HPP_INCLUDED #define APPLICATION_HPP_INCLUDED /* Copyright © 2011 Christopher Joseph Dean Schaefer (disks86) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "ClientTransmissionManager.hpp" #include "ClientConfigurationManager.hpp" #include "SoundManager.hpp" namespace Enigma { class Application : public IApplicationEventListener, public IChatEventListener { private: bool mIsStopped; bool mIsUnloaded; size_t mGameMode; ClientTransmissionManager mClientTransmissionManager; SoundManager mSoundManager; protected: /* * Initialize variables to null or other default values. * This should not result in an exception. */ void PreInit(); /* * Initialize variables to sane and useable values. * Can cause exceptions. */ void Init(int argc, Enigma::c8** argv); /* * Load all required resources for execution. * Can result in an exception if resources cannot be loaded. */ void Load(); void LoadUnsafely(); /* * Unload or release all resources loaded during the load part of the life cycle. * */ void Unload(); /* * Steps through the object life cycle can starts calling poll until stopped. (This is a thread entry point if applicable.) * May result in an exception if any portion of the object life cycle results in an exception. */ void EnterLoop(int argc, Enigma::c8** argv); /* * Performs executions processes. * May result in an exception if any of those processes fail. */ void Poll(); bool PollSafe(); public: Application(); ~Application(); //returns true if the application has recieved a halt command else false. bool GetIsStopped(); //Starts the application. void Start(int argc, Enigma::c8** argv); //Stops the application. void Stop(); void DoApplicationEvents(); void DoAudioEvents(); void DoChatEvents(); void DoSceneEvents(); virtual void onExit(); virtual void onChangeGameMode(size_t gameMode); virtual void onLog(const std::string& message); virtual void onOpenBrowserWindow(const std::string& url){} virtual void onOpenVideoWindow(const std::string& url){} virtual void onReceivedCharacterList(const std::vector<std::string>& characters){} virtual void onInvited(size_t chatType, size_t inviteId, const std::string& organizationName); virtual void onJoined(size_t chatType, const std::string& organizationName); virtual void onRankModified(size_t chatType, const std::string& rankName, size_t permissions); virtual void onModified(size_t chatType, const std::string& playerName, const std::string& rankName); virtual void onExpelled(size_t chatType, const std::string& organizationName, const std::string& reason); virtual void onReceivedMessage(size_t chatType, const std::string& message, const std::string& sender); virtual void onNpcResponse(size_t npcId, const std::string& response, const std::vector<std::string>& playerResponses); }; }; #endif // APPLICATION_HPP_INCLUDED
[ [ [ 1, 108 ] ] ]
e37c3323235d174c0e1d669f5648c661baa43939
ef8e875dbd9e81d84edb53b502b495e25163725c
/litewiz/src/file_clusters/file_cluster.cpp
8e890eeaae117513c28e7e4bb8438de335fa5450
[]
no_license
panone/litewiz
22b9d549097727754c9a1e6286c50c5ad8e94f2d
e80ed9f9d845b08c55b687117acb1ed9b6e9a444
refs/heads/master
2021-01-10T19:54:31.146153
2010-10-01T13:29:38
2010-10-01T13:29:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,294
cpp
/******************************************************************************* *******************************************************************************/ #include <QList> #include <QString> #include "file_cluster.h" /******************************************************************************* *******************************************************************************/ FileCluster::FileCluster ( QString const & name, QString const & stem, QList< FileCluster * > const & collection ) : name( name ), stem( stem ), collection( collection ) { excluded = false; } /******************************************************************************* *******************************************************************************/ QString FileCluster::getName ( void ) const { return name; } /******************************************************************************* *******************************************************************************/ void FileCluster::setName ( QString const & name ) { this->name = name; } /******************************************************************************* *******************************************************************************/ QString FileCluster::getStem ( void ) const { return stem; } /******************************************************************************* *******************************************************************************/ int FileCluster::getIndex ( void ) const { return collection.indexOf( const_cast< FileCluster * >( this ) ); } /******************************************************************************* *******************************************************************************/ void FileCluster::exclude ( bool const exclude ) { excluded = exclude; } /******************************************************************************* *******************************************************************************/ bool FileCluster::isExcluded ( void ) const { return excluded; } /******************************************************************************/
[ [ [ 1, 87 ] ] ]
49d8c4cd057ed6e82cc54eb98123f71f7b47d642
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/entropy_encoder_model/entropy_encoder_model_kernel_5.h
241b36f33fddac42df9c1ff2a82803af97e695c4
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
26,897
h
// Copyright (C) 2005 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_ENTROPY_ENCODER_MODEL_KERNEl_5_ #define DLIB_ENTROPY_ENCODER_MODEL_KERNEl_5_ #include "../algs.h" #include "entropy_encoder_model_kernel_abstract.h" #include "../assert.h" namespace dlib { namespace eemk5 { struct node { node* next; node* child_context; node* parent_context; unsigned short symbol; unsigned short count; unsigned short total; unsigned short escapes; }; } template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > class entropy_encoder_model_kernel_5 { /*! REQUIREMENTS ON total_nodes - 4096 < total_nodes - this is the total number of nodes that we will use in the tree REQUIREMENTS ON order - 0 <= order - this is the maximum depth-1 the tree will be allowed to go (note that the root level is depth 0). GENERAL NOTES This implementation follows more or less the implementation strategy laid out by Alistair Moffat in his paper Implementing the PPM data compression scheme. Published in IEEE Transactions on Communications, 38(11):1917-1921, 1990. The escape method used will be method D. This also uses Dmitry Shkarin's Information Inheritance scheme. (described in "PPM: one step to practicality" and "Improving the Efficiency of the PPM Algorithm") INITIAL VALUE - root == pointer to an array of total_nodes nodes - next_node == 1 - cur == root - cur_order = 0 - root->next == 0 - root->parent_context == 0 - root->child_context == 0 - root->escapes == 0 - root->total == 0 - stack_size == 0 - exc_used == false - for all i: exc[i] == 0 CONVENTION - pop() == stack[stack_size-1].n and stack[stack_size-1].nc - exc_used == something_is_excluded() - is_excluded(symbol) == bit symbol&0x1F from exc[symbol>>5] - &get_entropy_encoder() == coder - root == pointer to an array of total_nodes nodes. this is also the root of the tree. - if (next_node < total_nodes) then - next_node == the next node in root that has not yet been allocated - root->next == 0 - root->parent_context == 0 - for every node in the tree: { - NOTATION: - The "context" of a node is the string of symbols seen when you go from the root of the tree down (down though child context pointers) to the node, including the symbol at the node itself. (note that the context of the root node is "" or the empty string) - A set of nodes is in the same "context set" if all the node's contexts are of length n and all the node's contexts share the same prefix of length n-1. - The "child context set" of a node is a set of nodes with contexts that are one symbol longer and prefixed by the node's context. For example, if a node has a context "abc" then the nodes for contexts "abca", "abcb", "abcc", etc... are all in the child context set of the node. - The "parent context" of a node is the context that is one symbol shorter than the node's context and includes the symbol in the node. So the parent context of a node with context "abcd" would be the context "bcd". - if (next != 0) then - next == pointer to the next node in the same context set - if (child_context != 0) then - child_context == pointer to the first node of the child context set for this node. - escapes > 0 - if (parent_context != 0) then - parent_context == pointer to the parent context of this node. - else - this node is the root node of the tree - if (this is not the root node) then - symbol == the symbol represented with this node - count == the number of times this symbol has been seen in its parent context. - else - the root doesn't have a symbol. i.e. the context for the root node is "" or the empty string. - total == The sum of the counts of all the nodes in the child context set + escapes. - escapes == the escape count for the context represented by the node. - count > 0 } - cur_order < order - cur_order == the depth of the node cur in the tree. (note that the root node has depth 0) - cur == pointer to the node in the tree who's context matches the most recent symbols we have seen. !*/ typedef eemk5::node node; public: typedef entropy_encoder entropy_encoder_type; entropy_encoder_model_kernel_5 ( entropy_encoder& coder ); virtual ~entropy_encoder_model_kernel_5 ( ); inline void clear( ); inline void encode ( unsigned long symbol ); entropy_encoder& get_entropy_encoder ( ) { return coder; } static unsigned long get_alphabet_size ( ) { return alphabet_size; } private: inline eemk5::node* allocate_node ( ); /*! requires - space_left() == true ensures - returns a pointer to a new node !*/ inline bool space_left ( ) const; /*! ensures - returns true if there is at least 1 free node left. - returns false otherwise !*/ inline void exclude ( unsigned short symbol ); /*! ensures - #is_excluded(symbol) == true - #something_is_excluded() == true !*/ inline bool something_is_excluded ( ); /*! ensures - returns true if some symbol has been excluded. returns false otherwise !*/ inline bool is_excluded ( unsigned short symbol ); /*! ensures - if (symbol has been excluded) then - returns true - else - returns false !*/ inline void clear_exclusions ( ); /*! ensures - for all symbols #is_excluded(symbol) == false - #something_is_excluded() == true !*/ inline void scale_counts ( node* n ); /*! ensures - divides all the counts in the child context set of n by 2. - none of the nodes in the child context set will have a count of 0 !*/ inline void push ( node* n, node* nc ); /*! requires - stack_size < order ensures - #pop(a,b): a == n && b == nc !*/ inline void pop ( node*& n, node*& nc ); /*! requires - stack_size > 0 ensures - returns the two nodes at the top of the stack !*/ struct nodes { node* n; node* nc; }; unsigned long next_node; entropy_encoder& coder; node* root; node* cur; unsigned long cur_order; unsigned long exc[alphabet_size/32+1]; bool exc_used; nodes stack[order+1]; unsigned long stack_size; // restricted functions entropy_encoder_model_kernel_5(entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>&); // copy constructor entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>& operator=(entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>&); // assignment operator }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // member function definitions // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: entropy_encoder_model_kernel_5 ( entropy_encoder& coder_ ) : next_node(1), coder(coder_), cur_order(0), stack_size(0) { COMPILE_TIME_ASSERT( 1 < alphabet_size && alphabet_size < 65535 ); COMPILE_TIME_ASSERT( 4096 < total_nodes ); root = new node[total_nodes]; cur = root; root->child_context = 0; root->escapes = 0; root->next = 0; root->parent_context = 0; root->total = 0; clear_exclusions(); } // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: ~entropy_encoder_model_kernel_5 ( ) { delete [] root; } // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: clear( ) { next_node = 1; root->child_context = 0; root->escapes = 0; root->total = 0; cur = root; cur_order = 0; stack_size = 0; clear_exclusions(); } // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: encode ( unsigned long sym ) { unsigned short symbol = static_cast<unsigned short>(sym); node* temp = cur; cur = 0; unsigned short low_count, high_count, total_count; node* new_node = 0; // local_order will track the level of temp in the tree unsigned long local_order = cur_order; unsigned short c; // c == t(a|sk) unsigned short t; // t == T(sk) if (something_is_excluded()) clear_exclusions(); while (true) { low_count = 0; high_count = 0; if (space_left()) { total_count = temp->total; if (total_count > 0) { // check if we need to scale the counts if (total_count > 10000) { scale_counts(temp); total_count = temp->total; } // find the symbol we are looking for and put a pointer to it // into found_symbol. If it isn't found then found_symbol == 0. // also, low_count and high_count will be correctly set. node* n = temp->child_context; node* found_symbol = 0; node* last = 0; if (something_is_excluded()) { node* templast = 0; while (true) { if (is_excluded(n->symbol) == false) { exclude(n->symbol); if (found_symbol == 0) { high_count += n->count; if (n->symbol == symbol) { found_symbol = n; last = templast; low_count = high_count - n->count; } } } else { total_count -= n->count; } if (n->next == 0) break; templast = n; n = n->next; } } else { while (true) { high_count += n->count; exclude(n->symbol); if (n->symbol == symbol) { found_symbol = n; low_count = high_count - n->count; break; } if (n->next == 0) break; last = n; n = n->next; } } // if we found the symbol if (found_symbol) { n = found_symbol; if (new_node != 0) { new_node->parent_context = found_symbol; } coder.encode(low_count,high_count,total_count); c = n->count += 8; t = temp->total += 8; // move this node to the front if (last) { last->next = n->next; n->next = temp->child_context; temp->child_context = n; } if (cur == 0) { if (local_order >= order) { cur = n->parent_context; cur_order = local_order; } else { cur_order = local_order+1; cur = n; } } break; } // if we hit the end of the context set without finding the symbol else { // finish excluding all the symbols while (n->next) { exclude(n->symbol); n = n->next; } if (new_node != 0) { new_node->parent_context = allocate_node(); new_node = new_node->parent_context; } else { new_node = allocate_node(); } n->next = new_node; // write an escape to a lower context coder.encode(high_count,total_count,total_count); } } else // if (total_count == 0) { // this means that temp->child_context == 0 so we should make // a new node here. if (new_node != 0) { new_node->parent_context = allocate_node(); new_node = new_node->parent_context; } else { new_node = allocate_node(); } temp->child_context = new_node; } if (cur == 0 && local_order < order) { cur = new_node; cur_order = local_order+1; } // fill out the new node new_node->child_context = 0; new_node->escapes = 0; new_node->next = 0; new_node->total = 0; push(new_node,temp); if (temp != root) { temp = temp->parent_context; --local_order; continue; } t = 2056; c = 8; // since this is the root we are going to the order-(-1) context // so we can just take care of that here. new_node->parent_context = root; coder.encode(symbol,symbol+1,alphabet_size); if (cur == 0) { cur = root; cur_order = 0; } break; } else { // there isn't enough space so we should throw away the tree clear(); temp = cur; local_order = cur_order; cur = 0; new_node = 0; } } // while (true) // initialize the counts and symbol for any new nodes we have added // to the tree. node* n, *nc; while (stack_size > 0) { pop(n,nc); n->symbol = static_cast<unsigned short>(symbol); // if nc is not a determnistic context if (nc->total) { unsigned long temp2 = t-c+nc->total - nc->escapes - nc->escapes; unsigned long temp = nc->total; temp *= c; temp /= (temp2|1); // this oring by 1 is just to make sure that temp2 is never zero temp += 2; if (temp > 50000) temp = 50000; n->count = static_cast<unsigned short>(temp); nc->escapes += 4; nc->total += static_cast<unsigned short>(temp) + 4; } else { n->count = 3 + 5*(c)/(t-c); nc->escapes = 4; nc->total = n->count + 4; } while (nc->total > 10000) { scale_counts(nc); } } } // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // private member function definitions // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > eemk5::node* entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: allocate_node ( ) { node* temp; temp = root + next_node; ++next_node; return temp; } // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > bool entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: space_left ( ) const { return (next_node < total_nodes); } // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: exclude ( unsigned short symbol ) { exc_used = true; unsigned long temp = 1; temp <<= symbol&0x1F; exc[symbol>>5] |= temp; } // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > bool entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: is_excluded ( unsigned short symbol ) { unsigned long temp = 1; temp <<= symbol&0x1F; return ((exc[symbol>>5]&temp) != 0); } // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: clear_exclusions ( ) { exc_used = false; for (unsigned long i = 0; i < alphabet_size/32+1; ++i) { exc[i] = 0; } } // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > bool entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: something_is_excluded ( ) { return exc_used; } // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: push ( node* n, node* nc ) { stack[stack_size].n = n; stack[stack_size].nc = nc; ++stack_size; } // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: pop ( node*& n, node*& nc ) { --stack_size; n = stack[stack_size].n; nc = stack[stack_size].nc; } // ---------------------------------------------------------------------------------------- template < unsigned long alphabet_size, typename entropy_encoder, unsigned long total_nodes, unsigned long order > void entropy_encoder_model_kernel_5<alphabet_size,entropy_encoder,total_nodes,order>:: scale_counts ( node* temp ) { if (temp->escapes > 1) temp->escapes >>= 1; temp->total = temp->escapes; node* n = temp->child_context; while (n != 0) { if (n->count > 1) n->count >>= 1; temp->total += n->count; n = n->next; } } // ---------------------------------------------------------------------------------------- } #endif // DLIB_ENTROPY_ENCODER_MODEL_KERNEl_5_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 817 ] ] ]
a3a84419c7b721d4bf7e677cf6984d7f69c76edc
02cd7f7be30f7660f6928a1b8262dc935673b2d7
/ invols --username [email protected]/DrawScene.cpp
1244287da8024726bdde2a5c43825990774a3da5
[]
no_license
hksonngan/invols
f0886a304ffb81594016b3b82affc58bd61c4c0b
336b8c2d11d97892881c02afc2fa114dbf56b973
refs/heads/master
2021-01-10T10:04:55.844101
2011-11-09T07:44:24
2011-11-09T07:44:24
46,898,469
1
0
null
null
null
null
UTF-8
C++
false
false
12,983
cpp
#include <stdio.h> #include <stdlib.h> #include "AllDef.h" #include "Mouse.h" #include "Camera.h" #include "Draw.h" #include "Render.h" #include "Draw2D.h" #include <Math.h> #include <ivec3.h> #include "output.h" #include "CT.h" #include "MainFrame.h" #include "GLCanvas.h" #include "DicomReader.h" #include "CPU_VD.h" #include "RenderToTexture.h" #include "seg_points.h" #include "bounding_cells.h" void DrawGrid(vec3 a,vec3 b,float step); void Draw2DInfo(); namespace CT { extern bool rendering_to_file; void DrawCS1() { glDisable(GL_NORMALIZE); glDisable(GL_LIGHTING); glLineWidth(3); float k=0.06f,arr_h=0.02f,arr_d=0.003f,wh=width/float(height+1); glPushMatrix(); vec3 dt; if(cam.GetProjection()) dt = cam.GetPosition()+cam.GetNav()*0.6f-(cam.GetLeft()*wh+cam.GetTop())*0.2f; else { float CameraZoom2D=0.3f,zz=CameraZoom2D*cam.GetDistance()*3.2; dt = cam.GetPosition()+cam.GetNav()*0.5f-(cam.GetLeft()*wh+cam.GetTop())*0.2f*zz; k*=zz;arr_h*=zz;arr_d*=zz; } glTranslated(dt.x,dt.y,dt.z); glColor4f(1,0,0,0.5); glMYLine(0,0,0,k,0,0); DrawPrizma(vec3(k,0,0),vec3(k-arr_h,arr_d,0),vec3(k-arr_h,0,arr_d),vec3(k-arr_h,-arr_d,-arr_d)); glColor4f(0,1,0,0.5); glMYLine(0,0,0,0,k,0); DrawPrizma(vec3(0,k,0),vec3(arr_d,k-arr_h,0),vec3(-arr_d,k-arr_h,-arr_d),vec3(0,k-arr_h,arr_d)); glColor4f(0,0,1,0.5); glMYLine(0,0,0,0,0,k); DrawPrizma(vec3(0,0,k),vec3(arr_d,0,k-arr_h),vec3(-arr_d,-arr_d,k-arr_h),vec3(0,arr_d,k-arr_h)); glPopMatrix(); glEnable(GL_LIGHTING); glEnable(GL_NORMALIZE); glLineWidth(1); } void SetLight(vec3 pos) { GLfloat ps[4] = {pos.x,pos.y,pos.z,0}; glLightfv(GL_LIGHT0,GL_POSITION, ps); } void DrawLightSources() { glColor3f(1,1,0); vec3 cc = (iso->GetBoundingBox(0)+iso->GetBoundingBox(1))*0.5f; vec3 ln = iso->GetLightDir(); //DrawCylinder(cc+ln*1.5,cc+ln*1,0.03f); glLineWidth(3); DrawLine(cc+ln*1.5,cc+ln*1); glLineWidth(1); //DrawSphere(iso->GetDotLight(),0.05f); } bool IsFastView() { //return 0; return (is_changing_tf || is_changing_box || is_changing || (d_zoom!=1)) && (fast_res!=1) && (!stereo_on ||(stereo_on==1 && RenderingType==2)); } int GetFastWidth() { return IsFastView()?(width/fast_res):width; } int GetFastHeight() { return IsFastView()?(height/fast_res):height; } void DrawScene_() { //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); vec3 ps = cam.GetCenter(); if(stereo_on) { cam.SetCenter(ps+cam.GetLeft()*stereo_step*(is_left?-1:1)); if(stereo_on==1) { iso->SetAnag(anag,is_left); } } cam.SetupPosition(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); SetLight(iso->GetLightDir()); int cur_rm = iso->GetCurRMID(); vec3 bb1=iso->GetBoundingBox(0),bb2=iso->GetBoundingBox(1); if(draw_frame_is && !stereo_on) { DrawLightSources(); glEnable(GL_DEPTH_TEST); DrawCS1(); DrawGrid(bb1,bb2,10/DicomReader::GetScale()); //bc_Draw(); if(use_bounding_mesh && draw_bounding_mesh) seg_Draw(); } iso->Draw(draw_small_data); if(rendering_to_file) { glReadBuffer(GL_BACK); int width1=width; int height1=height; int psize=4; unsigned char *dt0 = new unsigned char [width1*height1*psize]; unsigned char *dt = new unsigned char [width1*height1*psize]; glReadPixels(0, 0, width1,height1, GL_RGBA,GL_UNSIGNED_BYTE,dt0); //for(int i=0;i<height1;i++) // memcpy(dt+(height1-i-1)*width1*psize,dt0+i*width1*psize,width1*psize); for(int i=0;i<height1;i++) for(int j=0;j<width1;j++) for(int k=0;k<3;k++) { dt[(j+i*width1)*3+k] = dt0[(j+(height1-i-1)*width1)*4+k]; //memcpy(dt+(height1-i-1)*width1*psize,dt0+i*width1*psize,width1*psize); } wxImage img(width1,height1,dt,true); wxBitmap bp(img); bp.SaveFile(screenshot_dst,wxBITMAP_TYPE_PNG); delete[]dt; delete[]dt0; } /* glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glViewport(0,0,width,height); Begin2D(width,height); if(!is_changing_box) if(use_bounding_mesh && (CT::mouse.btn&1) && !RM_pic_man ) { glColor4f(1,1,1,0.6f); DrawRectangle(vec2(old_mouse_pos.x,old_mouse_pos.y),vec2(mouse.oldx,mouse.oldy)); } End2D(); glEnable(GL_DEPTH_TEST); */ if(stereo_on) cam.SetCenter(ps); } void DrawScene() { //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); int width1 = GetFastWidth(); int height1 = GetFastHeight(); vec3 ps = cam.GetCenter(); if(stereo_on) { cam.SetCenter(ps+cam.GetLeft()*stereo_step*(is_left?-1:1)); if(stereo_on==1) { iso->SetAnag(anag,is_left); } } cam.SetupPosition(); glEnable(GL_DEPTH_TEST); if(IsFastView()) { rtt_Update(width/fast_res,height/fast_res); } if(!draw_bounding_mesh) if(use_bounding_mesh) { static ShaderProgram sp("common_shaders//srf.vs", "common_shaders//store_dist.fs"); sp.Use(); sp.SetVar("pos",CT::cam.GetPosition()); sp.SetVar("nav",CT::cam.GetNav()); sp.SetVar("screen_width",(float)width1); sp.SetVar("screen_height",(float)height1); sp.SetVar("free_depth",0.99f); glBlendFunc(GL_ONE, GL_ZERO); glClearColor(0,0,0,0); for(int fr=0;fr<2;fr++) { if(fr)glCullFace(GL_FRONT); rtt_Begin(fr+1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); rtt_End(); rtt_Begin(3); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); rtt_End(); for(int d=0;d<4;d++) { int id_store = fr+1,id_copy = 3; if(!(d&1))swap(id_store,id_copy); sp.SetVar("fdepth",d); sp.SetVar("dist_txt", rtt_SetID(2,rtt_GetTexture(id_copy))); if(d==3 && fr){glClearDepth(0.0f); glDepthFunc(GL_GREATER); sp.SetVar("free_depth",0.01f);} rtt_Begin(id_store); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); seg_DrawMesh(); if(d==3 && fr){glClearDepth(1.0f); glDepthFunc(GL_LESS);} rtt_End(); } if(fr)glCullFace(GL_BACK); } sp.UnUse(); glClearColor(bg_color.x,bg_color.y,bg_color.z,1.0); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } ///if(IsFastView()) { rtt_Begin(0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); } SetLight(iso->GetLightDir()); int cur_rm = iso->GetCurRMID(); for(int i=0;i<iso->rendering_methods.size();i++) { if(RM_pic_man) { vec2 pos = (iso->rendering_methods[i]->pos-RM_center)*RM_scale*height1/800.0f; vec2 size = iso->rendering_methods[i]->size*RM_scale*height1/800.0f; cam.SetupProjection(pos.x,height1-pos.y-size.y,size.x,size.y); } vec3 bb1=iso->GetBoundingBox(0),bb2=iso->GetBoundingBox(1); if(draw_frame_is && !stereo_on) { /* glColor3d(1,1,1); DrawLine(marker-vec3(1,0,0),marker+vec3(1,0,0)); DrawLine(marker-vec3(0,1,0),marker+vec3(0,1,0)); DrawLine(marker-vec3(0,0,1),marker+vec3(0,0,1)); */ DrawLightSources(); glEnable(GL_DEPTH_TEST); DrawCS1(); DrawGrid(bb1,bb2,10/DicomReader::GetScale()); //bc_Draw(); if(use_bounding_mesh && draw_bounding_mesh) seg_Draw(); } if(RM_pic_man)iso->SetCurRM(i); if(!draw_bounding_mesh) iso->Draw(draw_small_data); if(!RM_pic_man)break; } if(RM_pic_man) iso->SetCurRM(cur_rm); if(RM_pic_man) // if(draw_frame_is) { glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glViewport(0,0,width1,height1); Begin2D(width1,height1); for(int i=0;i<iso->rendering_methods.size();i++) { vec2 pos = (iso->rendering_methods[i]->pos-RM_center)*RM_scale*height1/800.0f; vec2 size = iso->rendering_methods[i]->size*RM_scale*height1/800.0f; if(i == iso->GetCurRMID())glColor3d(1,1,0.5);else glColor3d(0.3,0.3,0.3); DrawRectangle(pos,pos+size); DrawFilledRectangle(pos+vec2(0,-size.y*0.1f),pos+vec2(size.x,0)); } End2D(); //Draw2DInfo(); } //if(IsFastView()) if(rendering_to_file) { glReadBuffer(GL_COLOR_ATTACHMENT0_EXT); int width1=width; int height1=height; int psize=4; unsigned char *dt0 = new unsigned char [width1*height1*psize]; unsigned char *dt = new unsigned char [width1*height1*psize]; glReadPixels(0, 0, width1,height1, GL_RGBA,GL_UNSIGNED_BYTE,dt0); //for(int i=0;i<height1;i++) // memcpy(dt+(height1-i-1)*width1*psize,dt0+i*width1*psize,width1*psize); for(int i=0;i<height1;i++) for(int j=0;j<width1;j++) for(int k=0;k<3;k++) { dt[(j+i*width1)*3+k] = dt0[(j+(height1-i-1)*width1)*4+k]; //memcpy(dt+(height1-i-1)*width1*psize,dt0+i*width1*psize,width1*psize); } wxImage img(width1,height1,dt,true); wxBitmap bp(img); bp.SaveFile(screenshot_dst,wxBITMAP_TYPE_PNG); delete[]dt; delete[]dt0; } rtt_End(); // glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); //glDisable(GL_CULL_FACE); glViewport(0,0,width,height); glColor3d(1,1,0); Begin2D(width,height); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, rtt_GetTexture(0)); static ShaderProgram sp("common_shaders//srf.vs", "common_shaders//fast_view.fs"); sp.Use(); sp.SetVar("f_text",0); sp.SetVar("txt_size",vec4(rtt_GetTextureSize().x,rtt_GetTextureSize().y,!use_bicubic_filtering,0)); //DrawFilledRectangle(vec2(0,0),vec2(width,height),vec2(0),vec2(1.0f/fast_res)); DrawFilledRectangle(vec2(0,0),vec2(width,height)); sp.UnUse(); //glEnable(GL_CULL_FACE); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); End2D(); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glViewport(0,0,width,height); Begin2D(width,height); if(!is_changing_box) if(use_bounding_mesh && (CT::mouse.btn&1) && !RM_pic_man ) { glColor4f(1,1,1,0.6f); DrawRectangle(vec2(old_mouse_pos.x,old_mouse_pos.y),vec2(mouse.oldx,mouse.oldy)); } End2D(); glEnable(GL_DEPTH_TEST); if(IsFastView()) { rtt_Update(width,height); } if(stereo_on) cam.SetCenter(ps); } void DrawScene1() { cam.SetupPosition(); glEnable(GL_DEPTH_TEST); SetLight(iso->GetLightDir()); vec3 center = GetCenter(); vec3 scale = CPU_VD::GetScale(); vec3 bb1=iso->GetBoundingBox(0),bb2=iso->GetBoundingBox(1); if(draw_frame_is) { DrawLightSources(); DrawCS1(); DrawGrid(bb1,bb2,10/DicomReader::GetScale()); glDisable(GL_LIGHTING); ShaderProgram*sp = CT::viewMPR_sp; sp->Use(); sp->SetVar("min_level",CT::iso->GetWindow().x); sp->SetVar("max_level",CT::iso->GetWindow().y); sp->SetVar("LightDir",CT::iso->GetLightDir()); sp->SetVar("pos",CT::cam.GetPosition()); sp->SetVar("scale",CPU_VD::GetScale()); sp->SetVar("txt_level_color",CT::iso->GetTFTexture()->SetID(2)); //if(0) for(int i=0;i<3;i++) if(draw_MRP[i]) if(MyApp::frame->v2d[i]) if(MyApp::frame->v2d[i]->v2d->txt2)// || MyApp::frame->v2d[i]->v2d->txt_reg) { //glBindTexture(GL_TEXTURE_2D,MyApp::frame->v2d[i]->v2d->txt2->SetID(1)); if(MyApp::frame->v2d[i]->v2d->txt2)sp->SetVar("txt",MyApp::frame->v2d[i]->v2d->txt2->SetID(1)); // if(MyApp::frame->v2d[i]->v2d->txt_reg)sp->SetVar("txt_reg",MyApp::frame->v2d[i]->v2d->txt_reg->GetTexture()); if(i==0)DrawCube(vec3(center.x*scale.x,0,0),vec3(center.x*scale.x,scale.y,scale.z)); if(i==1)DrawCube(vec3(0,center.y*scale.y,0),vec3(scale.x,center.y*scale.y,scale.z)); if(i==2)DrawCube(vec3(0,0,center.z*scale.z),vec3(scale.x,scale.y,center.z*scale.z)); } sp->UnUse(); /// glColor3f(1,0,0); if(draw_MRP[0])DrawCubeFrame(vec3(center.x*scale.x,0,0),vec3(center.x*scale.x,scale.y,scale.z)); glColor3f(0,1,0); if(draw_MRP[1])DrawCubeFrame(vec3(0,center.y*scale.y,0),vec3(scale.x,center.y*scale.y,scale.z)); glColor3f(0,0,1); if(draw_MRP[2])DrawCubeFrame(vec3(0,0,center.z*scale.z),vec3(scale.x,scale.y,center.z*scale.z)); glEnable(GL_LINE_STIPPLE); glColor3f(1,0,0); glPushMatrix(); CS3 cs11 = CT::iso->volume_transform[CT::GetCurDataID()]; ChangeCoordSystem(cs11); DrawCubeFrame(vec3(0),vec3(1)); glPopMatrix(); glColor3f(0.8f,0.8f,0); if(draw_frame_is) DrawCubeFrame(vec3(0),vec3(1)); glColor3f(0.4f,0.4f,1); if(draw_gpu_box) DrawCubeFrame(CPU_VD::real_gpu_b1,CPU_VD::real_gpu_b2); bb1 = (CPU_VD::GetRecomendedGPUOffset().ToVec3()/CPU_VD::full_data.GetSize().ToVec3())*scale; bb2 = ((CPU_VD::GetRecomendedGPUOffset()+CPU_VD::gpu_size_dummy).ToVec3()/CPU_VD::full_data.GetSize().ToVec3())*scale; glColor3f(0,1,0); if(draw_gpu_dummy) DrawCubeFrame(bb1,bb2); glDisable(GL_LINE_STIPPLE); } iso->Draw(draw_small_data); glEnable(GL_LIGHTING); /* if(stereo_on!=1) { glColor3d(1,1,1); if(keyboard['3']) DrawDot(iso->GetMinBox()); if(keyboard['4']) DrawDot(iso->GetMaxBox()); } */ } }
[ [ [ 1, 525 ] ] ]
b1e86c21679bcab611085e2f4c5c5c7ba5edd5e0
5e6ff9e6e8427078135a7b4d3b194bcbf631e9cd
/EngineSource/dpslim/dpslim/Simulation/Headers/SegmentWriter.h
bfd63fbea8ae6fc84cb1aa2f9d15091d01b56f67
[]
no_license
karakots/dpresurrection
1a6f3fca00edd24455f1c8ae50764142bb4106e7
46725077006571cec1511f31d314ccd7f5a5eeef
refs/heads/master
2016-09-05T09:26:26.091623
2010-02-01T11:24:41
2010-02-01T11:24:41
32,189,181
0
0
null
null
null
null
UTF-8
C++
false
false
1,338
h
#pragma once #define _CRT_SECURE_NO_WARNINGS // SegmentWriter.h // // Copyright 2006 DecisionPower // // SegmentWriter Class // // Author; Isaac S. Noble // Date: 6/1/2006 #include "stdafx.h" class SegDataRecordset; class CMicroSegment; class SegmentData; class SegmentDataAcc { public: SegmentDataAcc(const CTime&); void AddInfo(CMicroSegment*, Pcn pcn); void getInfo(SegmentData*); void reset(const CTime&); CTime getDate(); CTime getLastWrite(); private: CTime m_lastWrite; long m_segmentID; long m_productID; long m_channelID; CTime m_date; double m_percent_aware_sku_cum; double m_persuasion_sku; double m_GRPs_SKU_tick; double m_promoprice; double m_unpromoprice; double m_sku_dollar_purchased_tick; double m_percent_preuse_distribution_sku; double m_percent_on_display_sku; double m_percent_sku_at_promo_price; double m_num_sku_bought; double m_num_units_unpromo; double m_num_units_promo; double m_num_units_display; double m_display_price; double m_percent_at_display_price; double m_eq_units; double m_volume; long m_num_adds_sku; long m_num_drop_sku; long m_num_coupon_redemptions; long m_num_units_bought_on_coupon; long m_num_sku_triers; long m_num_sku_repeaters; long m_num_sku_repeater_trips_cum; long num_trips; };
[ "Isaac.Noble@fd82578e-0ebe-11df-96d9-85c6b80b8d9c" ]
[ [ [ 1, 63 ] ] ]
0e41bfab25c410fc5616c2f5b075d7775f2a48cd
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Base/Memory/Util/Stack/hkStackMemory.inl
7d20fb7e3c7ebc89c38a2dd7d37509f9d1ec6baf
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
4,089
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #if !defined(HK_PLATFORM_PS3_SPU) hkStackMemory::hkStackMemory() { m_next = HK_NULL; m_start = HK_NULL; m_end = 0; #if defined (HK_PLATFORM_SIM) m_numAllocInfos = 0; #endif } HK_FORCE_INLINE hkStackMemory::~hkStackMemory() { #if defined (HK_PLATFORM_SIM) HK_ASSERT2(0x5f82931b, !m_numAllocInfos, "Not all allocations got freed"); #endif } #endif void hkStackMemory::initMemory(void* p, int size) { m_start = p; m_next = p; m_end = hkAddByteOffset(p, size); #if defined (HK_PLATFORM_SIM) hkMemUtil::memSet(p, 0xcd, size); m_maxStackSize = size; #endif } #if !defined (HK_PLATFORM_SIM) // See .cpp for out of line implementaion for HK_PLATFORM_SIM HK_FORCE_INLINE void* hkStackMemory::allocateStack(int numBytes, const char* what) { HK_ASSERT2(0xaf8365de, !(numBytes & 0x7f) , "Allocation-size should be a multiple of 128."); if ( numBytes > getFreeStackSize() ) { HK_ERROR(0xaf8365df, "Out of stack memory."); } void* current = m_next; m_next = hkAddByteOffset(current, numBytes); return current; } #endif void* hkStackMemory::allocateStackRoundSizeTo128WithCriticalAssert(int numBytes, const char* what) { HK_CRITICAL_ASSERT2(0xaf8365df, getFreeStackSize() >= numBytes, "Out of stack memory."); int allocationSize = HK_NEXT_MULTIPLE_OF(128, numBytes); return allocateStack( allocationSize, what ); } void* hkStackMemory::allocateStackRoundSizeTo128(int numBytes, const char* what) { int allocationSize = HK_NEXT_MULTIPLE_OF(128, numBytes); return allocateStack( allocationSize, what ); } void hkStackMemory::deallocateStack(void* p) { #if defined (HK_PLATFORM_SIM) { AllocInfo& allocInfo = m_allocInfos[--m_numAllocInfos]; HK_ASSERT2(0xaf83d35f, allocInfo.m_p == p, "Deallocating invalid memory pointer." ); hkMemUtil::memSet(allocInfo.m_p, 0xcd, allocInfo.m_size); hkMemUtil::memSet(&allocInfo, 0x0, sizeof(AllocInfo)); } #endif HK_ASSERT2( 0xf0345456, p <= m_next && p >= m_start, "Inconsistent use of stack memory" ); m_next = p; } void hkStackMemory::shrinkAllocatedStack(void* p, int newSize ) { #if defined (HK_PLATFORM_SIM) { AllocInfo& allocInfo = m_allocInfos[m_numAllocInfos-1]; HK_ASSERT2(0xaf83d35f, allocInfo.m_p == p, "Deallocating invalid memory pointer." ); allocInfo.m_size = newSize; } #endif m_next = hkAddByteOffset(p, newSize); } void hkStackMemory::deallocateStack(int numBytes) { #if defined (HK_PLATFORM_SIM) { AllocInfo& allocInfo = m_allocInfos[--m_numAllocInfos]; HK_ASSERT2(0xaf83d35f, allocInfo.m_size == numBytes, "Deallocating invalid memory size." ); hkMemUtil::memSet(allocInfo.m_p, 0xcd, allocInfo.m_size); hkMemUtil::memSet(&allocInfo, 0x0, sizeof(AllocInfo)); } #endif m_next = hkAddByteOffset(m_next.val(), -numBytes); HK_ASSERT2( 0x34a0e762, m_next >= m_start, "Stack underflow!" ); } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 137 ] ] ]
2bbb01c877a9bfc01ef17e5afed658d9f2067ea8
db5271c632341a315c709b638cbd4ea1fb147864
/kg3_1/main.cpp
cb1b067a6258ca40f252186e88a66f61cb77d989
[]
no_license
spetz911/CG
b81974913040c5820718e8d64f9061ba5a52b052
dac535c69c9228ec32d241f4fc21c566b514cbb2
refs/heads/master
2021-01-20T07:04:51.304452
2011-09-30T22:53:08
2011-09-30T22:53:08
2,492,573
0
0
null
null
null
null
UTF-8
C++
false
false
194
cpp
#include <QtGui/QApplication> #include "widget.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.init(); w.show(); return a.exec(); }
[ [ [ 1, 11 ] ] ]
744f1fd5678fbbbe86744c882bfd4204367259fa
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/test/testwave/testfiles/t_5_028.cpp
2ad2898af0787f0fad00bf714518c620d47d6977
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
3,290
cpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2006 Hartmut Kaiser. 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) The tests included in this file were initially taken from the mcpp V2.5 preprocessor validation suite and were modified to fit into the Boost.Wave unit test requirements. The original files of the mcpp preprocessor are distributed under the license reproduced at the end of this file. =============================================================================*/ // Tests whether macro arguments are pre-expanded (unless the argument is an // operand of # or ## operator) separately, that is, are macro-replaced // completely prior to rescanning. #define ZERO_TOKEN #define MACRO_0 0 #define MACRO_1 1 #define TWO_ARGS a,b #define SUB(x, y) (x - y) #define GLUE(a, b) a ## b #define XGLUE(a, b) GLUE( a, b) #define STR(a) # a // 25.1: "TWO_ARGS" is read as one argument to "SUB", then expanded to // "a,b", then "x" is substituted by "a,b". //R #line 32 "t_5_028.cpp" SUB(TWO_ARGS, 1) //R (a,b - 1) // 25.2: An argument pre-expanded to 0-token. */ //R #line 36 "t_5_028.cpp" SUB(ZERO_TOKEN, a) //R ( - a) // 25.3: "glue( a, b)" is pre-expanded. */ //R #line 40 "t_5_028.cpp" XGLUE(GLUE(a, b), c) //R abc // 25.4: Operands of ## operator are not pre-expanded. //R #line 44 "t_5_028.cpp" GLUE(MACRO_0, MACRO_1) //R MACRO_0MACRO_1 // 25.5: Operand of # operator is not pre-expanded. //R #line 48 "t_5_028.cpp" STR(ZERO_TOKEN) //R "ZERO_TOKEN" /*- * Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 75 ] ] ]
087c55f5713b6825987e2be44f47ccf24b1a5619
74b0667a0585cfef6eca1ddc0e31424cce1031a1
/officevillagers/_Source/LevelLogic/actor.h
bfa829dd1e02da7b962dd1ecade25903e1b7e065
[]
no_license
IPv6/officevillagers
14e599f27beba5023dd89d28d5c5ad2c10b814ae
94ab3660c71e59099fd6a2d9c0465c0a9ef905e0
refs/heads/master
2020-05-20T11:29:17.509396
2008-09-19T02:00:31
2008-09-19T02:00:31
32,118,932
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
10,469
h
#ifndef _H_PROTECTOR_LEVELACTOR #define _H_PROTECTOR_LEVELACTOR #include "../engineBindings.h" #include "navigation.h" #include "actorItem.h" #define SUBID_BODY 10000 #define SUBID_HEAD 10001 #define SUBID_LABELS 10002 #define SUBID_LB_NAME 10003 #define SUBID_ITEMATTACH 10004 #define SUBID_SHADOW 10005 #define SUBID_SIT_AVATAR 10099 #define SUBID_SIT_0 10100 #define SUBID_SIT_MAX 10109 #define SUBID_SITX_0 10110 #define SUBID_SITX_MAX 10119 #define SUBID_DEFDROP 10200 #define BY_STOP_MOTION 10 #define BY_STOP_LEVELEND 11 #define DEF_ACTOR_Z -0.001f #define DEF_NONEXISTABLEACTOR "NONEXISTABLENAME!" class CAction; class CProphession: public StorageNamed::CXmlStruct { public: CProphession() { lCounter=0; bChangeNavigation=0; lNoPocketPosSync=0; } CString sName; CString sBaseName; long iBodySpr; long lNoThink; long lNoPocketPosSync; long lCounter; long bChangeNavigation;//0-не меняет проходимость. 1-меняет, автогенерация подходов. 2-меняет, без автогенерации подходов (стены) float w; float h; MAP2XML_BEGIN("Prophession") MAP2XML (&sName, "Name") MAP2XML_DEF (&sBaseName, "BaseName", "") MAP2XML_DEF (&iBodySpr, "BodySpr", -1) MAP2XML_DEF (&lNoThink, "NoThink", 0) MAP2XML_DEF (&lNoPocketPosSync, "NoPocketPosSync", 0) MAP2XML_DEF (&bChangeNavigation, "ChangeNavigation", 0) MAP2XML_DEF (&w, "defWidth", 2.0f) MAP2XML_DEF (&h, "defHeight", 2.0f) MAP2XML_END() }; typedef core::array<CProphession*> _array_CProphession; class CNextActionOrder { public: CNextActionOrder() { sActionToSwitchTo=""; bManual=0; } CString sActionToSwitchTo; BOOL bManual; CNextActionOrder& CNextActionOrder::operator=(const CNextActionOrder& other) { sActionToSwitchTo=other.sActionToSwitchTo; bManual=other.bManual; return *this; } }; #define NO_ACTION "#NOACTION!#" class CActor: public irr::IReferenceCounted, public StorageNamed::CXmlStruct { public: void Init(); CActor(){Init();}; ~CActor(); //=================== //=================== // Сохраняемые данные struct CSerializableData { CString p_sName;// Уникальное в рамкам всего-всего имя CString p_sNameLocalized; long p_Enabled; long p_iBody; long p_iHead; long p_iBodyLock;//У перса 0-от професси меняется тело,1-не меняется. У объекта 0 - локейшн не влияет на проходимость, 1- клияет long p_iActorType;//-1-Офис, глобальный, 0-Неподвижный, 1-Подвижный f32 p_fCreationTime; _v2 p_pos; CString p_posLocator; CString p_actorLocationInitial; CString p_actorLocationEntrance; f32 p_speedRate; f32 p_CurrentFaceDirection; _v2 p_CurrentBodyDirection; CString p_Sprite; CString p_CurrentActionName; f32 fActionBeginTime; CString p_ProfessionName; CString p_ValidProphession; CString p_FollowToActor; CUniOptionsHolder p_Attributes; CString p_AttributesAsStr;// Паковка в строку... CString p_AttributesOverload;// Хардкод некоторых левых значений... _array_CItemP p_items;// Важен именно масиив и порядок... CString p_sScriptOnCreate; CString p_sScriptOnDelete; CString p_sScriptOnEnable; CString p_sScriptOnDisable; CString p_sInPocket_Actor; CString p_sInPocket_Item; void CopyFrom(const CActor& other) { // Копируем только data! p_sName=other.data.p_sName; p_sNameLocalized=other.data.p_sNameLocalized; p_Enabled=other.data.p_Enabled; p_iBody=other.data.p_iBody; p_iHead=other.data.p_iHead; p_iBodyLock=other.data.p_iBodyLock; p_iActorType=other.data.p_iActorType; p_fCreationTime=other.data.p_fCreationTime; p_pos=other.data.p_pos; p_posLocator=other.data.p_posLocator; p_actorLocationInitial=other.data.p_actorLocationInitial; p_actorLocationEntrance=other.data.p_actorLocationEntrance; p_speedRate=other.data.p_speedRate; p_CurrentFaceDirection=other.data.p_CurrentFaceDirection; p_CurrentBodyDirection=other.data.p_CurrentBodyDirection; p_Sprite=other.data.p_Sprite; p_CurrentActionName=other.data.p_CurrentActionName; fActionBeginTime=other.data.fActionBeginTime; p_ProfessionName=other.data.p_ProfessionName; p_ValidProphession=other.data.p_ValidProphession; p_FollowToActor=other.data.p_FollowToActor; p_AttributesAsStr=other.data.p_AttributesAsStr; p_sScriptOnCreate=other.data.p_sScriptOnCreate; p_sScriptOnDelete=other.data.p_sScriptOnDelete; p_sScriptOnEnable=other.data.p_sScriptOnEnable; p_sScriptOnDisable=other.data.p_sScriptOnDisable; p_sInPocket_Actor=other.data.p_sInPocket_Actor; p_sInPocket_Item=other.data.p_sInPocket_Item; } } data; long iActorID;// Уникальный в рамках игросессии код SquirrelObject scriptMirror; BOOL actionAttachDone; CAction* p_CurrentAction; CProphession* p_Profession; CLocation* actorLocationLocator; CString sActorStatusTextOverload; void SetStatusTextOverload(const char* sz); long _autoClone; _v3 posOffset; MAP2XML_BEGIN("Actor") MAP2XML (&data.p_sName, "Name") MAP2XML_DEF (&data.p_sNameLocalized, "NameLocalized", "") MAP2XML_DEF (&data.p_Enabled, "Enabled", 1) MAP2XML_DEF (&data.p_Sprite, "Sprite", "") MAP2XML_DEF (&data.p_iBody, "Body", 0) MAP2XML_DEF (&data.p_iHead, "Head", 0) MAP2XML_DEF (&data.p_iBodyLock, "BodyLock", 0) MAP2XML_DEF (&data.p_pos.X, "Position.x", 0) MAP2XML_DEF (&data.p_pos.Y, "Position.y", 0) MAP2XML_DEF (&data.p_posLocator, "Position.Location", "") MAP2XML_DEF (&data.p_actorLocationInitial, "Position.LocationInit", "") MAP2XML_DEF (&data.p_actorLocationEntrance, "Position.LocationEntr", "") MAP2XML_DEF (&data.p_iActorType, "ActorType", 0) MAP2XML_DEF (&data.p_fCreationTime, "CreationTime", -1.0f) MAP2XML (&data.p_ProfessionName, "ActorProphession") MAP2XML_DEF (&data.p_ValidProphession, "ActorValidProphession", "NONE") MAP2XML_DEF (&data.p_FollowToActor, "FollowToActor", "") MAP2XML_DEF (&data.p_sInPocket_Actor, "InPocket_Actor", "") MAP2XML_DEF (&data.p_sInPocket_Item, "InPocket_Item", "") MAP2XML_DEF (&data.p_CurrentActionName, "CurrentAction", "") MAP2XML_DEF (&data.p_AttributesAsStr, "Attributes", "") MAP2XML_DEF (&data.p_AttributesOverload, "AttributesOverload", "") MAP2XML (&data.p_items, "Items") MAP2XML_DEF (&_autoClone, "AutoClone", 0) MAP2XML_DEF (&data.p_sScriptOnCreate, "ScriptOnCreate", "") MAP2XML_DEF (&data.p_sScriptOnDelete, "ScriptOnDelete", "") MAP2XML_DEF (&data.p_sScriptOnEnable, "ScriptOnEnable", "") MAP2XML_DEF (&data.p_sScriptOnDisable, "ScriptOnDisable", "") MAP2XML_END() void PrepareSerialization(); void ApplySerialization(); //=================== //=================== BOOL isError; BOOL bNodeSpawned; BOOL isInteractive; BOOL GetInteractive(); void SetInteractive(BOOL bValue); void SetProf(const char* szProf,BOOL bUIOnly); void SetLocation(CLocation* loc); void SetLocation(const _v2& newPos); void SetEnable(BOOL bEnable,BOOL bForceScriptUpdate); float GetWalkSpeed(); BOOL AI_TuneCrowdBehaviour(_v2& fromp, _v2& point, _rctf& safeZone); CCriticalSection csactiveNavigationMap; CNextActionOrder nextAction; CWalkData walkData; void StopBodyMotion(BOOL bLevelEnd=FALSE); void StopBodyMotionUI(BOOL bLevelEnd=FALSE); u32 lastThinkTime; void SpawnPersUI(); void SetBodyZeroSprite(); void RefreshBodyAccordingDirection(_v2 direction,BOOL bWalking); void RefreshHeadAccordingDirection(float fBodyAddonAngle,int iAngleShift=0, BOOL bRelative=1, BOOL bTrim=1); void ReattachItems(); void Think(u32 timeMs,BOOL bFastForward=0); void ThinkMovements(u32 timeMs); void ThinkFollower(); void ThinkActions(); void ThinkItems(); BOOL ThinkPocket(BOOL bForceUpdate=FALSE); // Локация - цель. юзаем динамические координаты CString activeNavigationDotLocationName;// По идее надо запоминать. НО! с учетом того, что при загрузке степ начинается сначала, activeNavigationDotLocationName при активации действия _v2 lastFollowerToPosition; CSpriteNode* node; BOOL bMovementsIsPaused; int bMovementsIsPausedToTime; #ifdef _DEBUG CString dbgActionHistory; #endif CActor* lastInPocketActor; u32 lastHeadYawTime; void ShowActorLabels(BOOL b, CNodeBasement* onNode=0); BOOL bHasBodyAndCanMove; _v2 getPosition(); void AI_SyncPosition(BOOL bForceUpdate=0);//0-взять координаты, 1-установить координаты в спрайт, 2-синхронизировать локатор наплевав на тип BOOL AI_SetMove2TargetPos(_v2 newpos); BOOL AI_SetMove2TargetPos(const char* szLocation); int AI_PauseMovements(BOOL bPuase); void PauseMovementsForSec(int iSecs); BOOL AI_MakeWalkablePathTo(_v2 targetPosition); BOOL AI_FinishWalkablePathTo(); BOOL AI_SwitchToAction(const char* szActionName,BOOL bManual, BOOL bNOW=FALSE); BOOL AI_SetFollowTo(CActor* targetAuthor); BOOL AI_EnsureMinDist2Actor(CActor* movableActor, f32 dist,bool forceDistAsNeared); BOOL SetActionAccordingOrder(); BOOL AddAttribute(const char* szName, const char* value); BOOL AddAttribute(const char* szName, long value); BOOL AddAttribute(const char* szName, f32 value); CString GetAttributeStr(const char* szName); long GetAttributeLong(const char* szName); f32 GetAttributeF32(const char* szName); BOOL DelAttribute(const char* szName); BOOL AddItem(const char* szName,const char* szParamsRaw,const char* szCustomParam); BOOL DelItem(const char* szName); BOOL DelItem(CActorItem* p); CActorItem* GetItemByName(const char* szName); CActorItem* GetItemByIndex(int iIndex); CActorItem* GetItemByMask(const char* szName); int AutoClearItems(const char* szName); BOOL PutInPocket(const char* szToActor,const char* szToItem); BOOL MakePocketEmpty(); CString sLastInPocketActor; }; #endif
[ "wplabs@5873e4e3-2a54-0410-bc5d-d38544d033f4" ]
[ [ [ 1, 281 ] ] ]
74ea06a74e72f6a3d31198e9f5ba462077da4917
7e6c795d359cc4943a7ff311660d2fbacdfe6645
/src/AutoMasonQT3/bbb_Lively.cpp
c5a9c9fee9c15d2009e4c669e50d7b47149c4fd8
[]
no_license
keencode/AutomasonMP3
3dc1550a3f506d0d6743df64e337d013c81c8e80
9af3d7668fff252c2c3a6a0432cfaf71e75a326b
refs/heads/master
2020-05-19T13:32:12.522715
2011-09-21T00:13:21
2011-09-21T00:13:21
2,114,357
0
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
#include "bbb_Lively.h" void bbb_Lively::run() { // for( int count = 0; count < 20; count++ ) { while(quit == false) { sleep( 1 ); // qDebug( "Ping!" ); qApp->processEvents(); qWgt->updateGL(); } } bbb_Lively::bbb_Lively(QApplication * _qApp, QGLWidget * _qWgt) { quit = false; qApp = _qApp; qWgt = _qWgt; } bbb_Lively::~bbb_Lively(void) { }
[ [ [ 1, 24 ] ] ]
e19ed62bc6fb200d0d19fb5d7f7d7944c9c218ad
aefc3d630a28e054a438d13ab16d32f2d39ccb1e
/Dialog.cpp
28c623ab32a3ceb212901cef84f5d3157d25d0e1
[]
no_license
imcooder/publicwince
e64305d86496b550116c312d2e9a67e7fb33c6f8
58a337768161e1a10664b4d5edc2aadfb2ab1328
refs/heads/master
2021-05-28T10:40:35.786601
2010-06-27T06:25:09
2010-06-27T06:25:09
32,301,144
1
0
null
null
null
null
UTF-8
C++
false
false
7,426
cpp
#include "stdafx.h" #include "Dialog.h" #include "Ext_type.h" #include <windows.h> #include <HWDebug.h> CXUE_Dialog::CXUE_Dialog() { m_bModalless = FALSE; } CXUE_Dialog::~CXUE_Dialog() { m_bModalless = FALSE; } BOOL CALLBACK CXUE_Dialog::DialogProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { CXUE_Dialog *pDialog = NULL; if (WM_INITDIALOG == message) { pDialog = (CXUE_Dialog *)lparam; SetWindowLong(hwnd, DWL_USER, (LONG)pDialog); } else { pDialog = (CXUE_Dialog *) GetWindowLong(hwnd, DWL_USER); } if (!pDialog) { return 0;//DefWindowProc(hwnd, message, wparam, lparam); } else { return pDialog->_DialogProc(hwnd, message, wparam, lparam); } } LRESULT CXUE_Dialog::_DialogProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: { m_hWnd = hWnd; return OnInitDialog(hWnd, message, wParam, lParam); } break; case WM_DESTROY: { return OnDestroy(hWnd, message, wParam, lParam); } break; case WM_COMMAND: { return OnCommand(hWnd, message, wParam, lParam); } break; case WM_SIZE: { return OnSize(hWnd, message, wParam, lParam); } break; case WM_ERASEBKGND: { return OnEraseBackground(hWnd, message, wParam, lParam); } break; case WM_SETCURSOR: { return OnSetCursor(hWnd, message, wParam, lParam); } break; case WM_MOVE: { return OnMove(hWnd, message,wParam, lParam); } break; case WM_LBUTTONDOWN: { return OnLButtonDown(hWnd, message, wParam, lParam); } break; case WM_LBUTTONDBLCLK: { return OnLButtonDbClk(hWnd, message, wParam, lParam); } break; case WM_MOUSEMOVE: { return OnMouseMove(hWnd, message, wParam, lParam); } break; case WM_LBUTTONUP: { return OnLButtonUp(hWnd, message, wParam, lParam); } break; case WM_SHOWWINDOW: { return OnShowWindow(hWnd, message, wParam, lParam); } break; case WM_TIMER: { return OnTimer(hWnd, message, wParam, lParam); } break; case WM_HSCROLL: { return OnHScroll(hWnd, message, wParam, lParam); } break; case WM_VSCROLL: { return OnVScroll(hWnd, message, wParam, lParam); } break; default: { return 0;//DefWindowProc(hDlg, message, wParam, lParam); } break; } return FALSE; } LRESULT CXUE_Dialog::OnInitDialog( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { return 0;//DefWindowProc(hDlg, message, wParam, lParam);; } LRESULT CXUE_Dialog::OnCommand(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { return 0;//DefWindowProc(hDlg, message, wParam, lParam); } LRESULT CXUE_Dialog::OnDestroy(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { return 0;//DefWindowProc(hDlg, message, wParam, lParam); } LRESULT CXUE_Dialog::OnSize(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return 0; } LRESULT CXUE_Dialog::OnMove(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return 0; } LRESULT CXUE_Dialog::OnEraseBackground(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return 0; } LRESULT CXUE_Dialog::OnMouseMove(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return 0; } LRESULT CXUE_Dialog::OnLButtonDown(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return 0; } LRESULT CXUE_Dialog::OnLButtonDbClk(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return 0; } LRESULT CXUE_Dialog::OnLButtonUp(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return 0; } LRESULT CXUE_Dialog::OnShowWindow(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return 0; } LRESULT CXUE_Dialog::OnSetCursor(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { return 0; } LRESULT CXUE_Dialog::OnTimer(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return 0; } LRESULT CXUE_Dialog::OnHScroll(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return 0; } LRESULT CXUE_Dialog::OnVScroll(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { return 0; } BOOL CXUE_Dialog::CheckDlgButton( UINT nID, UINT nCheck) { if (IsWindow()) { return ::CheckDlgButton(GetSafeHwnd(), nID, nCheck); } return FALSE; } UINT CXUE_Dialog::IsDlgButtonChecked( UINT nID) { if (IsWindow()) { return ::IsDlgButtonChecked(GetSafeHwnd(), nID); } return BST_UNCHECKED; } int CXUE_Dialog::GetItemWindowText(UINT nID, LPTSTR pszStr, int nMax) { HWND hItem = GetDlgItem(nID); if (hItem) { return GetWindowText(hItem, pszStr, nMax); } return -1; } BOOL CXUE_Dialog::SetItemText(UINT nID, LPCTSTR pszStr) { HWND hCtrl = GetDlgItem(nID); if (hCtrl) { return ::SetWindowText(hCtrl, pszStr); } return FALSE; } BOOL CXUE_Dialog::EnableItemWindow( UINT nID, BOOL bEnable) { HWND hCtrl = ::GetDlgItem(GetSafeHwnd(), nID); if (hCtrl) { return ::EnableWindow(hCtrl, bEnable); } return FALSE; } HWND CXUE_Dialog::GetDlgItem( UINT nID) { if (IsWindow()) { return GetDlgItem(GetSafeHwnd(), nID); } return NULL; } HWND CXUE_Dialog::GetDlgItem(HWND hDlg, UINT nID) { return ::GetDlgItem(hDlg, nID); } LRESULT CXUE_Dialog::DestroyWindow() { if (IsWindow()) { if (m_bModalless) { return ::DestroyWindow(GetSafeHwnd()) ? ERROR_SUCCESS : ERROR_INVALID_DATA; } else { return ::EndDialog(GetSafeHwnd(), 0) ? ERROR_SUCCESS : ERROR_INVALID_DATA; } } return ERROR_INVALID_DATA; } LRESULT CXUE_Dialog::CreateModalDialog(HINSTANCE hInstance, LPCTSTR lpTemplate, HWND hWndParent) { if (!lpTemplate) { return ERROR_INVALID_PARAMETER; } if (IsWindow()) { return ERROR_SUCCESS; } m_hInstance = hInstance; m_bModalless = FALSE; m_hWndCreator = hWndParent; return DialogBoxParam(hInstance, lpTemplate, hWndParent, (DLGPROC)DialogProc, (LONG)this); } LRESULT CXUE_Dialog::CreateModalDialog(HINSTANCE hInstance, UINT nTemplate, HWND hWndParent) { return CreateModalDialog(hInstance, MAKEINTRESOURCE(nTemplate), hWndParent); } LRESULT CXUE_Dialog::CreateModallessDialog(HINSTANCE hInstance, LPCTSTR lpTemplate, HWND hWndParent) { if (!lpTemplate) { return ERROR_INVALID_PARAMETER; } if (IsWindow()) { return ERROR_SUCCESS; } m_hInstance = hInstance; m_bModalless = TRUE; m_hWndCreator = hWndParent; ::CreateDialogParam(hInstance, lpTemplate, hWndParent, DialogProc, (LPARAM)this); return IsWindow()? ERROR_SUCCESS : ERROR_INVALID_DATA; } LRESULT CXUE_Dialog::CreateModallessDialog( HINSTANCE hInstance, UINT nTemplate, HWND hWndParent) { return CreateModallessDialog(hInstance, MAKEINTRESOURCE(nTemplate), hWndParent); } UINT CXUE_Dialog::GetDlgItemText( int nIDDlgItem, LPTSTR lpString, int nMaxCount ) { return GetDlgItemText(GetSafeHwnd(), nIDDlgItem, lpString, nMaxCount); } UINT CXUE_Dialog::GetDlgItemText( HWND hDlg, int nIDDlgItem, LPTSTR lpString, int nMaxCount ) { return ::GetDlgItemText(hDlg, nIDDlgItem, lpString, nMaxCount); } BOOL CXUE_Dialog::SetDlgItemText( int nIDDlgItem, LPCTSTR lpString) { return SetDlgItemText(GetSafeHwnd(), nIDDlgItem, lpString); } BOOL CXUE_Dialog::SetDlgItemText( HWND hDlg, int nIDDlgItem, LPCTSTR lpString) { return ::SetDlgItemText(hDlg, nIDDlgItem, lpString); }
[ "[email protected]@a9ac5a9c-960a-11de-b8e1-0bcae535652c" ]
[ [ [ 1, 338 ] ] ]
224cfc1dc0cc2eaaa21808e8a1b04a92211a9c86
7f6f9788d020e97f729af85df4f6741260274bee
/src/afx/Framework.cpp
48419723e0d9fcb3a05e797314079c967914f15b
[]
no_license
cnsuhao/nyanco
0fb88ed1cf2aa9390fa62f6723e8424ba9a42ed4
ba199267a33d4c6d2e473ed4b777765057aaf844
refs/heads/master
2021-05-31T05:37:51.892873
2008-05-27T05:23:19
2008-05-27T05:23:19
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
9,397
cpp
/*! @file Framework.cpp @author dasyprocta */ #include "Framework.hpp" #include "GraphicsDevice.hpp" #include "InputDevice.hpp" #include "Application.h" // TEST: GUI の組み込み #include "GuiInterface.h" //#include "DefaultMenu.hpp" namespace nyanco { GuiInterface::Factory GuiInterface::Factory_ = 0; // ---------------------------------------------------------------------------- void Framework::initialize() { // HACK: hwnd_ = createWindow( hinstance_, L"nyanco framework", 640, 480); // graphics { impl::GraphicsDevice& device = impl::GraphicsDevice::GetImplement(); device.create(hwnd_, 640, 480, false); } // input { impl::InputDevice& device = impl::InputDevice::GetImplement(); device.create(hinstance_, hwnd_); } // TEST: GUI { GuiInterface::Implement(); guiPtr_ = GuiInterface::Instanciate(); guiPtr_->onInitialize(); //impl::setupMenu(); } appPtr_->onInitialize(); } // ---------------------------------------------------------------------------- void Framework::finalize() { guiPtr_->onFinalize(); appPtr_->onFinalize(); } // ---------------------------------------------------------------------------- void Framework::run() { MSG msg = { 0, 0, 0, 0 }; bool isDeviceLost = false; DWORD prevTime = ::timeGetTime(); ::ShowWindow(hwnd_, SW_SHOW); ::UpdateWindow(hwnd_); impl::GraphicsDevice& device = impl::GraphicsDevice::GetImplement(); LPDIRECT3DDEVICE9 d3dDevice = device.getD3dDevice(); while (msg.message != WM_QUIT) { if (::PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } else { // デバイスが消失していれば復元 if (isDeviceLost) { if (!device.checkReset()) { // デバイスが復元可能状態ではない continue; } // 復元 reset(); isDeviceLost = false; } // TEST: 入力取得 { impl::InputDevice& device = impl::InputDevice::GetImplement(); device.acquire(); } DWORD time = ::timeGetTime(); // TEST: GUI の更新 guiPtr_->onUpdate(); { appPtr_->onUpdate(); impl::InputDevice& device = impl::InputDevice::GetImplement(); impl::Keyboard& keyboard = device.getImplKeyboard(); impl::Mouse& mouse = device.getImplMouse(); keyboard.clear(); mouse.clear(); } d3dDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff000000, 1.f, 0); d3dDevice->BeginScene(); D3DRECT rect; guiPtr_->getClientRect(rect.x1, rect.y1, rect.x2, rect.y2); d3dDevice->Clear(1, &rect, D3DCLEAR_TARGET, 0xff000088, 1.f, 0); appPtr_->onDraw(); // TEST: GUI の描画 guiPtr_->onDraw(); d3dDevice->EndScene(); if (!device.present()) { isDeviceLost = true; } prevTime = time; } } } // ---------------------------------------------------------------------------- void Framework::adjustWindow( HWND hwnd, int clientWidth, int clientHeight) { RECT windowRect; RECT clientRect; ::GetWindowRect(hwnd, &windowRect); ::GetClientRect(hwnd, &clientRect); int const dw = (windowRect.right - windowRect.left) - (clientRect.right - clientRect.left); int const dh = (windowRect.bottom - windowRect.top) - (clientRect.bottom - clientRect.top); int const width = clientWidth + dw; int const height = clientHeight + dh; ::MoveWindow( hwnd, (::GetSystemMetrics(SM_CXSCREEN) - width) / 2, (::GetSystemMetrics(SM_CYSCREEN) - height) / 2, width, height, TRUE); } // ---------------------------------------------------------------------------- HWND Framework::createWindow( HINSTANCE hinstance, LPCTSTR title, int width, int height, bool fullscreen) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = 0; wcex.lpfnWndProc = (WNDPROC)nyanco::Framework::mapProcedure; wcex.cbClsExtra = 0; wcex.cbWndExtra = sizeof(LONG); // Framework class extra field wcex.hInstance = hinstance; wcex.hIcon = ::LoadIcon(0, IDI_APPLICATION); wcex.hCursor = ::LoadCursor(0, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = 0; wcex.lpszClassName = title; wcex.hIconSm = ::LoadIcon(0, IDI_WINLOGO); ::RegisterClassEx(&wcex); DWORD style = fullscreen? FullscreenStyle: SizableWindowStyle; HWND hwnd = ::CreateWindow( title, title, style, CW_USEDEFAULT, CW_USEDEFAULT, width, height, 0, 0, hinstance, 0); adjustWindow(hwnd, width, height); ::SetWindowLong(hwnd, 0, reinterpret_cast<LONG>(this)); return hwnd; } // ---------------------------------------------------------------------------- void Framework::reset() { impl::GraphicsDevice& device = impl::GraphicsDevice::GetImplement(); appPtr_->onLostDevice(); device.reset(); appPtr_->onResetDevice(); } // ---------------------------------------------------------------------------- LRESULT Framework::mapProcedure( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { Framework* fwp = reinterpret_cast<Framework*>(::GetWindowLong(hwnd, 0)); if (fwp != 0) { return fwp->messageProcedure(hwnd, msg, wparam, lparam); } return ::DefWindowProc(hwnd, msg, wparam, lparam); } // ---------------------------------------------------------------------------- LRESULT Framework::messageProcedure( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { switch (msg) { case WM_DESTROY: ::PostQuitMessage(0); break; case WM_SIZE: { impl::GraphicsDevice& device = impl::GraphicsDevice::GetImplement(); D3DPRESENT_PARAMETERS& pp = device.getPresentParameters(); pp.BackBufferWidth = LOWORD(lparam); pp.BackBufferHeight = HIWORD(lparam); reset(); guiPtr_->setClientRect(0, 0, pp.BackBufferWidth, pp.BackBufferHeight); } break; case WM_KEYDOWN: case WM_SYSKEYDOWN: { impl::InputDevice& device = impl::InputDevice::GetImplement(); impl::Keyboard& keyboard = device.getImplKeyboard(); keyboard.setVirtualKey(static_cast<uint8>(wparam)); } break; case WM_CHAR: { impl::InputDevice& device = impl::InputDevice::GetImplement(); impl::Keyboard& keyboard = device.getImplKeyboard(); keyboard.setAscii(static_cast<sint8>(wparam)); } break; case WM_LBUTTONDOWN: // TEST: マウスのキーリピートは取れない? { impl::InputDevice& device = impl::InputDevice::GetImplement(); impl::Mouse& mouse = device.getImplMouse(); mouse.setVirtualKey(VK_LBUTTON); } break; case WM_SETFOCUS: { impl::InputDevice& device = impl::InputDevice::GetImplement(); device.acquire(); } break; default: return ::DefWindowProc(hwnd, msg, wparam, lparam); } return 0; } } // namespace nyanco // ---------------------------------------------------------------------------- int WINAPI WinMain( HINSTANCE hinstance, HINSTANCE , // hPrevInstance LPSTR , // szCmdLine int ) // iCmdShow { using namespace nyanco; extern Application* NyancoCreateApp(); Framework framework(hinstance, NyancoCreateApp()); framework.initialize(); framework.run(); framework.finalize(); return 0; }
[ "dasyprocta@27943c09-b335-0410-ab52-7f3c671fdcc1" ]
[ [ [ 1, 322 ] ] ]